File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1255: download - view: text, annotated - select for diffs
Wed Apr 16 14:40:05 2014 UTC (10 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Course requests for unofficial courses, textbook courses and communities
  can include validation.
  - lonrequestcourse.pm
    - New subroutine: pending_validation_form() generates web form used to
      proceed to validation (can be local script, or script on remote server)
    - Prepended new arg to args passed to: &print_request_outcome() and
      &process_request()  -- $lonhost (lonHostID of current server).
 - localenroll.pm
   - &validate_crsreq() accepts additional (optional) arg -- ref to hash of
     custominfo.
   - &crsreq_updates() supports additional action type ('prevalidate') which
     is used to generate form elements needed for validation of request.
 - lond
   - &validate_crsreq_handler() accepts additional -- $customdata
     which is a frozen hash of custominfo passed in from lonnet.pm
 - lonnet.pm
   - &auto_courserequest_validation() accepts additional arg -- ref to hash of
     custominfo (contains key => value for custm form elements retrieved from
     course request review page.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1255 2014/04/16 14:40:05 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:         %returnhash = %{$domdefs{'inststatustypes'}};
 1749:         @order = @{$domdefs{'inststatusorder'}};
 1750:     } else {
 1751:         if (defined(&domain($udom,'primary'))) {
 1752:             my $uhome=&domain($udom,'primary');
 1753:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1754:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1755:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1756:                 return (\%returnhash,\@order);
 1757:             }
 1758:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1759:             my @pairs=split(/\&/,$hashitems);
 1760:             foreach my $item (@pairs) {
 1761:                 my ($key,$value)=split(/=/,$item,2);
 1762:                 $key = &unescape($key);
 1763:                 next if ($key =~ /^error: 2 /);
 1764:                 $returnhash{$key}=&thaw_unescape($value);
 1765:             }
 1766:             my @esc_order = split(/\&/,$orderitems);
 1767:             foreach my $item (@esc_order) {
 1768:                 push(@order,&unescape($item));
 1769:             }
 1770:         } else {
 1771:             &logthis("get_dom failed - no primary domain server for $udom");
 1772:         }
 1773:     }
 1774:     return (\%returnhash,\@order);
 1775: }
 1776: 
 1777: sub is_domainimage {
 1778:     my ($url) = @_;
 1779:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1780:         if (&domain($1) ne '') {
 1781:             return '1';
 1782:         }
 1783:     }
 1784:     return;
 1785: }
 1786: 
 1787: sub inst_directory_query {
 1788:     my ($srch) = @_;
 1789:     my $udom = $srch->{'srchdomain'};
 1790:     my %results;
 1791:     my $homeserver = &domain($udom,'primary');
 1792:     my $outcome;
 1793:     if ($homeserver ne '') {
 1794: 	my $queryid=&reply("querysend:instdirsearch:".
 1795: 			   &escape($srch->{'srchby'}).':'.
 1796: 			   &escape($srch->{'srchterm'}).':'.
 1797: 			   &escape($srch->{'srchtype'}),$homeserver);
 1798: 	my $host=&hostname($homeserver);
 1799: 	if ($queryid !~/^\Q$host\E\_/) {
 1800: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1801: 	    return;
 1802: 	}
 1803: 	my $response = &get_query_reply($queryid);
 1804: 	my $maxtries = 5;
 1805: 	my $tries = 1;
 1806: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1807: 	    $response = &get_query_reply($queryid);
 1808: 	    $tries ++;
 1809: 	}
 1810: 
 1811:         if (!&error($response) && $response ne 'refused') {
 1812:             if ($response eq 'unavailable') {
 1813:                 $outcome = $response;
 1814:             } else {
 1815:                 $outcome = 'ok';
 1816:                 my @matches = split(/\n/,$response);
 1817:                 foreach my $match (@matches) {
 1818:                     my ($key,$value) = split(/=/,$match);
 1819:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1820:                 }
 1821:             }
 1822:         }
 1823:     }
 1824:     return ($outcome,%results);
 1825: }
 1826: 
 1827: sub usersearch {
 1828:     my ($srch) = @_;
 1829:     my $dom = $srch->{'srchdomain'};
 1830:     my %results;
 1831:     my %libserv = &all_library();
 1832:     my $query = 'usersearch';
 1833:     foreach my $tryserver (keys(%libserv)) {
 1834:         if (&host_domain($tryserver) eq $dom) {
 1835:             my $host=&hostname($tryserver);
 1836:             my $queryid=
 1837:                 &reply("querysend:".&escape($query).':'.
 1838:                        &escape($srch->{'srchby'}).':'.
 1839:                        &escape($srch->{'srchtype'}).':'.
 1840:                        &escape($srch->{'srchterm'}),$tryserver);
 1841:             if ($queryid !~/^\Q$host\E\_/) {
 1842:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1843:                 next;
 1844:             }
 1845:             my $reply = &get_query_reply($queryid);
 1846:             my $maxtries = 1;
 1847:             my $tries = 1;
 1848:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1849:                 $reply = &get_query_reply($queryid);
 1850:                 $tries ++;
 1851:             }
 1852:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1853:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1854:             } else {
 1855:                 my @matches;
 1856:                 if ($reply =~ /\n/) {
 1857:                     @matches = split(/\n/,$reply);
 1858:                 } else {
 1859:                     @matches = split(/\&/,$reply);
 1860:                 }
 1861:                 foreach my $match (@matches) {
 1862:                     my ($uname,$udom,%userhash);
 1863:                     foreach my $entry (split(/:/,$match)) {
 1864:                         my ($key,$value) =
 1865:                             map {&unescape($_);} split(/=/,$entry);
 1866:                         $userhash{$key} = $value;
 1867:                         if ($key eq 'username') {
 1868:                             $uname = $value;
 1869:                         } elsif ($key eq 'domain') {
 1870:                             $udom = $value;
 1871:                         }
 1872:                     }
 1873:                     $results{$uname.':'.$udom} = \%userhash;
 1874:                 }
 1875:             }
 1876:         }
 1877:     }
 1878:     return %results;
 1879: }
 1880: 
 1881: sub get_instuser {
 1882:     my ($udom,$uname,$id) = @_;
 1883:     my $homeserver = &domain($udom,'primary');
 1884:     my ($outcome,%results);
 1885:     if ($homeserver ne '') {
 1886:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1887:                            &escape($id).':'.&escape($udom),$homeserver);
 1888:         my $host=&hostname($homeserver);
 1889:         if ($queryid !~/^\Q$host\E\_/) {
 1890:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1891:             return;
 1892:         }
 1893:         my $response = &get_query_reply($queryid);
 1894:         my $maxtries = 5;
 1895:         my $tries = 1;
 1896:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1897:             $response = &get_query_reply($queryid);
 1898:             $tries ++;
 1899:         }
 1900:         if (!&error($response) && $response ne 'refused') {
 1901:             if ($response eq 'unavailable') {
 1902:                 $outcome = $response;
 1903:             } else {
 1904:                 $outcome = 'ok';
 1905:                 my @matches = split(/\n/,$response);
 1906:                 foreach my $match (@matches) {
 1907:                     my ($key,$value) = split(/=/,$match);
 1908:                     $results{&unescape($key)} = &thaw_unescape($value);
 1909:                 }
 1910:             }
 1911:         }
 1912:     }
 1913:     my %userinfo;
 1914:     if (ref($results{$uname}) eq 'HASH') {
 1915:         %userinfo = %{$results{$uname}};
 1916:     } 
 1917:     return ($outcome,%userinfo);
 1918: }
 1919: 
 1920: sub inst_rulecheck {
 1921:     my ($udom,$uname,$id,$item,$rules) = @_;
 1922:     my %returnhash;
 1923:     if ($udom ne '') {
 1924:         if (ref($rules) eq 'ARRAY') {
 1925:             @{$rules} = map {&escape($_);} (@{$rules});
 1926:             my $rulestr = join(':',@{$rules});
 1927:             my $homeserver=&domain($udom,'primary');
 1928:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1929:                 my $response;
 1930:                 if ($item eq 'username') {                
 1931:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1932:                                               ':'.&escape($uname).':'.$rulestr,
 1933:                                               $homeserver));
 1934:                 } elsif ($item eq 'id') {
 1935:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1936:                                               ':'.&escape($id).':'.$rulestr,
 1937:                                               $homeserver));
 1938:                 } elsif ($item eq 'selfcreate') {
 1939:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1940:                                                &escape($udom).':'.&escape($uname).
 1941:                                               ':'.$rulestr,$homeserver));
 1942:                 }
 1943:                 if ($response ne 'refused') {
 1944:                     my @pairs=split(/\&/,$response);
 1945:                     foreach my $item (@pairs) {
 1946:                         my ($key,$value)=split(/=/,$item,2);
 1947:                         $key = &unescape($key);
 1948:                         next if ($key =~ /^error: 2 /);
 1949:                         $returnhash{$key}=&thaw_unescape($value);
 1950:                     }
 1951:                 }
 1952:             }
 1953:         }
 1954:     }
 1955:     return %returnhash;
 1956: }
 1957: 
 1958: sub inst_userrules {
 1959:     my ($udom,$check) = @_;
 1960:     my (%ruleshash,@ruleorder);
 1961:     if ($udom ne '') {
 1962:         my $homeserver=&domain($udom,'primary');
 1963:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1964:             my $response;
 1965:             if ($check eq 'id') {
 1966:                 $response=&reply('instidrules:'.&escape($udom),
 1967:                                  $homeserver);
 1968:             } elsif ($check eq 'email') {
 1969:                 $response=&reply('instemailrules:'.&escape($udom),
 1970:                                  $homeserver);
 1971:             } else {
 1972:                 $response=&reply('instuserrules:'.&escape($udom),
 1973:                                  $homeserver);
 1974:             }
 1975:             if (($response ne 'refused') && ($response ne 'error') && 
 1976:                 ($response ne 'unknown_cmd') && 
 1977:                 ($response ne 'no_such_host')) {
 1978:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1979:                 my @pairs=split(/\&/,$hashitems);
 1980:                 foreach my $item (@pairs) {
 1981:                     my ($key,$value)=split(/=/,$item,2);
 1982:                     $key = &unescape($key);
 1983:                     next if ($key =~ /^error: 2 /);
 1984:                     $ruleshash{$key}=&thaw_unescape($value);
 1985:                 }
 1986:                 my @esc_order = split(/\&/,$orderitems);
 1987:                 foreach my $item (@esc_order) {
 1988:                     push(@ruleorder,&unescape($item));
 1989:                 }
 1990:             }
 1991:         }
 1992:     }
 1993:     return (\%ruleshash,\@ruleorder);
 1994: }
 1995: 
 1996: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1997: 
 1998: sub get_domain_defaults {
 1999:     my ($domain,$ignore_cache) = @_;
 2000:     return if (($domain eq '') || ($domain eq 'public'));
 2001:     my $cachetime = 60*60*24;
 2002:     unless ($ignore_cache) {
 2003:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2004:         if (defined($cached)) {
 2005:             if (ref($result) eq 'HASH') {
 2006:                 return %{$result};
 2007:             }
 2008:         }
 2009:     }
 2010:     my %domdefaults;
 2011:     my %domconfig =
 2012:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2013:                                   'requestcourses','inststatus',
 2014:                                   'coursedefaults','usersessions',
 2015:                                   'requestauthor','selfenrollment'],$domain);
 2016:     my @coursetypes = ('official','unofficial','community','textbook');
 2017:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2018:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2019:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2020:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2021:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2022:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2023:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2024:     } else {
 2025:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2026:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2027:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2028:     }
 2029:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2030:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2031:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2032:         } else {
 2033:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2034:         }
 2035:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2036:         foreach my $item (@usertools) {
 2037:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2038:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2039:             }
 2040:         }
 2041:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2042:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2043:         }
 2044:     }
 2045:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2046:         foreach my $item ('official','unofficial','community','textbook') {
 2047:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2048:         }
 2049:     }
 2050:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2051:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2052:     }
 2053:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2054:         foreach my $item ('inststatustypes','inststatusorder') {
 2055:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2056:         }
 2057:     }
 2058:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2059:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2060:         foreach my $type (@coursetypes) {
 2061:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2062:                 unless ($type eq 'community') {
 2063:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2064:                 }
 2065:             }
 2066:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2067:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2068:             }
 2069:         }
 2070:     }
 2071:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2072:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2073:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2074:         }
 2075:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2076:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2077:         }
 2078:     }
 2079:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2080:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2081:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2082:                             'approval','limit');
 2083:             foreach my $type (@coursetypes) {
 2084:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2085:                     my @mgrdc = ();
 2086:                     foreach my $item (@settings) {
 2087:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2088:                             push(@mgrdc,$item);
 2089:                         }
 2090:                     }
 2091:                     if (@mgrdc) {
 2092:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2093:                     }
 2094:                 }
 2095:             }
 2096:         }
 2097:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2098:             foreach my $type (@coursetypes) {
 2099:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2100:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2101:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2102:                     }
 2103:                 }
 2104:             }
 2105:         }
 2106:     }
 2107:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2108:     return %domdefaults;
 2109: }
 2110: 
 2111: # --------------------------------------------------- Assign a key to a student
 2112: 
 2113: sub assign_access_key {
 2114: #
 2115: # a valid key looks like uname:udom#comments
 2116: # comments are being appended
 2117: #
 2118:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2119:     $kdom=
 2120:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2121:     $knum=
 2122:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2123:     $cdom=
 2124:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2125:     $cnum=
 2126:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2127:     $udom=$env{'user.name'} unless (defined($udom));
 2128:     $uname=$env{'user.domain'} unless (defined($uname));
 2129:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2130:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2131:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2132:                                                   # assigned to this person
 2133:                                                   # - this should not happen,
 2134:                                                   # unless something went wrong
 2135:                                                   # the first time around
 2136: # ready to assign
 2137:         $logentry=$1.'; '.$logentry;
 2138:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2139:                                                  $kdom,$knum) eq 'ok') {
 2140: # key now belongs to user
 2141: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2142:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2143:                 &appenv({'environment.'.$envkey => $ckey});
 2144:                 return 'ok';
 2145:             } else {
 2146:                 return 
 2147:   'error: Count not permanently assign key, will need to be re-entered later.';
 2148: 	    }
 2149:         } else {
 2150:             return 'error: Could not assign key, try again later.';
 2151:         }
 2152:     } elsif (!$existing{$ckey}) {
 2153: # the key does not exist
 2154: 	return 'error: The key does not exist';
 2155:     } else {
 2156: # the key is somebody else's
 2157: 	return 'error: The key is already in use';
 2158:     }
 2159: }
 2160: 
 2161: # ------------------------------------------ put an additional comment on a key
 2162: 
 2163: sub comment_access_key {
 2164: #
 2165: # a valid key looks like uname:udom#comments
 2166: # comments are being appended
 2167: #
 2168:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2169:     $cdom=
 2170:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2171:     $cnum=
 2172:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2173:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2174:     if ($existing{$ckey}) {
 2175:         $existing{$ckey}.='; '.$logentry;
 2176: # ready to assign
 2177:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2178:                                                  $cdom,$cnum) eq 'ok') {
 2179: 	    return 'ok';
 2180:         } else {
 2181: 	    return 'error: Count not store comment.';
 2182:         }
 2183:     } else {
 2184: # the key does not exist
 2185: 	return 'error: The key does not exist';
 2186:     }
 2187: }
 2188: 
 2189: # ------------------------------------------------------ Generate a set of keys
 2190: 
 2191: sub generate_access_keys {
 2192:     my ($number,$cdom,$cnum,$logentry)=@_;
 2193:     $cdom=
 2194:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2195:     $cnum=
 2196:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2197:     unless (&allowed('mky',$cdom)) { return 0; }
 2198:     unless (($cdom) && ($cnum)) { return 0; }
 2199:     if ($number>10000) { return 0; }
 2200:     sleep(2); # make sure don't get same seed twice
 2201:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2202:     my $total=0;
 2203:     for (my $i=1;$i<=$number;$i++) {
 2204:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2205:                   sprintf("%lx",int(100000*rand)).'-'.
 2206:                   sprintf("%lx",int(100000*rand));
 2207:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2208:        $newkey=~s/0/h/g; # and also 0 and O
 2209:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2210:        if ($existing{$newkey}) {
 2211:            $i--;
 2212:        } else {
 2213: 	  if (&put('accesskeys',
 2214:               { $newkey => '# generated '.localtime().
 2215:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2216:                            '; '.$logentry },
 2217: 		   $cdom,$cnum) eq 'ok') {
 2218:               $total++;
 2219: 	  }
 2220:        }
 2221:     }
 2222:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2223:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2224:     return $total;
 2225: }
 2226: 
 2227: # ------------------------------------------------------- Validate an accesskey
 2228: 
 2229: sub validate_access_key {
 2230:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2231:     $cdom=
 2232:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2233:     $cnum=
 2234:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2235:     $udom=$env{'user.domain'} unless (defined($udom));
 2236:     $uname=$env{'user.name'} unless (defined($uname));
 2237:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2238:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2239: }
 2240: 
 2241: # ------------------------------------- Find the section of student in a course
 2242: sub devalidate_getsection_cache {
 2243:     my ($udom,$unam,$courseid)=@_;
 2244:     my $hashid="$udom:$unam:$courseid";
 2245:     &devalidate_cache_new('getsection',$hashid);
 2246: }
 2247: 
 2248: sub courseid_to_courseurl {
 2249:     my ($courseid) = @_;
 2250:     #already url style courseid
 2251:     return $courseid if ($courseid =~ m{^/});
 2252: 
 2253:     if (exists($env{'course.'.$courseid.'.num'})) {
 2254: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2255: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2256: 	return "/$cdom/$cnum";
 2257:     }
 2258: 
 2259:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2260:     if (exists($courseinfo{'num'})) {
 2261: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2262:     }
 2263: 
 2264:     return undef;
 2265: }
 2266: 
 2267: sub getsection {
 2268:     my ($udom,$unam,$courseid)=@_;
 2269:     my $cachetime=1800;
 2270: 
 2271:     my $hashid="$udom:$unam:$courseid";
 2272:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2273:     if (defined($cached)) { return $result; }
 2274: 
 2275:     my %Pending; 
 2276:     my %Expired;
 2277:     #
 2278:     # Each role can either have not started yet (pending), be active, 
 2279:     #    or have expired.
 2280:     #
 2281:     # If there is an active role, we are done.
 2282:     #
 2283:     # If there is more than one role which has not started yet, 
 2284:     #     choose the one which will start sooner
 2285:     # If there is one role which has not started yet, return it.
 2286:     #
 2287:     # If there is more than one expired role, choose the one which ended last.
 2288:     # If there is a role which has expired, return it.
 2289:     #
 2290:     $courseid = &courseid_to_courseurl($courseid);
 2291:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2292:     foreach my $key (keys(%roleshash)) {
 2293:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2294:         my $section=$1;
 2295:         if ($key eq $courseid.'_st') { $section=''; }
 2296:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2297:         my $now=time;
 2298:         if (defined($end) && $end && ($now > $end)) {
 2299:             $Expired{$end}=$section;
 2300:             next;
 2301:         }
 2302:         if (defined($start) && $start && ($now < $start)) {
 2303:             $Pending{$start}=$section;
 2304:             next;
 2305:         }
 2306:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2307:     }
 2308:     #
 2309:     # Presumedly there will be few matching roles from the above
 2310:     # loop and the sorting time will be negligible.
 2311:     if (scalar(keys(%Pending))) {
 2312:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2313:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2314:     } 
 2315:     if (scalar(keys(%Expired))) {
 2316:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2317:         my $time = pop(@sorted);
 2318:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2319:     }
 2320:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2321: }
 2322: 
 2323: sub save_cache {
 2324:     &purge_remembered();
 2325:     #&Apache::loncommon::validate_page();
 2326:     undef(%env);
 2327:     undef($env_loaded);
 2328: }
 2329: 
 2330: my $to_remember=-1;
 2331: my %remembered;
 2332: my %accessed;
 2333: my $kicks=0;
 2334: my $hits=0;
 2335: sub make_key {
 2336:     my ($name,$id) = @_;
 2337:     if (length($id) > 65 
 2338: 	&& length(&escape($id)) > 200) {
 2339: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2340:     }
 2341:     return &escape($name.':'.$id);
 2342: }
 2343: 
 2344: sub devalidate_cache_new {
 2345:     my ($name,$id,$debug) = @_;
 2346:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2347:     $id=&make_key($name,$id);
 2348:     $memcache->delete($id);
 2349:     delete($remembered{$id});
 2350:     delete($accessed{$id});
 2351: }
 2352: 
 2353: sub is_cached_new {
 2354:     my ($name,$id,$debug) = @_;
 2355:     $id=&make_key($name,$id);
 2356:     if (exists($remembered{$id})) {
 2357: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2358: 	$accessed{$id}=[&gettimeofday()];
 2359: 	$hits++;
 2360: 	return ($remembered{$id},1);
 2361:     }
 2362:     my $value = $memcache->get($id);
 2363:     if (!(defined($value))) {
 2364: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2365: 	return (undef,undef);
 2366:     }
 2367:     if ($value eq '__undef__') {
 2368: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2369: 	$value=undef;
 2370:     }
 2371:     &make_room($id,$value,$debug);
 2372:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2373:     return ($value,1);
 2374: }
 2375: 
 2376: sub do_cache_new {
 2377:     my ($name,$id,$value,$time,$debug) = @_;
 2378:     $id=&make_key($name,$id);
 2379:     my $setvalue=$value;
 2380:     if (!defined($setvalue)) {
 2381: 	$setvalue='__undef__';
 2382:     }
 2383:     if (!defined($time) ) {
 2384: 	$time=600;
 2385:     }
 2386:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2387:     my $result = $memcache->set($id,$setvalue,$time);
 2388:     if (! $result) {
 2389: 	&logthis("caching of id -> $id  failed");
 2390: 	$memcache->disconnect_all();
 2391:     }
 2392:     # need to make a copy of $value
 2393:     &make_room($id,$value,$debug);
 2394:     return $value;
 2395: }
 2396: 
 2397: sub make_room {
 2398:     my ($id,$value,$debug)=@_;
 2399: 
 2400:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2401:                                     : $value;
 2402:     if ($to_remember<0) { return; }
 2403:     $accessed{$id}=[&gettimeofday()];
 2404:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2405:     my $to_kick;
 2406:     my $max_time=0;
 2407:     foreach my $other (keys(%accessed)) {
 2408: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2409: 	    $to_kick=$other;
 2410: 	    $max_time=&tv_interval($accessed{$other});
 2411: 	}
 2412:     }
 2413:     delete($remembered{$to_kick});
 2414:     delete($accessed{$to_kick});
 2415:     $kicks++;
 2416:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2417:     return;
 2418: }
 2419: 
 2420: sub purge_remembered {
 2421:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2422:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2423:     undef(%remembered);
 2424:     undef(%accessed);
 2425: }
 2426: # ------------------------------------- Read an entry from a user's environment
 2427: 
 2428: sub userenvironment {
 2429:     my ($udom,$unam,@what)=@_;
 2430:     my $items;
 2431:     foreach my $item (@what) {
 2432:         $items.=&escape($item).'&';
 2433:     }
 2434:     $items=~s/\&$//;
 2435:     my %returnhash=();
 2436:     my $uhome = &homeserver($unam,$udom);
 2437:     unless ($uhome eq 'no_host') {
 2438:         my @answer=split(/\&/, 
 2439:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2440:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2441:             return %returnhash;
 2442:         }
 2443:         my $i;
 2444:         for ($i=0;$i<=$#what;$i++) {
 2445: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2446:         }
 2447:     }
 2448:     return %returnhash;
 2449: }
 2450: 
 2451: # ---------------------------------------------------------- Get a studentphoto
 2452: sub studentphoto {
 2453:     my ($udom,$unam,$ext) = @_;
 2454:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2455:     if (defined($env{'request.course.id'})) {
 2456:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2457:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2458:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2459:             } else {
 2460:                 my ($result,$perm_reqd)=
 2461: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2462:                 if ($result eq 'ok') {
 2463:                     if (!($perm_reqd eq 'yes')) {
 2464:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2465:                     }
 2466:                 }
 2467:             }
 2468:         }
 2469:     } else {
 2470:         my ($result,$perm_reqd) = 
 2471: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2472:         if ($result eq 'ok') {
 2473:             if (!($perm_reqd eq 'yes')) {
 2474:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2475:             }
 2476:         }
 2477:     }
 2478:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2479: }
 2480: 
 2481: sub retrievestudentphoto {
 2482:     my ($udom,$unam,$ext,$type) = @_;
 2483:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2484:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2485:     if ($ret eq 'ok') {
 2486:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2487:         if ($type eq 'thumbnail') {
 2488:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2489:         }
 2490:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2491:         return $tokenurl;
 2492:     } else {
 2493:         if ($type eq 'thumbnail') {
 2494:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2495:         } else { 
 2496:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2497:         }
 2498:     }
 2499: }
 2500: 
 2501: # -------------------------------------------------------------------- New chat
 2502: 
 2503: sub chatsend {
 2504:     my ($newentry,$anon,$group)=@_;
 2505:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2506:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2507:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2508:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2509: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2510: 		   &escape($newentry)).':'.$group,$chome);
 2511: }
 2512: 
 2513: # ------------------------------------------ Find current version of a resource
 2514: 
 2515: sub getversion {
 2516:     my $fname=&clutter(shift);
 2517:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2518:     return &currentversion(&filelocation('',$fname));
 2519: }
 2520: 
 2521: sub currentversion {
 2522:     my $fname=shift;
 2523:     my $author=$fname;
 2524:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2525:     my ($udom,$uname)=split(/\//,$author);
 2526:     my $home=&homeserver($uname,$udom);
 2527:     if ($home eq 'no_host') { 
 2528:         return -1; 
 2529:     }
 2530:     my $answer=&reply("currentversion:$fname",$home);
 2531:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2532: 	return -1;
 2533:     }
 2534:     return $answer;
 2535: }
 2536: 
 2537: #
 2538: # Return special version number of resource if set by override, empty otherwise
 2539: #
 2540: sub usedversion {
 2541:     my $fname=shift;
 2542:     unless ($fname) { $fname=$env{'request.uri'}; }
 2543:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2544:     if ($urlversion) { return $urlversion; }
 2545:     return '';
 2546: }
 2547: 
 2548: # ----------------------------- Subscribe to a resource, return URL if possible
 2549: 
 2550: sub subscribe {
 2551:     my $fname=shift;
 2552:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2553:     $fname=~s/[\n\r]//g;
 2554:     my $author=$fname;
 2555:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2556:     my ($udom,$uname)=split(/\//,$author);
 2557:     my $home=homeserver($uname,$udom);
 2558:     if ($home eq 'no_host') {
 2559:         return 'not_found';
 2560:     }
 2561:     my $answer=reply("sub:$fname",$home);
 2562:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2563: 	$answer.=' by '.$home;
 2564:     }
 2565:     return $answer;
 2566: }
 2567:     
 2568: # -------------------------------------------------------------- Replicate file
 2569: 
 2570: sub repcopy {
 2571:     my $filename=shift;
 2572:     $filename=~s/\/+/\//g;
 2573:     my $londocroot = $perlvar{'lonDocRoot'};
 2574:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2575:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2576:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2577: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2578: 	return &repcopy_userfile($filename);
 2579:     }
 2580:     $filename=~s/[\n\r]//g;
 2581:     my $transname="$filename.in.transfer";
 2582: # FIXME: this should flock
 2583:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2584:     my $remoteurl=subscribe($filename);
 2585:     if ($remoteurl =~ /^con_lost by/) {
 2586: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2587:            return 'unavailable';
 2588:     } elsif ($remoteurl eq 'not_found') {
 2589: 	   #&logthis("Subscribe returned not_found: $filename");
 2590: 	   return 'not_found';
 2591:     } elsif ($remoteurl =~ /^rejected by/) {
 2592: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2593:            return 'forbidden';
 2594:     } elsif ($remoteurl eq 'directory') {
 2595:            return 'ok';
 2596:     } else {
 2597:         my $author=$filename;
 2598:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2599:         my ($udom,$uname)=split(/\//,$author);
 2600:         my $home=homeserver($uname,$udom);
 2601:         unless ($home eq $perlvar{'lonHostID'}) {
 2602:            my @parts=split(/\//,$filename);
 2603:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2604:            if ($path ne "$londocroot/res") {
 2605:                &logthis("Malconfiguration for replication: $filename");
 2606: 	       return 'bad_request';
 2607:            }
 2608:            my $count;
 2609:            for ($count=5;$count<$#parts;$count++) {
 2610:                $path.="/$parts[$count]";
 2611:                if ((-e $path)!=1) {
 2612: 		   mkdir($path,0777);
 2613:                }
 2614:            }
 2615:            my $ua=new LWP::UserAgent;
 2616:            my $request=new HTTP::Request('GET',"$remoteurl");
 2617:            my $response=$ua->request($request,$transname);
 2618:            if ($response->is_error()) {
 2619: 	       unlink($transname);
 2620:                my $message=$response->status_line;
 2621:                &logthis("<font color=\"blue\">WARNING:"
 2622:                        ." LWP get: $message: $filename</font>");
 2623:                return 'unavailable';
 2624:            } else {
 2625: 	       if ($remoteurl!~/\.meta$/) {
 2626:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2627:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2628:                   if ($mresponse->is_error()) {
 2629: 		      unlink($filename.'.meta');
 2630:                       &logthis(
 2631:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2632:                   }
 2633: 	       }
 2634:                rename($transname,$filename);
 2635:                return 'ok';
 2636:            }
 2637:        }
 2638:     }
 2639: }
 2640: 
 2641: # ------------------------------------------------ Get server side include body
 2642: sub ssi_body {
 2643:     my ($filelink,%form)=@_;
 2644:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2645:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2646:     }
 2647:     my $output='';
 2648:     my $response;
 2649:     if ($filelink=~/^https?\:/) {
 2650:        ($output,$response)=&externalssi($filelink);
 2651:     } else {
 2652:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2653:        $filelink .= 'inhibitmenu=yes';
 2654:        ($output,$response)=&ssi($filelink,%form);
 2655:     }
 2656:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2657:     $output=~s/^.*?\<body[^\>]*\>//si;
 2658:     $output=~s/\<\/body\s*\>.*?$//si;
 2659:     if (wantarray) {
 2660:         return ($output, $response);
 2661:     } else {
 2662:         return $output;
 2663:     }
 2664: }
 2665: 
 2666: # --------------------------------------------------------- Server Side Include
 2667: 
 2668: sub absolute_url {
 2669:     my ($host_name) = @_;
 2670:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2671:     if ($host_name eq '') {
 2672: 	$host_name = $ENV{'SERVER_NAME'};
 2673:     }
 2674:     return $protocol.$host_name;
 2675: }
 2676: 
 2677: #
 2678: #   Server side include.
 2679: # Parameters:
 2680: #  fn     Possibly encrypted resource name/id.
 2681: #  form   Hash that describes how the rendering should be done
 2682: #         and other things.
 2683: # Returns:
 2684: #   Scalar context: The content of the response.
 2685: #   Array context:  2 element list of the content and the full response object.
 2686: #     
 2687: sub ssi {
 2688: 
 2689:     my ($fn,%form)=@_;
 2690:     my $ua=new LWP::UserAgent;
 2691:     my $request;
 2692: 
 2693:     $form{'no_update_last_known'}=1;
 2694:     &Apache::lonenc::check_encrypt(\$fn);
 2695:     if (%form) {
 2696:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2697:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2698:     } else {
 2699:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2700:     }
 2701: 
 2702:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2703:     my $response= $ua->request($request);
 2704:     my $content = $response->content;
 2705: 
 2706: 
 2707:     if (wantarray) {
 2708: 	return ($content, $response);
 2709:     } else {
 2710: 	return $content;
 2711:     }
 2712: }
 2713: 
 2714: sub externalssi {
 2715:     my ($url)=@_;
 2716:     my $ua=new LWP::UserAgent;
 2717:     my $request=new HTTP::Request('GET',$url);
 2718:     my $response=$ua->request($request);
 2719:     if (wantarray) {
 2720:         return ($response->content, $response);
 2721:     } else {
 2722:         return $response->content;
 2723:     }
 2724: }
 2725: 
 2726: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2727: 
 2728: sub allowuploaded {
 2729:     my ($srcurl,$url)=@_;
 2730:     $url=&clutter(&declutter($url));
 2731:     my $dir=$url;
 2732:     $dir=~s/\/[^\/]+$//;
 2733:     my %httpref=();
 2734:     my $httpurl=&hreflocation('',$url);
 2735:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2736:     &Apache::lonnet::appenv(\%httpref);
 2737: }
 2738: 
 2739: #
 2740: # Determine if the current user should be able to edit a particular resource,
 2741: # when viewing in course context.
 2742: # (a) When viewing resource used to determine if "Edit" item is included in 
 2743: #     Functions.
 2744: # (b) When displaying folder contents in course editor, used to determine if
 2745: #     "Edit" link will be displayed alongside resource.
 2746: #
 2747: #  input: six args -- filename (decluttered), course number, course domain,
 2748: #                   url, symb (if registered) and group (if this is a group
 2749: #                   item -- e.g., bulletin board, group page etc.).
 2750: #  output: array of five scalars -- 
 2751: #          $cfile -- url for file editing if editable on current server
 2752: #          $home -- homeserver of resource (i.e., for author if published,
 2753: #                                           or course if uploaded.).
 2754: #          $switchserver --  1 if server switch will be needed.
 2755: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2756: #          $forceview -- 1 if icon/link should be to go to view mode
 2757: #
 2758: 
 2759: sub can_edit_resource {
 2760:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2761:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2762: #
 2763: # For aboutme pages user can only edit his/her own.
 2764: #
 2765:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2766:         my ($sdom,$sname) = ($1,$2);
 2767:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2768:             $home = $env{'user.home'};
 2769:             $cfile = $resurl;
 2770:             if ($env{'form.forceedit'}) {
 2771:                 $forceview = 1;
 2772:             } else {
 2773:                 $forceedit = 1;
 2774:             }
 2775:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2776:         } else {
 2777:             return;
 2778:         }
 2779:     }
 2780: 
 2781:     if ($env{'request.course.id'}) {
 2782:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2783:         if ($group ne '') {
 2784: # if this is a group homepage or group bulletin board, check group privs
 2785:             my $allowed = 0;
 2786:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2787:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2788:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2789:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2790:                     $allowed = 1;
 2791:                 }
 2792:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2793:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2794:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2795:                     $allowed = 1;
 2796:                 }
 2797:             }
 2798:             if ($allowed) {
 2799:                 $home=&homeserver($cnum,$cdom);
 2800:                 if ($env{'form.forceedit'}) {
 2801:                     $forceview = 1;
 2802:                 } else {
 2803:                     $forceedit = 1;
 2804:                 }
 2805:                 $cfile = $resurl;
 2806:             } else {
 2807:                 return;
 2808:             }
 2809:         } else {
 2810:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2811:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2812:                     return;
 2813:                 }
 2814:             } elsif (!$crsedit) {
 2815: #
 2816: # No edit allowed where CC has switched to student role.
 2817: #
 2818:                 return;
 2819:             }
 2820:         }
 2821:     }
 2822: 
 2823:     if ($file ne '') {
 2824:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2825:             if (&is_course_upload($file,$cnum,$cdom)) {
 2826:                 $uploaded = 1;
 2827:                 $incourse = 1;
 2828:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2829:                     $cfile = &hreflocation('',$file);
 2830:                     if ($env{'form.forceedit'}) {
 2831:                         $forceview = 1;
 2832:                     } else {
 2833:                         $forceedit = 1;
 2834:                     }
 2835:                 }
 2836:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2837:                 $incourse = 1;
 2838:                 if ($env{'form.forceedit'}) {
 2839:                     $forceview = 1;
 2840:                 } else {
 2841:                     $forceedit = 1;
 2842:                 }
 2843:                 $cfile = $resurl;
 2844:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2845:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2846:                     $incourse = 1;
 2847:                     if ($env{'form.forceedit'}) {
 2848:                         $forceview = 1;
 2849:                     } else {
 2850:                         $forceedit = 1;
 2851:                     }
 2852:                     $cfile = $resurl;
 2853:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2854:                     $incourse = 1;
 2855:                     $cfile = $resurl.'/smpedit';
 2856:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2857:                     $incourse = 1;
 2858:                     if ($env{'form.forceedit'}) {
 2859:                         $forceview = 1;
 2860:                     } else {
 2861:                         $forceedit = 1;
 2862:                     }
 2863:                     $cfile = $resurl;
 2864:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2865:                     $incourse = 1;
 2866:                     if ($env{'form.forceedit'}) {
 2867:                         $forceview = 1;
 2868:                     } else {
 2869:                         $forceedit = 1;
 2870:                     }
 2871:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2872:                 }
 2873:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2874:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2875:                 if (&is_on_map($template)) { 
 2876:                     $incourse = 1;
 2877:                     $forceview = 1;
 2878:                     $cfile = $template;
 2879:                 }
 2880:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2881:                     $incourse = 1;
 2882:                     if ($env{'form.forceedit'}) {
 2883:                         $forceview = 1;
 2884:                     } else {
 2885:                         $forceedit = 1;
 2886:                     }
 2887:                     $cfile = $resurl;
 2888:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2889:                 $incourse = 1;
 2890:                 $forceview = 1;
 2891:                 if ($symb) {
 2892:                     my ($map,$id,$res)=&decode_symb($symb);
 2893:                     $env{'request.symb'} = $symb;
 2894:                     $cfile = &clutter($res);
 2895:                 } else {
 2896:                     $cfile = $env{'form.suppurl'};
 2897:                     $cfile =~ s{^http://}{};
 2898:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2899:                 }
 2900:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2901:                 if ($env{'form.forceedit'}) {
 2902:                     $forceview = 1;
 2903:                 } else {
 2904:                     $forceedit = 1;
 2905:                 }
 2906:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2907:             }
 2908:         }
 2909:         if ($uploaded || $incourse) {
 2910:             $home=&homeserver($cnum,$cdom);
 2911:         } elsif ($file !~ m{/$}) {
 2912:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2913:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2914:             # Check that the user has permission to edit this resource
 2915:             my $setpriv = 1;
 2916:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2917:             if (defined($cfudom)) {
 2918:                 $home=&homeserver($cfuname,$cfudom);
 2919:                 $cfile=$file;
 2920:             }
 2921:         }
 2922:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2923:             (($home ne '') && ($home ne 'no_host'))) {
 2924:             my @ids=&current_machine_ids();
 2925:             unless (grep(/^\Q$home\E$/,@ids)) {
 2926:                 $switchserver=1;
 2927:             }
 2928:         }
 2929:     }
 2930:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2931: }
 2932: 
 2933: sub is_course_upload {
 2934:     my ($file,$cnum,$cdom) = @_;
 2935:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2936:     $uploadpath =~ s{^\/}{};
 2937:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2938:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2939:         return 1;
 2940:     }
 2941:     return;
 2942: }
 2943: 
 2944: sub in_course {
 2945:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2946:     if ($hideprivileged) {
 2947:         my $skipuser;
 2948:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2949:         my @possdoms = ($cdom);  
 2950:         if ($coursehash{'checkforpriv'}) { 
 2951:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2952:         }
 2953:         if (&privileged($uname,$udom,\@possdoms)) {
 2954:             $skipuser = 1;
 2955:             if ($coursehash{'nothideprivileged'}) {
 2956:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2957:                     my $user;
 2958:                     if ($item =~ /:/) {
 2959:                         $user = $item;
 2960:                     } else {
 2961:                         $user = join(':',split(/[\@]/,$item));
 2962:                     }
 2963:                     if ($user eq $uname.':'.$udom) {
 2964:                         undef($skipuser);
 2965:                         last;
 2966:                     }
 2967:                 }
 2968:             }
 2969:             if ($skipuser) {
 2970:                 return 0;
 2971:             }
 2972:         }
 2973:     }
 2974:     $type ||= 'any';
 2975:     if (!defined($cdom) || !defined($cnum)) {
 2976:         my $cid  = $env{'request.course.id'};
 2977:         $cdom = $env{'course.'.$cid.'.domain'};
 2978:         $cnum = $env{'course.'.$cid.'.num'};
 2979:     }
 2980:     my $typesref;
 2981:     if (($type eq 'any') || ($type eq 'all')) {
 2982:         $typesref = ['active','previous','future'];
 2983:     } elsif ($type eq 'previous' || $type eq 'future') {
 2984:         $typesref = [$type];
 2985:     }
 2986:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2987:                               $typesref,undef,[$cdom]);
 2988:     my ($tmp) = keys(%roles);
 2989:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2990:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2991:     if (@course_roles > 0) {
 2992:         return 1;
 2993:     }
 2994:     return 0;
 2995: }
 2996: 
 2997: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2998: # input: action, courseID, current domain, intended
 2999: #        path to file, source of file, instruction to parse file for objects,
 3000: #        ref to hash for embedded objects,
 3001: #        ref to hash for codebase of java objects.
 3002: #        reference to scalar to accommodate mime type determined
 3003: #          from File::MMagic if $parser = parse.
 3004: #
 3005: # output: url to file (if action was uploaddoc), 
 3006: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3007: #
 3008: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3009: # course.
 3010: #
 3011: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3012: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3013: #          course's home server.
 3014: #
 3015: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3016: #          be copied from $source (current location) to 
 3017: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3018: #         and will then be copied to
 3019: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3020: #         course's home server.
 3021: #
 3022: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3023: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3024: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3025: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3026: #         in course's home server.
 3027: #
 3028: 
 3029: sub process_coursefile {
 3030:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3031:         $mimetype)=@_;
 3032:     my $fetchresult;
 3033:     my $home=&homeserver($docuname,$docudom);
 3034:     if ($action eq 'propagate') {
 3035:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3036: 			     $home);
 3037:     } else {
 3038:         my $fpath = '';
 3039:         my $fname = $file;
 3040:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3041:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3042:         my $filepath = &build_filepath($fpath);
 3043:         if ($action eq 'copy') {
 3044:             if ($source eq '') {
 3045:                 $fetchresult = 'no source file';
 3046:                 return $fetchresult;
 3047:             } else {
 3048:                 my $destination = $filepath.'/'.$fname;
 3049:                 rename($source,$destination);
 3050:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3051:                                  $home);
 3052:             }
 3053:         } elsif ($action eq 'uploaddoc') {
 3054:             open(my $fh,'>'.$filepath.'/'.$fname);
 3055:             print $fh $env{'form.'.$source};
 3056:             close($fh);
 3057:             if ($parser eq 'parse') {
 3058:                 my $mm = new File::MMagic;
 3059:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3060:                 if ($type eq 'text/html') {
 3061:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3062:                     unless ($parse_result eq 'ok') {
 3063:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3064:                     }
 3065:                 }
 3066:                 if (ref($mimetype)) {
 3067:                     $$mimetype = $type;
 3068:                 } 
 3069:             }
 3070:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3071:                                  $home);
 3072:             if ($fetchresult eq 'ok') {
 3073:                 return '/uploaded/'.$fpath.'/'.$fname;
 3074:             } else {
 3075:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3076:                         ' to host '.$home.': '.$fetchresult);
 3077:                 return '/adm/notfound.html';
 3078:             }
 3079:         }
 3080:     }
 3081:     unless ( $fetchresult eq 'ok') {
 3082:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3083:              ' to host '.$home.': '.$fetchresult);
 3084:     }
 3085:     return $fetchresult;
 3086: }
 3087: 
 3088: sub build_filepath {
 3089:     my ($fpath) = @_;
 3090:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3091:     unless ($fpath eq '') {
 3092:         my @parts=split('/',$fpath);
 3093:         foreach my $part (@parts) {
 3094:             $filepath.= '/'.$part;
 3095:             if ((-e $filepath)!=1) {
 3096:                 mkdir($filepath,0777);
 3097:             }
 3098:         }
 3099:     }
 3100:     return $filepath;
 3101: }
 3102: 
 3103: sub store_edited_file {
 3104:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3105:     my $file = $primary_url;
 3106:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3107:     my $fpath = '';
 3108:     my $fname = $file;
 3109:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3110:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3111:     my $filepath = &build_filepath($fpath);
 3112:     open(my $fh,'>'.$filepath.'/'.$fname);
 3113:     print $fh $content;
 3114:     close($fh);
 3115:     my $home=&homeserver($docuname,$docudom);
 3116:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3117: 			  $home);
 3118:     if ($$fetchresult eq 'ok') {
 3119:         return '/uploaded/'.$fpath.'/'.$fname;
 3120:     } else {
 3121:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3122: 		 ' to host '.$home.': '.$$fetchresult);
 3123:         return '/adm/notfound.html';
 3124:     }
 3125: }
 3126: 
 3127: sub clean_filename {
 3128:     my ($fname,$args)=@_;
 3129: # Replace Windows backslashes by forward slashes
 3130:     $fname=~s/\\/\//g;
 3131:     if (!$args->{'keep_path'}) {
 3132:         # Get rid of everything but the actual filename
 3133: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3134:     }
 3135: # Replace spaces by underscores
 3136:     $fname=~s/\s+/\_/g;
 3137: # Replace all other weird characters by nothing
 3138:     $fname=~s{[^/\w\.\-]}{}g;
 3139: # Replace all .\d. sequences with _\d. so they no longer look like version
 3140: # numbers
 3141:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3142:     return $fname;
 3143: }
 3144: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3145: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3146: # image with the same aspect ratio as the original, but with dimensions which do 
 3147: # not exceed $resizewidth and $resizeheight.
 3148:  
 3149: sub resizeImage {
 3150:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3151:     my $ima = Image::Magick->new;
 3152:     my $resized;
 3153:     if (-e $img_path) {
 3154:         $ima->Read($img_path);
 3155:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3156:             my $width = $ima->Get('width');
 3157:             my $height = $ima->Get('height');
 3158:             if ($width > $resizewidth) {
 3159: 	        my $factor = $width/$resizewidth;
 3160:                 my $newheight = $height/$factor;
 3161:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3162:                 $resized = 1;
 3163:             }
 3164:         }
 3165:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3166:             my $width = $ima->Get('width');
 3167:             my $height = $ima->Get('height');
 3168:             if ($height > $resizeheight) {
 3169:                 my $factor = $height/$resizeheight;
 3170:                 my $newwidth = $width/$factor;
 3171:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3172:                 $resized = 1;
 3173:             }
 3174:         }
 3175:         if ($resized) {
 3176:             $ima->Write($img_path);
 3177:         }
 3178:     }
 3179:     return;
 3180: }
 3181: 
 3182: # --------------- Take an uploaded file and put it into the userfiles directory
 3183: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3184: #                    the desired filename is in $env{"form.$formname.filename"}
 3185: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3186: #                                    canceloverwrite, or ''. 
 3187: #                   if 'coursedoc': upload to the current course
 3188: #                   if 'existingfile': write file to tmp/overwrites directory 
 3189: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3190: #                   $context is passed as argument to &finishuserfileupload
 3191: #        $subdir - directory in userfile to store the file into
 3192: #        $parser - instruction to parse file for objects ($parser = parse)    
 3193: #        $allfiles - reference to hash for embedded objects
 3194: #        $codebase - reference to hash for codebase of java objects
 3195: #        $desuname - username for permanent storage of uploaded file
 3196: #        $dsetudom - domain for permanaent storage of uploaded file
 3197: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3198: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3199: #        $resizewidth - width (pixels) to which to resize uploaded image
 3200: #        $resizeheight - height (pixels) to which to resize uploaded image
 3201: #        $mimetype - reference to scalar to accommodate mime type determined
 3202: #                    from File::MMagic.
 3203: # 
 3204: # output: url of file in userspace, or error: <message> 
 3205: #             or /adm/notfound.html if failure to upload occurse
 3206: 
 3207: sub userfileupload {
 3208:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3209:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3210:     if (!defined($subdir)) { $subdir='unknown'; }
 3211:     my $fname=$env{'form.'.$formname.'.filename'};
 3212:     $fname=&clean_filename($fname);
 3213:     # See if there is anything left
 3214:     unless ($fname) { return 'error: no uploaded file'; }
 3215:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3216:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3217:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3218:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3219:         my $now = time;
 3220:         my $filepath;
 3221:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3222:              $filepath = 'tmp/helprequests/'.$now;
 3223:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3224:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3225:                          '_'.$env{'user.domain'}.'/pending';
 3226:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3227:             my ($docuname,$docudom);
 3228:             if ($destudom) {
 3229:                 $docudom = $destudom;
 3230:             } else {
 3231:                 $docudom = $env{'user.domain'};
 3232:             }
 3233:             if ($destuname) {
 3234:                 $docuname = $destuname;
 3235:             } else {
 3236:                 $docuname = $env{'user.name'};
 3237:             }
 3238:             if (exists($env{'form.group'})) {
 3239:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3240:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3241:             }
 3242:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3243:             if ($context eq 'canceloverwrite') {
 3244:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3245:                 if (-e  $tempfile) {
 3246:                     my @info = stat($tempfile);
 3247:                     if ($info[9] eq $env{'form.timestamp'}) {
 3248:                         unlink($tempfile);
 3249:                     }
 3250:                 }
 3251:                 return;
 3252:             }
 3253:         }
 3254:         # Create the directory if not present
 3255:         my @parts=split(/\//,$filepath);
 3256:         my $fullpath = $perlvar{'lonDaemons'};
 3257:         for (my $i=0;$i<@parts;$i++) {
 3258:             $fullpath .= '/'.$parts[$i];
 3259:             if ((-e $fullpath)!=1) {
 3260:                 mkdir($fullpath,0777);
 3261:             }
 3262:         }
 3263:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3264:         print $fh $env{'form.'.$formname};
 3265:         close($fh);
 3266:         if ($context eq 'existingfile') {
 3267:             my @info = stat($fullpath.'/'.$fname);
 3268:             return ($fullpath.'/'.$fname,$info[9]);
 3269:         } else {
 3270:             return $fullpath.'/'.$fname;
 3271:         }
 3272:     }
 3273:     if ($subdir eq 'scantron') {
 3274:         $fname = 'scantron_orig_'.$fname;
 3275:     } else {
 3276:         $fname="$subdir/$fname";
 3277:     }
 3278:     if ($context eq 'coursedoc') {
 3279: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3280: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3281:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3282:             return &finishuserfileupload($docuname,$docudom,
 3283: 					 $formname,$fname,$parser,$allfiles,
 3284: 					 $codebase,$thumbwidth,$thumbheight,
 3285:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3286:         } else {
 3287:             if ($env{'form.folder'}) {
 3288:                 $fname=$env{'form.folder'}.'/'.$fname;
 3289:             }
 3290:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3291: 				       $fname,$formname,$parser,
 3292: 				       $allfiles,$codebase,$mimetype);
 3293:         }
 3294:     } elsif (defined($destuname)) {
 3295:         my $docuname=$destuname;
 3296:         my $docudom=$destudom;
 3297: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3298: 				     $parser,$allfiles,$codebase,
 3299:                                      $thumbwidth,$thumbheight,
 3300:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3301:     } else {
 3302:         my $docuname=$env{'user.name'};
 3303:         my $docudom=$env{'user.domain'};
 3304:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3305:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3306:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3307:         }
 3308: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3309: 				     $parser,$allfiles,$codebase,
 3310:                                      $thumbwidth,$thumbheight,
 3311:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3312:     }
 3313: }
 3314: 
 3315: sub finishuserfileupload {
 3316:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3317:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3318:     my $path=$docudom.'/'.$docuname.'/';
 3319:     my $filepath=$perlvar{'lonDocRoot'};
 3320:   
 3321:     my ($fnamepath,$file,$fetchthumb);
 3322:     $file=$fname;
 3323:     if ($fname=~m|/|) {
 3324:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3325: 	$path.=$fnamepath.'/';
 3326:     }
 3327:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3328:     my $count;
 3329:     for ($count=4;$count<=$#parts;$count++) {
 3330:         $filepath.="/$parts[$count]";
 3331:         if ((-e $filepath)!=1) {
 3332: 	    mkdir($filepath,0777);
 3333:         }
 3334:     }
 3335: 
 3336: # Save the file
 3337:     {
 3338: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3339: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3340: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3341: 	    return '/adm/notfound.html';
 3342: 	}
 3343:         if ($context eq 'overwrite') {
 3344:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3345:             my $target = $filepath.'/'.$file;
 3346:             if (-e $source) {
 3347:                 my @info = stat($source);
 3348:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3349:                     unless (&File::Copy::move($source,$target)) {
 3350:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3351:                         return "Moving from $source failed";
 3352:                     }
 3353:                 } else {
 3354:                     return "Temporary file: $source had unexpected date/time for last modification";
 3355:                 }
 3356:             } else {
 3357:                 return "Temporary file: $source missing";
 3358:             }
 3359:         } elsif (!print FH ($env{'form.'.$formname})) {
 3360: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3361: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3362: 	    return '/adm/notfound.html';
 3363: 	}
 3364: 	close(FH);
 3365:         if ($resizewidth && $resizeheight) {
 3366:             my $mm = new File::MMagic;
 3367:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3368:             if ($mime_type =~ m{^image/}) {
 3369: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3370:             }  
 3371: 	}
 3372:     }
 3373:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3374:         if (ref($mimetype)) {
 3375:             if ($$mimetype eq '') {
 3376:                 my $mm = new File::MMagic;
 3377:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3378:                 $$mimetype = $type;
 3379:             }
 3380:         }
 3381:     }
 3382:     if ($parser eq 'parse') {
 3383:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3384:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3385:                                                        $allfiles,$codebase);
 3386:             unless ($parse_result eq 'ok') {
 3387:                 &logthis('Failed to parse '.$filepath.$file.
 3388: 	   	         ' for embedded media: '.$parse_result); 
 3389:             }
 3390:         }
 3391:     }
 3392:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3393:         my $input = $filepath.'/'.$file;
 3394:         my $output = $filepath.'/'.'tn-'.$file;
 3395:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3396:         system("convert -sample $thumbsize $input $output");
 3397:         if (-e $filepath.'/'.'tn-'.$file) {
 3398:             $fetchthumb  = 1; 
 3399:         }
 3400:     }
 3401:  
 3402: # Notify homeserver to grep it
 3403: #
 3404:     my $docuhome=&homeserver($docuname,$docudom);	
 3405:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3406:     if ($fetchresult eq 'ok') {
 3407:         if ($fetchthumb) {
 3408:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3409:             if ($thumbresult ne 'ok') {
 3410:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3411:                          $docuhome.': '.$thumbresult);
 3412:             }
 3413:         }
 3414: #
 3415: # Return the URL to it
 3416:         return '/uploaded/'.$path.$file;
 3417:     } else {
 3418:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3419: 		 ': '.$fetchresult);
 3420:         return '/adm/notfound.html';
 3421:     }
 3422: }
 3423: 
 3424: sub extract_embedded_items {
 3425:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3426:     my @state = ();
 3427:     my (%lastids,%related,%shockwave,%flashvars);
 3428:     my %javafiles = (
 3429:                       codebase => '',
 3430:                       code => '',
 3431:                       archive => ''
 3432:                     );
 3433:     my %mediafiles = (
 3434:                       src => '',
 3435:                       movie => '',
 3436:                      );
 3437:     my $p;
 3438:     if ($content) {
 3439:         $p = HTML::LCParser->new($content);
 3440:     } else {
 3441:         $p = HTML::LCParser->new($fullpath);
 3442:     }
 3443:     while (my $t=$p->get_token()) {
 3444: 	if ($t->[0] eq 'S') {
 3445: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3446: 	    push(@state, $tagname);
 3447:             if (lc($tagname) eq 'allow') {
 3448:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3449:             }
 3450: 	    if (lc($tagname) eq 'img') {
 3451: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3452: 	    }
 3453: 	    if (lc($tagname) eq 'a') {
 3454:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3455:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3456:                 }
 3457: 	    }
 3458:             if (lc($tagname) eq 'script') {
 3459:                 my $src;
 3460:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3461:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3462:                 } else {
 3463:                     if ($attr->{'src'} ne '') {
 3464:                         $src = $attr->{'src'};
 3465:                         &add_filetype($allfiles,$src,'src');
 3466:                     }
 3467:                 }
 3468:                 my $text = $p->get_trimmed_text();
 3469:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3470:                     my @swfargs = split(/,/,$1);
 3471:                     foreach my $item (@swfargs) {
 3472:                         $item =~ s/["']//g;
 3473:                         $item =~ s/^\s+//;
 3474:                         $item =~ s/\s+$//;
 3475:                     }
 3476:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3477:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3478:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3479:                         } else {
 3480:                             $related{$swfargs[0]} = [$swfargs[2]];
 3481:                         }
 3482:                     }
 3483:                 }
 3484:             }
 3485:             if (lc($tagname) eq 'link') {
 3486:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3487:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3488:                 }
 3489:             }
 3490: 	    if (lc($tagname) eq 'object' ||
 3491: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3492: 		foreach my $item (keys(%javafiles)) {
 3493: 		    $javafiles{$item} = '';
 3494: 		}
 3495:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3496:                     $lastids{lc($tagname)} = $attr->{'id'};
 3497:                 }
 3498: 	    }
 3499: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3500: 		my $name = lc($attr->{'name'});
 3501: 		foreach my $item (keys(%javafiles)) {
 3502: 		    if ($name eq $item) {
 3503: 			$javafiles{$item} = $attr->{'value'};
 3504: 			last;
 3505: 		    }
 3506: 		}
 3507:                 my $pathfrom;
 3508: 		foreach my $item (keys(%mediafiles)) {
 3509: 		    if ($name eq $item) {
 3510:                         $pathfrom = $attr->{'value'};
 3511:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3512: 			&add_filetype($allfiles,$pathfrom,$name);
 3513: 			last;
 3514: 		    }
 3515: 		}
 3516:                 if ($name eq 'flashvars') {
 3517:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3518:                 }
 3519:                 if ($pathfrom ne '') {
 3520:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3521:                                          $pathfrom);
 3522:                 }
 3523: 	    }
 3524: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3525: 		foreach my $item (keys(%javafiles)) {
 3526: 		    if ($attr->{$item}) {
 3527: 			$javafiles{$item} = $attr->{$item};
 3528: 			last;
 3529: 		    }
 3530: 		}
 3531: 		foreach my $item (keys(%mediafiles)) {
 3532: 		    if ($attr->{$item}) {
 3533: 			&add_filetype($allfiles,$attr->{$item},$item);
 3534: 			last;
 3535: 		    }
 3536: 		}
 3537:                 if (lc($tagname) eq 'embed') {
 3538:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3539:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3540:                                              $attr->{'src'});
 3541:                     }
 3542:                 }
 3543: 	    }
 3544:             if (lc($tagname) eq 'iframe') {
 3545:                 my $src = $attr->{'src'} ;
 3546:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3547:                     &add_filetype($allfiles,$src,'src');
 3548:                 } elsif ($src =~ m{^/}) {
 3549:                     if ($env{'request.course.id'}) {
 3550:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3551:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3552:                         my $url = &hreflocation('',$fullpath);
 3553:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3554:                             my $relpath = $1;
 3555:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3556:                                 &add_filetype($allfiles,$1,'src');
 3557:                             }
 3558:                         }
 3559:                     }
 3560:                 }
 3561:             }
 3562:             if ($t->[4] =~ m{/>$}) {
 3563:                 pop(@state);
 3564:             }
 3565: 	} elsif ($t->[0] eq 'E') {
 3566: 	    my ($tagname) = ($t->[1]);
 3567: 	    if ($javafiles{'codebase'} ne '') {
 3568: 		$javafiles{'codebase'} .= '/';
 3569: 	    }  
 3570: 	    if (lc($tagname) eq 'applet' ||
 3571: 		lc($tagname) eq 'object' ||
 3572: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3573: 		) {
 3574: 		foreach my $item (keys(%javafiles)) {
 3575: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3576: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3577: 			&add_filetype($allfiles,$file,$item);
 3578: 		    }
 3579: 		}
 3580: 	    } 
 3581: 	    pop @state;
 3582: 	}
 3583:     }
 3584:     foreach my $id (sort(keys(%flashvars))) {
 3585:         if ($shockwave{$id} ne '') {
 3586:             my @pairs = split(/\&/,$flashvars{$id});
 3587:             foreach my $pair (@pairs) {
 3588:                 my ($key,$value) = split(/\=/,$pair);
 3589:                 if ($key eq 'thumb') {
 3590:                     &add_filetype($allfiles,$value,$key);
 3591:                 } elsif ($key eq 'content') {
 3592:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3593:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3594:                     if ($ext ne '') {
 3595:                         &add_filetype($allfiles,$path.$value,$ext);
 3596:                     }
 3597:                 }
 3598:             }
 3599:         }
 3600:     }
 3601:     return 'ok';
 3602: }
 3603: 
 3604: sub add_filetype {
 3605:     my ($allfiles,$file,$type)=@_;
 3606:     if (exists($allfiles->{$file})) {
 3607: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3608: 	    push(@{$allfiles->{$file}}, &escape($type));
 3609: 	}
 3610:     } else {
 3611: 	@{$allfiles->{$file}} = (&escape($type));
 3612:     }
 3613: }
 3614: 
 3615: sub embedded_dependency {
 3616:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3617:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3618:         if (($identifier ne '') &&
 3619:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3620:             ($pathfrom ne '')) {
 3621:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3622:             foreach my $dep (@{$related->{$identifier}}) {
 3623:                 &add_filetype($allfiles,$path.$dep,'object');
 3624:             }
 3625:         }
 3626:     }
 3627:     return;
 3628: }
 3629: 
 3630: sub removeuploadedurl {
 3631:     my ($url)=@_;	
 3632:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3633:     return &removeuserfile($uname,$udom,$fname);
 3634: }
 3635: 
 3636: sub removeuserfile {
 3637:     my ($docuname,$docudom,$fname)=@_;
 3638:     my $home=&homeserver($docuname,$docudom);    
 3639:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3640:     if ($result eq 'ok') {	
 3641:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3642:             my $metafile = $fname.'.meta';
 3643:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3644: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3645:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3646:             my $sqlresult = 
 3647:                 &update_portfolio_table($docuname,$docudom,$file,
 3648:                                         'portfolio_metadata',$group,
 3649:                                         'delete');
 3650:         }
 3651:     }
 3652:     return $result;
 3653: }
 3654: 
 3655: sub mkdiruserfile {
 3656:     my ($docuname,$docudom,$dir)=@_;
 3657:     my $home=&homeserver($docuname,$docudom);
 3658:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3659: }
 3660: 
 3661: sub renameuserfile {
 3662:     my ($docuname,$docudom,$old,$new)=@_;
 3663:     my $home=&homeserver($docuname,$docudom);
 3664:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3665:                         &escape("$old").':'.&escape("$new"),$home);
 3666:     if ($result eq 'ok') {
 3667:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3668:             my $oldmeta = $old.'.meta';
 3669:             my $newmeta = $new.'.meta';
 3670:             my $metaresult = 
 3671:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3672: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3673:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3674:             my $sqlresult = 
 3675:                 &update_portfolio_table($docuname,$docudom,$file,
 3676:                                         'portfolio_metadata',$group,
 3677:                                         'delete');
 3678:         }
 3679:     }
 3680:     return $result;
 3681: }
 3682: 
 3683: # ------------------------------------------------------------------------- Log
 3684: 
 3685: sub log {
 3686:     my ($dom,$nam,$hom,$what)=@_;
 3687:     return critical("log:$dom:$nam:$what",$hom);
 3688: }
 3689: 
 3690: # ------------------------------------------------------------------ Course Log
 3691: #
 3692: # This routine flushes several buffers of non-mission-critical nature
 3693: #
 3694: 
 3695: sub flushcourselogs {
 3696:     &logthis('Flushing log buffers');
 3697: #
 3698: # course logs
 3699: # This is a log of all transactions in a course, which can be used
 3700: # for data mining purposes
 3701: #
 3702: # It also collects the courseid database, which lists last transaction
 3703: # times and course titles for all courseids
 3704: #
 3705:     my %courseidbuffer=();
 3706:     foreach my $crsid (keys(%courselogs)) {
 3707:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3708: 		          &escape($courselogs{$crsid}),
 3709: 		          $coursehombuf{$crsid}) eq 'ok') {
 3710: 	    delete $courselogs{$crsid};
 3711:         } else {
 3712:             &logthis('Failed to flush log buffer for '.$crsid);
 3713:             if (length($courselogs{$crsid})>40000) {
 3714:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3715:                         " exceeded maximum size, deleting.</font>");
 3716:                delete $courselogs{$crsid};
 3717:             }
 3718:         }
 3719:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3720:             'description' => $coursedescrbuf{$crsid},
 3721:             'inst_code'    => $courseinstcodebuf{$crsid},
 3722:             'type'        => $coursetypebuf{$crsid},
 3723:             'owner'       => $courseownerbuf{$crsid},
 3724:         };
 3725:     }
 3726: #
 3727: # Write course id database (reverse lookup) to homeserver of courses 
 3728: # Is used in pickcourse
 3729: #
 3730:     foreach my $crs_home (keys(%courseidbuffer)) {
 3731:         my $response = &courseidput(&host_domain($crs_home),
 3732:                                     $courseidbuffer{$crs_home},
 3733:                                     $crs_home,'timeonly');
 3734:     }
 3735: #
 3736: # File accesses
 3737: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3738: #
 3739:     foreach my $entry (keys(%accesshash)) {
 3740:         if ($entry =~ /___count$/) {
 3741:             my ($dom,$name);
 3742:             ($dom,$name,undef)=
 3743: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3744:             if (! defined($dom) || $dom eq '' || 
 3745:                 ! defined($name) || $name eq '') {
 3746:                 my $cid = $env{'request.course.id'};
 3747:                 $dom  = $env{'request.'.$cid.'.domain'};
 3748:                 $name = $env{'request.'.$cid.'.num'};
 3749:             }
 3750:             my $value = $accesshash{$entry};
 3751:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3752:             my %temphash=($url => $value);
 3753:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3754:             if ($result eq 'ok') {
 3755:                 delete $accesshash{$entry};
 3756:             }
 3757:         } else {
 3758:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3759:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3760:             my %temphash=($entry => $accesshash{$entry});
 3761:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3762:                 delete $accesshash{$entry};
 3763:             }
 3764:         }
 3765:     }
 3766: #
 3767: # Roles
 3768: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3769: #
 3770:     foreach my $entry (keys(%userrolehash)) {
 3771:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3772: 	    split(/\:/,$entry);
 3773:         if (&Apache::lonnet::put('nohist_userroles',
 3774:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3775:                 $rudom,$runame) eq 'ok') {
 3776: 	    delete $userrolehash{$entry};
 3777:         }
 3778:     }
 3779: #
 3780: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3781: #
 3782:     my %domrolebuffer = ();
 3783:     foreach my $entry (keys(%domainrolehash)) {
 3784:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3785:         if ($domrolebuffer{$rudom}) {
 3786:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3787:                       '='.&escape($domainrolehash{$entry});
 3788:         } else {
 3789:             $domrolebuffer{$rudom}.=&escape($entry).
 3790:                       '='.&escape($domainrolehash{$entry});
 3791:         }
 3792:         delete $domainrolehash{$entry};
 3793:     }
 3794:     foreach my $dom (keys(%domrolebuffer)) {
 3795: 	my %servers = &get_servers($dom,'library');
 3796: 	foreach my $tryserver (keys(%servers)) {
 3797: 	    unless (&reply('domroleput:'.$dom.':'.
 3798: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3799: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3800: 	    }
 3801:         }
 3802:     }
 3803:     $dumpcount++;
 3804: }
 3805: 
 3806: sub courselog {
 3807:     my $what=shift;
 3808:     $what=time.':'.$what;
 3809:     unless ($env{'request.course.id'}) { return ''; }
 3810:     $coursedombuf{$env{'request.course.id'}}=
 3811:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3812:     $coursenumbuf{$env{'request.course.id'}}=
 3813:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3814:     $coursehombuf{$env{'request.course.id'}}=
 3815:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3816:     $coursedescrbuf{$env{'request.course.id'}}=
 3817:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3818:     $courseinstcodebuf{$env{'request.course.id'}}=
 3819:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3820:     $courseownerbuf{$env{'request.course.id'}}=
 3821:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3822:     $coursetypebuf{$env{'request.course.id'}}=
 3823:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3824:     if (defined $courselogs{$env{'request.course.id'}}) {
 3825: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3826:     } else {
 3827: 	$courselogs{$env{'request.course.id'}}.=$what;
 3828:     }
 3829:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3830: 	&flushcourselogs();
 3831:     }
 3832: }
 3833: 
 3834: sub courseacclog {
 3835:     my $fnsymb=shift;
 3836:     unless ($env{'request.course.id'}) { return ''; }
 3837:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3838:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3839:         $what.=':POST';
 3840:         # FIXME: Probably ought to escape things....
 3841: 	foreach my $key (keys(%env)) {
 3842:             if ($key=~/^form\.(.*)/) {
 3843:                 my $formitem = $1;
 3844:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3845:                     $what.=':'.$formitem.'='.$env{$key};
 3846:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3847:                     $what.=':'.$formitem.'='.$env{$key};
 3848:                 }
 3849:             }
 3850:         }
 3851:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3852:         # FIXME: We should not be depending on a form parameter that someone
 3853:         # editing lonsearchcat.pm might change in the future.
 3854:         if ($env{'form.phase'} eq 'course_search') {
 3855:             $what.= ':POST';
 3856:             # FIXME: Probably ought to escape things....
 3857:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3858:                                  'crsdiscuss') {
 3859:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3860:             }
 3861:         }
 3862:     }
 3863:     &courselog($what);
 3864: }
 3865: 
 3866: sub countacc {
 3867:     my $url=&declutter(shift);
 3868:     return if (! defined($url) || $url eq '');
 3869:     unless ($env{'request.course.id'}) { return ''; }
 3870: #
 3871: # Mark that this url was used in this course
 3872: #
 3873:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3874: #
 3875: # Increase the access count for this resource in this child process
 3876: #
 3877:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3878:     $accesshash{$key}++;
 3879: }
 3880: 
 3881: sub linklog {
 3882:     my ($from,$to)=@_;
 3883:     $from=&declutter($from);
 3884:     $to=&declutter($to);
 3885:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3886:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3887: }
 3888: 
 3889: sub statslog {
 3890:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3891:     if ($users<2) { return; }
 3892:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3893:             'course'       => $env{'request.course.id'},
 3894:             'sections'     => '"all"',
 3895:             'num_students' => $users,
 3896:             'part'         => $part,
 3897:             'symb'         => $symb,
 3898:             'mean_tries'   => $av_attempts,
 3899:             'deg_of_diff'  => $degdiff});
 3900:     foreach my $key (keys(%dynstore)) {
 3901:         $accesshash{$key}=$dynstore{$key};
 3902:     }
 3903: }
 3904:   
 3905: sub userrolelog {
 3906:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3907:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3908:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3909:        $userrolehash
 3910:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3911:                     =$tend.':'.$tstart;
 3912:     }
 3913:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3914:        $userrolehash
 3915:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3916:                     =$tend.':'.$tstart;
 3917:     }
 3918:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3919:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3920:        $domainrolehash
 3921:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3922:                     = $tend.':'.$tstart;
 3923:     }
 3924: }
 3925: 
 3926: sub courserolelog {
 3927:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3928:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3929:         my $cdom = $1;
 3930:         my $cnum = $2;
 3931:         my $sec = $3;
 3932:         my $namespace = 'rolelog';
 3933:         my %storehash = (
 3934:                            role    => $trole,
 3935:                            start   => $tstart,
 3936:                            end     => $tend,
 3937:                            selfenroll => $selfenroll,
 3938:                            context    => $context,
 3939:                         );
 3940:         if ($trole eq 'gr') {
 3941:             $namespace = 'groupslog';
 3942:             $storehash{'group'} = $sec;
 3943:         } else {
 3944:             $storehash{'section'} = $sec;
 3945:         }
 3946:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3947:                    $domain,$cnum,$cdom);
 3948:         if (($trole ne 'st') || ($sec ne '')) {
 3949:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3950:         }
 3951:     }
 3952:     return;
 3953: }
 3954: 
 3955: sub domainrolelog {
 3956:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3957:     if ($area =~ m{^/($match_domain)/$}) {
 3958:         my $cdom = $1;
 3959:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3960:         my $namespace = 'rolelog';
 3961:         my %storehash = (
 3962:                            role    => $trole,
 3963:                            start   => $tstart,
 3964:                            end     => $tend,
 3965:                            context => $context,
 3966:                         );
 3967:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3968:                    $domain,$domconfiguser,$cdom);
 3969:     }
 3970:     return;
 3971: 
 3972: }
 3973: 
 3974: sub coauthorrolelog {
 3975:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3976:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3977:         my $audom = $1;
 3978:         my $auname = $2;
 3979:         my $namespace = 'rolelog';
 3980:         my %storehash = (
 3981:                            role    => $trole,
 3982:                            start   => $tstart,
 3983:                            end     => $tend,
 3984:                            context => $context,
 3985:                         );
 3986:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3987:                    $domain,$auname,$audom);
 3988:     }
 3989:     return;
 3990: }
 3991: 
 3992: sub get_course_adv_roles {
 3993:     my ($cid,$codes) = @_;
 3994:     $cid=$env{'request.course.id'} unless (defined($cid));
 3995:     my %coursehash=&coursedescription($cid);
 3996:     my $crstype = &Apache::loncommon::course_type($cid);
 3997:     my %nothide=();
 3998:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3999:         if ($user !~ /:/) {
 4000: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4001:         } else {
 4002:             $nothide{$user}=1;
 4003:         }
 4004:     }
 4005:     my @possdoms = ($coursehash{'domain'});
 4006:     if ($coursehash{'checkforpriv'}) {
 4007:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4008:     }
 4009:     my %returnhash=();
 4010:     my %dumphash=
 4011:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4012:     my $now=time;
 4013:     my %privileged;
 4014:     foreach my $entry (keys(%dumphash)) {
 4015: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4016:         if (($tstart) && ($tstart<0)) { next; }
 4017:         if (($tend) && ($tend<$now)) { next; }
 4018:         if (($tstart) && ($now<$tstart)) { next; }
 4019:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4020: 	if ($username eq '' || $domain eq '') { next; }
 4021:         if ((&privileged($username,$domain,\@possdoms)) &&
 4022:             (!$nothide{$username.':'.$domain})) { next; }
 4023: 	if ($role eq 'cr') { next; }
 4024:         if ($codes) {
 4025:             if ($section) { $role .= ':'.$section; }
 4026:             if ($returnhash{$role}) {
 4027:                 $returnhash{$role}.=','.$username.':'.$domain;
 4028:             } else {
 4029:                 $returnhash{$role}=$username.':'.$domain;
 4030:             }
 4031:         } else {
 4032:             my $key=&plaintext($role,$crstype);
 4033:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4034:             if ($returnhash{$key}) {
 4035: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4036:             } else {
 4037:                 $returnhash{$key}=$username.':'.$domain;
 4038:             }
 4039:         }
 4040:     }
 4041:     return %returnhash;
 4042: }
 4043: 
 4044: sub get_my_roles {
 4045:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4046:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4047:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4048:     my (%dumphash,%nothide);
 4049:     if ($context eq 'userroles') {
 4050:         %dumphash = &dump('roles',$udom,$uname);
 4051:     } else {
 4052:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4053:         if ($hidepriv) {
 4054:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4055:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4056:                 if ($user !~ /:/) {
 4057:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4058:                 } else {
 4059:                     $nothide{$user} = 1;
 4060:                 }
 4061:             }
 4062:         }
 4063:     }
 4064:     my %returnhash=();
 4065:     my $now=time;
 4066:     my %privileged;
 4067:     foreach my $entry (keys(%dumphash)) {
 4068:         my ($role,$tend,$tstart);
 4069:         if ($context eq 'userroles') {
 4070:             next if ($entry =~ /^rolesdef/);
 4071: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4072:         } else {
 4073:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4074:         }
 4075:         if (($tstart) && ($tstart<0)) { next; }
 4076:         my $status = 'active';
 4077:         if (($tend) && ($tend<=$now)) {
 4078:             $status = 'previous';
 4079:         } 
 4080:         if (($tstart) && ($now<$tstart)) {
 4081:             $status = 'future';
 4082:         }
 4083:         if (ref($types) eq 'ARRAY') {
 4084:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4085:                 next;
 4086:             } 
 4087:         } else {
 4088:             if ($status ne 'active') {
 4089:                 next;
 4090:             }
 4091:         }
 4092:         my ($rolecode,$username,$domain,$section,$area);
 4093:         if ($context eq 'userroles') {
 4094:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4095:             (undef,$domain,$username,$section) = split(/\//,$area);
 4096:         } else {
 4097:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4098:         }
 4099:         if (ref($roledoms) eq 'ARRAY') {
 4100:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4101:                 next;
 4102:             }
 4103:         }
 4104:         if (ref($roles) eq 'ARRAY') {
 4105:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4106:                 if ($role =~ /^cr\//) {
 4107:                     if (!grep(/^cr$/,@{$roles})) {
 4108:                         next;
 4109:                     }
 4110:                 } elsif ($role =~ /^gr\//) {
 4111:                     if (!grep(/^gr$/,@{$roles})) {
 4112:                         next;
 4113:                     }
 4114:                 } else {
 4115:                     next;
 4116:                 }
 4117:             }
 4118:         }
 4119:         if ($hidepriv) {
 4120:             my @privroles = ('dc','su');
 4121:             if ($context eq 'userroles') {
 4122:                 next if (grep(/^\Q$role\E$/,@privroles));
 4123:             } else {
 4124:                 my $possdoms = [$domain];
 4125:                 if (ref($roledoms) eq 'ARRAY') {
 4126:                    push(@{$possdoms},@{$roledoms}); 
 4127:                 }
 4128:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4129:                     if (!$nothide{$username.':'.$domain}) {
 4130:                         next;
 4131:                     }
 4132:                 }
 4133:             }
 4134:         }
 4135:         if ($withsec) {
 4136:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4137:                 $tstart.':'.$tend;
 4138:         } else {
 4139:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4140:         }
 4141:     }
 4142:     return %returnhash;
 4143: }
 4144: 
 4145: # ----------------------------------------------------- Frontpage Announcements
 4146: #
 4147: #
 4148: 
 4149: sub postannounce {
 4150:     my ($server,$text)=@_;
 4151:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4152:     unless ($text=~/\w/) { $text=''; }
 4153:     return &reply('setannounce:'.&escape($text),$server);
 4154: }
 4155: 
 4156: sub getannounce {
 4157: 
 4158:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4159: 	my $announcement='';
 4160: 	while (my $line = <$fh>) { $announcement .= $line; }
 4161: 	close($fh);
 4162: 	if ($announcement=~/\w/) { 
 4163: 	    return 
 4164:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4165:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4166: 	} else {
 4167: 	    return '';
 4168: 	}
 4169:     } else {
 4170: 	return '';
 4171:     }
 4172: }
 4173: 
 4174: # ---------------------------------------------------------- Course ID routines
 4175: # Deal with domain's nohist_courseid.db files
 4176: #
 4177: 
 4178: sub courseidput {
 4179:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4180:     return unless (ref($storehash) eq 'HASH');
 4181:     my $outcome;
 4182:     if ($caller eq 'timeonly') {
 4183:         my $cids = '';
 4184:         foreach my $item (keys(%$storehash)) {
 4185:             $cids.=&escape($item).'&';
 4186:         }
 4187:         $cids=~s/\&$//;
 4188:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4189:                           $coursehome);       
 4190:     } else {
 4191:         my $items = '';
 4192:         foreach my $item (keys(%$storehash)) {
 4193:             $items.= &escape($item).'='.
 4194:                      &freeze_escape($$storehash{$item}).'&';
 4195:         }
 4196:         $items=~s/\&$//;
 4197:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4198:                           $coursehome);
 4199:     }
 4200:     if ($outcome eq 'unknown_cmd') {
 4201:         my $what;
 4202:         foreach my $cid (keys(%$storehash)) {
 4203:             $what .= &escape($cid).'=';
 4204:             foreach my $item ('description','inst_code','owner','type') {
 4205:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4206:             }
 4207:             $what =~ s/\:$/&/;
 4208:         }
 4209:         $what =~ s/\&$//;  
 4210:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4211:     } else {
 4212:         return $outcome;
 4213:     }
 4214: }
 4215: 
 4216: sub courseiddump {
 4217:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4218:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4219:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4220:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4221:         $hasuniquecode)=@_;
 4222:     my $as_hash = 1;
 4223:     my %returnhash;
 4224:     if (!$domfilter) { $domfilter=''; }
 4225:     my %libserv = &all_library();
 4226:     foreach my $tryserver (keys(%libserv)) {
 4227:         if ( (  $hostidflag == 1 
 4228: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4229: 	     || (!defined($hostidflag)) ) {
 4230: 
 4231: 	    if (($domfilter eq '') ||
 4232: 		(&host_domain($tryserver) eq $domfilter)) {
 4233:                 my $rep;
 4234:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4235:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4236:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4237:                                 &escape($descfilter), &escape($instcodefilter), 
 4238:                                 &escape($ownerfilter), &escape($coursefilter),
 4239:                                 &escape($typefilter), &escape($regexp_ok), 
 4240:                                 $as_hash, &escape($selfenrollonly), 
 4241:                                 &escape($catfilter), $showhidden, $caller, 
 4242:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4243:                                 &escape($createdbefore), &escape($createdafter), 
 4244:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4245:                 } else {
 4246:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4247:                              $sincefilter.':'.&escape($descfilter).':'.
 4248:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4249:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4250:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4251:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4252:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4253:                              &escape($cc_clone).':'.$cloneonly.':'.
 4254:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4255:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4256:                              $tryserver);
 4257:                 }
 4258:                      
 4259:                 my @pairs=split(/\&/,$rep);
 4260:                 foreach my $item (@pairs) {
 4261:                     my ($key,$value)=split(/\=/,$item,2);
 4262:                     $key = &unescape($key);
 4263:                     next if ($key =~ /^error: 2 /);
 4264:                     my $result = &thaw_unescape($value);
 4265:                     if (ref($result) eq 'HASH') {
 4266:                         $returnhash{$key}=$result;
 4267:                     } else {
 4268:                         my @responses = split(/:/,$value);
 4269:                         my @items = ('description','inst_code','owner','type');
 4270:                         for (my $i=0; $i<@responses; $i++) {
 4271:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4272:                         }
 4273:                     }
 4274:                 }
 4275:             }
 4276:         }
 4277:     }
 4278:     return %returnhash;
 4279: }
 4280: 
 4281: sub courselastaccess {
 4282:     my ($cdom,$cnum,$hostidref) = @_;
 4283:     my %returnhash;
 4284:     if ($cdom && $cnum) {
 4285:         my $chome = &homeserver($cnum,$cdom);
 4286:         if ($chome ne 'no_host') {
 4287:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4288:             &extract_lastaccess(\%returnhash,$rep);
 4289:         }
 4290:     } else {
 4291:         if (!$cdom) { $cdom=''; }
 4292:         my %libserv = &all_library();
 4293:         foreach my $tryserver (keys(%libserv)) {
 4294:             if (ref($hostidref) eq 'ARRAY') {
 4295:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4296:             } 
 4297:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4298:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4299:                 &extract_lastaccess(\%returnhash,$rep);
 4300:             }
 4301:         }
 4302:     }
 4303:     return %returnhash;
 4304: }
 4305: 
 4306: sub extract_lastaccess {
 4307:     my ($returnhash,$rep) = @_;
 4308:     if (ref($returnhash) eq 'HASH') {
 4309:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4310:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4311:                  $rep eq '') {
 4312:             my @pairs=split(/\&/,$rep);
 4313:             foreach my $item (@pairs) {
 4314:                 my ($key,$value)=split(/\=/,$item,2);
 4315:                 $key = &unescape($key);
 4316:                 next if ($key =~ /^error: 2 /);
 4317:                 $returnhash->{$key} = &thaw_unescape($value);
 4318:             }
 4319:         }
 4320:     }
 4321:     return;
 4322: }
 4323: 
 4324: # ---------------------------------------------------------- DC e-mail
 4325: 
 4326: sub dcmailput {
 4327:     my ($domain,$msgid,$message,$server)=@_;
 4328:     my $status = &Apache::lonnet::critical(
 4329:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4330:        &escape($message),$server);
 4331:     return $status;
 4332: }
 4333: 
 4334: sub dcmaildump {
 4335:     my ($dom,$startdate,$enddate,$senders) = @_;
 4336:     my %returnhash=();
 4337: 
 4338:     if (defined(&domain($dom,'primary'))) {
 4339:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4340:                                                          &escape($enddate).':';
 4341: 	my @esc_senders=map { &escape($_)} @$senders;
 4342: 	$cmd.=&escape(join('&',@esc_senders));
 4343: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4344:             my ($key,$value) = split(/\=/,$line,2);
 4345:             if (($key) && ($value)) {
 4346:                 $returnhash{&unescape($key)} = &unescape($value);
 4347:             }
 4348:         }
 4349:     }
 4350:     return %returnhash;
 4351: }
 4352: # ---------------------------------------------------------- Domain roles
 4353: 
 4354: sub get_domain_roles {
 4355:     my ($dom,$roles,$startdate,$enddate)=@_;
 4356:     if ((!defined($startdate)) || ($startdate eq '')) {
 4357:         $startdate = '.';
 4358:     }
 4359:     if ((!defined($enddate)) || ($enddate eq '')) {
 4360:         $enddate = '.';
 4361:     }
 4362:     my $rolelist;
 4363:     if (ref($roles) eq 'ARRAY') {
 4364:         $rolelist = join('&',@{$roles});
 4365:     }
 4366:     my %personnel = ();
 4367: 
 4368:     my %servers = &get_servers($dom,'library');
 4369:     foreach my $tryserver (keys(%servers)) {
 4370: 	%{$personnel{$tryserver}}=();
 4371: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4372: 					    &escape($startdate).':'.
 4373: 					    &escape($enddate).':'.
 4374: 					    &escape($rolelist), $tryserver))) {
 4375: 	    my ($key,$value) = split(/\=/,$line,2);
 4376: 	    if (($key) && ($value)) {
 4377: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4378: 	    }
 4379: 	}
 4380:     }
 4381:     return %personnel;
 4382: }
 4383: 
 4384: # ----------------------------------------------------------- Interval timing 
 4385: 
 4386: {
 4387: # Caches needed for speedup of navmaps
 4388: # We don't want to cache this for very long at all (5 seconds at most)
 4389: # 
 4390: # The user for whom we cache
 4391: my $cachedkey='';
 4392: # The cached times for this user
 4393: my %cachedtimes=();
 4394: # When this was last done
 4395: my $cachedtime=();
 4396: 
 4397: sub load_all_first_access {
 4398:     my ($uname,$udom)=@_;
 4399:     if (($cachedkey eq $uname.':'.$udom) &&
 4400:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4401:         return;
 4402:     }
 4403:     $cachedtime=time;
 4404:     $cachedkey=$uname.':'.$udom;
 4405:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4406: }
 4407: 
 4408: sub get_first_access {
 4409:     my ($type,$argsymb,$argmap)=@_;
 4410:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4411:     if ($argsymb) { $symb=$argsymb; }
 4412:     my ($map,$id,$res)=&decode_symb($symb);
 4413:     if ($argmap) { $map = $argmap; }
 4414:     if ($type eq 'course') {
 4415: 	$res='course';
 4416:     } elsif ($type eq 'map') {
 4417: 	$res=&symbread($map);
 4418:     } else {
 4419: 	$res=$symb;
 4420:     }
 4421:     &load_all_first_access($uname,$udom);
 4422:     return $cachedtimes{"$courseid\0$res"};
 4423: }
 4424: 
 4425: sub set_first_access {
 4426:     my ($type,$interval)=@_;
 4427:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4428:     my ($map,$id,$res)=&decode_symb($symb);
 4429:     if ($type eq 'course') {
 4430: 	$res='course';
 4431:     } elsif ($type eq 'map') {
 4432: 	$res=&symbread($map);
 4433:     } else {
 4434: 	$res=$symb;
 4435:     }
 4436:     $cachedkey='';
 4437:     my $firstaccess=&get_first_access($type,$symb,$map);
 4438:     if (!$firstaccess) {
 4439:         my $start = time;
 4440: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4441:                           $udom,$uname);
 4442:         if ($putres eq 'ok') {
 4443:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4444:                  $udom,$uname); 
 4445:             &appenv(
 4446:                      {
 4447:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4448:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4449:                      }
 4450:                   );
 4451:         }
 4452:         return $putres;
 4453:     }
 4454:     return 'already_set';
 4455: }
 4456: }
 4457: # --------------------------------------------- Set Expire Date for Spreadsheet
 4458: 
 4459: sub expirespread {
 4460:     my ($uname,$udom,$stype,$usymb)=@_;
 4461:     my $cid=$env{'request.course.id'}; 
 4462:     if ($cid) {
 4463:        my $now=time;
 4464:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4465:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4466:                             $env{'course.'.$cid.'.num'}.
 4467: 	        	    ':nohist_expirationdates:'.
 4468:                             &escape($key).'='.$now,
 4469:                             $env{'course.'.$cid.'.home'})
 4470:     }
 4471:     return 'ok';
 4472: }
 4473: 
 4474: # ----------------------------------------------------- Devalidate Spreadsheets
 4475: 
 4476: sub devalidate {
 4477:     my ($symb,$uname,$udom)=@_;
 4478:     my $cid=$env{'request.course.id'}; 
 4479:     if ($cid) {
 4480:         # delete the stored spreadsheets for
 4481:         # - the student level sheet of this user in course's homespace
 4482:         # - the assessment level sheet for this resource 
 4483:         #   for this user in user's homespace
 4484: 	# - current conditional state info
 4485: 	my $key=$uname.':'.$udom.':';
 4486:         my $status=
 4487: 	    &del('nohist_calculatedsheets',
 4488: 		 [$key.'studentcalc:'],
 4489: 		 $env{'course.'.$cid.'.domain'},
 4490: 		 $env{'course.'.$cid.'.num'})
 4491: 		.' '.
 4492: 	    &del('nohist_calculatedsheets_'.$cid,
 4493: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4494:         unless ($status eq 'ok ok') {
 4495:            &logthis('Could not devalidate spreadsheet '.
 4496:                     $uname.' at '.$udom.' for '.
 4497: 		    $symb.': '.$status);
 4498:         }
 4499: 	&delenv('user.state.'.$cid);
 4500:     }
 4501: }
 4502: 
 4503: sub get_scalar {
 4504:     my ($string,$end) = @_;
 4505:     my $value;
 4506:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4507: 	$value = $1;
 4508:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4509: 	$value = $1;
 4510:     }
 4511:     return &unescape($value);
 4512: }
 4513: 
 4514: sub array2str {
 4515:   my (@array) = @_;
 4516:   my $result=&arrayref2str(\@array);
 4517:   $result=~s/^__ARRAY_REF__//;
 4518:   $result=~s/__END_ARRAY_REF__$//;
 4519:   return $result;
 4520: }
 4521: 
 4522: sub arrayref2str {
 4523:   my ($arrayref) = @_;
 4524:   my $result='__ARRAY_REF__';
 4525:   foreach my $elem (@$arrayref) {
 4526:     if(ref($elem) eq 'ARRAY') {
 4527:       $result.=&arrayref2str($elem).'&';
 4528:     } elsif(ref($elem) eq 'HASH') {
 4529:       $result.=&hashref2str($elem).'&';
 4530:     } elsif(ref($elem)) {
 4531:       #print("Got a ref of ".(ref($elem))." skipping.");
 4532:     } else {
 4533:       $result.=&escape($elem).'&';
 4534:     }
 4535:   }
 4536:   $result=~s/\&$//;
 4537:   $result .= '__END_ARRAY_REF__';
 4538:   return $result;
 4539: }
 4540: 
 4541: sub hash2str {
 4542:   my (%hash) = @_;
 4543:   my $result=&hashref2str(\%hash);
 4544:   $result=~s/^__HASH_REF__//;
 4545:   $result=~s/__END_HASH_REF__$//;
 4546:   return $result;
 4547: }
 4548: 
 4549: sub hashref2str {
 4550:   my ($hashref)=@_;
 4551:   my $result='__HASH_REF__';
 4552:   foreach my $key (sort(keys(%$hashref))) {
 4553:     if (ref($key) eq 'ARRAY') {
 4554:       $result.=&arrayref2str($key).'=';
 4555:     } elsif (ref($key) eq 'HASH') {
 4556:       $result.=&hashref2str($key).'=';
 4557:     } elsif (ref($key)) {
 4558:       $result.='=';
 4559:       #print("Got a ref of ".(ref($key))." skipping.");
 4560:     } else {
 4561: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4562:     }
 4563: 
 4564:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4565:       $result.=&arrayref2str($hashref->{$key}).'&';
 4566:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4567:       $result.=&hashref2str($hashref->{$key}).'&';
 4568:     } elsif(ref($hashref->{$key})) {
 4569:        $result.='&';
 4570:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4571:     } else {
 4572:       $result.=&escape($hashref->{$key}).'&';
 4573:     }
 4574:   }
 4575:   $result=~s/\&$//;
 4576:   $result .= '__END_HASH_REF__';
 4577:   return $result;
 4578: }
 4579: 
 4580: sub str2hash {
 4581:     my ($string)=@_;
 4582:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4583:     return %$hash;
 4584: }
 4585: 
 4586: sub str2hashref {
 4587:   my ($string) = @_;
 4588: 
 4589:   my %hash;
 4590: 
 4591:   if($string !~ /^__HASH_REF__/) {
 4592:       if (! ($string eq '' || !defined($string))) {
 4593: 	  $hash{'error'}='Not hash reference';
 4594:       }
 4595:       return (\%hash, $string);
 4596:   }
 4597: 
 4598:   $string =~ s/^__HASH_REF__//;
 4599: 
 4600:   while($string !~ /^__END_HASH_REF__/) {
 4601:       #key
 4602:       my $key='';
 4603:       if($string =~ /^__HASH_REF__/) {
 4604:           ($key, $string)=&str2hashref($string);
 4605:           if(defined($key->{'error'})) {
 4606:               $hash{'error'}='Bad data';
 4607:               return (\%hash, $string);
 4608:           }
 4609:       } elsif($string =~ /^__ARRAY_REF__/) {
 4610:           ($key, $string)=&str2arrayref($string);
 4611:           if($key->[0] eq 'Array reference error') {
 4612:               $hash{'error'}='Bad data';
 4613:               return (\%hash, $string);
 4614:           }
 4615:       } else {
 4616:           $string =~ s/^(.*?)=//;
 4617: 	  $key=&unescape($1);
 4618:       }
 4619:       $string =~ s/^=//;
 4620: 
 4621:       #value
 4622:       my $value='';
 4623:       if($string =~ /^__HASH_REF__/) {
 4624:           ($value, $string)=&str2hashref($string);
 4625:           if(defined($value->{'error'})) {
 4626:               $hash{'error'}='Bad data';
 4627:               return (\%hash, $string);
 4628:           }
 4629:       } elsif($string =~ /^__ARRAY_REF__/) {
 4630:           ($value, $string)=&str2arrayref($string);
 4631:           if($value->[0] eq 'Array reference error') {
 4632:               $hash{'error'}='Bad data';
 4633:               return (\%hash, $string);
 4634:           }
 4635:       } else {
 4636: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4637:       }
 4638:       $string =~ s/^&//;
 4639: 
 4640:       $hash{$key}=$value;
 4641:   }
 4642: 
 4643:   $string =~ s/^__END_HASH_REF__//;
 4644: 
 4645:   return (\%hash, $string);
 4646: }
 4647: 
 4648: sub str2array {
 4649:     my ($string)=@_;
 4650:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4651:     return @$array;
 4652: }
 4653: 
 4654: sub str2arrayref {
 4655:   my ($string) = @_;
 4656:   my @array;
 4657: 
 4658:   if($string !~ /^__ARRAY_REF__/) {
 4659:       if (! ($string eq '' || !defined($string))) {
 4660: 	  $array[0]='Array reference error';
 4661:       }
 4662:       return (\@array, $string);
 4663:   }
 4664: 
 4665:   $string =~ s/^__ARRAY_REF__//;
 4666: 
 4667:   while($string !~ /^__END_ARRAY_REF__/) {
 4668:       my $value='';
 4669:       if($string =~ /^__HASH_REF__/) {
 4670:           ($value, $string)=&str2hashref($string);
 4671:           if(defined($value->{'error'})) {
 4672:               $array[0] ='Array reference error';
 4673:               return (\@array, $string);
 4674:           }
 4675:       } elsif($string =~ /^__ARRAY_REF__/) {
 4676:           ($value, $string)=&str2arrayref($string);
 4677:           if($value->[0] eq 'Array reference error') {
 4678:               $array[0] ='Array reference error';
 4679:               return (\@array, $string);
 4680:           }
 4681:       } else {
 4682: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4683:       }
 4684:       $string =~ s/^&//;
 4685: 
 4686:       push(@array, $value);
 4687:   }
 4688: 
 4689:   $string =~ s/^__END_ARRAY_REF__//;
 4690: 
 4691:   return (\@array, $string);
 4692: }
 4693: 
 4694: # -------------------------------------------------------------------Temp Store
 4695: 
 4696: sub tmpreset {
 4697:   my ($symb,$namespace,$domain,$stuname) = @_;
 4698:   if (!$symb) {
 4699:     $symb=&symbread();
 4700:     if (!$symb) { $symb= $env{'request.url'}; }
 4701:   }
 4702:   $symb=escape($symb);
 4703: 
 4704:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4705:   $namespace=~s/\//\_/g;
 4706:   $namespace=~s/\W//g;
 4707: 
 4708:   if (!$domain) { $domain=$env{'user.domain'}; }
 4709:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4710:   if ($domain eq 'public' && $stuname eq 'public') {
 4711:       $stuname=$ENV{'REMOTE_ADDR'};
 4712:   }
 4713:   my $path=LONCAPA::tempdir();
 4714:   my %hash;
 4715:   if (tie(%hash,'GDBM_File',
 4716: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4717: 	  &GDBM_WRCREAT(),0640)) {
 4718:     foreach my $key (keys(%hash)) {
 4719:       if ($key=~ /:$symb/) {
 4720: 	delete($hash{$key});
 4721:       }
 4722:     }
 4723:   }
 4724: }
 4725: 
 4726: sub tmpstore {
 4727:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4728: 
 4729:   if (!$symb) {
 4730:     $symb=&symbread();
 4731:     if (!$symb) { $symb= $env{'request.url'}; }
 4732:   }
 4733:   $symb=escape($symb);
 4734: 
 4735:   if (!$namespace) {
 4736:     # I don't think we would ever want to store this for a course.
 4737:     # it seems this will only be used if we don't have a course.
 4738:     #$namespace=$env{'request.course.id'};
 4739:     #if (!$namespace) {
 4740:       $namespace=$env{'request.state'};
 4741:     #}
 4742:   }
 4743:   $namespace=~s/\//\_/g;
 4744:   $namespace=~s/\W//g;
 4745:   if (!$domain) { $domain=$env{'user.domain'}; }
 4746:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4747:   if ($domain eq 'public' && $stuname eq 'public') {
 4748:       $stuname=$ENV{'REMOTE_ADDR'};
 4749:   }
 4750:   my $now=time;
 4751:   my %hash;
 4752:   my $path=LONCAPA::tempdir();
 4753:   if (tie(%hash,'GDBM_File',
 4754: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4755: 	  &GDBM_WRCREAT(),0640)) {
 4756:     $hash{"version:$symb"}++;
 4757:     my $version=$hash{"version:$symb"};
 4758:     my $allkeys=''; 
 4759:     foreach my $key (keys(%$storehash)) {
 4760:       $allkeys.=$key.':';
 4761:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4762:     }
 4763:     $hash{"$version:$symb:timestamp"}=$now;
 4764:     $allkeys.='timestamp';
 4765:     $hash{"$version:keys:$symb"}=$allkeys;
 4766:     if (untie(%hash)) {
 4767:       return 'ok';
 4768:     } else {
 4769:       return "error:$!";
 4770:     }
 4771:   } else {
 4772:     return "error:$!";
 4773:   }
 4774: }
 4775: 
 4776: # -----------------------------------------------------------------Temp Restore
 4777: 
 4778: sub tmprestore {
 4779:   my ($symb,$namespace,$domain,$stuname) = @_;
 4780: 
 4781:   if (!$symb) {
 4782:     $symb=&symbread();
 4783:     if (!$symb) { $symb= $env{'request.url'}; }
 4784:   }
 4785:   $symb=escape($symb);
 4786: 
 4787:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4788: 
 4789:   if (!$domain) { $domain=$env{'user.domain'}; }
 4790:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4791:   if ($domain eq 'public' && $stuname eq 'public') {
 4792:       $stuname=$ENV{'REMOTE_ADDR'};
 4793:   }
 4794:   my %returnhash;
 4795:   $namespace=~s/\//\_/g;
 4796:   $namespace=~s/\W//g;
 4797:   my %hash;
 4798:   my $path=LONCAPA::tempdir();
 4799:   if (tie(%hash,'GDBM_File',
 4800: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4801: 	  &GDBM_READER(),0640)) {
 4802:     my $version=$hash{"version:$symb"};
 4803:     $returnhash{'version'}=$version;
 4804:     my $scope;
 4805:     for ($scope=1;$scope<=$version;$scope++) {
 4806:       my $vkeys=$hash{"$scope:keys:$symb"};
 4807:       my @keys=split(/:/,$vkeys);
 4808:       my $key;
 4809:       $returnhash{"$scope:keys"}=$vkeys;
 4810:       foreach $key (@keys) {
 4811: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4812: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4813:       }
 4814:     }
 4815:     if (!(untie(%hash))) {
 4816:       return "error:$!";
 4817:     }
 4818:   } else {
 4819:     return "error:$!";
 4820:   }
 4821:   return %returnhash;
 4822: }
 4823: 
 4824: # ----------------------------------------------------------------------- Store
 4825: 
 4826: sub store {
 4827:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4828:     my $home='';
 4829: 
 4830:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4831: 
 4832:     $symb=&symbclean($symb);
 4833:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4834: 
 4835:     if (!$domain) { $domain=$env{'user.domain'}; }
 4836:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4837: 
 4838:     &devalidate($symb,$stuname,$domain);
 4839: 
 4840:     $symb=escape($symb);
 4841:     if (!$namespace) { 
 4842:        unless ($namespace=$env{'request.course.id'}) { 
 4843:           return ''; 
 4844:        } 
 4845:     }
 4846:     if (!$home) { $home=$env{'user.home'}; }
 4847: 
 4848:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4849:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4850: 
 4851:     my $namevalue='';
 4852:     foreach my $key (keys(%$storehash)) {
 4853:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4854:     }
 4855:     $namevalue=~s/\&$//;
 4856:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4857:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4858: }
 4859: 
 4860: # -------------------------------------------------------------- Critical Store
 4861: 
 4862: sub cstore {
 4863:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4864:     my $home='';
 4865: 
 4866:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4867: 
 4868:     $symb=&symbclean($symb);
 4869:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4870: 
 4871:     if (!$domain) { $domain=$env{'user.domain'}; }
 4872:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4873: 
 4874:     &devalidate($symb,$stuname,$domain);
 4875: 
 4876:     $symb=escape($symb);
 4877:     if (!$namespace) { 
 4878:        unless ($namespace=$env{'request.course.id'}) { 
 4879:           return ''; 
 4880:        } 
 4881:     }
 4882:     if (!$home) { $home=$env{'user.home'}; }
 4883: 
 4884:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4885:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4886: 
 4887:     my $namevalue='';
 4888:     foreach my $key (keys(%$storehash)) {
 4889:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4890:     }
 4891:     $namevalue=~s/\&$//;
 4892:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4893:     return critical
 4894:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4895: }
 4896: 
 4897: # --------------------------------------------------------------------- Restore
 4898: 
 4899: sub restore {
 4900:     my ($symb,$namespace,$domain,$stuname) = @_;
 4901:     my $home='';
 4902: 
 4903:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4904: 
 4905:     if (!$symb) {
 4906:         return if ($namespace eq 'courserequests');
 4907:         unless ($symb=escape(&symbread())) { return ''; }
 4908:     } else {
 4909:         unless ($namespace eq 'courserequests') {
 4910:             $symb=&escape(&symbclean($symb));
 4911:         }
 4912:     }
 4913:     if (!$namespace) { 
 4914:        unless ($namespace=$env{'request.course.id'}) { 
 4915:           return ''; 
 4916:        } 
 4917:     }
 4918:     if (!$domain) { $domain=$env{'user.domain'}; }
 4919:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4920:     if (!$home) { $home=$env{'user.home'}; }
 4921:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4922: 
 4923:     my %returnhash=();
 4924:     foreach my $line (split(/\&/,$answer)) {
 4925: 	my ($name,$value)=split(/\=/,$line);
 4926:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4927:     }
 4928:     my $version;
 4929:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4930:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4931:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4932:        }
 4933:     }
 4934:     return %returnhash;
 4935: }
 4936: 
 4937: # ---------------------------------------------------------- Course Description
 4938: #
 4939: #  
 4940: 
 4941: sub coursedescription {
 4942:     my ($courseid,$args)=@_;
 4943:     $courseid=~s/^\///;
 4944:     $courseid=~s/\_/\//g;
 4945:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4946:     my $chome=&homeserver($cnum,$cdomain);
 4947:     my $normalid=$cdomain.'_'.$cnum;
 4948:     # need to always cache even if we get errors otherwise we keep 
 4949:     # trying and trying and trying to get the course description.
 4950:     my %envhash=();
 4951:     my %returnhash=();
 4952:     
 4953:     my $expiretime=600;
 4954:     if ($env{'request.course.id'} eq $normalid) {
 4955: 	$expiretime=120;
 4956:     }
 4957: 
 4958:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4959:     if (!$args->{'freshen_cache'}
 4960: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4961: 	foreach my $key (keys(%env)) {
 4962: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4963: 	    my ($setting) = $1;
 4964: 	    $returnhash{$setting} = $env{$key};
 4965: 	}
 4966: 	return %returnhash;
 4967:     }
 4968: 
 4969:     # get the data again
 4970: 
 4971:     if (!$args->{'one_time'}) {
 4972: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4973:     }
 4974: 
 4975:     if ($chome ne 'no_host') {
 4976:        %returnhash=&dump('environment',$cdomain,$cnum);
 4977:        if (!exists($returnhash{'con_lost'})) {
 4978: 	   my $username = $env{'user.name'}; # Defult username
 4979: 	   if(defined $args->{'user'}) {
 4980: 	       $username = $args->{'user'};
 4981: 	   }
 4982:            $returnhash{'home'}= $chome;
 4983: 	   $returnhash{'domain'} = $cdomain;
 4984: 	   $returnhash{'num'} = $cnum;
 4985:            if (!defined($returnhash{'type'})) {
 4986:                $returnhash{'type'} = 'Course';
 4987:            }
 4988:            while (my ($name,$value) = each %returnhash) {
 4989:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4990:            }
 4991:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4992:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4993: 	       $username.'_'.$cdomain.'_'.$cnum;
 4994:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4995:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4996:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4997:        }
 4998:     }
 4999:     if (!$args->{'one_time'}) {
 5000: 	&appenv(\%envhash);
 5001:     }
 5002:     return %returnhash;
 5003: }
 5004: 
 5005: sub update_released_required {
 5006:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5007:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5008:         $cid = $env{'request.course.id'};
 5009:         $cdom = $env{'course.'.$cid.'.domain'};
 5010:         $cnum = $env{'course.'.$cid.'.num'};
 5011:         $chome = $env{'course.'.$cid.'.home'};
 5012:     }
 5013:     if ($needsrelease) {
 5014:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5015:         my $needsupdate;
 5016:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5017:             $needsupdate = 1;
 5018:         } else {
 5019:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5020:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5021:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5022:                 $needsupdate = 1;
 5023:             }
 5024:         }
 5025:         if ($needsupdate) {
 5026:             my %needshash = (
 5027:                              'internal.releaserequired' => $needsrelease,
 5028:                             );
 5029:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5030:             if ($putresult eq 'ok') {
 5031:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5032:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5033:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5034:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5035:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5036:                 }
 5037:             }
 5038:         }
 5039:     }
 5040:     return;
 5041: }
 5042: 
 5043: # -------------------------------------------------See if a user is privileged
 5044: 
 5045: sub privileged {
 5046:     my ($username,$domain,$possdomains,$possroles)=@_;
 5047:     my $now = time;
 5048:     my $roles;
 5049:     if (ref($possroles) eq 'ARRAY') {
 5050:         $roles = $possroles; 
 5051:     } else {
 5052:         $roles = ['dc','su'];
 5053:     }
 5054:     if (ref($possdomains) eq 'ARRAY') {
 5055:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5056:         foreach my $dom (@{$possdomains}) {
 5057:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5058:                 (ref($privileged{$dom}) eq 'HASH')) {
 5059:                 foreach my $role (@{$roles}) {
 5060:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5061:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5062:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5063:                             return 1 unless (($end && $end < $now) ||
 5064:                                              ($start && $start > $now));
 5065:                         }
 5066:                     }
 5067:                 }
 5068:             }
 5069:         }
 5070:     } else {
 5071:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5072:         my $now = time;
 5073: 
 5074:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5075:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5076:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5077:                 return 1 unless ($tend && $tend < $now) 
 5078:                         or ($tstart && $tstart > $now);
 5079:             }
 5080:         }
 5081:     }
 5082:     return 0;
 5083: }
 5084: 
 5085: sub privileged_by_domain {
 5086:     my ($domains,$roles) = @_;
 5087:     my %privileged = ();
 5088:     my $cachetime = 60*60*24;
 5089:     my $now = time;
 5090:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5091:         return %privileged;
 5092:     }
 5093:     foreach my $dom (@{$domains}) {
 5094:         next if (ref($privileged{$dom}) eq 'HASH');
 5095:         my $needroles;
 5096:         foreach my $role (@{$roles}) {
 5097:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5098:             if (defined($cached)) {
 5099:                 if (ref($result) eq 'HASH') {
 5100:                     $privileged{$dom}{$role} = $result;
 5101:                 }
 5102:             } else {
 5103:                 $needroles = 1;
 5104:             }
 5105:         }
 5106:         if ($needroles) {
 5107:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5108:             $privileged{$dom} = {};
 5109:             foreach my $server (keys(%dompersonnel)) {
 5110:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5111:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5112:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5113:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5114:                         next if ($end && $end < $now);
 5115:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5116:                             $dompersonnel{$server}{$item};
 5117:                     }
 5118:                 }
 5119:             }
 5120:             if (ref($privileged{$dom}) eq 'HASH') {
 5121:                 foreach my $role (@{$roles}) {
 5122:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5123:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5124:                     } else {
 5125:                         my %hash = ();
 5126:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5127:                     }
 5128:                 }
 5129:             }
 5130:         }
 5131:     }
 5132:     return %privileged;
 5133: }
 5134: 
 5135: # -------------------------------------------------------- Get user privileges
 5136: 
 5137: sub rolesinit {
 5138:     my ($domain, $username) = @_;
 5139:     my %userroles = ('user.login.time' => time);
 5140:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5141: 
 5142:     # firstaccess and timerinterval are related to timed maps/resources. 
 5143:     # also, blocking can be triggered by an activating timer
 5144:     # it's saved in the user's %env.
 5145:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5146:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5147:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5148:         %timerintchk, %timerintenv);
 5149: 
 5150:     foreach my $key (keys(%firstaccess)) {
 5151:         my ($cid, $rest) = split(/\0/, $key);
 5152:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5153:     }
 5154: 
 5155:     foreach my $key (keys(%timerinterval)) {
 5156:         my ($cid,$rest) = split(/\0/,$key);
 5157:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5158:     }
 5159: 
 5160:     my %allroles=();
 5161:     my %allgroups=();
 5162: 
 5163:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5164:         my $role = $rolesdump{$area};
 5165:         $area =~ s/\_\w\w$//;
 5166: 
 5167:         my ($trole, $tend, $tstart, $group_privs);
 5168: 
 5169:         if ($role =~ /^cr/) {
 5170:         # Custom role, defined by a user 
 5171:         # e.g., user.role.cr/msu/smith/mynewrole
 5172:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5173:                 $trole = $1;
 5174:                 ($tend, $tstart) = split('_', $2);
 5175:             } else {
 5176:                 $trole = $role;
 5177:             }
 5178:         } elsif ($role =~ m|^gr/|) {
 5179:         # Role of member in a group, defined within a course/community
 5180:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5181:             ($trole, $tend, $tstart) = split(/_/, $role);
 5182:             next if $tstart eq '-1';
 5183:             ($trole, $group_privs) = split(/\//, $trole);
 5184:             $group_privs = &unescape($group_privs);
 5185:         } else {
 5186:         # Just a normal role, defined in roles.tab
 5187:             ($trole, $tend, $tstart) = split(/_/,$role);
 5188:         }
 5189: 
 5190:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5191:                  $username);
 5192:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5193: 
 5194:         # role expired or not available yet?
 5195:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5196:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5197: 
 5198:         next if $area eq '' or $trole eq '';
 5199: 
 5200:         my $spec = "$trole.$area";
 5201:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5202: 
 5203:         if ($trole =~ /^cr\//) {
 5204:         # Custom role, defined by a user
 5205:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5206:         } elsif ($trole eq 'gr') {
 5207:         # Role of a member in a group, defined within a course/community
 5208:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5209:             next;
 5210:         } else {
 5211:         # Normal role, defined in roles.tab
 5212:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5213:         }
 5214: 
 5215:         my $cid = $tdomain.'_'.$trest;
 5216:         unless ($firstaccchk{$cid}) {
 5217:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5218:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5219:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5220:                         $coursetimerstarts{$cid}{$item}; 
 5221:                 }
 5222:             }
 5223:             $firstaccchk{$cid} = 1;
 5224:         }
 5225:         unless ($timerintchk{$cid}) {
 5226:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5227:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5228:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5229:                        $coursetimerintervals{$cid}{$item};
 5230:                 }
 5231:             }
 5232:             $timerintchk{$cid} = 1;
 5233:         }
 5234:     }
 5235: 
 5236:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5237:         \%allroles, \%allgroups);
 5238:     $env{'user.adv'} = $userroles{'user.adv'};
 5239: 
 5240:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5241: }
 5242: 
 5243: sub set_arearole {
 5244:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5245:     unless ($nolog) {
 5246: # log the associated role with the area
 5247:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5248:     }
 5249:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5250: }
 5251: 
 5252: sub custom_roleprivs {
 5253:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5254:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5255:     my $homsvr = &homeserver($rauthor,$rdomain);
 5256:     if (&hostname($homsvr) ne '') {
 5257:         my ($rdummy,$roledef)=
 5258:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5259:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5260:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5261:             if (defined($syspriv)) {
 5262:                 if ($trest =~ /^$match_community$/) {
 5263:                     $syspriv =~ s/bre\&S//; 
 5264:                 }
 5265:                 $$allroles{'cm./'}.=':'.$syspriv;
 5266:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5267:             }
 5268:             if ($tdomain ne '') {
 5269:                 if (defined($dompriv)) {
 5270:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5271:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5272:                 }
 5273:                 if (($trest ne '') && (defined($coursepriv))) {
 5274:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5275:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5276:                 }
 5277:             }
 5278:         }
 5279:     }
 5280: }
 5281: 
 5282: sub group_roleprivs {
 5283:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5284:     my $access = 1;
 5285:     my $now = time;
 5286:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5287:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5288:     if ($access) {
 5289:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5290:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5291:     }
 5292: }
 5293: 
 5294: sub standard_roleprivs {
 5295:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5296:     if (defined($pr{$trole.':s'})) {
 5297:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5298:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5299:     }
 5300:     if ($tdomain ne '') {
 5301:         if (defined($pr{$trole.':d'})) {
 5302:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5303:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5304:         }
 5305:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5306:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5307:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5308:         }
 5309:     }
 5310: }
 5311: 
 5312: sub set_userprivs {
 5313:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5314:     my $author=0;
 5315:     my $adv=0;
 5316:     my %grouproles = ();
 5317:     if (keys(%{$allgroups}) > 0) {
 5318:         my @groupkeys; 
 5319:         foreach my $role (keys(%{$allroles})) {
 5320:             push(@groupkeys,$role);
 5321:         }
 5322:         if (ref($groups_roles) eq 'HASH') {
 5323:             foreach my $key (keys(%{$groups_roles})) {
 5324:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5325:                     push(@groupkeys,$key);
 5326:                 }
 5327:             }
 5328:         }
 5329:         if (@groupkeys > 0) {
 5330:             foreach my $role (@groupkeys) {
 5331:                 my ($trole,$area,$sec,$extendedarea);
 5332:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5333:                     $trole = $1;
 5334:                     $area = $2;
 5335:                     $sec = $3;
 5336:                     $extendedarea = $area.$sec;
 5337:                     if (exists($$allgroups{$area})) {
 5338:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5339:                             my $spec = $trole.'.'.$extendedarea;
 5340:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5341:                                                 $$allgroups{$area}{$group};
 5342:                         }
 5343:                     }
 5344:                 }
 5345:             }
 5346:         }
 5347:     }
 5348:     foreach my $group (keys(%grouproles)) {
 5349:         $$allroles{$group} = $grouproles{$group};
 5350:     }
 5351:     foreach my $role (keys(%{$allroles})) {
 5352:         my %thesepriv;
 5353:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5354:         foreach my $item (split(/:/,$$allroles{$role})) {
 5355:             if ($item ne '') {
 5356:                 my ($privilege,$restrictions)=split(/&/,$item);
 5357:                 if ($restrictions eq '') {
 5358:                     $thesepriv{$privilege}='F';
 5359:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5360:                     $thesepriv{$privilege}.=$restrictions;
 5361:                 }
 5362:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5363:             }
 5364:         }
 5365:         my $thesestr='';
 5366:         foreach my $priv (sort(keys(%thesepriv))) {
 5367: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5368: 	}
 5369:         $userroles->{'user.priv.'.$role} = $thesestr;
 5370:     }
 5371:     return ($author,$adv);
 5372: }
 5373: 
 5374: sub role_status {
 5375:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5376:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5377:         my ($one,$two) = split(m{\./},$rolekey,2);
 5378:         (undef,undef,$$role) = split(/\./,$one,3);
 5379:         unless (!defined($$role) || $$role eq '') {
 5380:             $$where = '/'.$two;
 5381:             $$trolecode=$$role.'.'.$$where;
 5382:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5383:             $$tstatus='is';
 5384:             if ($$tstart && $$tstart>$update) {
 5385:                 $$tstatus='future';
 5386:                 if ($$tstart<$now) {
 5387:                     if ($$tstart && $$tstart>$refresh) {
 5388:                         if (($$where ne '') && ($$role ne '')) {
 5389:                             my (%allroles,%allgroups,$group_privs,
 5390:                                 %groups_roles,@rolecodes);
 5391:                             my %userroles = (
 5392:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5393:                             );
 5394:                             @rolecodes = ('cm'); 
 5395:                             my $spec=$$role.'.'.$$where;
 5396:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5397:                             if ($$role =~ /^cr\//) {
 5398:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5399:                                 push(@rolecodes,'cr');
 5400:                             } elsif ($$role eq 'gr') {
 5401:                                 push(@rolecodes,$$role);
 5402:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5403:                                                     $env{'user.name'});
 5404:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5405:                                 (undef,my $group_privs) = split(/\//,$trole);
 5406:                                 $group_privs = &unescape($group_privs);
 5407:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5408:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5409:                                 &get_groups_roles($tdomain,$trest,
 5410:                                                   \%course_roles,\@rolecodes,
 5411:                                                   \%groups_roles);
 5412:                             } else {
 5413:                                 push(@rolecodes,$$role);
 5414:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5415:                             }
 5416:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5417:                             &appenv(\%userroles,\@rolecodes);
 5418:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5419:                         }
 5420:                     }
 5421:                     $$tstatus = 'is';
 5422:                 }
 5423:             }
 5424:             if ($$tend) {
 5425:                 if ($$tend<$update) {
 5426:                     $$tstatus='expired';
 5427:                 } elsif ($$tend<$now) {
 5428:                     $$tstatus='will_not';
 5429:                 }
 5430:             }
 5431:         }
 5432:     }
 5433: }
 5434: 
 5435: sub get_groups_roles {
 5436:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5437:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5438:                   (ref($rolecodes) eq 'ARRAY') && 
 5439:                   (ref($groups_roles) eq 'HASH')); 
 5440:     if (keys(%{$cdom_courseroles}) > 0) {
 5441:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5442:         if ($cdom ne '' && $cnum ne '') {
 5443:             foreach my $key (keys(%{$cdom_courseroles})) {
 5444:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5445:                     my $crsrole = $1;
 5446:                     my $crssec = $2;
 5447:                     if ($crsrole =~ /^cr/) {
 5448:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5449:                             push(@{$rolecodes},'cr');
 5450:                         }
 5451:                     } else {
 5452:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5453:                             push(@{$rolecodes},$crsrole);
 5454:                         }
 5455:                     }
 5456:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5457:                     if ($crssec ne '') {
 5458:                         $rolekey .= "/$crssec";
 5459:                     }
 5460:                     $rolekey .= './';
 5461:                     $groups_roles->{$rolekey} = $rolecodes;
 5462:                 }
 5463:             }
 5464:         }
 5465:     }
 5466:     return;
 5467: }
 5468: 
 5469: sub delete_env_groupprivs {
 5470:     my ($where,$courseroles,$possroles) = @_;
 5471:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5472:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5473:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5474:         %{$courseroles->{$udom}} =
 5475:             &get_my_roles('','','userroles',['active'],
 5476:                           $possroles,[$udom],1);
 5477:     }
 5478:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5479:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5480:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5481:             my $area = '/'.$cdom.'/'.$cnum;
 5482:             my $privkey = "user.priv.$crsrole.$area";
 5483:             if ($crssec ne '') {
 5484:                 $privkey .= '/'.$crssec;
 5485:             }
 5486:             $privkey .= ".$area/$group";
 5487:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5488:         }
 5489:     }
 5490:     return;
 5491: }
 5492: 
 5493: sub check_adhoc_privs {
 5494:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5495:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5496:     my $setprivs;
 5497:     if ($env{$cckey}) {
 5498:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5499:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5500:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5501:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5502:             $setprivs = 1;
 5503:         }
 5504:     } else {
 5505:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5506:         $setprivs = 1;
 5507:     }
 5508:     return $setprivs;
 5509: }
 5510: 
 5511: sub set_adhoc_privileges {
 5512: # role can be cc or ca
 5513:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5514:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5515:     my $spec = $role.'.'.$area;
 5516:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5517:                                   $env{'user.name'},1);
 5518:     my %ccrole = ();
 5519:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5520:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5521:     &appenv(\%userroles,[$role,'cm']);
 5522:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5523:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5524:         &appenv( {'request.role'        => $spec,
 5525:                   'request.role.domain' => $dcdom,
 5526:                   'request.course.sec'  => ''
 5527:                  }
 5528:                );
 5529:         my $tadv=0;
 5530:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5531:         &appenv({'request.role.adv'    => $tadv});
 5532:     }
 5533: }
 5534: 
 5535: # --------------------------------------------------------------- get interface
 5536: 
 5537: sub get {
 5538:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5539:    my $items='';
 5540:    foreach my $item (@$storearr) {
 5541:        $items.=&escape($item).'&';
 5542:    }
 5543:    $items=~s/\&$//;
 5544:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5545:    if (!$uname) { $uname=$env{'user.name'}; }
 5546:    my $uhome=&homeserver($uname,$udomain);
 5547: 
 5548:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5549:    my @pairs=split(/\&/,$rep);
 5550:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5551:      return @pairs;
 5552:    }
 5553:    my %returnhash=();
 5554:    my $i=0;
 5555:    foreach my $item (@$storearr) {
 5556:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5557:       $i++;
 5558:    }
 5559:    return %returnhash;
 5560: }
 5561: 
 5562: # --------------------------------------------------------------- del interface
 5563: 
 5564: sub del {
 5565:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5566:    my $items='';
 5567:    foreach my $item (@$storearr) {
 5568:        $items.=&escape($item).'&';
 5569:    }
 5570: 
 5571:    $items=~s/\&$//;
 5572:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5573:    if (!$uname) { $uname=$env{'user.name'}; }
 5574:    my $uhome=&homeserver($uname,$udomain);
 5575:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5576: }
 5577: 
 5578: # -------------------------------------------------------------- dump interface
 5579: 
 5580: sub unserialize {
 5581:     my ($rep, $escapedkeys) = @_;
 5582: 
 5583:     return {} if $rep =~ /^error/;
 5584: 
 5585:     my %returnhash=();
 5586: 	foreach my $item (split(/\&/,$rep)) {
 5587: 	    my ($key, $value) = split(/=/, $item, 2);
 5588: 	    $key = unescape($key) unless $escapedkeys;
 5589: 	    next if $key =~ /^error: 2 /;
 5590: 	    $returnhash{$key} = &thaw_unescape($value);
 5591: 	}
 5592:     #return %returnhash;
 5593:     return \%returnhash;
 5594: }        
 5595: 
 5596: # see Lond::dump_with_regexp
 5597: # if $escapedkeys hash keys won't get unescaped.
 5598: sub dump {
 5599:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5600:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5601:     if (!$uname) { $uname=$env{'user.name'}; }
 5602:     my $uhome=&homeserver($uname,$udomain);
 5603: 
 5604:     my $reply;
 5605:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5606:         # user is hosted on this machine
 5607:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5608:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5609:         return %{unserialize($reply, $escapedkeys)};
 5610:     }
 5611:     if ($regexp) {
 5612: 	$regexp=&escape($regexp);
 5613:     } else {
 5614: 	$regexp='.';
 5615:     }
 5616:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5617:     my @pairs=split(/\&/,$rep);
 5618:     my %returnhash=();
 5619:     if (!($rep =~ /^error/ )) {
 5620: 	foreach my $item (@pairs) {
 5621: 	    my ($key,$value)=split(/=/,$item,2);
 5622:         $key = unescape($key) unless $escapedkeys;
 5623:         #$key = &unescape($key);
 5624: 	    next if ($key =~ /^error: 2 /);
 5625: 	    $returnhash{$key}=&thaw_unescape($value);
 5626: 	}
 5627:     }
 5628:     return %returnhash;
 5629: }
 5630: 
 5631: 
 5632: # --------------------------------------------------------- dumpstore interface
 5633: 
 5634: sub dumpstore {
 5635:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5636:    # same as dump but keys must be escaped. They may contain colon separated
 5637:    # lists of values that may themself contain colons (e.g. symbs).
 5638:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5639: }
 5640: 
 5641: # -------------------------------------------------------------- keys interface
 5642: 
 5643: sub getkeys {
 5644:    my ($namespace,$udomain,$uname)=@_;
 5645:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5646:    if (!$uname) { $uname=$env{'user.name'}; }
 5647:    my $uhome=&homeserver($uname,$udomain);
 5648:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5649:    my @keyarray=();
 5650:    foreach my $key (split(/\&/,$rep)) {
 5651:       next if ($key =~ /^error: 2 /);
 5652:       push(@keyarray,&unescape($key));
 5653:    }
 5654:    return @keyarray;
 5655: }
 5656: 
 5657: # --------------------------------------------------------------- currentdump
 5658: sub currentdump {
 5659:    my ($courseid,$sdom,$sname)=@_;
 5660:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5661:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5662:    $sname    = $env{'user.name'}         if (! defined($sname));
 5663:    my $uhome = &homeserver($sname,$sdom);
 5664:    my $rep;
 5665: 
 5666:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5667:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5668:                    $courseid)));
 5669:    } else {
 5670:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5671:    }
 5672: 
 5673:    return if ($rep =~ /^(error:|no_such_host)/);
 5674:    #
 5675:    my %returnhash=();
 5676:    #
 5677:    if ($rep eq "unknown_cmd") { 
 5678:        # an old lond will not know currentdump
 5679:        # Do a dump and make it look like a currentdump
 5680:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5681:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5682:        my %hash = @tmp;
 5683:        @tmp=();
 5684:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5685:    } else {
 5686:        my @pairs=split(/\&/,$rep);
 5687:        foreach my $pair (@pairs) {
 5688:            my ($key,$value)=split(/=/,$pair,2);
 5689:            my ($symb,$param) = split(/:/,$key);
 5690:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5691:                                                         &thaw_unescape($value);
 5692:        }
 5693:    }
 5694:    return %returnhash;
 5695: }
 5696: 
 5697: sub convert_dump_to_currentdump{
 5698:     my %hash = %{shift()};
 5699:     my %returnhash;
 5700:     # Code ripped from lond, essentially.  The only difference
 5701:     # here is the unescaping done by lonnet::dump().  Conceivably
 5702:     # we might run in to problems with parameter names =~ /^v\./
 5703:     while (my ($key,$value) = each(%hash)) {
 5704:         my ($v,$symb,$param) = split(/:/,$key);
 5705: 	$symb  = &unescape($symb);
 5706: 	$param = &unescape($param);
 5707:         next if ($v eq 'version' || $symb eq 'keys');
 5708:         next if (exists($returnhash{$symb}) &&
 5709:                  exists($returnhash{$symb}->{$param}) &&
 5710:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5711:         $returnhash{$symb}->{$param}=$value;
 5712:         $returnhash{$symb}->{'v.'.$param}=$v;
 5713:     }
 5714:     #
 5715:     # Remove all of the keys in the hashes which keep track of
 5716:     # the version of the parameter.
 5717:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5718:         # use a foreach because we are going to delete from the hash.
 5719:         foreach my $key (keys(%$param_hash)) {
 5720:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5721:         }
 5722:     }
 5723:     return \%returnhash;
 5724: }
 5725: 
 5726: # ------------------------------------------------------ critical inc interface
 5727: 
 5728: sub cinc {
 5729:     return &inc(@_,'critical');
 5730: }
 5731: 
 5732: # --------------------------------------------------------------- inc interface
 5733: 
 5734: sub inc {
 5735:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5736:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5737:     if (!$uname) { $uname=$env{'user.name'}; }
 5738:     my $uhome=&homeserver($uname,$udomain);
 5739:     my $items='';
 5740:     if (! ref($store)) {
 5741:         # got a single value, so use that instead
 5742:         $items = &escape($store).'=&';
 5743:     } elsif (ref($store) eq 'SCALAR') {
 5744:         $items = &escape($$store).'=&';        
 5745:     } elsif (ref($store) eq 'ARRAY') {
 5746:         $items = join('=&',map {&escape($_);} @{$store});
 5747:     } elsif (ref($store) eq 'HASH') {
 5748:         while (my($key,$value) = each(%{$store})) {
 5749:             $items.= &escape($key).'='.&escape($value).'&';
 5750:         }
 5751:     }
 5752:     $items=~s/\&$//;
 5753:     if ($critical) {
 5754: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5755:     } else {
 5756: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5757:     }
 5758: }
 5759: 
 5760: # --------------------------------------------------------------- put interface
 5761: 
 5762: sub put {
 5763:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5764:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5765:    if (!$uname) { $uname=$env{'user.name'}; }
 5766:    my $uhome=&homeserver($uname,$udomain);
 5767:    my $items='';
 5768:    foreach my $item (keys(%$storehash)) {
 5769:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5770:    }
 5771:    $items=~s/\&$//;
 5772:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5773: }
 5774: 
 5775: # ------------------------------------------------------------ newput interface
 5776: 
 5777: sub newput {
 5778:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5779:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5780:    if (!$uname) { $uname=$env{'user.name'}; }
 5781:    my $uhome=&homeserver($uname,$udomain);
 5782:    my $items='';
 5783:    foreach my $key (keys(%$storehash)) {
 5784:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5785:    }
 5786:    $items=~s/\&$//;
 5787:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5788: }
 5789: 
 5790: # ---------------------------------------------------------  putstore interface
 5791: 
 5792: sub putstore {
 5793:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5794:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5795:    if (!$uname) { $uname=$env{'user.name'}; }
 5796:    my $uhome=&homeserver($uname,$udomain);
 5797:    my $items='';
 5798:    foreach my $key (keys(%$storehash)) {
 5799:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5800:    }
 5801:    $items=~s/\&$//;
 5802:    my $esc_symb=&escape($symb);
 5803:    my $esc_v=&escape($version);
 5804:    my $reply =
 5805:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5806: 	      $uhome);
 5807:    if ($reply eq 'unknown_cmd') {
 5808:        # gfall back to way things use to be done
 5809:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5810: 			    $uname);
 5811:    }
 5812:    return $reply;
 5813: }
 5814: 
 5815: sub old_putstore {
 5816:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5817:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5818:     if (!$uname) { $uname=$env{'user.name'}; }
 5819:     my $uhome=&homeserver($uname,$udomain);
 5820:     my %newstorehash;
 5821:     foreach my $item (keys(%$storehash)) {
 5822: 	my $key = $version.':'.&escape($symb).':'.$item;
 5823: 	$newstorehash{$key} = $storehash->{$item};
 5824:     }
 5825:     my $items='';
 5826:     my %allitems = ();
 5827:     foreach my $item (keys(%newstorehash)) {
 5828: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5829: 	    my $key = $1.':keys:'.$2;
 5830: 	    $allitems{$key} .= $3.':';
 5831: 	}
 5832: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5833:     }
 5834:     foreach my $item (keys(%allitems)) {
 5835: 	$allitems{$item} =~ s/\:$//;
 5836: 	$items.= $item.'='.$allitems{$item}.'&';
 5837:     }
 5838:     $items=~s/\&$//;
 5839:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5840: }
 5841: 
 5842: # ------------------------------------------------------ critical put interface
 5843: 
 5844: sub cput {
 5845:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5846:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5847:    if (!$uname) { $uname=$env{'user.name'}; }
 5848:    my $uhome=&homeserver($uname,$udomain);
 5849:    my $items='';
 5850:    foreach my $item (keys(%$storehash)) {
 5851:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5852:    }
 5853:    $items=~s/\&$//;
 5854:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5855: }
 5856: 
 5857: # -------------------------------------------------------------- eget interface
 5858: 
 5859: sub eget {
 5860:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5861:    my $items='';
 5862:    foreach my $item (@$storearr) {
 5863:        $items.=&escape($item).'&';
 5864:    }
 5865:    $items=~s/\&$//;
 5866:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5867:    if (!$uname) { $uname=$env{'user.name'}; }
 5868:    my $uhome=&homeserver($uname,$udomain);
 5869:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5870:    my @pairs=split(/\&/,$rep);
 5871:    my %returnhash=();
 5872:    my $i=0;
 5873:    foreach my $item (@$storearr) {
 5874:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5875:       $i++;
 5876:    }
 5877:    return %returnhash;
 5878: }
 5879: 
 5880: # ------------------------------------------------------------ tmpput interface
 5881: sub tmpput {
 5882:     my ($storehash,$server,$context)=@_;
 5883:     my $items='';
 5884:     foreach my $item (keys(%$storehash)) {
 5885: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5886:     }
 5887:     $items=~s/\&$//;
 5888:     if (defined($context)) {
 5889:         $items .= ':'.&escape($context);
 5890:     }
 5891:     return &reply("tmpput:$items",$server);
 5892: }
 5893: 
 5894: # ------------------------------------------------------------ tmpget interface
 5895: sub tmpget {
 5896:     my ($token,$server)=@_;
 5897:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5898:     my $rep=&reply("tmpget:$token",$server);
 5899:     my %returnhash;
 5900:     foreach my $item (split(/\&/,$rep)) {
 5901: 	my ($key,$value)=split(/=/,$item);
 5902:         next if ($key =~ /^error: 2 /);
 5903: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5904:     }
 5905:     return %returnhash;
 5906: }
 5907: 
 5908: # ------------------------------------------------------------ tmpdel interface
 5909: sub tmpdel {
 5910:     my ($token,$server)=@_;
 5911:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5912:     return &reply("tmpdel:$token",$server);
 5913: }
 5914: 
 5915: # ------------------------------------------------------------ get_timebased_id 
 5916: 
 5917: sub get_timebased_id {
 5918:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5919:         $maxtries) = @_;
 5920:     my ($newid,$error,$dellock);
 5921:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5922:         return ('','ok','invalid call to get suffix');
 5923:     }
 5924: 
 5925: # set defaults for any optional args for which values were not supplied
 5926:     if ($who eq '') {
 5927:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5928:     }
 5929:     if (!$locktries) {
 5930:         $locktries = 3;
 5931:     }
 5932:     if (!$maxtries) {
 5933:         $maxtries = 10;
 5934:     }
 5935:     
 5936:     if (($cdom eq '') || ($cnum eq '')) {
 5937:         if ($env{'request.course.id'}) {
 5938:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5939:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5940:         }
 5941:         if (($cdom eq '') || ($cnum eq '')) {
 5942:             return ('','ok','call to get suffix not in course context');
 5943:         }
 5944:     }
 5945: 
 5946: # construct locking item
 5947:     my $lockhash = {
 5948:                       $prefix."\0".'locked_'.$keyid => $who,
 5949:                    };
 5950:     my $tries = 0;
 5951: 
 5952: # attempt to get lock on nohist_$namespace file
 5953:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5954:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5955:         $tries ++;
 5956:         sleep 1;
 5957:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5958:     }
 5959: 
 5960: # attempt to get unique identifier, based on current timestamp
 5961:     if ($gotlock eq 'ok') {
 5962:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5963:         my $id = time;
 5964:         $newid = $id;
 5965:         my $idtries = 0;
 5966:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5967:             if ($idtype eq 'concat') {
 5968:                 $newid = $id.$idtries;
 5969:             } else {
 5970:                 $newid ++;
 5971:             }
 5972:             $idtries ++;
 5973:         }
 5974:         if (!exists($inuse{$prefix."\0".$newid})) {
 5975:             my %new_item =  (
 5976:                               $prefix."\0".$newid => $who,
 5977:                             );
 5978:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5979:                                                  $cdom,$cnum);
 5980:             if ($putresult ne 'ok') {
 5981:                 undef($newid);
 5982:                 $error = 'error saving new item: '.$putresult;
 5983:             }
 5984:         } else {
 5985:              $error = ('error: no unique suffix available for the new item ');
 5986:         }
 5987: #  remove lock
 5988:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5989:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5990:     } else {
 5991:         $error = "error: could not obtain lockfile\n";
 5992:         $dellock = 'ok';
 5993:     }
 5994:     return ($newid,$dellock,$error);
 5995: }
 5996: 
 5997: # -------------------------------------------------- portfolio access checking
 5998: 
 5999: sub portfolio_access {
 6000:     my ($requrl) = @_;
 6001:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6002:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 6003:     if ($result) {
 6004:         my %setters;
 6005:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6006:             my ($startblock,$endblock) =
 6007:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6008:             if ($startblock && $endblock) {
 6009:                 return 'B';
 6010:             }
 6011:         } else {
 6012:             my ($startblock,$endblock) =
 6013:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6014:             if ($startblock && $endblock) {
 6015:                 return 'B';
 6016:             }
 6017:         }
 6018:     }
 6019:     if ($result eq 'ok') {
 6020:        return 'F';
 6021:     } elsif ($result =~ /^[^:]+:guest_/) {
 6022:        return 'A';
 6023:     }
 6024:     return '';
 6025: }
 6026: 
 6027: sub get_portfolio_access {
 6028:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 6029: 
 6030:     if (!ref($access_hash)) {
 6031: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6032: 	my %access_controls = &get_access_controls($current_perms,$group,
 6033: 						   $file_name);
 6034: 	$access_hash = $access_controls{$file_name};
 6035:     }
 6036: 
 6037:     my ($public,$guest,@domains,@users,@courses,@groups);
 6038:     my $now = time;
 6039:     if (ref($access_hash) eq 'HASH') {
 6040:         foreach my $key (keys(%{$access_hash})) {
 6041:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6042:             if ($start > $now) {
 6043:                 next;
 6044:             }
 6045:             if ($end && $end<$now) {
 6046:                 next;
 6047:             }
 6048:             if ($scope eq 'public') {
 6049:                 $public = $key;
 6050:                 last;
 6051:             } elsif ($scope eq 'guest') {
 6052:                 $guest = $key;
 6053:             } elsif ($scope eq 'domains') {
 6054:                 push(@domains,$key);
 6055:             } elsif ($scope eq 'users') {
 6056:                 push(@users,$key);
 6057:             } elsif ($scope eq 'course') {
 6058:                 push(@courses,$key);
 6059:             } elsif ($scope eq 'group') {
 6060:                 push(@groups,$key);
 6061:             }
 6062:         }
 6063:         if ($public) {
 6064:             return 'ok';
 6065:         }
 6066:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6067:             if ($guest) {
 6068:                 return $guest;
 6069:             }
 6070:         } else {
 6071:             if (@domains > 0) {
 6072:                 foreach my $domkey (@domains) {
 6073:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6074:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6075:                             return 'ok';
 6076:                         }
 6077:                     }
 6078:                 }
 6079:             }
 6080:             if (@users > 0) {
 6081:                 foreach my $userkey (@users) {
 6082:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6083:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6084:                             if (ref($item) eq 'HASH') {
 6085:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6086:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6087:                                     return 'ok';
 6088:                                 }
 6089:                             }
 6090:                         }
 6091:                     } 
 6092:                 }
 6093:             }
 6094:             my %roleshash;
 6095:             my @courses_and_groups = @courses;
 6096:             push(@courses_and_groups,@groups); 
 6097:             if (@courses_and_groups > 0) {
 6098:                 my (%allgroups,%allroles); 
 6099:                 my ($start,$end,$role,$sec,$group);
 6100:                 foreach my $envkey (%env) {
 6101:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6102:                         my $cid = $2.'_'.$3; 
 6103:                         if ($1 eq 'gr') {
 6104:                             $group = $4;
 6105:                             $allgroups{$cid}{$group} = $env{$envkey};
 6106:                         } else {
 6107:                             if ($4 eq '') {
 6108:                                 $sec = 'none';
 6109:                             } else {
 6110:                                 $sec = $4;
 6111:                             }
 6112:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6113:                         }
 6114:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6115:                         my $cid = $2.'_'.$3;
 6116:                         if ($4 eq '') {
 6117:                             $sec = 'none';
 6118:                         } else {
 6119:                             $sec = $4;
 6120:                         }
 6121:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6122:                     }
 6123:                 }
 6124:                 if (keys(%allroles) == 0) {
 6125:                     return;
 6126:                 }
 6127:                 foreach my $key (@courses_and_groups) {
 6128:                     my %content = %{$$access_hash{$key}};
 6129:                     my $cnum = $content{'number'};
 6130:                     my $cdom = $content{'domain'};
 6131:                     my $cid = $cdom.'_'.$cnum;
 6132:                     if (!exists($allroles{$cid})) {
 6133:                         next;
 6134:                     }    
 6135:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6136:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6137:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6138:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6139:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6140:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6141:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6142:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6143:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6144:                                         if (grep/^all$/,@sections) {
 6145:                                             return 'ok';
 6146:                                         } else {
 6147:                                             if (grep/^$sec$/,@sections) {
 6148:                                                 return 'ok';
 6149:                                             }
 6150:                                         }
 6151:                                     }
 6152:                                 }
 6153:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6154:                                     if (grep/^none$/,@groups) {
 6155:                                         return 'ok';
 6156:                                     }
 6157:                                 } else {
 6158:                                     if (grep/^all$/,@groups) {
 6159:                                         return 'ok';
 6160:                                     } 
 6161:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6162:                                         if (grep/^$group$/,@groups) {
 6163:                                             return 'ok';
 6164:                                         }
 6165:                                     }
 6166:                                 } 
 6167:                             }
 6168:                         }
 6169:                     }
 6170:                 }
 6171:             }
 6172:             if ($guest) {
 6173:                 return $guest;
 6174:             }
 6175:         }
 6176:     }
 6177:     return;
 6178: }
 6179: 
 6180: sub course_group_datechecker {
 6181:     my ($dates,$now,$status) = @_;
 6182:     my ($start,$end) = split(/\./,$dates);
 6183:     if (!$start && !$end) {
 6184:         return 'ok';
 6185:     }
 6186:     if (grep/^active$/,@{$status}) {
 6187:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6188:             return 'ok';
 6189:         }
 6190:     }
 6191:     if (grep/^previous$/,@{$status}) {
 6192:         if ($end > $now ) {
 6193:             return 'ok';
 6194:         }
 6195:     }
 6196:     if (grep/^future$/,@{$status}) {
 6197:         if ($start > $now) {
 6198:             return 'ok';
 6199:         }
 6200:     }
 6201:     return; 
 6202: }
 6203: 
 6204: sub parse_portfolio_url {
 6205:     my ($url) = @_;
 6206: 
 6207:     my ($type,$udom,$unum,$group,$file_name);
 6208:     
 6209:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6210: 	$type = 1;
 6211:         $udom = $1;
 6212:         $unum = $2;
 6213:         $file_name = $3;
 6214:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6215: 	$type = 2;
 6216:         $udom = $1;
 6217:         $unum = $2;
 6218:         $group = $3;
 6219:         $file_name = $3.'/'.$4;
 6220:     }
 6221:     if (wantarray) {
 6222: 	return ($type,$udom,$unum,$file_name,$group);
 6223:     }
 6224:     return $type;
 6225: }
 6226: 
 6227: sub is_portfolio_url {
 6228:     my ($url) = @_;
 6229:     return scalar(&parse_portfolio_url($url));
 6230: }
 6231: 
 6232: sub is_portfolio_file {
 6233:     my ($file) = @_;
 6234:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6235:         return 1;
 6236:     }
 6237:     return;
 6238: }
 6239: 
 6240: sub usertools_access {
 6241:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6242:     my ($access,%tools);
 6243:     if ($context eq '') {
 6244:         $context = 'tools';
 6245:     }
 6246:     if ($context eq 'requestcourses') {
 6247:         %tools = (
 6248:                       official   => 1,
 6249:                       unofficial => 1,
 6250:                       community  => 1,
 6251:                       textbook   => 1,
 6252:                  );
 6253:     } elsif ($context eq 'requestauthor') {
 6254:         %tools = (
 6255:                       requestauthor => 1,
 6256:                  );
 6257:     } else {
 6258:         %tools = (
 6259:                       aboutme   => 1,
 6260:                       blog      => 1,
 6261:                       webdav    => 1,
 6262:                       portfolio => 1,
 6263:                  );
 6264:     }
 6265:     return if (!defined($tools{$tool}));
 6266: 
 6267:     if (($udom eq '') || ($uname eq '')) {
 6268:         $udom = $env{'user.domain'};
 6269:         $uname = $env{'user.name'};
 6270:     }
 6271: 
 6272:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6273:         if ($action ne 'reload') {
 6274:             if ($context eq 'requestcourses') {
 6275:                 return $env{'environment.canrequest.'.$tool};
 6276:             } elsif ($context eq 'requestauthor') {
 6277:                 return $env{'environment.canrequest.author'};
 6278:             } else {
 6279:                 return $env{'environment.availabletools.'.$tool};
 6280:             }
 6281:         }
 6282:     }
 6283: 
 6284:     my ($toolstatus,$inststatus,$envkey);
 6285:     if ($context eq 'requestauthor') {
 6286:         $envkey = $context; 
 6287:     } else {
 6288:         $envkey = $context.'.'.$tool;
 6289:     }
 6290: 
 6291:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6292:          ($action ne 'reload')) {
 6293:         $toolstatus = $env{'environment.'.$envkey};
 6294:         $inststatus = $env{'environment.inststatus'};
 6295:     } else {
 6296:         if (ref($userenvref) eq 'HASH') {
 6297:             $toolstatus = $userenvref->{$envkey};
 6298:             $inststatus = $userenvref->{'inststatus'};
 6299:         } else {
 6300:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6301:             $toolstatus = $userenv{$envkey};
 6302:             $inststatus = $userenv{'inststatus'};
 6303:         }
 6304:     }
 6305: 
 6306:     if ($toolstatus ne '') {
 6307:         if ($toolstatus) {
 6308:             $access = 1;
 6309:         } else {
 6310:             $access = 0;
 6311:         }
 6312:         return $access;
 6313:     }
 6314: 
 6315:     my ($is_adv,%domdef);
 6316:     if (ref($is_advref) eq 'HASH') {
 6317:         $is_adv = $is_advref->{'is_adv'};
 6318:     } else {
 6319:         $is_adv = &is_advanced_user($udom,$uname);
 6320:     }
 6321:     if (ref($domdefref) eq 'HASH') {
 6322:         %domdef = %{$domdefref};
 6323:     } else {
 6324:         %domdef = &get_domain_defaults($udom);
 6325:     }
 6326:     if (ref($domdef{$tool}) eq 'HASH') {
 6327:         if ($is_adv) {
 6328:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6329:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6330:                     $access = 1;
 6331:                 } else {
 6332:                     $access = 0;
 6333:                 }
 6334:                 return $access;
 6335:             }
 6336:         }
 6337:         if ($inststatus ne '') {
 6338:             my ($hasaccess,$hasnoaccess);
 6339:             foreach my $affiliation (split(/:/,$inststatus)) {
 6340:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6341:                     if ($domdef{$tool}{$affiliation}) {
 6342:                         $hasaccess = 1;
 6343:                     } else {
 6344:                         $hasnoaccess = 1;
 6345:                     }
 6346:                 }
 6347:             }
 6348:             if ($hasaccess || $hasnoaccess) {
 6349:                 if ($hasaccess) {
 6350:                     $access = 1;
 6351:                 } elsif ($hasnoaccess) {
 6352:                     $access = 0; 
 6353:                 }
 6354:                 return $access;
 6355:             }
 6356:         } else {
 6357:             if ($domdef{$tool}{'default'} ne '') {
 6358:                 if ($domdef{$tool}{'default'}) {
 6359:                     $access = 1;
 6360:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6361:                     $access = 0;
 6362:                 }
 6363:                 return $access;
 6364:             }
 6365:         }
 6366:     } else {
 6367:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6368:             $access = 1;
 6369:         } else {
 6370:             $access = 0;
 6371:         }
 6372:         return $access;
 6373:     }
 6374: }
 6375: 
 6376: sub is_course_owner {
 6377:     my ($cdom,$cnum,$udom,$uname) = @_;
 6378:     if (($udom eq '') || ($uname eq '')) {
 6379:         $udom = $env{'user.domain'};
 6380:         $uname = $env{'user.name'};
 6381:     }
 6382:     unless (($udom eq '') || ($uname eq '')) {
 6383:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6384:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6385:                 return 1;
 6386:             } else {
 6387:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6388:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6389:                     return 1;
 6390:                 }
 6391:             }
 6392:         }
 6393:     }
 6394:     return;
 6395: }
 6396: 
 6397: sub is_advanced_user {
 6398:     my ($udom,$uname) = @_;
 6399:     if ($udom ne '' && $uname ne '') {
 6400:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6401:             if (wantarray) {
 6402:                 return ($env{'user.adv'},$env{'user.author'});
 6403:             } else {
 6404:                 return $env{'user.adv'};
 6405:             }
 6406:         }
 6407:     }
 6408:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6409:     my %allroles;
 6410:     my ($is_adv,$is_author);
 6411:     foreach my $role (keys(%roleshash)) {
 6412:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6413:         my $area = '/'.$tdomain.'/'.$trest;
 6414:         if ($sec ne '') {
 6415:             $area .= '/'.$sec;
 6416:         }
 6417:         if (($area ne '') && ($trole ne '')) {
 6418:             my $spec=$trole.'.'.$area;
 6419:             if ($trole =~ /^cr\//) {
 6420:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6421:             } elsif ($trole ne 'gr') {
 6422:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6423:             }
 6424:             if ($trole eq 'au') {
 6425:                 $is_author = 1;
 6426:             }
 6427:         }
 6428:     }
 6429:     foreach my $role (keys(%allroles)) {
 6430:         last if ($is_adv);
 6431:         foreach my $item (split(/:/,$allroles{$role})) {
 6432:             if ($item ne '') {
 6433:                 my ($privilege,$restrictions)=split(/&/,$item);
 6434:                 if ($privilege eq 'adv') {
 6435:                     $is_adv = 1;
 6436:                     last;
 6437:                 }
 6438:             }
 6439:         }
 6440:     }
 6441:     if (wantarray) {
 6442:         return ($is_adv,$is_author);
 6443:     }
 6444:     return $is_adv;
 6445: }
 6446: 
 6447: sub check_can_request {
 6448:     my ($dom,$can_request,$request_domains) = @_;
 6449:     my $canreq = 0;
 6450:     my ($types,$typename) = &Apache::loncommon::course_types();
 6451:     my @options = ('approval','validate','autolimit');
 6452:     my $optregex = join('|',@options);
 6453:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6454:         foreach my $type (@{$types}) {
 6455:             if (&usertools_access($env{'user.name'},
 6456:                                   $env{'user.domain'},
 6457:                                   $type,undef,'requestcourses')) {
 6458:                 $canreq ++;
 6459:                 if (ref($request_domains) eq 'HASH') {
 6460:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6461:                 }
 6462:                 if ($dom eq $env{'user.domain'}) {
 6463:                     $can_request->{$type} = 1;
 6464:                 }
 6465:             }
 6466:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6467:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6468:                 if (@curr > 0) {
 6469:                     foreach my $item (@curr) {
 6470:                         if (ref($request_domains) eq 'HASH') {
 6471:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6472:                             if ($otherdom ne '') {
 6473:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6474:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6475:                                         push(@{$request_domains->{$type}},$otherdom);
 6476:                                     }
 6477:                                 } else {
 6478:                                     push(@{$request_domains->{$type}},$otherdom);
 6479:                                 }
 6480:                             }
 6481:                         }
 6482:                     }
 6483:                     unless($dom eq $env{'user.domain'}) {
 6484:                         $canreq ++;
 6485:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6486:                             $can_request->{$type} = 1;
 6487:                         }
 6488:                     }
 6489:                 }
 6490:             }
 6491:         }
 6492:     }
 6493:     return $canreq;
 6494: }
 6495: 
 6496: # ---------------------------------------------- Custom access rule evaluation
 6497: 
 6498: sub customaccess {
 6499:     my ($priv,$uri)=@_;
 6500:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6501:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6502:     $udom = &LONCAPA::clean_domain($udom);
 6503:     $ucrs = &LONCAPA::clean_username($ucrs);
 6504:     my $access=0;
 6505:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6506: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6507: 	if ($type eq 'user') {
 6508: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6509: 		my ($tdom,$tuname)=split(m{/},$scope);
 6510: 		if ($tdom) {
 6511: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6512: 		}
 6513: 		if ($tuname) {
 6514: 		    if ($tuname ne $env{'user.name'}) { next; }
 6515: 		}
 6516: 		$access=($effect eq 'allow');
 6517: 		last;
 6518: 	    }
 6519: 	} else {
 6520: 	    if ($role) {
 6521: 		if ($role ne $urole) { next; }
 6522: 	    }
 6523: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6524: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6525: 		if ($tdom) {
 6526: 		    if ($tdom ne $udom) { next; }
 6527: 		}
 6528: 		if ($tcrs) {
 6529: 		    if ($tcrs ne $ucrs) { next; }
 6530: 		}
 6531: 		if ($tsec) {
 6532: 		    if ($tsec ne $usec) { next; }
 6533: 		}
 6534: 		$access=($effect eq 'allow');
 6535: 		last;
 6536: 	    }
 6537: 	    if ($realm eq '' && $role eq '') {
 6538: 		$access=($effect eq 'allow');
 6539: 	    }
 6540: 	}
 6541:     }
 6542:     return $access;
 6543: }
 6544: 
 6545: # ------------------------------------------------- Check for a user privilege
 6546: 
 6547: sub allowed {
 6548:     my ($priv,$uri,$symb,$role)=@_;
 6549:     my $ver_orguri=$uri;
 6550:     $uri=&deversion($uri);
 6551:     my $orguri=$uri;
 6552:     $uri=&declutter($uri);
 6553: 
 6554:     if ($priv eq 'evb') {
 6555: # Evade communication block restrictions for specified role in a course
 6556:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6557:             return $1;
 6558:         } else {
 6559:             return;
 6560:         }
 6561:     }
 6562: 
 6563:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6564: # Free bre access to adm and meta resources
 6565:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6566: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6567: 	&& ($priv eq 'bre')) {
 6568: 	return 'F';
 6569:     }
 6570: 
 6571: # Free bre access to user's own portfolio contents
 6572:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6573:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6574: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6575:         my %setters;
 6576:         my ($startblock,$endblock) = 
 6577:             &Apache::loncommon::blockcheck(\%setters,'port');
 6578:         if ($startblock && $endblock) {
 6579:             return 'B';
 6580:         } else {
 6581:             return 'F';
 6582:         }
 6583:     }
 6584: 
 6585: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6586:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6587:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6588:         if (exists($env{'request.course.id'})) {
 6589:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6590:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6591:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6592:                 my $courseprivid=$env{'request.course.id'};
 6593:                 $courseprivid=~s/\_/\//;
 6594:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6595:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6596:                     return $1; 
 6597:                 } else {
 6598:                     if ($env{'request.course.sec'}) {
 6599:                         $courseprivid.='/'.$env{'request.course.sec'};
 6600:                     }
 6601:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6602:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6603:                         return $2;
 6604:                     }
 6605:                 }
 6606:             }
 6607:         }
 6608:     }
 6609: 
 6610: # Free bre to public access
 6611: 
 6612:     if ($priv eq 'bre') {
 6613:         my $copyright=&metadata($uri,'copyright');
 6614: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6615:            return 'F'; 
 6616:         }
 6617:         if ($copyright eq 'priv') {
 6618:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6619: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6620: 		return '';
 6621:             }
 6622:         }
 6623:         if ($copyright eq 'domain') {
 6624:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6625: 	    unless (($env{'user.domain'} eq $1) ||
 6626:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6627: 		return '';
 6628:             }
 6629:         }
 6630:         if ($env{'request.role'}=~ /li\.\//) {
 6631:             # Library role, so allow browsing of resources in this domain.
 6632:             return 'F';
 6633:         }
 6634:         if ($copyright eq 'custom') {
 6635: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6636:         }
 6637:     }
 6638:     # Domain coordinator is trying to create a course
 6639:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6640:         # uri is the requested domain in this case.
 6641:         # comparison to 'request.role.domain' shows if the user has selected
 6642:         # a role of dc for the domain in question.
 6643:         return 'F' if ($uri eq $env{'request.role.domain'});
 6644:     }
 6645: 
 6646:     my $thisallowed='';
 6647:     my $statecond=0;
 6648:     my $courseprivid='';
 6649: 
 6650:     my $ownaccess;
 6651:     # Community Coordinator or Assistant Co-author browsing resource space.
 6652:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6653:         if ($uri eq '') {
 6654:             $ownaccess = 1;
 6655:         } else {
 6656:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6657:                 my $udom = $env{'user.domain'};
 6658:                 my $uname = $env{'user.name'};
 6659:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6660:                     $ownaccess = 1;
 6661:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6662:                     unless ($uri =~ m{\.\./}) {
 6663:                         $ownaccess = 1;
 6664:                     }
 6665:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6666:                     my $now = time;
 6667:                     if ($uri =~ m{^([^/]+)/?$}) {
 6668:                         my $adom = $1;
 6669:                         foreach my $key (keys(%env)) {
 6670:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6671:                                 my ($start,$end) = split('.',$env{$key});
 6672:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6673:                                     $ownaccess = 1;
 6674:                                     last;
 6675:                                 }
 6676:                             }
 6677:                         }
 6678:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6679:                         my $adom = $1;
 6680:                         my $aname = $2;
 6681:                         foreach my $role ('ca','aa') { 
 6682:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6683:                                 my ($start,$end) =
 6684:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6685:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6686:                                     $ownaccess = 1;
 6687:                                     last;
 6688:                                 }
 6689:                             }
 6690:                         }
 6691:                     }
 6692:                 }
 6693:             }
 6694:         }
 6695:     }
 6696: 
 6697: # Course
 6698: 
 6699:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6700:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6701:             $thisallowed.=$1;
 6702:         }
 6703:     }
 6704: 
 6705: # Domain
 6706: 
 6707:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6708:        =~/\Q$priv\E\&([^\:]*)/) {
 6709:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6710:             $thisallowed.=$1;
 6711:         }
 6712:     }
 6713: 
 6714: # User who is not author or co-author might still be able to edit
 6715: # resource of an author in the domain (e.g., if Domain Coordinator).
 6716:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6717:         (&allowed('mdc',$env{'request.course.id'}))) {
 6718:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6719:             $thisallowed.=$1;
 6720:         }
 6721:     }
 6722: 
 6723: # Course: uri itself is a course
 6724:     my $courseuri=$uri;
 6725:     $courseuri=~s/\_(\d)/\/$1/;
 6726:     $courseuri=~s/^([^\/])/\/$1/;
 6727: 
 6728:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6729:        =~/\Q$priv\E\&([^\:]*)/) {
 6730:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6731:             $thisallowed.=$1;
 6732:         }
 6733:     }
 6734: 
 6735: # URI is an uploaded document for this course, default permissions don't matter
 6736: # not allowing 'edit' access (editupload) to uploaded course docs
 6737:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6738: 	$thisallowed='';
 6739:         my ($match)=&is_on_map($uri);
 6740:         if ($match) {
 6741:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6742:                   =~/\Q$priv\E\&([^\:]*)/) {
 6743:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6744:                 if (@blockers > 0) {
 6745:                     $thisallowed = 'B';
 6746:                 } else {
 6747:                     $thisallowed.=$1;
 6748:                 }
 6749:             }
 6750:         } else {
 6751:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6752:             if ($refuri) {
 6753:                 if ($refuri =~ m|^/adm/|) {
 6754:                     $thisallowed='F';
 6755:                 } else {
 6756:                     $refuri=&declutter($refuri);
 6757:                     my ($match) = &is_on_map($refuri);
 6758:                     if ($match) {
 6759:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6760:                         if (@blockers > 0) {
 6761:                             $thisallowed = 'B';
 6762:                         } else {
 6763:                             $thisallowed='F';
 6764:                         }
 6765:                     }
 6766:                 }
 6767:             }
 6768:         }
 6769:     }
 6770: 
 6771:     if ($priv eq 'bre'
 6772: 	&& $thisallowed ne 'F' 
 6773: 	&& $thisallowed ne '2'
 6774: 	&& &is_portfolio_url($uri)) {
 6775: 	$thisallowed = &portfolio_access($uri);
 6776:     }
 6777: 
 6778: # Full access at system, domain or course-wide level? Exit.
 6779:     if ($thisallowed=~/F/) {
 6780: 	return 'F';
 6781:     }
 6782: 
 6783: # If this is generating or modifying users, exit with special codes
 6784: 
 6785:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6786: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6787: 	    my ($audom,$auname)=split('/',$uri);
 6788: # no author name given, so this just checks on the general right to make a co-author in this domain
 6789: 	    unless ($auname) { return $thisallowed; }
 6790: # an author name is given, so we are about to actually make a co-author for a certain account
 6791: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6792: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6793: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6794: 	}
 6795: 	return $thisallowed;
 6796:     }
 6797: #
 6798: # Gathered so far: system, domain and course wide privileges
 6799: #
 6800: # Course: See if uri or referer is an individual resource that is part of 
 6801: # the course
 6802: 
 6803:     if ($env{'request.course.id'}) {
 6804: 
 6805:        $courseprivid=$env{'request.course.id'};
 6806:        if ($env{'request.course.sec'}) {
 6807:           $courseprivid.='/'.$env{'request.course.sec'};
 6808:        }
 6809:        $courseprivid=~s/\_/\//;
 6810:        my $checkreferer=1;
 6811:        my ($match,$cond)=&is_on_map($uri);
 6812:        if ($match) {
 6813:            $statecond=$cond;
 6814:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6815:                =~/\Q$priv\E\&([^\:]*)/) {
 6816:                my $value = $1;
 6817:                if ($priv eq 'bre') {
 6818:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6819:                    if (@blockers > 0) {
 6820:                        $thisallowed = 'B';
 6821:                    } else {
 6822:                        $thisallowed.=$value;
 6823:                    }
 6824:                } else {
 6825:                    $thisallowed.=$value;
 6826:                }
 6827:                $checkreferer=0;
 6828:            }
 6829:        }
 6830:        
 6831:        if ($checkreferer) {
 6832: 	  my $refuri=$env{'httpref.'.$orguri};
 6833:             unless ($refuri) {
 6834:                 foreach my $key (keys(%env)) {
 6835: 		    if ($key=~/^httpref\..*\*/) {
 6836: 			my $pattern=$key;
 6837:                         $pattern=~s/^httpref\.\/res\///;
 6838:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6839:                         $pattern=~s/\//\\\//g;
 6840:                         if ($orguri=~/$pattern/) {
 6841: 			    $refuri=$env{$key};
 6842:                         }
 6843:                     }
 6844:                 }
 6845:             }
 6846: 
 6847:          if ($refuri) { 
 6848: 	  $refuri=&declutter($refuri);
 6849:           my ($match,$cond)=&is_on_map($refuri);
 6850:             if ($match) {
 6851:               my $refstatecond=$cond;
 6852:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6853:                   =~/\Q$priv\E\&([^\:]*)/) {
 6854:                   my $value = $1;
 6855:                   if ($priv eq 'bre') {
 6856:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6857:                       if (@blockers > 0) {
 6858:                           $thisallowed = 'B';
 6859:                       } else {
 6860:                           $thisallowed.=$value;
 6861:                       }
 6862:                   } else {
 6863:                       $thisallowed.=$value;
 6864:                   }
 6865:                   $uri=$refuri;
 6866:                   $statecond=$refstatecond;
 6867:               }
 6868:           }
 6869:         }
 6870:        }
 6871:    }
 6872: 
 6873: #
 6874: # Gathered now: all privileges that could apply, and condition number
 6875: # 
 6876: #
 6877: # Full or no access?
 6878: #
 6879: 
 6880:     if ($thisallowed=~/F/) {
 6881: 	return 'F';
 6882:     }
 6883: 
 6884:     unless ($thisallowed) {
 6885:         return '';
 6886:     }
 6887: 
 6888: # Restrictions exist, deal with them
 6889: #
 6890: #   C:according to course preferences
 6891: #   R:according to resource settings
 6892: #   L:unless locked
 6893: #   X:according to user session state
 6894: #
 6895: 
 6896: # Possibly locked functionality, check all courses
 6897: # Locks might take effect only after 10 minutes cache expiration for other
 6898: # courses, and 2 minutes for current course
 6899: 
 6900:     my $envkey;
 6901:     if ($thisallowed=~/L/) {
 6902:         foreach $envkey (keys(%env)) {
 6903:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6904:                my $courseid=$2;
 6905:                my $roleid=$1.'.'.$2;
 6906:                $courseid=~s/^\///;
 6907:                my $expiretime=600;
 6908:                if ($env{'request.role'} eq $roleid) {
 6909: 		  $expiretime=120;
 6910:                }
 6911: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6912:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6913:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6914: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6915:                }
 6916:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6917:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6918: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6919:                        &log($env{'user.domain'},$env{'user.name'},
 6920:                             $env{'user.home'},
 6921:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6922:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6923:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6924: 		       return '';
 6925:                    }
 6926:                }
 6927:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6928:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6929: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6930:                        &log($env{'user.domain'},$env{'user.name'},
 6931:                             $env{'user.home'},
 6932:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6933:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6934:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6935: 		       return '';
 6936:                    }
 6937:                }
 6938: 	   }
 6939:        }
 6940:     }
 6941:    
 6942: #
 6943: # Rest of the restrictions depend on selected course
 6944: #
 6945: 
 6946:     unless ($env{'request.course.id'}) {
 6947: 	if ($thisallowed eq 'A') {
 6948: 	    return 'A';
 6949:         } elsif ($thisallowed eq 'B') {
 6950:             return 'B';
 6951: 	} else {
 6952: 	    return '1';
 6953: 	}
 6954:     }
 6955: 
 6956: #
 6957: # Now user is definitely in a course
 6958: #
 6959: 
 6960: 
 6961: # Course preferences
 6962: 
 6963:    if ($thisallowed=~/C/) {
 6964:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6965:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6966:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6967: 	   =~/\Q$rolecode\E/) {
 6968: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6969: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6970: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6971: 			$env{'request.course.id'});
 6972: 	   }
 6973:            return '';
 6974:        }
 6975: 
 6976:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6977: 	   =~/\Q$unamedom\E/) {
 6978: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6979: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6980: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6981: 			$env{'request.course.id'});
 6982: 	   }
 6983:            return '';
 6984:        }
 6985:    }
 6986: 
 6987: # Resource preferences
 6988: 
 6989:    if ($thisallowed=~/R/) {
 6990:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6991:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6992: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6993: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6994: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6995: 	   }
 6996: 	   return '';
 6997:        }
 6998:    }
 6999: 
 7000: # Restricted by state or randomout?
 7001: 
 7002:    if ($thisallowed=~/X/) {
 7003:       if ($env{'acc.randomout'}) {
 7004: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7005:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7006:             return ''; 
 7007:          }
 7008:       }
 7009:       if (&condval($statecond)) {
 7010: 	 return '2';
 7011:       } else {
 7012:          return '';
 7013:       }
 7014:    }
 7015: 
 7016:     if ($thisallowed eq 'A') {
 7017: 	return 'A';
 7018:     } elsif ($thisallowed eq 'B') {
 7019:         return 'B';
 7020:     }
 7021:    return 'F';
 7022: }
 7023: 
 7024: # ------------------------------------------- Check construction space access
 7025: 
 7026: sub constructaccess {
 7027:     my ($url,$setpriv)=@_;
 7028: 
 7029: # We do not allow editing of previous versions of files
 7030:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7031: 
 7032: # Get username and domain from URL
 7033:     my ($ownername,$ownerdomain,$ownerhome);
 7034: 
 7035:     ($ownerdomain,$ownername) =
 7036:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7037: 
 7038: # The URL does not really point to any authorspace, forget it
 7039:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7040: 
 7041: # Now we need to see if the user has access to the authorspace of
 7042: # $ownername at $ownerdomain
 7043: 
 7044:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7045: # Real author for this?
 7046:        $ownerhome = $env{'user.home'};
 7047:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7048:           return ($ownername,$ownerdomain,$ownerhome);
 7049:        }
 7050:     } else {
 7051: # Co-author for this?
 7052:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7053:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7054:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7055:             return ($ownername,$ownerdomain,$ownerhome);
 7056:         }
 7057:     }
 7058: 
 7059: # We don't have any access right now. If we are not possibly going to do anything about this,
 7060: # we might as well leave
 7061:    unless ($setpriv) { return ''; }
 7062: 
 7063: # Backdoor access?
 7064:     my $allowed=&allowed('eco',$ownerdomain);
 7065: # Nope
 7066:     unless ($allowed) { return ''; }
 7067: # Looks like we may have access, but could be locked by the owner of the construction space
 7068:     if ($allowed eq 'U') {
 7069:         my %blocked=&get('environment',['domcoord.author'],
 7070:                          $ownerdomain,$ownername);
 7071: # Is blocked by owner
 7072:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7073:     }
 7074:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7075: # Grant temporary access
 7076:         my $then=$env{'user.login.time'};
 7077:         my $update=$env{'user.update.time'};
 7078:         if (!$update) { $update = $then; }
 7079:         my $refresh=$env{'user.refresh.time'};
 7080:         if (!$refresh) { $refresh = $update; }
 7081:         my $now = time;
 7082:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7083:                            $now,'ca','constructaccess');
 7084:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7085:         return($ownername,$ownerdomain,$ownerhome);
 7086:     }
 7087: # No business here
 7088:     return '';
 7089: }
 7090: 
 7091: sub get_comm_blocks {
 7092:     my ($cdom,$cnum) = @_;
 7093:     if ($cdom eq '' || $cnum eq '') {
 7094:         return unless ($env{'request.course.id'});
 7095:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7096:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7097:     }
 7098:     my %commblocks;
 7099:     my $hashid=$cdom.'_'.$cnum;
 7100:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7101:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7102:         %commblocks = %{$blocksref};
 7103:     } else {
 7104:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7105:         my $cachetime = 600;
 7106:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7107:     }
 7108:     return %commblocks;
 7109: }
 7110: 
 7111: sub has_comm_blocking {
 7112:     my ($priv,$symb,$uri,$blocks) = @_;
 7113:     return unless ($env{'request.course.id'});
 7114:     return unless ($priv eq 'bre');
 7115:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7116:     my %commblocks;
 7117:     if (ref($blocks) eq 'HASH') {
 7118:         %commblocks = %{$blocks};
 7119:     } else {
 7120:         %commblocks = &get_comm_blocks();
 7121:     }
 7122:     return unless (keys(%commblocks) > 0);
 7123:     if (!$symb) { $symb=&symbread($uri,1); }
 7124:     my ($map,$resid,undef)=&decode_symb($symb);
 7125:     my %tocheck = (
 7126:                     maps      => $map,
 7127:                     resources => $symb,
 7128:                   );
 7129:     my @blockers;
 7130:     my $now = time;
 7131:     my $navmap = Apache::lonnavmaps::navmap->new();
 7132:     foreach my $block (keys(%commblocks)) {
 7133:         if ($block =~ /^(\d+)____(\d+)$/) {
 7134:             my ($start,$end) = ($1,$2);
 7135:             if ($start <= $now && $end >= $now) {
 7136:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7137:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7138:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7139:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7140:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7141:                                     push(@blockers,$block);
 7142:                                 }
 7143:                             }
 7144:                         }
 7145:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7146:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7147:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7148:                                     push(@blockers,$block);
 7149:                                 }
 7150:                             }
 7151:                         }
 7152:                     }
 7153:                 }
 7154:             }
 7155:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7156:             my $item = $1;
 7157:             my @to_test;
 7158:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7159:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7160:                     my $check_interval;
 7161:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7162:                         my @interval;
 7163:                         my $type = 'map';
 7164:                         if ($item eq 'course') {
 7165:                             $type = 'course';
 7166:                             @interval=&EXT("resource.0.interval");
 7167:                         } else {
 7168:                             if ($item =~ /___\d+___/) {
 7169:                                 $type = 'resource';
 7170:                                 @interval=&EXT("resource.0.interval",$item);
 7171:                                 if (ref($navmap)) {                        
 7172:                                     my $res = $navmap->getBySymb($item); 
 7173:                                     push(@to_test,$res);
 7174:                                 }
 7175:                             } else {
 7176:                                 my $mapsymb = &symbread($item,1);
 7177:                                 if ($mapsymb) {
 7178:                                     if (ref($navmap)) {
 7179:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7180:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7181:                                         foreach my $res (@to_test) {
 7182:                                             my $symb = $res->symb();
 7183:                                             next if ($symb eq $mapsymb);
 7184:                                             if ($symb ne '') {
 7185:                                                 @interval=&EXT("resource.0.interval",$symb);
 7186:                                                 last;
 7187:                                             }
 7188:                                         }
 7189:                                     }
 7190:                                 }
 7191:                             }
 7192:                         }
 7193:                         if ($interval[0] =~ /\d+/) {
 7194:                             my $first_access;
 7195:                             if ($type eq 'resource') {
 7196:                                 $first_access=&get_first_access($interval[1],$item);
 7197:                             } elsif ($type eq 'map') {
 7198:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7199:                             } else {
 7200:                                 $first_access=&get_first_access($interval[1]);
 7201:                             }
 7202:                             if ($first_access) {
 7203:                                 my $timesup = $first_access+$interval[0];
 7204:                                 if ($timesup > $now) {
 7205:                                     foreach my $res (@to_test) {
 7206:                                         if ($res->is_problem()) {
 7207:                                             if ($res->completable()) {
 7208:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7209:                                                     push(@blockers,$block);
 7210:                                                 }
 7211:                                                 last;
 7212:                                             }
 7213:                                         }
 7214:                                     }
 7215:                                 }
 7216:                             }
 7217:                         }
 7218:                     }
 7219:                 }
 7220:             }
 7221:         }
 7222:     }
 7223:     return @blockers;
 7224: }
 7225: 
 7226: sub check_docs_block {
 7227:     my ($docsblock,$tocheck) =@_;
 7228:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7229:         return;
 7230:     }
 7231:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7232:         if ($tocheck->{'maps'}) {
 7233:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7234:                 return 1;
 7235:             }
 7236:         }
 7237:     }
 7238:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7239:         if ($tocheck->{'resources'}) {
 7240:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7241:                 return 1;
 7242:             }
 7243:         }
 7244:     }
 7245:     return;
 7246: }
 7247: 
 7248: #
 7249: #   Removes the versino from a URI and
 7250: #   splits it in to its filename and path to the filename.
 7251: #   Seems like File::Basename could have done this more clearly.
 7252: #   Parameters:
 7253: #      $uri   - input URI
 7254: #   Returns:
 7255: #     Two element list consisting of 
 7256: #     $pathname  - the URI up to and excluding the trailing /
 7257: #     $filename  - The part of the URI following the last /
 7258: #  NOTE:
 7259: #    Another realization of this is simply:
 7260: #    use File::Basename;
 7261: #    ...
 7262: #    $uri = shift;
 7263: #    $filename = basename($uri);
 7264: #    $path     = dirname($uri);
 7265: #    return ($filename, $path);
 7266: #
 7267: #     The implementation below is probably faster however.
 7268: #
 7269: sub split_uri_for_cond {
 7270:     my $uri=&deversion(&declutter(shift));
 7271:     my @uriparts=split(/\//,$uri);
 7272:     my $filename=pop(@uriparts);
 7273:     my $pathname=join('/',@uriparts);
 7274:     return ($pathname,$filename);
 7275: }
 7276: # --------------------------------------------------- Is a resource on the map?
 7277: 
 7278: sub is_on_map {
 7279:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7280:     #Trying to find the conditional for the file
 7281:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7282: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7283:     if ($match) {
 7284: 	return (1,$1);
 7285:     } else {
 7286: 	return (0,0);
 7287:     }
 7288: }
 7289: 
 7290: # --------------------------------------------------------- Get symb from alias
 7291: 
 7292: sub get_symb_from_alias {
 7293:     my $symb=shift;
 7294:     my ($map,$resid,$url)=&decode_symb($symb);
 7295: # Already is a symb
 7296:     if ($url) { return $symb; }
 7297: # Must be an alias
 7298:     my $aliassymb='';
 7299:     my %bighash;
 7300:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7301:                             &GDBM_READER(),0640)) {
 7302:         my $rid=$bighash{'mapalias_'.$symb};
 7303: 	if ($rid) {
 7304: 	    my ($mapid,$resid)=split(/\./,$rid);
 7305: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7306: 				    $resid,$bighash{'src_'.$rid});
 7307: 	}
 7308:         untie %bighash;
 7309:     }
 7310:     return $aliassymb;
 7311: }
 7312: 
 7313: # ----------------------------------------------------------------- Define Role
 7314: 
 7315: sub definerole {
 7316:   if (allowed('mcr','/')) {
 7317:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7318:     foreach my $role (split(':',$sysrole)) {
 7319: 	my ($crole,$cqual)=split(/\&/,$role);
 7320:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7321:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7322: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7323:                return "refused:s:$crole&$cqual"; 
 7324:             }
 7325:         }
 7326:     }
 7327:     foreach my $role (split(':',$domrole)) {
 7328: 	my ($crole,$cqual)=split(/\&/,$role);
 7329:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7330:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7331: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7332:                return "refused:d:$crole&$cqual"; 
 7333:             }
 7334:         }
 7335:     }
 7336:     foreach my $role (split(':',$courole)) {
 7337: 	my ($crole,$cqual)=split(/\&/,$role);
 7338:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7339:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7340: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7341:                return "refused:c:$crole&$cqual"; 
 7342:             }
 7343:         }
 7344:     }
 7345:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7346:                 "$env{'user.domain'}:$env{'user.name'}:".
 7347: 	        "rolesdef_$rolename=".
 7348:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7349:     return reply($command,$env{'user.home'});
 7350:   } else {
 7351:     return 'refused';
 7352:   }
 7353: }
 7354: 
 7355: # ---------------- Make a metadata query against the network of library servers
 7356: 
 7357: sub metadata_query {
 7358:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7359:     my %rhash;
 7360:     my %libserv = &all_library();
 7361:     my @server_list = (defined($server_array) ? @$server_array
 7362:                                               : keys(%libserv) );
 7363:     for my $server (@server_list) {
 7364:         my $domains = ''; 
 7365:         if (ref($domains_hash) eq 'HASH') {
 7366:             $domains = $domains_hash->{$server}; 
 7367:         }
 7368: 	unless ($custom or $customshow) {
 7369: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7370: 	    $rhash{$server}=$reply;
 7371: 	}
 7372: 	else {
 7373: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7374: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7375: 			     $server);
 7376: 	    $rhash{$server}=$reply;
 7377: 	}
 7378:     }
 7379:     return \%rhash;
 7380: }
 7381: 
 7382: # ----------------------------------------- Send log queries and wait for reply
 7383: 
 7384: sub log_query {
 7385:     my ($uname,$udom,$query,%filters)=@_;
 7386:     my $uhome=&homeserver($uname,$udom);
 7387:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7388:     my $uhost=&hostname($uhome);
 7389:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7390:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7391:                        $uhome);
 7392:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7393:     return get_query_reply($queryid);
 7394: }
 7395: 
 7396: # -------------------------- Update MySQL table for portfolio file
 7397: 
 7398: sub update_portfolio_table {
 7399:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7400:     if ($group ne '') {
 7401:         $file_name =~s /^\Q$group\E//;
 7402:     }
 7403:     my $homeserver = &homeserver($uname,$udom);
 7404:     my $queryid=
 7405:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7406:                ':'.&escape($file_name).':'.$action,$homeserver);
 7407:     my $reply = &get_query_reply($queryid);
 7408:     return $reply;
 7409: }
 7410: 
 7411: # -------------------------- Update MySQL allusers table
 7412: 
 7413: sub update_allusers_table {
 7414:     my ($uname,$udom,$names) = @_;
 7415:     my $homeserver = &homeserver($uname,$udom);
 7416:     my $queryid=
 7417:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7418:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7419:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7420:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7421:                'generation='.&escape($names->{'generation'}).'%%'.
 7422:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7423:                'id='.&escape($names->{'id'}),$homeserver);
 7424:     return;
 7425: }
 7426: 
 7427: # ------- Request retrieval of institutional classlists for course(s)
 7428: 
 7429: sub fetch_enrollment_query {
 7430:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7431:     my $homeserver;
 7432:     my $maxtries = 1;
 7433:     if ($context eq 'automated') {
 7434:         $homeserver = $perlvar{'lonHostID'};
 7435:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7436:     } else {
 7437:         $homeserver = &homeserver($cnum,$dom);
 7438:     }
 7439:     my $host=&hostname($homeserver);
 7440:     my $cmd = '';
 7441:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7442:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7443:     }
 7444:     $cmd =~ s/%%$//;
 7445:     $cmd = &escape($cmd);
 7446:     my $query = 'fetchenrollment';
 7447:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7448:     unless ($queryid=~/^\Q$host\E\_/) { 
 7449:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7450:         return 'error: '.$queryid;
 7451:     }
 7452:     my $reply = &get_query_reply($queryid);
 7453:     my $tries = 1;
 7454:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7455:         $reply = &get_query_reply($queryid);
 7456:         $tries ++;
 7457:     }
 7458:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7459:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7460:     } else {
 7461:         my @responses = split(/:/,$reply);
 7462:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7463:             foreach my $line (@responses) {
 7464:                 my ($key,$value) = split(/=/,$line,2);
 7465:                 $$replyref{$key} = $value;
 7466:             }
 7467:         } else {
 7468:             my $pathname = LONCAPA::tempdir();
 7469:             foreach my $line (@responses) {
 7470:                 my ($key,$value) = split(/=/,$line);
 7471:                 $$replyref{$key} = $value;
 7472:                 if ($value > 0) {
 7473:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7474:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7475:                         my $destname = $pathname.'/'.$filename;
 7476:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7477:                         if ($xml_classlist =~ /^error/) {
 7478:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7479:                         } else {
 7480:                             if ( open(FILE,">$destname") ) {
 7481:                                 print FILE &unescape($xml_classlist);
 7482:                                 close(FILE);
 7483:                             } else {
 7484:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7485:                             }
 7486:                         }
 7487:                     }
 7488:                 }
 7489:             }
 7490:         }
 7491:         return 'ok';
 7492:     }
 7493:     return 'error';
 7494: }
 7495: 
 7496: sub get_query_reply {
 7497:     my $queryid=shift;
 7498:     my $replyfile=LONCAPA::tempdir().$queryid;
 7499:     my $reply='';
 7500:     for (1..100) {
 7501: 	sleep 2;
 7502:         if (-e $replyfile.'.end') {
 7503: 	    if (open(my $fh,$replyfile)) {
 7504: 		$reply = join('',<$fh>);
 7505: 		close($fh);
 7506: 	   } else { return 'error: reply_file_error'; }
 7507:            return &unescape($reply);
 7508: 	}
 7509:     }
 7510:     return 'timeout:'.$queryid;
 7511: }
 7512: 
 7513: sub courselog_query {
 7514: #
 7515: # possible filters:
 7516: # url: url or symb
 7517: # username
 7518: # domain
 7519: # action: view, submit, grade
 7520: # start: timestamp
 7521: # end: timestamp
 7522: #
 7523:     my (%filters)=@_;
 7524:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7525:     if ($filters{'url'}) {
 7526: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7527:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7528:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7529:     }
 7530:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7531:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7532:     return &log_query($cname,$cdom,'courselog',%filters);
 7533: }
 7534: 
 7535: sub userlog_query {
 7536: #
 7537: # possible filters:
 7538: # action: log check role
 7539: # start: timestamp
 7540: # end: timestamp
 7541: #
 7542:     my ($uname,$udom,%filters)=@_;
 7543:     return &log_query($uname,$udom,'userlog',%filters);
 7544: }
 7545: 
 7546: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7547: 
 7548: sub auto_run {
 7549:     my ($cnum,$cdom) = @_;
 7550:     my $response = 0;
 7551:     my $settings;
 7552:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7553:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7554:         $settings = $domconfig{'autoenroll'};
 7555:         if ($settings->{'run'} eq '1') {
 7556:             $response = 1;
 7557:         }
 7558:     } else {
 7559:         my $homeserver;
 7560:         if (&is_course($cdom,$cnum)) {
 7561:             $homeserver = &homeserver($cnum,$cdom);
 7562:         } else {
 7563:             $homeserver = &domain($cdom,'primary');
 7564:         }
 7565:         if ($homeserver ne 'no_host') {
 7566:             $response = &reply('autorun:'.$cdom,$homeserver);
 7567:         }
 7568:     }
 7569:     return $response;
 7570: }
 7571: 
 7572: sub auto_get_sections {
 7573:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7574:     my $homeserver;
 7575:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7576:         $homeserver = &homeserver($cnum,$cdom);
 7577:     }
 7578:     if (!defined($homeserver)) { 
 7579:         if ($cdom =~ /^$match_domain$/) {
 7580:             $homeserver = &domain($cdom,'primary');
 7581:         }
 7582:     }
 7583:     my @secs;
 7584:     if (defined($homeserver)) {
 7585:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7586:         unless ($response eq 'refused') {
 7587:             @secs = split(/:/,$response);
 7588:         }
 7589:     }
 7590:     return @secs;
 7591: }
 7592: 
 7593: sub auto_new_course {
 7594:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7595:     my $homeserver = &homeserver($cnum,$cdom);
 7596:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7597:     return $response;
 7598: }
 7599: 
 7600: sub auto_validate_courseID {
 7601:     my ($cnum,$cdom,$inst_course_id) = @_;
 7602:     my $homeserver = &homeserver($cnum,$cdom);
 7603:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7604:     return $response;
 7605: }
 7606: 
 7607: sub auto_validate_instcode {
 7608:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7609:     my ($homeserver,$response);
 7610:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7611:         $homeserver = &homeserver($cnum,$cdom);
 7612:     }
 7613:     if (!defined($homeserver)) {
 7614:         if ($cdom =~ /^$match_domain$/) {
 7615:             $homeserver = &domain($cdom,'primary');
 7616:         }
 7617:     }
 7618:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7619:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7620:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7621:     return ($outcome,$description,$defaultcredits);
 7622: }
 7623: 
 7624: sub auto_create_password {
 7625:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7626:     my ($homeserver,$response);
 7627:     my $create_passwd = 0;
 7628:     my $authchk = '';
 7629:     if ($udom =~ /^$match_domain$/) {
 7630:         $homeserver = &domain($udom,'primary');
 7631:     }
 7632:     if ($homeserver eq '') {
 7633:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7634:             $homeserver = &homeserver($cnum,$cdom);
 7635:         }
 7636:     }
 7637:     if ($homeserver eq '') {
 7638:         $authchk = 'nodomain';
 7639:     } else {
 7640:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7641:         if ($response eq 'refused') {
 7642:             $authchk = 'refused';
 7643:         } else {
 7644:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7645:         }
 7646:     }
 7647:     return ($authparam,$create_passwd,$authchk);
 7648: }
 7649: 
 7650: sub auto_photo_permission {
 7651:     my ($cnum,$cdom,$students) = @_;
 7652:     my $homeserver = &homeserver($cnum,$cdom);
 7653:     my ($outcome,$perm_reqd,$conditions) = 
 7654: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7655:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7656: 	return (undef,undef);
 7657:     }
 7658:     return ($outcome,$perm_reqd,$conditions);
 7659: }
 7660: 
 7661: sub auto_checkphotos {
 7662:     my ($uname,$udom,$pid) = @_;
 7663:     my $homeserver = &homeserver($uname,$udom);
 7664:     my ($result,$resulttype);
 7665:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7666: 				   &escape($uname).':'.&escape($pid),
 7667: 				   $homeserver));
 7668:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7669: 	return (undef,undef);
 7670:     }
 7671:     if ($outcome) {
 7672:         ($result,$resulttype) = split(/:/,$outcome);
 7673:     } 
 7674:     return ($result,$resulttype);
 7675: }
 7676: 
 7677: sub auto_photochoice {
 7678:     my ($cnum,$cdom) = @_;
 7679:     my $homeserver = &homeserver($cnum,$cdom);
 7680:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7681: 						       &escape($cdom),
 7682: 						       $homeserver)));
 7683:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7684: 	return (undef,undef);
 7685:     }
 7686:     return ($update,$comment);
 7687: }
 7688: 
 7689: sub auto_photoupdate {
 7690:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7691:     my $homeserver = &homeserver($cnum,$dom);
 7692:     my $host=&hostname($homeserver);
 7693:     my $cmd = '';
 7694:     my $maxtries = 1;
 7695:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7696:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7697:     }
 7698:     $cmd =~ s/%%$//;
 7699:     $cmd = &escape($cmd);
 7700:     my $query = 'institutionalphotos';
 7701:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7702:     unless ($queryid=~/^\Q$host\E\_/) {
 7703:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7704:         return 'error: '.$queryid;
 7705:     }
 7706:     my $reply = &get_query_reply($queryid);
 7707:     my $tries = 1;
 7708:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7709:         $reply = &get_query_reply($queryid);
 7710:         $tries ++;
 7711:     }
 7712:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7713:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7714:     } else {
 7715:         my @responses = split(/:/,$reply);
 7716:         my $outcome = shift(@responses); 
 7717:         foreach my $item (@responses) {
 7718:             my ($key,$value) = split(/=/,$item);
 7719:             $$photo{$key} = $value;
 7720:         }
 7721:         return $outcome;
 7722:     }
 7723:     return 'error';
 7724: }
 7725: 
 7726: sub auto_instcode_format {
 7727:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7728: 	$cat_order) = @_;
 7729:     my $courses = '';
 7730:     my @homeservers;
 7731:     if ($caller eq 'global') {
 7732: 	my %servers = &get_servers($codedom,'library');
 7733: 	foreach my $tryserver (keys(%servers)) {
 7734: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7735: 		push(@homeservers,$tryserver);
 7736: 	    }
 7737:         }
 7738:     } elsif ($caller eq 'requests') {
 7739:         if ($codedom =~ /^$match_domain$/) {
 7740:             my $chome = &domain($codedom,'primary');
 7741:             unless ($chome eq 'no_host') {
 7742:                 push(@homeservers,$chome);
 7743:             }
 7744:         }
 7745:     } else {
 7746:         push(@homeservers,&homeserver($caller,$codedom));
 7747:     }
 7748:     foreach my $code (keys(%{$instcodes})) {
 7749:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7750:     }
 7751:     chop($courses);
 7752:     my $ok_response = 0;
 7753:     my $response;
 7754:     while (@homeservers > 0 && $ok_response == 0) {
 7755:         my $server = shift(@homeservers); 
 7756:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7757:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7758:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7759: 		split(/:/,$response);
 7760:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7761:             push(@{$codetitles},&str2array($codetitles_str));
 7762:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7763:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7764:             $ok_response = 1;
 7765:         }
 7766:     }
 7767:     if ($ok_response) {
 7768:         return 'ok';
 7769:     } else {
 7770:         return $response;
 7771:     }
 7772: }
 7773: 
 7774: sub auto_instcode_defaults {
 7775:     my ($domain,$returnhash,$code_order) = @_;
 7776:     my @homeservers;
 7777: 
 7778:     my %servers = &get_servers($domain,'library');
 7779:     foreach my $tryserver (keys(%servers)) {
 7780: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7781: 	    push(@homeservers,$tryserver);
 7782: 	}
 7783:     }
 7784: 
 7785:     my $response;
 7786:     foreach my $server (@homeservers) {
 7787:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7788:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7789: 	
 7790: 	foreach my $pair (split(/\&/,$response)) {
 7791: 	    my ($name,$value)=split(/\=/,$pair);
 7792: 	    if ($name eq 'code_order') {
 7793: 		@{$code_order} = split(/\&/,&unescape($value));
 7794: 	    } else {
 7795: 		$returnhash->{&unescape($name)}=&unescape($value);
 7796: 	    }
 7797: 	}
 7798: 	return 'ok';
 7799:     }
 7800: 
 7801:     return $response;
 7802: }
 7803: 
 7804: sub auto_possible_instcodes {
 7805:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7806:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7807:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7808:         return;
 7809:     }
 7810:     my (@homeservers,$uhome);
 7811:     if (defined(&domain($domain,'primary'))) {
 7812:         $uhome=&domain($domain,'primary');
 7813:         push(@homeservers,&domain($domain,'primary'));
 7814:     } else {
 7815:         my %servers = &get_servers($domain,'library');
 7816:         foreach my $tryserver (keys(%servers)) {
 7817:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7818:                 push(@homeservers,$tryserver);
 7819:             }
 7820:         }
 7821:     }
 7822:     my $response;
 7823:     foreach my $server (@homeservers) {
 7824:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7825:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7826:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7827:             split(':',$response);
 7828:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7829:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7830:         foreach my $item (split('&',$cat_title)) {   
 7831:             my ($name,$value)=split('=',$item);
 7832:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7833:         }
 7834:         foreach my $item (split('&',$cat_order)) {
 7835:             my ($name,$value)=split('=',$item);
 7836:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7837:         }
 7838:         return 'ok';
 7839:     }
 7840:     return $response;
 7841: }
 7842: 
 7843: sub auto_courserequest_checks {
 7844:     my ($dom) = @_;
 7845:     my ($homeserver,%validations);
 7846:     if ($dom =~ /^$match_domain$/) {
 7847:         $homeserver = &domain($dom,'primary');
 7848:     }
 7849:     unless ($homeserver eq 'no_host') {
 7850:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7851:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7852:             my @items = split(/&/,$response);
 7853:             foreach my $item (@items) {
 7854:                 my ($key,$value) = split('=',$item);
 7855:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7856:             }
 7857:         }
 7858:     }
 7859:     return %validations; 
 7860: }
 7861: 
 7862: sub auto_courserequest_validation {
 7863:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 7864:     my ($homeserver,$response);
 7865:     if ($dom =~ /^$match_domain$/) {
 7866:         $homeserver = &domain($dom,'primary');
 7867:     }
 7868:     unless ($homeserver eq 'no_host') {
 7869:         my $customdata;
 7870:         if (ref($custominfo) eq 'HASH') {
 7871:             $customdata = &freeze_escape($custominfo);
 7872:         }
 7873:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7874:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7875:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 7876:                                     $customdata,$homeserver));
 7877:     }
 7878:     return $response;
 7879: }
 7880: 
 7881: sub auto_validate_class_sec {
 7882:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7883:     my $homeserver = &homeserver($cnum,$cdom);
 7884:     my $ownerlist;
 7885:     if (ref($owners) eq 'ARRAY') {
 7886:         $ownerlist = join(',',@{$owners});
 7887:     } else {
 7888:         $ownerlist = $owners;
 7889:     }
 7890:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7891:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7892:     return $response;
 7893: }
 7894: 
 7895: sub auto_crsreq_update {
 7896:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 7897:         $code,$inbound) = @_;
 7898:     my ($homeserver,%crsreqresponse);
 7899:     if ($cdom =~ /^$match_domain$/) {
 7900:         $homeserver = &domain($cdom,'primary');
 7901:     }
 7902:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 7903:         my $info;
 7904:         if (ref($inbound) eq 'HASH') {
 7905:             $info = &freeze_escape($inbound);
 7906:         }
 7907:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 7908:                             ':'.&escape($action).':'.&escape($ownername).':'.
 7909:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 7910:                             &escape($title).':'.&escape($code).':'.$info,$homeserver);
 7911:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7912:             my @items = split(/&/,$response);
 7913:             foreach my $item (@items) {
 7914:                 my ($key,$value) = split('=',$item);
 7915:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 7916:             }
 7917:         }
 7918:     }
 7919:     return \%crsreqresponse;
 7920: }
 7921: 
 7922: # ------------------------------------------------------- Course Group routines
 7923: 
 7924: sub get_coursegroups {
 7925:     my ($cdom,$cnum,$group,$namespace) = @_;
 7926:     return(&dump($namespace,$cdom,$cnum,$group));
 7927: }
 7928: 
 7929: sub modify_coursegroup {
 7930:     my ($cdom,$cnum,$groupsettings) = @_;
 7931:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7932: }
 7933: 
 7934: sub toggle_coursegroup_status {
 7935:     my ($cdom,$cnum,$group,$action) = @_;
 7936:     my ($from_namespace,$to_namespace);
 7937:     if ($action eq 'delete') {
 7938:         $from_namespace = 'coursegroups';
 7939:         $to_namespace = 'deleted_groups';
 7940:     } else {
 7941:         $from_namespace = 'deleted_groups';
 7942:         $to_namespace = 'coursegroups';
 7943:     }
 7944:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7945:     if (my $tmp = &error(%curr_group)) {
 7946:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7947:         return ('read error',$tmp);
 7948:     } else {
 7949:         my %savedsettings = %curr_group; 
 7950:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7951:         my $deloutcome;
 7952:         if ($result eq 'ok') {
 7953:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7954:         } else {
 7955:             return ('write error',$result);
 7956:         }
 7957:         if ($deloutcome eq 'ok') {
 7958:             return 'ok';
 7959:         } else {
 7960:             return ('delete error',$deloutcome);
 7961:         }
 7962:     }
 7963: }
 7964: 
 7965: sub modify_group_roles {
 7966:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7967:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7968:     my $role = 'gr/'.&escape($userprivs);
 7969:     my ($uname,$udom) = split(/:/,$user);
 7970:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7971:     if ($result eq 'ok') {
 7972:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7973:     }
 7974:     return $result;
 7975: }
 7976: 
 7977: sub modify_coursegroup_membership {
 7978:     my ($cdom,$cnum,$membership) = @_;
 7979:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7980:     return $result;
 7981: }
 7982: 
 7983: sub get_active_groups {
 7984:     my ($udom,$uname,$cdom,$cnum) = @_;
 7985:     my $now = time;
 7986:     my %groups = ();
 7987:     foreach my $key (keys(%env)) {
 7988:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7989:             my ($start,$end) = split(/\./,$env{$key});
 7990:             if (($end!=0) && ($end<$now)) { next; }
 7991:             if (($start!=0) && ($start>$now)) { next; }
 7992:             if ($1 eq $cdom && $2 eq $cnum) {
 7993:                 $groups{$3} = $env{$key} ;
 7994:             }
 7995:         }
 7996:     }
 7997:     return %groups;
 7998: }
 7999: 
 8000: sub get_group_membership {
 8001:     my ($cdom,$cnum,$group) = @_;
 8002:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8003: }
 8004: 
 8005: sub get_users_groups {
 8006:     my ($udom,$uname,$courseid) = @_;
 8007:     my @usersgroups;
 8008:     my $cachetime=1800;
 8009: 
 8010:     my $hashid="$udom:$uname:$courseid";
 8011:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8012:     if (defined($cached)) {
 8013:         @usersgroups = split(/:/,$grouplist);
 8014:     } else {  
 8015:         $grouplist = '';
 8016:         my $courseurl = &courseid_to_courseurl($courseid);
 8017:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8018:         my $access_end = $env{'course.'.$courseid.
 8019:                               '.default_enrollment_end_date'};
 8020:         my $now = time;
 8021:         foreach my $key (keys(%roleshash)) {
 8022:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8023:                 my $group = $1;
 8024:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8025:                     my $start = $2;
 8026:                     my $end = $1;
 8027:                     if ($start == -1) { next; } # deleted from group
 8028:                     if (($start!=0) && ($start>$now)) { next; }
 8029:                     if (($end!=0) && ($end<$now)) {
 8030:                         if ($access_end && $access_end < $now) {
 8031:                             if ($access_end - $end < 86400) {
 8032:                                 push(@usersgroups,$group);
 8033:                             }
 8034:                         }
 8035:                         next;
 8036:                     }
 8037:                     push(@usersgroups,$group);
 8038:                 }
 8039:             }
 8040:         }
 8041:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8042:         $grouplist = join(':',@usersgroups);
 8043:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8044:     }
 8045:     return @usersgroups;
 8046: }
 8047: 
 8048: sub devalidate_getgroups_cache {
 8049:     my ($udom,$uname,$cdom,$cnum)=@_;
 8050:     my $courseid = $cdom.'_'.$cnum;
 8051: 
 8052:     my $hashid="$udom:$uname:$courseid";
 8053:     &devalidate_cache_new('getgroups',$hashid);
 8054: }
 8055: 
 8056: # ------------------------------------------------------------------ Plain Text
 8057: 
 8058: sub plaintext {
 8059:     my ($short,$type,$cid,$forcedefault) = @_;
 8060:     if ($short =~ m{^cr/}) {
 8061: 	return (split('/',$short))[-1];
 8062:     }
 8063:     if (!defined($cid)) {
 8064:         $cid = $env{'request.course.id'};
 8065:     }
 8066:     my %rolenames = (
 8067:                       Course    => 'std',
 8068:                       Community => 'alt1',
 8069:                     );
 8070:     if ($cid ne '') {
 8071:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8072:             unless ($forcedefault) {
 8073:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8074:                 &Apache::lonlocal::mt_escape(\$roletext);
 8075:                 return &Apache::lonlocal::mt($roletext);
 8076:             }
 8077:         }
 8078:     }
 8079:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8080:         (defined($rolenames{$type})) && 
 8081:         (defined($prp{$short}{$rolenames{$type}}))) {
 8082:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8083:     } elsif ($cid ne '') {
 8084:         my $crstype = $env{'course.'.$cid.'.type'};
 8085:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8086:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8087:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8088:         }
 8089:     }
 8090:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8091: }
 8092: 
 8093: # ----------------------------------------------------------------- Assign Role
 8094: 
 8095: sub assignrole {
 8096:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8097:         $context)=@_;
 8098:     my $mrole;
 8099:     if ($role =~ /^cr\//) {
 8100:         my $cwosec=$url;
 8101:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8102: 	unless (&allowed('ccr',$cwosec)) {
 8103:            my $refused = 1;
 8104:            if ($context eq 'requestcourses') {
 8105:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8106:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8107:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8108:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8109:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8110:                            if ($crsenv{'internal.courseowner'} eq
 8111:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8112:                                $refused = '';
 8113:                            }
 8114:                        }
 8115:                    }
 8116:                }
 8117:            }
 8118:            if ($refused) {
 8119:                &logthis('Refused custom assignrole: '.
 8120:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8121:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8122:                return 'refused';
 8123:            }
 8124:         }
 8125:         $mrole='cr';
 8126:     } elsif ($role =~ /^gr\//) {
 8127:         my $cwogrp=$url;
 8128:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8129:         unless (&allowed('mdg',$cwogrp)) {
 8130:             &logthis('Refused group assignrole: '.
 8131:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8132:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8133:             return 'refused';
 8134:         }
 8135:         $mrole='gr';
 8136:     } else {
 8137:         my $cwosec=$url;
 8138:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8139:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8140:             my $refused;
 8141:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8142:                 if (!(&allowed('c'.$role,$url))) {
 8143:                     $refused = 1;
 8144:                 }
 8145:             } else {
 8146:                 $refused = 1;
 8147:             }
 8148:             if ($refused) {
 8149:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8150:                 if (!$selfenroll && $context eq 'course') {
 8151:                     my %crsenv;
 8152:                     if ($role eq 'cc' || $role eq 'co') {
 8153:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8154:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8155:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8156:                                 if ($crsenv{'internal.courseowner'} eq 
 8157:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8158:                                     $refused = '';
 8159:                                 }
 8160:                             }
 8161:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8162:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8163:                                 if ($crsenv{'internal.courseowner'} eq 
 8164:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8165:                                     $refused = '';
 8166:                                 }
 8167:                             }
 8168:                         }
 8169:                     }
 8170:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8171:                     $refused = '';
 8172:                 } elsif ($context eq 'requestcourses') {
 8173:                     my @possroles = ('st','ta','ep','in','cc','co');
 8174:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8175:                         my $wrongcc;
 8176:                         if ($cnum =~ /^$match_community$/) {
 8177:                             $wrongcc = 1 if ($role eq 'cc');
 8178:                         } else {
 8179:                             $wrongcc = 1 if ($role eq 'co');
 8180:                         }
 8181:                         unless ($wrongcc) {
 8182:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8183:                             if ($crsenv{'internal.courseowner'} eq 
 8184:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8185:                                 $refused = '';
 8186:                             }
 8187:                         }
 8188:                     }
 8189:                 } elsif ($context eq 'requestauthor') {
 8190:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8191:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8192:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8193:                             $refused = '';
 8194:                         } else {
 8195:                             my %domdefaults = &get_domain_defaults($udom);
 8196:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8197:                                 my $checkbystatus;
 8198:                                 if ($env{'user.adv'}) { 
 8199:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8200:                                     if ($disposition eq 'automatic') {
 8201:                                         $refused = '';
 8202:                                     } elsif ($disposition eq '') {
 8203:                                         $checkbystatus = 1;
 8204:                                     } 
 8205:                                 } else {
 8206:                                     $checkbystatus = 1;
 8207:                                 }
 8208:                                 if ($checkbystatus) {
 8209:                                     if ($env{'environment.inststatus'}) {
 8210:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8211:                                         foreach my $type (@inststatuses) {
 8212:                                             if (($type ne '') &&
 8213:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8214:                                                 $refused = '';
 8215:                                             }
 8216:                                         }
 8217:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8218:                                         $refused = '';
 8219:                                     }
 8220:                                 }
 8221:                             }
 8222:                         }
 8223:                     }
 8224:                 }
 8225:                 if ($refused) {
 8226:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8227:                              ' '.$role.' '.$end.' '.$start.' by '.
 8228: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8229:                     return 'refused';
 8230:                 }
 8231:             }
 8232:         } elsif ($role eq 'au') {
 8233:             if ($url ne '/'.$udom.'/') {
 8234:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8235:                          ' to assign author role for '.$uname.':'.$udom.
 8236:                          ' in domain: '.$url.' refused (wrong domain).');
 8237:                 return 'refused';
 8238:             }
 8239:         }
 8240:         $mrole=$role;
 8241:     }
 8242:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8243:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8244:     if ($end) { $command.='_'.$end; }
 8245:     if ($start) {
 8246: 	if ($end) { 
 8247:            $command.='_'.$start; 
 8248:         } else {
 8249:            $command.='_0_'.$start;
 8250:         }
 8251:     }
 8252:     my $origstart = $start;
 8253:     my $origend = $end;
 8254:     my $delflag;
 8255: # actually delete
 8256:     if ($deleteflag) {
 8257: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8258: # modify command to delete the role
 8259:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8260:                 "$udom:$uname:$url".'_'."$mrole";
 8261: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8262: # set start and finish to negative values for userrolelog
 8263:            $start=-1;
 8264:            $end=-1;
 8265:            $delflag = 1;
 8266:         }
 8267:     }
 8268: # send command
 8269:     my $answer=&reply($command,&homeserver($uname,$udom));
 8270: # log new user role if status is ok
 8271:     if ($answer eq 'ok') {
 8272: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8273:         if (($role eq 'cc') || ($role eq 'in') ||
 8274:             ($role eq 'ep') || ($role eq 'ad') ||
 8275:             ($role eq 'ta') || ($role eq 'st') ||
 8276:             ($role=~/^cr/) || ($role eq 'gr') ||
 8277:             ($role eq 'co')) {
 8278: # for course roles, perform group memberships changes triggered by role change.
 8279:             unless ($role =~ /^gr/) {
 8280:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8281:                                                  $origstart,$selfenroll,$context);
 8282:             }
 8283:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8284:                            $selfenroll,$context);
 8285:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8286:                  ($role eq 'au') || ($role eq 'dc')) {
 8287:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8288:                            $context);
 8289:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8290:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8291:                              $context); 
 8292:         }
 8293:         if ($role eq 'cc') {
 8294:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8295:         }
 8296:     }
 8297:     return $answer;
 8298: }
 8299: 
 8300: sub autoupdate_coowners {
 8301:     my ($url,$end,$start,$uname,$udom) = @_;
 8302:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8303:     if (($cdom ne '') && ($cnum ne '')) {
 8304:         my $now = time;
 8305:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8306:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8307:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8308:             my $instcode = $coursehash{'internal.coursecode'};
 8309:             if ($instcode ne '') {
 8310:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8311:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8312:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8313:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8314:                         if ($result eq 'valid') {
 8315:                             if ($coursehash{'internal.co-owners'}) {
 8316:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8317:                                     push(@newcoowners,$coowner);
 8318:                                 }
 8319:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8320:                                     push(@newcoowners,$uname.':'.$udom);
 8321:                                 }
 8322:                                 @newcoowners = sort(@newcoowners);
 8323:                             } else {
 8324:                                 push(@newcoowners,$uname.':'.$udom);
 8325:                             }
 8326:                         } else {
 8327:                             if ($coursehash{'internal.co-owners'}) {
 8328:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8329:                                     unless ($coowner eq $uname.':'.$udom) {
 8330:                                         push(@newcoowners,$coowner);
 8331:                                     }
 8332:                                 }
 8333:                                 unless (@newcoowners > 0) {
 8334:                                     $delcoowners = 1;
 8335:                                     $coowners = '';
 8336:                                 }
 8337:                             }
 8338:                         }
 8339:                         if (@newcoowners || $delcoowners) {
 8340:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8341:                                             $delcoowners,@newcoowners);
 8342:                         }
 8343:                     }
 8344:                 }
 8345:             }
 8346:         }
 8347:     }
 8348: }
 8349: 
 8350: sub store_coowners {
 8351:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8352:     my $cid = $cdom.'_'.$cnum;
 8353:     my ($coowners,$delresult,$putresult);
 8354:     if (@newcoowners) {
 8355:         $coowners = join(',',@newcoowners);
 8356:         my %coownershash = (
 8357:                             'internal.co-owners' => $coowners,
 8358:                            );
 8359:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8360:         if ($putresult eq 'ok') {
 8361:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8362:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8363:             }
 8364:         }
 8365:     }
 8366:     if ($delcoowners) {
 8367:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8368:         if ($delresult eq 'ok') {
 8369:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8370:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8371:             }
 8372:         }
 8373:     }
 8374:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8375:         my %crsinfo =
 8376:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8377:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8378:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8379:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8380:         }
 8381:     }
 8382: }
 8383: 
 8384: # -------------------------------------------------- Modify user authentication
 8385: # Overrides without validation
 8386: 
 8387: sub modifyuserauth {
 8388:     my ($udom,$uname,$umode,$upass)=@_;
 8389:     my $uhome=&homeserver($uname,$udom);
 8390:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8391:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8392:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8393:              ' in domain '.$env{'request.role.domain'});  
 8394:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8395: 		     &escape($upass),$uhome);
 8396:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8397:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8398:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8399:     &log($udom,,$uname,$uhome,
 8400:         'Authentication changed by '.$env{'user.domain'}.', '.
 8401:                                      $env{'user.name'}.', '.$umode.
 8402:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8403:     unless ($reply eq 'ok') {
 8404:         &logthis('Authentication mode error: '.$reply);
 8405: 	return 'error: '.$reply;
 8406:     }   
 8407:     return 'ok';
 8408: }
 8409: 
 8410: # --------------------------------------------------------------- Modify a user
 8411: 
 8412: sub modifyuser {
 8413:     my ($udom,    $uname, $uid,
 8414:         $umode,   $upass, $first,
 8415:         $middle,  $last,  $gene,
 8416:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8417:     $udom= &LONCAPA::clean_domain($udom);
 8418:     $uname=&LONCAPA::clean_username($uname);
 8419:     my $showcandelete = 'none';
 8420:     if (ref($candelete) eq 'ARRAY') {
 8421:         if (@{$candelete} > 0) {
 8422:             $showcandelete = join(', ',@{$candelete});
 8423:         }
 8424:     }
 8425:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8426:              $umode.', '.$first.', '.$middle.', '.
 8427: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8428:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8429:                                      ' desiredhome not specified'). 
 8430:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8431:              ' in domain '.$env{'request.role.domain'});
 8432:     my $uhome=&homeserver($uname,$udom,'true');
 8433:     my $newuser;
 8434:     if ($uhome eq 'no_host') {
 8435:         $newuser = 1;
 8436:     }
 8437: # ----------------------------------------------------------------- Create User
 8438:     if (($uhome eq 'no_host') && 
 8439: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8440:         my $unhome='';
 8441:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8442:             $unhome = $desiredhome;
 8443: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8444: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8445:         } else { # load balancing routine for determining $unhome
 8446:             my $loadm=10000000;
 8447: 	    my %servers = &get_servers($udom,'library');
 8448: 	    foreach my $tryserver (keys(%servers)) {
 8449: 		my $answer=reply('load',$tryserver);
 8450: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8451: 		    $loadm=$answer;
 8452: 		    $unhome=$tryserver;
 8453: 		}
 8454: 	    }
 8455:         }
 8456:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8457: 	    return 'error: unable to find a home server for '.$uname.
 8458:                    ' in domain '.$udom;
 8459:         }
 8460:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8461:                          &escape($upass),$unhome);
 8462: 	unless ($reply eq 'ok') {
 8463:             return 'error: '.$reply;
 8464:         }   
 8465:         $uhome=&homeserver($uname,$udom,'true');
 8466:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8467: 	    return 'error: unable verify users home machine.';
 8468:         }
 8469:     }   # End of creation of new user
 8470: # ---------------------------------------------------------------------- Add ID
 8471:     if ($uid) {
 8472:        $uid=~tr/A-Z/a-z/;
 8473:        my %uidhash=&idrget($udom,$uname);
 8474:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8475:          && (!$forceid)) {
 8476: 	  unless ($uid eq $uidhash{$uname}) {
 8477: 	      return 'error: user id "'.$uid.'" does not match '.
 8478:                   'current user id "'.$uidhash{$uname}.'".';
 8479:           }
 8480:        } else {
 8481: 	  &idput($udom,($uname => $uid));
 8482:        }
 8483:     }
 8484: # -------------------------------------------------------------- Add names, etc
 8485:     my @tmp=&get('environment',
 8486: 		   ['firstname','middlename','lastname','generation','id',
 8487:                     'permanentemail','inststatus'],
 8488: 		   $udom,$uname);
 8489:     my (%names,%oldnames);
 8490:     if ($tmp[0] =~ m/^error:.*/) { 
 8491:         %names=(); 
 8492:     } else {
 8493:         %names = @tmp;
 8494:         %oldnames = %names;
 8495:     }
 8496: #
 8497: # If name, email and/or uid are blank (e.g., because an uploaded file
 8498: # of users did not contain them), do not overwrite existing values
 8499: # unless field is in $candelete array ref.  
 8500: #
 8501: 
 8502:     my @fields = ('firstname','middlename','lastname','generation',
 8503:                   'permanentemail','id');
 8504:     my %newvalues;
 8505:     if (ref($candelete) eq 'ARRAY') {
 8506:         foreach my $field (@fields) {
 8507:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8508:                 if ($field eq 'firstname') {
 8509:                     $names{$field} = $first;
 8510:                 } elsif ($field eq 'middlename') {
 8511:                     $names{$field} = $middle;
 8512:                 } elsif ($field eq 'lastname') {
 8513:                     $names{$field} = $last;
 8514:                 } elsif ($field eq 'generation') { 
 8515:                     $names{$field} = $gene;
 8516:                 } elsif ($field eq 'permanentemail') {
 8517:                     $names{$field} = $email;
 8518:                 } elsif ($field eq 'id') {
 8519:                     $names{$field}  = $uid;
 8520:                 }
 8521:             }
 8522:         }
 8523:     }
 8524:     if ($first)  { $names{'firstname'}  = $first; }
 8525:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8526:     if ($last)   { $names{'lastname'}   = $last; }
 8527:     if (defined($gene))   { $names{'generation'} = $gene; }
 8528:     if ($email) {
 8529:        $email=~s/[^\w\@\.\-\,]//gs;
 8530:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8531:     }
 8532:     if ($uid) { $names{'id'}  = $uid; }
 8533:     if (defined($inststatus)) {
 8534:         $names{'inststatus'} = '';
 8535:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8536:         if (ref($usertypes) eq 'HASH') {
 8537:             my @okstatuses; 
 8538:             foreach my $item (split(/:/,$inststatus)) {
 8539:                 if (defined($usertypes->{$item})) {
 8540:                     push(@okstatuses,$item);  
 8541:                 }
 8542:             }
 8543:             if (@okstatuses) {
 8544:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8545:             }
 8546:         }
 8547:     }
 8548:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8549:                  $umode.', '.$first.', '.$middle.', '.
 8550:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8551:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8552:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8553:     } else {
 8554:         $logmsg .= ' during self creation';
 8555:     }
 8556:     my $changed;
 8557:     if ($newuser) {
 8558:         $changed = 1;
 8559:     } else {
 8560:         foreach my $field (@fields) {
 8561:             if ($names{$field} ne $oldnames{$field}) {
 8562:                 $changed = 1;
 8563:                 last;
 8564:             }
 8565:         }
 8566:     }
 8567:     unless ($changed) {
 8568:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8569:         &logthis($logmsg);
 8570:         return 'ok';
 8571:     }
 8572:     my $reply = &put('environment', \%names, $udom,$uname);
 8573:     if ($reply ne 'ok') { 
 8574:         return 'error: '.$reply;
 8575:     }
 8576:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8577:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8578:     }
 8579:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8580:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8581:     $logmsg = 'Success modifying user '.$logmsg;
 8582:     &logthis($logmsg);
 8583:     return 'ok';
 8584: }
 8585: 
 8586: # -------------------------------------------------------------- Modify student
 8587: 
 8588: sub modifystudent {
 8589:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8590:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8591:         $selfenroll,$context,$inststatus,$credits)=@_;
 8592:     if (!$cid) {
 8593: 	unless ($cid=$env{'request.course.id'}) {
 8594: 	    return 'not_in_class';
 8595: 	}
 8596:     }
 8597: # --------------------------------------------------------------- Make the user
 8598:     my $reply=&modifyuser
 8599: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8600:          $desiredhome,$email,$inststatus);
 8601:     unless ($reply eq 'ok') { return $reply; }
 8602:     # This will cause &modify_student_enrollment to get the uid from the
 8603:     # student's environment
 8604:     $uid = undef if (!$forceid);
 8605:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8606:                                         $gene,$usec,$end,$start,$type,$locktype,
 8607:                                         $cid,$selfenroll,$context,$credits);
 8608:     return $reply;
 8609: }
 8610: 
 8611: sub modify_student_enrollment {
 8612:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8613:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8614:     my ($cdom,$cnum,$chome);
 8615:     if (!$cid) {
 8616: 	unless ($cid=$env{'request.course.id'}) {
 8617: 	    return 'not_in_class';
 8618: 	}
 8619: 	$cdom=$env{'course.'.$cid.'.domain'};
 8620: 	$cnum=$env{'course.'.$cid.'.num'};
 8621:     } else {
 8622: 	($cdom,$cnum)=split(/_/,$cid);
 8623:     }
 8624:     $chome=$env{'course.'.$cid.'.home'};
 8625:     if (!$chome) {
 8626: 	$chome=&homeserver($cnum,$cdom);
 8627:     }
 8628:     if (!$chome) { return 'unknown_course'; }
 8629:     # Make sure the user exists
 8630:     my $uhome=&homeserver($uname,$udom);
 8631:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8632: 	return 'error: no such user';
 8633:     }
 8634:     # Get student data if we were not given enough information
 8635:     if (!defined($first)  || $first  eq '' || 
 8636:         !defined($last)   || $last   eq '' || 
 8637:         !defined($uid)    || $uid    eq '' || 
 8638:         !defined($middle) || $middle eq '' || 
 8639:         !defined($gene)   || $gene   eq '') {
 8640:         # They did not supply us with enough data to enroll the student, so
 8641:         # we need to pick up more information.
 8642:         my %tmp = &get('environment',
 8643:                        ['firstname','middlename','lastname', 'generation','id']
 8644:                        ,$udom,$uname);
 8645: 
 8646:         #foreach my $key (keys(%tmp)) {
 8647:         #    &logthis("key $key = ".$tmp{$key});
 8648:         #}
 8649:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8650:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8651:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8652:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8653:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8654:     }
 8655:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8656:     my $user = "$uname:$udom";
 8657:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8658:     my $reply=cput('classlist',
 8659: 		   {$user => 
 8660: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8661: 		   $cdom,$cnum);
 8662:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8663:         &devalidate_getsection_cache($udom,$uname,$cid);
 8664:     } else { 
 8665: 	return 'error: '.$reply;
 8666:     }
 8667:     # Add student role to user
 8668:     my $uurl='/'.$cid;
 8669:     $uurl=~s/\_/\//g;
 8670:     if ($usec) {
 8671: 	$uurl.='/'.$usec;
 8672:     }
 8673:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8674:                              $selfenroll,$context);
 8675:     if ($result ne 'ok') {
 8676:         if ($old_entry{$user} ne '') {
 8677:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8678:         } else {
 8679:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8680:         }
 8681:     }
 8682:     return $result; 
 8683: }
 8684: 
 8685: sub format_name {
 8686:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8687:     my $name;
 8688:     if ($first ne 'lastname') {
 8689: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8690:     } else {
 8691: 	if ($lastname=~/\S/) {
 8692: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8693: 	    $name=~s/\s+,/,/;
 8694: 	} else {
 8695: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8696: 	}
 8697:     }
 8698:     $name=~s/^\s+//;
 8699:     $name=~s/\s+$//;
 8700:     $name=~s/\s+/ /g;
 8701:     return $name;
 8702: }
 8703: 
 8704: # ------------------------------------------------- Write to course preferences
 8705: 
 8706: sub writecoursepref {
 8707:     my ($courseid,%prefs)=@_;
 8708:     $courseid=~s/^\///;
 8709:     $courseid=~s/\_/\//g;
 8710:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8711:     my $chome=homeserver($cnum,$cdomain);
 8712:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8713: 	return 'error: no such course';
 8714:     }
 8715:     my $cstring='';
 8716:     foreach my $pref (keys(%prefs)) {
 8717: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8718:     }
 8719:     $cstring=~s/\&$//;
 8720:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8721: }
 8722: 
 8723: # ---------------------------------------------------------- Make/modify course
 8724: 
 8725: sub createcourse {
 8726:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8727:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8728:     $url=&declutter($url);
 8729:     my $cid='';
 8730:     if ($context eq 'requestcourses') {
 8731:         my $can_create = 0;
 8732:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8733:         if ($udom eq $ownerdom) {
 8734:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8735:                                   $context)) {
 8736:                 $can_create = 1;
 8737:             }
 8738:         } else {
 8739:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8740:                                            $category);
 8741:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8742:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8743:                 if (@curr > 0) {
 8744:                     my @options = qw(approval validate autolimit);
 8745:                     my $optregex = join('|',@options);
 8746:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8747:                         $can_create = 1;
 8748:                     }
 8749:                 }
 8750:             }
 8751:         }
 8752:         if ($can_create) {
 8753:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8754:                 unless (&allowed('ccc',$udom)) {
 8755:                     return 'refused'; 
 8756:                 }
 8757:             }
 8758:         } else {
 8759:             return 'refused';
 8760:         }
 8761:     } elsif (!&allowed('ccc',$udom)) {
 8762:         return 'refused';
 8763:     }
 8764: # --------------------------------------------------------------- Get Unique ID
 8765:     my $uname;
 8766:     if ($cnum =~ /^$match_courseid$/) {
 8767:         my $chome=&homeserver($cnum,$udom,'true');
 8768:         if (($chome eq '') || ($chome eq 'no_host')) {
 8769:             $uname = $cnum;
 8770:         } else {
 8771:             $uname = &generate_coursenum($udom,$crstype);
 8772:         }
 8773:     } else {
 8774:         $uname = &generate_coursenum($udom,$crstype);
 8775:     }
 8776:     return $uname if ($uname =~ /^error/);
 8777: # -------------------------------------------------- Check supplied server name
 8778:     if (!defined($course_server)) {
 8779:         if (defined(&domain($udom,'primary'))) {
 8780:             $course_server = &domain($udom,'primary');
 8781:         } else {
 8782:             $course_server = $env{'user.home'}; 
 8783:         }
 8784:     }
 8785:     my %host_servers =
 8786:         &Apache::lonnet::get_servers($udom,'library');
 8787:     unless ($host_servers{$course_server}) {
 8788:         return 'error: invalid home server for course: '.$course_server;
 8789:     }
 8790: # ------------------------------------------------------------- Make the course
 8791:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8792:                       $course_server);
 8793:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8794:     my $uhome=&homeserver($uname,$udom,'true');
 8795:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8796: 	return 'error: no such course';
 8797:     }
 8798: # ----------------------------------------------------------------- Course made
 8799: # log existence
 8800:     my $now = time;
 8801:     my $newcourse = {
 8802:                     $udom.'_'.$uname => {
 8803:                                      description => $description,
 8804:                                      inst_code   => $inst_code,
 8805:                                      owner       => $course_owner,
 8806:                                      type        => $crstype,
 8807:                                      creator     => $env{'user.name'}.':'.
 8808:                                                     $env{'user.domain'},
 8809:                                      created     => $now,
 8810:                                      context     => $context,
 8811:                                                 },
 8812:                     };
 8813:     &courseidput($udom,$newcourse,$uhome,'notime');
 8814: # set toplevel url
 8815:     my $topurl=$url;
 8816:     unless ($nonstandard) {
 8817: # ------------------------------------------ For standard courses, make top url
 8818:         my $mapurl=&clutter($url);
 8819:         if ($mapurl eq '/res/') { $mapurl=''; }
 8820:         $env{'form.initmap'}=(<<ENDINITMAP);
 8821: <map>
 8822: <resource id="1" type="start"></resource>
 8823: <resource id="2" src="$mapurl"></resource>
 8824: <resource id="3" type="finish"></resource>
 8825: <link index="1" from="1" to="2"></link>
 8826: <link index="2" from="2" to="3"></link>
 8827: </map>
 8828: ENDINITMAP
 8829:         $topurl=&declutter(
 8830:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8831:                           );
 8832:     }
 8833: # ----------------------------------------------------------- Write preferences
 8834:     &writecoursepref($udom.'_'.$uname,
 8835:                      ('description'              => $description,
 8836:                       'url'                      => $topurl,
 8837:                       'internal.creator'         => $env{'user.name'}.':'.
 8838:                                                     $env{'user.domain'},
 8839:                       'internal.created'         => $now,
 8840:                       'internal.creationcontext' => $context)
 8841:                     );
 8842:     return '/'.$udom.'/'.$uname;
 8843: }
 8844: 
 8845: # ------------------------------------------------------------------- Create ID
 8846: sub generate_coursenum {
 8847:     my ($udom,$crstype) = @_;
 8848:     my $domdesc = &domain($udom);
 8849:     return 'error: invalid domain' if ($domdesc eq '');
 8850:     my $first;
 8851:     if ($crstype eq 'Community') {
 8852:         $first = '0';
 8853:     } else {
 8854:         $first = int(1+rand(9)); 
 8855:     } 
 8856:     my $uname=$first.
 8857:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8858:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8859:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8860: # ----------------------------------------------- Make sure that does not exist
 8861:     my $uhome=&homeserver($uname,$udom,'true');
 8862:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8863:         if ($crstype eq 'Community') {
 8864:             $first = '0';
 8865:         } else {
 8866:             $first = int(1+rand(9));
 8867:         }
 8868:         $uname=$first.
 8869:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8870:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8871:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8872:         $uhome=&homeserver($uname,$udom,'true');
 8873:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8874:             return 'error: unable to generate unique course-ID';
 8875:         }
 8876:     }
 8877:     return $uname;
 8878: }
 8879: 
 8880: sub is_course {
 8881:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8882:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8883: 
 8884:     return unless $cdom and $cnum;
 8885: 
 8886:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8887:         '.');
 8888: 
 8889:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8890:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8891: }
 8892: 
 8893: sub store_userdata {
 8894:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8895:     my $result;
 8896:     if ($datakey ne '') {
 8897:         if (ref($storehash) eq 'HASH') {
 8898:             if ($udom eq '' || $uname eq '') {
 8899:                 $udom = $env{'user.domain'};
 8900:                 $uname = $env{'user.name'};
 8901:             }
 8902:             my $uhome=&homeserver($uname,$udom);
 8903:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8904:                 $result = 'error: no_host';
 8905:             } else {
 8906:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8907:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8908: 
 8909:                 my $namevalue='';
 8910:                 foreach my $key (keys(%{$storehash})) {
 8911:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8912:                 }
 8913:                 $namevalue=~s/\&$//;
 8914:                 unless ($namespace eq 'courserequests') {
 8915:                     $datakey = &escape($datakey);
 8916:                 }
 8917:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8918:                                   $namevalue,$uhome);
 8919:             }
 8920:         } else {
 8921:             $result = 'error: data to store was not a hash reference'; 
 8922:         }
 8923:     } else {
 8924:         $result= 'error: invalid requestkey'; 
 8925:     }
 8926:     return $result;
 8927: }
 8928: 
 8929: # ---------------------------------------------------------- Assign Custom Role
 8930: 
 8931: sub assigncustomrole {
 8932:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8933:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8934:                        $end,$start,$deleteflag,$selfenroll,$context);
 8935: }
 8936: 
 8937: # ----------------------------------------------------------------- Revoke Role
 8938: 
 8939: sub revokerole {
 8940:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8941:     my $now=time;
 8942:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8943: }
 8944: 
 8945: # ---------------------------------------------------------- Revoke Custom Role
 8946: 
 8947: sub revokecustomrole {
 8948:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8949:     my $now=time;
 8950:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8951:            $deleteflag,$selfenroll,$context);
 8952: }
 8953: 
 8954: # ------------------------------------------------------------ Disk usage
 8955: sub diskusage {
 8956:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8957:     $directorypath =~ s/\/$//;
 8958:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8959:                        .&escape($getpropath).':'.&escape($uname).':'
 8960:                        .&escape($udom),homeserver($uname,$udom));
 8961:     if ($listing eq 'unknown_cmd') {
 8962:         if ($getpropath) {
 8963:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8964:         }
 8965:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8966:     }
 8967:     return $listing;
 8968: }
 8969: 
 8970: sub is_locked {
 8971:     my ($file_name, $domain, $user, $which) = @_;
 8972:     my @check;
 8973:     my $is_locked;
 8974:     push (@check,$file_name);
 8975:     my %locked = &get('file_permissions',\@check,
 8976: 		      $env{'user.domain'},$env{'user.name'});
 8977:     my ($tmp)=keys(%locked);
 8978:     if ($tmp=~/^error:/) { undef(%locked); }
 8979:     
 8980:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8981:         $is_locked = 'false';
 8982:         foreach my $entry (@{$locked{$file_name}}) {
 8983:            if (ref($entry) eq 'ARRAY') {
 8984:                $is_locked = 'true';
 8985:                if (ref($which) eq 'ARRAY') {
 8986:                    push(@{$which},$entry);
 8987:                } else {
 8988:                    last;
 8989:                }
 8990:            }
 8991:        }
 8992:     } else {
 8993:         $is_locked = 'false';
 8994:     }
 8995:     return $is_locked;
 8996: }
 8997: 
 8998: sub declutter_portfile {
 8999:     my ($file) = @_;
 9000:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9001:     return $file;
 9002: }
 9003: 
 9004: # ------------------------------------------------------------- Mark as Read Only
 9005: 
 9006: sub mark_as_readonly {
 9007:     my ($domain,$user,$files,$what) = @_;
 9008:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9009:     my ($tmp)=keys(%current_permissions);
 9010:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9011:     foreach my $file (@{$files}) {
 9012: 	$file = &declutter_portfile($file);
 9013:         push(@{$current_permissions{$file}},$what);
 9014:     }
 9015:     &put('file_permissions',\%current_permissions,$domain,$user);
 9016:     return;
 9017: }
 9018: 
 9019: # ------------------------------------------------------------Save Selected Files
 9020: 
 9021: sub save_selected_files {
 9022:     my ($user, $path, @files) = @_;
 9023:     my $filename = $user."savedfiles";
 9024:     my @other_files = &files_not_in_path($user, $path);
 9025:     open (OUT, '>'.$tmpdir.$filename);
 9026:     foreach my $file (@files) {
 9027:         print (OUT $env{'form.currentpath'}.$file."\n");
 9028:     }
 9029:     foreach my $file (@other_files) {
 9030:         print (OUT $file."\n");
 9031:     }
 9032:     close (OUT);
 9033:     return 'ok';
 9034: }
 9035: 
 9036: sub clear_selected_files {
 9037:     my ($user) = @_;
 9038:     my $filename = $user."savedfiles";
 9039:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9040:     print (OUT undef);
 9041:     close (OUT);
 9042:     return ("ok");    
 9043: }
 9044: 
 9045: sub files_in_path {
 9046:     my ($user, $path) = @_;
 9047:     my $filename = $user."savedfiles";
 9048:     my %return_files;
 9049:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9050:     while (my $line_in = <IN>) {
 9051:         chomp ($line_in);
 9052:         my @paths_and_file = split (m!/!, $line_in);
 9053:         my $file_part = pop (@paths_and_file);
 9054:         my $path_part = join ('/', @paths_and_file);
 9055:         $path_part.='/';
 9056:         my $path_and_file = $path_part.$file_part;
 9057:         if ($path_part eq $path) {
 9058:             $return_files{$file_part}= 'selected';
 9059:         }
 9060:     }
 9061:     close (IN);
 9062:     return (\%return_files);
 9063: }
 9064: 
 9065: # called in portfolio select mode, to show files selected NOT in current directory
 9066: sub files_not_in_path {
 9067:     my ($user, $path) = @_;
 9068:     my $filename = $user."savedfiles";
 9069:     my @return_files;
 9070:     my $path_part;
 9071:     open(IN, '<'.LONCAPA::.$filename);
 9072:     while (my $line = <IN>) {
 9073:         #ok, I know it's clunky, but I want it to work
 9074:         my @paths_and_file = split(m|/|, $line);
 9075:         my $file_part = pop(@paths_and_file);
 9076:         chomp($file_part);
 9077:         my $path_part = join('/', @paths_and_file);
 9078:         $path_part .= '/';
 9079:         my $path_and_file = $path_part.$file_part;
 9080:         if ($path_part ne $path) {
 9081:             push(@return_files, ($path_and_file));
 9082:         }
 9083:     }
 9084:     close(OUT);
 9085:     return (@return_files);
 9086: }
 9087: 
 9088: #----------------------------------------------Get portfolio file permissions
 9089: 
 9090: sub get_portfile_permissions {
 9091:     my ($domain,$user) = @_;
 9092:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9093:     my ($tmp)=keys(%current_permissions);
 9094:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9095:     return \%current_permissions;
 9096: }
 9097: 
 9098: #---------------------------------------------Get portfolio file access controls
 9099: 
 9100: sub get_access_controls {
 9101:     my ($current_permissions,$group,$file) = @_;
 9102:     my %access;
 9103:     my $real_file = $file;
 9104:     $file =~ s/\.meta$//;
 9105:     if (defined($file)) {
 9106:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9107:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9108:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9109:             }
 9110:         }
 9111:     } else {
 9112:         foreach my $key (keys(%{$current_permissions})) {
 9113:             if ($key =~ /\0accesscontrol$/) {
 9114:                 if (defined($group)) {
 9115:                     if ($key !~ m-^\Q$group\E/-) {
 9116:                         next;
 9117:                     }
 9118:                 }
 9119:                 my ($fullpath) = split(/\0/,$key);
 9120:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9121:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9122:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9123:                     }
 9124:                 }
 9125:             }
 9126:         }
 9127:     }
 9128:     return %access;
 9129: }
 9130: 
 9131: sub modify_access_controls {
 9132:     my ($file_name,$changes,$domain,$user)=@_;
 9133:     my ($outcome,$deloutcome);
 9134:     my %store_permissions;
 9135:     my %new_values;
 9136:     my %new_control;
 9137:     my %translation;
 9138:     my @deletions = ();
 9139:     my $now = time;
 9140:     if (exists($$changes{'activate'})) {
 9141:         if (ref($$changes{'activate'}) eq 'HASH') {
 9142:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9143:             my $numnew = scalar(@newitems);
 9144:             for (my $i=0; $i<$numnew; $i++) {
 9145:                 my $newkey = $newitems[$i];
 9146:                 my $newid = &Apache::loncommon::get_cgi_id();
 9147:                 if ($newkey =~ /^\d+:/) { 
 9148:                     $newkey =~ s/^(\d+)/$newid/;
 9149:                     $translation{$1} = $newid;
 9150:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9151:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9152:                     $translation{$1} = $newid;
 9153:                 }
 9154:                 $new_values{$file_name."\0".$newkey} = 
 9155:                                           $$changes{'activate'}{$newitems[$i]};
 9156:                 $new_control{$newkey} = $now;
 9157:             }
 9158:         }
 9159:     }
 9160:     my %todelete;
 9161:     my %changed_items;
 9162:     foreach my $action ('delete','update') {
 9163:         if (exists($$changes{$action})) {
 9164:             if (ref($$changes{$action}) eq 'HASH') {
 9165:                 foreach my $key (keys(%{$$changes{$action}})) {
 9166:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9167:                     if ($action eq 'delete') { 
 9168:                         $todelete{$itemnum} = 1;
 9169:                     } else {
 9170:                         $changed_items{$itemnum} = $key;
 9171:                     }
 9172:                 }
 9173:             }
 9174:         }
 9175:     }
 9176:     # get lock on access controls for file.
 9177:     my $lockhash = {
 9178:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9179:                                                        ':'.$env{'user.domain'},
 9180:                    }; 
 9181:     my $tries = 0;
 9182:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9183:    
 9184:     while (($gotlock ne 'ok') && $tries <3) {
 9185:         $tries ++;
 9186:         sleep 1;
 9187:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9188:     }
 9189:     if ($gotlock eq 'ok') {
 9190:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9191:         my ($tmp)=keys(%curr_permissions);
 9192:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9193:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9194:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9195:             if (ref($curr_controls) eq 'HASH') {
 9196:                 foreach my $control_item (keys(%{$curr_controls})) {
 9197:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9198:                     if (defined($todelete{$itemnum})) {
 9199:                         push(@deletions,$file_name."\0".$control_item);
 9200:                     } else {
 9201:                         if (defined($changed_items{$itemnum})) {
 9202:                             $new_control{$changed_items{$itemnum}} = $now;
 9203:                             push(@deletions,$file_name."\0".$control_item);
 9204:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9205:                         } else {
 9206:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9207:                         }
 9208:                     }
 9209:                 }
 9210:             }
 9211:         }
 9212:         my ($group);
 9213:         if (&is_course($domain,$user)) {
 9214:             ($group,my $file) = split(/\//,$file_name,2);
 9215:         }
 9216:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9217:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9218:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9219:         #  remove lock
 9220:         my @del_lock = ($file_name."\0".'locked_access_records');
 9221:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9222:         my $sqlresult =
 9223:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9224:                                     $group);
 9225:     } else {
 9226:         $outcome = "error: could not obtain lockfile\n";  
 9227:     }
 9228:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9229: }
 9230: 
 9231: sub make_public_indefinitely {
 9232:     my ($requrl) = @_;
 9233:     my $now = time;
 9234:     my $action = 'activate';
 9235:     my $aclnum = 0;
 9236:     if (&is_portfolio_url($requrl)) {
 9237:         my (undef,$udom,$unum,$file_name,$group) =
 9238:             &parse_portfolio_url($requrl);
 9239:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9240:         my %access_controls = &get_access_controls($current_perms,
 9241:                                                    $group,$file_name);
 9242:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9243:             my ($num,$scope,$end,$start) = 
 9244:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9245:             if ($scope eq 'public') {
 9246:                 if ($start <= $now && $end == 0) {
 9247:                     $action = 'none';
 9248:                 } else {
 9249:                     $action = 'update';
 9250:                     $aclnum = $num;
 9251:                 }
 9252:                 last;
 9253:             }
 9254:         }
 9255:         if ($action eq 'none') {
 9256:              return 'ok';
 9257:         } else {
 9258:             my %changes;
 9259:             my $newend = 0;
 9260:             my $newstart = $now;
 9261:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9262:             $changes{$action}{$newkey} = {
 9263:                 type => 'public',
 9264:                 time => {
 9265:                     start => $newstart,
 9266:                     end   => $newend,
 9267:                 },
 9268:             };
 9269:             my ($outcome,$deloutcome,$new_values,$translation) =
 9270:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9271:             return $outcome;
 9272:         }
 9273:     } else {
 9274:         return 'invalid';
 9275:     }
 9276: }
 9277: 
 9278: #------------------------------------------------------Get Marked as Read Only
 9279: 
 9280: sub get_marked_as_readonly {
 9281:     my ($domain,$user,$what,$group) = @_;
 9282:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9283:     my @readonly_files;
 9284:     my $cmp1=$what;
 9285:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9286:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9287:         if (defined($group)) {
 9288:             if ($file_name !~ m-^\Q$group\E/-) {
 9289:                 next;
 9290:             }
 9291:         }
 9292:         if (ref($value) eq "ARRAY"){
 9293:             foreach my $stored_what (@{$value}) {
 9294:                 my $cmp2=$stored_what;
 9295:                 if (ref($stored_what) eq 'ARRAY') {
 9296:                     $cmp2=join('',@{$stored_what});
 9297:                 }
 9298:                 if ($cmp1 eq $cmp2) {
 9299:                     push(@readonly_files, $file_name);
 9300:                     last;
 9301:                 } elsif (!defined($what)) {
 9302:                     push(@readonly_files, $file_name);
 9303:                     last;
 9304:                 }
 9305:             }
 9306:         }
 9307:     }
 9308:     return @readonly_files;
 9309: }
 9310: #-----------------------------------------------------------Get Marked as Read Only Hash
 9311: 
 9312: sub get_marked_as_readonly_hash {
 9313:     my ($current_permissions,$group,$what) = @_;
 9314:     my %readonly_files;
 9315:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9316:         if (defined($group)) {
 9317:             if ($file_name !~ m-^\Q$group\E/-) {
 9318:                 next;
 9319:             }
 9320:         }
 9321:         if (ref($value) eq "ARRAY"){
 9322:             foreach my $stored_what (@{$value}) {
 9323:                 if (ref($stored_what) eq 'ARRAY') {
 9324:                     foreach my $lock_descriptor(@{$stored_what}) {
 9325:                         if ($lock_descriptor eq 'graded') {
 9326:                             $readonly_files{$file_name} = 'graded';
 9327:                         } elsif ($lock_descriptor eq 'handback') {
 9328:                             $readonly_files{$file_name} = 'handback';
 9329:                         } else {
 9330:                             if (!exists($readonly_files{$file_name})) {
 9331:                                 $readonly_files{$file_name} = 'locked';
 9332:                             }
 9333:                         }
 9334:                     }
 9335:                 } 
 9336:             }
 9337:         } 
 9338:     }
 9339:     return %readonly_files;
 9340: }
 9341: # ------------------------------------------------------------ Unmark as Read Only
 9342: 
 9343: sub unmark_as_readonly {
 9344:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9345:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9346:     my ($domain,$user,$what,$file_name,$group) = @_;
 9347:     $file_name = &declutter_portfile($file_name);
 9348:     my $symb_crs = $what;
 9349:     if (ref($what)) { $symb_crs=join('',@$what); }
 9350:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9351:     my ($tmp)=keys(%current_permissions);
 9352:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9353:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9354:     foreach my $file (@readonly_files) {
 9355: 	my $clean_file = &declutter_portfile($file);
 9356: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9357: 	my $current_locks = $current_permissions{$file};
 9358:         my @new_locks;
 9359:         my @del_keys;
 9360:         if (ref($current_locks) eq "ARRAY"){
 9361:             foreach my $locker (@{$current_locks}) {
 9362:                 my $compare=$locker;
 9363:                 if (ref($locker) eq 'ARRAY') {
 9364:                     $compare=join('',@{$locker});
 9365:                     if ($compare ne $symb_crs) {
 9366:                         push(@new_locks, $locker);
 9367:                     }
 9368:                 }
 9369:             }
 9370:             if (scalar(@new_locks) > 0) {
 9371:                 $current_permissions{$file} = \@new_locks;
 9372:             } else {
 9373:                 push(@del_keys, $file);
 9374:                 &del('file_permissions',\@del_keys, $domain, $user);
 9375:                 delete($current_permissions{$file});
 9376:             }
 9377:         }
 9378:     }
 9379:     &put('file_permissions',\%current_permissions,$domain,$user);
 9380:     return;
 9381: }
 9382: 
 9383: # ------------------------------------------------------------ Directory lister
 9384: 
 9385: sub dirlist {
 9386:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9387:     $uri=~s/^\///;
 9388:     $uri=~s/\/$//;
 9389:     my ($udom, $uname);
 9390:     if ($getuserdir) {
 9391:         $udom = $userdomain;
 9392:         $uname = $username;
 9393:     } else {
 9394:         (undef,$udom,$uname)=split(/\//,$uri);
 9395:         if(defined($userdomain)) {
 9396:             $udom = $userdomain;
 9397:         }
 9398:         if(defined($username)) {
 9399:             $uname = $username;
 9400:         }
 9401:     }
 9402:     my ($dirRoot,$listing,@listing_results);
 9403: 
 9404:     $dirRoot = $perlvar{'lonDocRoot'};
 9405:     if (defined($getpropath)) {
 9406:         $dirRoot = &propath($udom,$uname);
 9407:         $dirRoot =~ s/\/$//;
 9408:     } elsif (defined($getuserdir)) {
 9409:         my $subdir=$uname.'__';
 9410:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9411:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9412:                    ."/$udom/$subdir/$uname";
 9413:     } elsif (defined($alternateRoot)) {
 9414:         $dirRoot = $alternateRoot;
 9415:     }
 9416: 
 9417:     if($udom) {
 9418:         if($uname) {
 9419:             my $uhome = &homeserver($uname,$udom);
 9420:             if ($uhome eq 'no_host') {
 9421:                 return ([],'no_host');
 9422:             }
 9423:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9424:                               .$getuserdir.':'.&escape($dirRoot)
 9425:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9426:             if ($listing eq 'unknown_cmd') {
 9427:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9428:             } else {
 9429:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9430:             }
 9431:             if ($listing eq 'unknown_cmd') {
 9432:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9433:                 @listing_results = split(/:/,$listing);
 9434:             } else {
 9435:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9436:             }
 9437:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9438:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9439:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9440:                 return ([],$listing);
 9441:             } else {
 9442:                 return (\@listing_results);
 9443:             }
 9444:         } elsif(!$alternateRoot) {
 9445:             my (%allusers,%listerror);
 9446: 	    my %servers = &get_servers($udom,'library');
 9447:  	    foreach my $tryserver (keys(%servers)) {
 9448:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9449:                                   &escape($udom),$tryserver);
 9450:                 if ($listing eq 'unknown_cmd') {
 9451: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9452: 				      $udom, $tryserver);
 9453:                 } else {
 9454:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9455:                 }
 9456: 		if ($listing eq 'unknown_cmd') {
 9457: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9458: 				      $udom, $tryserver);
 9459: 		    @listing_results = split(/:/,$listing);
 9460: 		} else {
 9461: 		    @listing_results =
 9462: 			map { &unescape($_); } split(/:/,$listing);
 9463: 		}
 9464:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9465:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9466:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9467:                     $listerror{$tryserver} = $listing;
 9468:                 } else {
 9469: 		    foreach my $line (@listing_results) {
 9470: 			my ($entry) = split(/&/,$line,2);
 9471: 			$allusers{$entry} = 1;
 9472: 		    }
 9473: 		}
 9474:             }
 9475:             my @alluserslist=();
 9476:             foreach my $user (sort(keys(%allusers))) {
 9477:                 push(@alluserslist,$user.'&user');
 9478:             }
 9479:             return (\@alluserslist);
 9480:         } else {
 9481:             return ([],'missing username');
 9482:         }
 9483:     } elsif(!defined($getpropath)) {
 9484:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9485:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9486:         return (\@all_domains);
 9487:     } else {
 9488:         return ([],'missing domain');
 9489:     }
 9490: }
 9491: 
 9492: # --------------------------------------------- GetFileTimestamp
 9493: # This function utilizes dirlist and returns the date stamp for
 9494: # when it was last modified.  It will also return an error of -1
 9495: # if an error occurs
 9496: 
 9497: sub GetFileTimestamp {
 9498:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9499:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9500:     $studentName   = &LONCAPA::clean_username($studentName);
 9501:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9502:                                     undef,$getuserdir);
 9503:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9504:         return -1;
 9505:     }
 9506:     if (ref($fileref) eq 'ARRAY') {
 9507:         my @stats = split('&',$fileref->[0]);
 9508:         # @stats contains first the filename, then the stat output
 9509:         return $stats[10]; # so this is 10 instead of 9.
 9510:     } else {
 9511:         return -1;
 9512:     }
 9513: }
 9514: 
 9515: sub stat_file {
 9516:     my ($uri) = @_;
 9517:     $uri = &clutter_with_no_wrapper($uri);
 9518: 
 9519:     my ($udom,$uname,$file);
 9520:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9521: 	($udom,$uname,$file) =
 9522: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9523: 	$file = 'userfiles/'.$file;
 9524:     }
 9525:     if ($uri =~ m-^/res/-) {
 9526: 	($udom,$uname) = 
 9527: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9528: 	$file = $uri;
 9529:     }
 9530: 
 9531:     if (!$udom || !$uname || !$file) {
 9532: 	# unable to handle the uri
 9533: 	return ();
 9534:     }
 9535:     my $getpropath;
 9536:     if ($file =~ /^userfiles\//) {
 9537:         $getpropath = 1;
 9538:     }
 9539:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9540:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9541:         return ();
 9542:     } else {
 9543:         if (ref($listref) eq 'ARRAY') {
 9544:             my @stats = split('&',$listref->[0]);
 9545: 	    shift(@stats); #filename is first
 9546: 	    return @stats;
 9547:         }
 9548:     }
 9549:     return ();
 9550: }
 9551: 
 9552: # -------------------------------------------------------- Value of a Condition
 9553: 
 9554: # gets the value of a specific preevaluated condition
 9555: #    stored in the string  $env{user.state.<cid>}
 9556: # or looks up a condition reference in the bighash and if if hasn't
 9557: # already been evaluated recurses into docondval to get the value of
 9558: # the condition, then memoizing it to 
 9559: #   $env{user.state.<cid>.<condition>}
 9560: sub directcondval {
 9561:     my $number=shift;
 9562:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9563: 	&Apache::lonuserstate::evalstate();
 9564:     }
 9565:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9566: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9567:     } elsif ($number =~ /^_/) {
 9568: 	my $sub_condition;
 9569: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9570: 		&GDBM_READER(),0640)) {
 9571: 	    $sub_condition=$bighash{'conditions'.$number};
 9572: 	    untie(%bighash);
 9573: 	}
 9574: 	my $value = &docondval($sub_condition);
 9575: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9576: 	return $value;
 9577:     }
 9578:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9579:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9580:     } else {
 9581:        return 2;
 9582:     }
 9583: }
 9584: 
 9585: # get the collection of conditions for this resource
 9586: sub condval {
 9587:     my $condidx=shift;
 9588:     my $allpathcond='';
 9589:     foreach my $cond (split(/\|/,$condidx)) {
 9590: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9591: 	    $allpathcond.=
 9592: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9593: 	}
 9594:     }
 9595:     $allpathcond=~s/\|$//;
 9596:     return &docondval($allpathcond);
 9597: }
 9598: 
 9599: #evaluates an expression of conditions
 9600: sub docondval {
 9601:     my ($allpathcond) = @_;
 9602:     my $result=0;
 9603:     if ($env{'request.course.id'}
 9604: 	&& defined($allpathcond)) {
 9605: 	my $operand='|';
 9606: 	my @stack;
 9607: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9608: 	    if ($chunk eq '(') {
 9609: 		push @stack,($operand,$result);
 9610: 	    } elsif ($chunk eq ')') {
 9611: 		my $before=pop @stack;
 9612: 		if (pop @stack eq '&') {
 9613: 		    $result=$result>$before?$before:$result;
 9614: 		} else {
 9615: 		    $result=$result>$before?$result:$before;
 9616: 		}
 9617: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9618: 		$operand=$chunk;
 9619: 	    } else {
 9620: 		my $new=directcondval($chunk);
 9621: 		if ($operand eq '&') {
 9622: 		    $result=$result>$new?$new:$result;
 9623: 		} else {
 9624: 		    $result=$result>$new?$result:$new;
 9625: 		}
 9626: 	    }
 9627: 	}
 9628:     }
 9629:     return $result;
 9630: }
 9631: 
 9632: # ---------------------------------------------------- Devalidate courseresdata
 9633: 
 9634: sub devalidatecourseresdata {
 9635:     my ($coursenum,$coursedomain)=@_;
 9636:     my $hashid=$coursenum.':'.$coursedomain;
 9637:     &devalidate_cache_new('courseres',$hashid);
 9638: }
 9639: 
 9640: 
 9641: # --------------------------------------------------- Course Resourcedata Query
 9642: #
 9643: #  Parameters:
 9644: #      $coursenum    - Number of the course.
 9645: #      $coursedomain - Domain at which the course was created.
 9646: #  Returns:
 9647: #     A hash of the course parameters along (I think) with timestamps
 9648: #     and version info.
 9649: 
 9650: sub get_courseresdata {
 9651:     my ($coursenum,$coursedomain)=@_;
 9652:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9653:     my $hashid=$coursenum.':'.$coursedomain;
 9654:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9655:     my %dumpreply;
 9656:     unless (defined($cached)) {
 9657: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9658: 	$result=\%dumpreply;
 9659: 	my ($tmp) = keys(%dumpreply);
 9660: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9661: 	    &do_cache_new('courseres',$hashid,$result,600);
 9662: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9663: 	    return $tmp;
 9664: 	} elsif ($tmp =~ /^(error)/) {
 9665: 	    $result=undef;
 9666: 	    &do_cache_new('courseres',$hashid,$result,600);
 9667: 	}
 9668:     }
 9669:     return $result;
 9670: }
 9671: 
 9672: sub devalidateuserresdata {
 9673:     my ($uname,$udom)=@_;
 9674:     my $hashid="$udom:$uname";
 9675:     &devalidate_cache_new('userres',$hashid);
 9676: }
 9677: 
 9678: sub get_userresdata {
 9679:     my ($uname,$udom)=@_;
 9680:     #most student don\'t have any data set, check if there is some data
 9681:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9682: 
 9683:     my $hashid="$udom:$uname";
 9684:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9685:     if (!defined($cached)) {
 9686: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9687: 	$result=\%resourcedata;
 9688: 	&do_cache_new('userres',$hashid,$result,600);
 9689:     }
 9690:     my ($tmp)=keys(%$result);
 9691:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9692: 	return $result;
 9693:     }
 9694:     #error 2 occurs when the .db doesn't exist
 9695:     if ($tmp!~/error: 2 /) {
 9696: 	&logthis("<font color=\"blue\">WARNING:".
 9697: 		 " Trying to get resource data for ".
 9698: 		 $uname." at ".$udom.": ".
 9699: 		 $tmp."</font>");
 9700:     } elsif ($tmp=~/error: 2 /) {
 9701: 	#&EXT_cache_set($udom,$uname);
 9702: 	&do_cache_new('userres',$hashid,undef,600);
 9703: 	undef($tmp); # not really an error so don't send it back
 9704:     }
 9705:     return $tmp;
 9706: }
 9707: #----------------------------------------------- resdata - return resource data
 9708: #  Purpose:
 9709: #    Return resource data for either users or for a course.
 9710: #  Parameters:
 9711: #     $name      - Course/user name.
 9712: #     $domain    - Name of the domain the user/course is registered on.
 9713: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9714: #     @which     - Array of names of resources desired.
 9715: #  Returns:
 9716: #     The value of the first reasource in @which that is found in the
 9717: #     resource hash.
 9718: #  Exceptional Conditions:
 9719: #     If the $type passed in is not valid (not the string 'course' or 
 9720: #     'user', an undefined  reference is returned.
 9721: #     If none of the resources are found, an undef is returned
 9722: sub resdata {
 9723:     my ($name,$domain,$type,@which)=@_;
 9724:     my $result;
 9725:     if ($type eq 'course') {
 9726: 	$result=&get_courseresdata($name,$domain);
 9727:     } elsif ($type eq 'user') {
 9728: 	$result=&get_userresdata($name,$domain);
 9729:     }
 9730:     if (!ref($result)) { return $result; }    
 9731:     foreach my $item (@which) {
 9732: 	if (defined($result->{$item->[0]})) {
 9733: 	    return [$result->{$item->[0]},$item->[1]];
 9734: 	}
 9735:     }
 9736:     return undef;
 9737: }
 9738: 
 9739: sub get_numsuppfiles {
 9740:     my ($cnum,$cdom,$ignorecache)=@_;
 9741:     my $hashid=$cnum.':'.$cdom;
 9742:     my ($suppcount,$cached);
 9743:     unless ($ignorecache) {
 9744:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9745:     }
 9746:     unless (defined($cached)) {
 9747:         my $chome=&homeserver($cnum,$cdom);
 9748:         unless ($chome eq 'no_host') {
 9749:             ($suppcount,my $errors) = (0,0);
 9750:             my $suppmap = 'supplemental.sequence';
 9751:             ($suppcount,$errors) = 
 9752:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9753:         }
 9754:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9755:     }
 9756:     return $suppcount;
 9757: }
 9758: 
 9759: #
 9760: # EXT resource caching routines
 9761: #
 9762: 
 9763: sub clear_EXT_cache_status {
 9764:     &delenv('cache.EXT.');
 9765: }
 9766: 
 9767: sub EXT_cache_status {
 9768:     my ($target_domain,$target_user) = @_;
 9769:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9770:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9771:         # We know already the user has no data
 9772:         return 1;
 9773:     } else {
 9774:         return 0;
 9775:     }
 9776: }
 9777: 
 9778: sub EXT_cache_set {
 9779:     my ($target_domain,$target_user) = @_;
 9780:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9781:     #&appenv({$cachename => time});
 9782: }
 9783: 
 9784: # --------------------------------------------------------- Value of a Variable
 9785: sub EXT {
 9786: 
 9787:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9788:     unless ($varname) { return ''; }
 9789:     #get real user name/domain, courseid and symb
 9790:     my $courseid;
 9791:     my $publicuser;
 9792:     if ($symbparm) {
 9793: 	$symbparm=&get_symb_from_alias($symbparm);
 9794:     }
 9795:     if (!($uname && $udom)) {
 9796:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9797:       if (!$symbparm) {	$symbparm=$cursymb; }
 9798:     } else {
 9799: 	$courseid=$env{'request.course.id'};
 9800:     }
 9801:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9802:     my $rest;
 9803:     if (defined($therest[0])) {
 9804:        $rest=join('.',@therest);
 9805:     } else {
 9806:        $rest='';
 9807:     }
 9808: 
 9809:     my $qualifierrest=$qualifier;
 9810:     if ($rest) { $qualifierrest.='.'.$rest; }
 9811:     my $spacequalifierrest=$space;
 9812:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9813:     if ($realm eq 'user') {
 9814: # --------------------------------------------------------------- user.resource
 9815: 	if ($space eq 'resource') {
 9816: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9817: 		  || defined($Apache::lonhomework::parsing_a_task))
 9818: 		 &&
 9819: 		 ($symbparm eq &symbread()) ) {	
 9820: 		# if we are in the middle of processing the resource the
 9821: 		# get the value we are planning on committing
 9822:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9823:                     return $Apache::lonhomework::results{$qualifierrest};
 9824:                 } else {
 9825:                     return $Apache::lonhomework::history{$qualifierrest};
 9826:                 }
 9827: 	    } else {
 9828: 		my %restored;
 9829: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9830: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9831: 		} else {
 9832: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9833: 		}
 9834: 		return $restored{$qualifierrest};
 9835: 	    }
 9836: # ----------------------------------------------------------------- user.access
 9837:         } elsif ($space eq 'access') {
 9838: 	    # FIXME - not supporting calls for a specific user
 9839:             return &allowed($qualifier,$rest);
 9840: # ------------------------------------------ user.preferences, user.environment
 9841:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9842: 	    if (($uname eq $env{'user.name'}) &&
 9843: 		($udom eq $env{'user.domain'})) {
 9844: 		return $env{join('.',('environment',$qualifierrest))};
 9845: 	    } else {
 9846: 		my %returnhash;
 9847: 		if (!$publicuser) {
 9848: 		    %returnhash=&userenvironment($udom,$uname,
 9849: 						 $qualifierrest);
 9850: 		}
 9851: 		return $returnhash{$qualifierrest};
 9852: 	    }
 9853: # ----------------------------------------------------------------- user.course
 9854:         } elsif ($space eq 'course') {
 9855: 	    # FIXME - not supporting calls for a specific user
 9856:             return $env{join('.',('request.course',$qualifier))};
 9857: # ------------------------------------------------------------------- user.role
 9858:         } elsif ($space eq 'role') {
 9859: 	    # FIXME - not supporting calls for a specific user
 9860:             my ($role,$where)=split(/\./,$env{'request.role'});
 9861:             if ($qualifier eq 'value') {
 9862: 		return $role;
 9863:             } elsif ($qualifier eq 'extent') {
 9864:                 return $where;
 9865:             }
 9866: # ----------------------------------------------------------------- user.domain
 9867:         } elsif ($space eq 'domain') {
 9868:             return $udom;
 9869: # ------------------------------------------------------------------- user.name
 9870:         } elsif ($space eq 'name') {
 9871:             return $uname;
 9872: # ---------------------------------------------------- Any other user namespace
 9873:         } else {
 9874: 	    my %reply;
 9875: 	    if (!$publicuser) {
 9876: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9877: 	    }
 9878: 	    return $reply{$qualifierrest};
 9879:         }
 9880:     } elsif ($realm eq 'query') {
 9881: # ---------------------------------------------- pull stuff out of query string
 9882:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9883: 						[$spacequalifierrest]);
 9884: 	return $env{'form.'.$spacequalifierrest}; 
 9885:    } elsif ($realm eq 'request') {
 9886: # ------------------------------------------------------------- request.browser
 9887:         if ($space eq 'browser') {
 9888:             return $env{'browser.'.$qualifier};
 9889: # ------------------------------------------------------------ request.filename
 9890:         } else {
 9891:             return $env{'request.'.$spacequalifierrest};
 9892:         }
 9893:     } elsif ($realm eq 'course') {
 9894: # ---------------------------------------------------------- course.description
 9895:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9896:     } elsif ($realm eq 'resource') {
 9897: 
 9898: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9899: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9900: 	}
 9901: 
 9902:         if ($qualifier eq '') {
 9903: 	    if ($space eq 'title') {
 9904: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9905: 	        return &gettitle($symbparm);
 9906: 	    }
 9907: 	
 9908: 	    if ($space eq 'map') {
 9909: 	        my ($map) = &decode_symb($symbparm);
 9910: 	        return &symbread($map);
 9911: 	    }
 9912:             if ($space eq 'maptitle') {
 9913:                 my ($map) = &decode_symb($symbparm);
 9914:                 return &gettitle($map);
 9915:             }
 9916: 	    if ($space eq 'filename') {
 9917: 	        if ($symbparm) {
 9918: 		    return &clutter((&decode_symb($symbparm))[2]);
 9919: 	        }
 9920: 	        return &hreflocation('',$env{'request.filename'});
 9921: 	    }
 9922: 
 9923:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9924:                 if ($space eq 'visibleparts') {
 9925:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9926:                     my $item;
 9927:                     if (ref($navmap)) {
 9928:                         my $res = $navmap->getBySymb($symbparm);
 9929:                         my $parts = $res->parts();
 9930:                         if (ref($parts) eq 'ARRAY') {
 9931:                             $item = join(',',@{$parts});
 9932:                         }
 9933:                         undef($navmap);
 9934:                     }
 9935:                     return $item;
 9936:                 }
 9937:             }
 9938:         }
 9939: 
 9940: 	my ($section, $group, @groups);
 9941: 	my ($courselevelm,$courselevel);
 9942:         if (($courseid eq '') && ($cid)) {
 9943:             $courseid = $cid;
 9944:         }
 9945: 	if (($symbparm && $courseid) && 
 9946: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9947: 
 9948: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9949: 
 9950: # ----------------------------------------------------- Cascading lookup scheme
 9951: 	    my $symbp=$symbparm;
 9952: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9953: 
 9954: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9955: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9956: 
 9957: 	    if (($env{'user.name'} eq $uname) &&
 9958: 		($env{'user.domain'} eq $udom)) {
 9959: 		$section=$env{'request.course.sec'};
 9960:                 @groups = split(/:/,$env{'request.course.groups'});  
 9961:                 @groups=&sort_course_groups($courseid,@groups); 
 9962: 	    } else {
 9963: 		if (! defined($usection)) {
 9964: 		    $section=&getsection($udom,$uname,$courseid);
 9965: 		} else {
 9966: 		    $section = $usection;
 9967: 		}
 9968:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9969: 	    }
 9970: 
 9971: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9972: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9973: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9974: 
 9975: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9976: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9977: 	    $courselevelm=$courseid.'.'.$mapparm;
 9978: 
 9979: # ----------------------------------------------------------- first, check user
 9980: 
 9981: 	    my $userreply=&resdata($uname,$udom,'user',
 9982: 				       ([$courselevelr,'resource'],
 9983: 					[$courselevelm,'map'     ],
 9984: 					[$courselevel, 'course'  ]));
 9985: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9986: 
 9987: # ------------------------------------------------ second, check some of course
 9988:             my $coursereply;
 9989:             if (@groups > 0) {
 9990:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9991:                                        $mapparm,$spacequalifierrest);
 9992:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9993:             }
 9994: 
 9995: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9996: 				  $env{'course.'.$courseid.'.domain'},
 9997: 				  'course',
 9998: 				  ([$seclevelr,   'resource'],
 9999: 				   [$seclevelm,   'map'     ],
10000: 				   [$seclevel,    'course'  ],
10001: 				   [$courselevelr,'resource']));
10002: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10003: 
10004: # ------------------------------------------------------ third, check map parms
10005: 	    my %parmhash=();
10006: 	    my $thisparm='';
10007: 	    if (tie(%parmhash,'GDBM_File',
10008: 		    $env{'request.course.fn'}.'_parms.db',
10009: 		    &GDBM_READER(),0640)) {
10010: 		$thisparm=$parmhash{$symbparm};
10011: 		untie(%parmhash);
10012: 	    }
10013: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10014: 	}
10015: # ------------------------------------------ fourth, look in resource metadata
10016: 
10017: 	$spacequalifierrest=~s/\./\_/;
10018: 	my $filename;
10019: 	if (!$symbparm) { $symbparm=&symbread(); }
10020: 	if ($symbparm) {
10021: 	    $filename=(&decode_symb($symbparm))[2];
10022: 	} else {
10023: 	    $filename=$env{'request.filename'};
10024: 	}
10025: 	my $metadata=&metadata($filename,$spacequalifierrest);
10026: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10027: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10028: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10029: 
10030: # ---------------------------------------------- fourth, look in rest of course
10031: 	if ($symbparm && defined($courseid) && 
10032: 	    $courseid eq $env{'request.course.id'}) {
10033: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10034: 				     $env{'course.'.$courseid.'.domain'},
10035: 				     'course',
10036: 				     ([$courselevelm,'map'   ],
10037: 				      [$courselevel, 'course']));
10038: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10039: 	}
10040: # ------------------------------------------------------------------ Cascade up
10041: 	unless ($space eq '0') {
10042: 	    my @parts=split(/_/,$space);
10043: 	    my $id=pop(@parts);
10044: 	    my $part=join('_',@parts);
10045: 	    if ($part eq '') { $part='0'; }
10046: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10047: 				 $symbparm,$udom,$uname,$section,1);
10048: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10049: 	}
10050: 	if ($recurse) { return undef; }
10051: 	my $pack_def=&packages_tab_default($filename,$varname);
10052: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10053: # ---------------------------------------------------- Any other user namespace
10054:     } elsif ($realm eq 'environment') {
10055: # ----------------------------------------------------------------- environment
10056: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10057: 	    return $env{'environment.'.$spacequalifierrest};
10058: 	} else {
10059: 	    if ($uname eq 'anonymous' && $udom eq '') {
10060: 		return '';
10061: 	    }
10062: 	    my %returnhash=&userenvironment($udom,$uname,
10063: 					    $spacequalifierrest);
10064: 	    return $returnhash{$spacequalifierrest};
10065: 	}
10066:     } elsif ($realm eq 'system') {
10067: # ----------------------------------------------------------------- system.time
10068: 	if ($space eq 'time') {
10069: 	    return time;
10070:         }
10071:     } elsif ($realm eq 'server') {
10072: # ----------------------------------------------------------------- system.time
10073: 	if ($space eq 'name') {
10074: 	    return $ENV{'SERVER_NAME'};
10075:         }
10076:     }
10077:     return '';
10078: }
10079: 
10080: sub get_reply {
10081:     my ($reply_value) = @_;
10082:     if (ref($reply_value) eq 'ARRAY') {
10083:         if (wantarray) {
10084: 	    return @$reply_value;
10085:         }
10086:         return $reply_value->[0];
10087:     } else {
10088:         return $reply_value;
10089:     }
10090: }
10091: 
10092: sub check_group_parms {
10093:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10094:     my @groupitems = ();
10095:     my $resultitem;
10096:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10097:     foreach my $group (@{$groups}) {
10098:         foreach my $level (@levels) {
10099:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10100:              push(@groupitems,[$item,$level->[1]]);
10101:         }
10102:     }
10103:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10104:                             $env{'course.'.$courseid.'.domain'},
10105:                                      'course',@groupitems);
10106:     return $coursereply;
10107: }
10108: 
10109: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10110:     my ($courseid,@groups) = @_;
10111:     @groups = sort(@groups);
10112:     return @groups;
10113: }
10114: 
10115: sub packages_tab_default {
10116:     my ($uri,$varname)=@_;
10117:     my (undef,$part,$name)=split(/\./,$varname);
10118: 
10119:     my (@extension,@specifics,$do_default);
10120:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10121: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10122: 	if ($pack_type eq 'default') {
10123: 	    $do_default=1;
10124: 	} elsif ($pack_type eq 'extension') {
10125: 	    push(@extension,[$package,$pack_type,$pack_part]);
10126: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10127: 	    # only look at packages defaults for packages that this id is
10128: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10129: 	}
10130:     }
10131:     # first look for a package that matches the requested part id
10132:     foreach my $package (@specifics) {
10133: 	my (undef,$pack_type,$pack_part)=@{$package};
10134: 	next if ($pack_part ne $part);
10135: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10136: 	    return $packagetab{"$pack_type&$name&default"};
10137: 	}
10138:     }
10139:     # look for any possible matching non extension_ package
10140:     foreach my $package (@specifics) {
10141: 	my (undef,$pack_type,$pack_part)=@{$package};
10142: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10143: 	    return $packagetab{"$pack_type&$name&default"};
10144: 	}
10145: 	if ($pack_type eq 'part') { $pack_part='0'; }
10146: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10147: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10148: 	}
10149:     }
10150:     # look for any posible extension_ match
10151:     foreach my $package (@extension) {
10152: 	my ($package,$pack_type)=@{$package};
10153: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10154: 	    return $packagetab{"$pack_type&$name&default"};
10155: 	}
10156: 	if (defined($packagetab{$package."&$name&default"})) {
10157: 	    return $packagetab{$package."&$name&default"};
10158: 	}
10159:     }
10160:     # look for a global default setting
10161:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10162: 	return $packagetab{"default&$name&default"};
10163:     }
10164:     return undef;
10165: }
10166: 
10167: sub add_prefix_and_part {
10168:     my ($prefix,$part)=@_;
10169:     my $keyroot;
10170:     if (defined($prefix) && $prefix !~ /^__/) {
10171: 	# prefix that has a part already
10172: 	$keyroot=$prefix;
10173:     } elsif (defined($prefix)) {
10174: 	# prefix that is missing a part
10175: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10176:     } else {
10177: 	# no prefix at all
10178: 	if (defined($part)) { $keyroot='_'.$part; }
10179:     }
10180:     return $keyroot;
10181: }
10182: 
10183: # ---------------------------------------------------------------- Get metadata
10184: 
10185: my %metaentry;
10186: my %importedpartids;
10187: sub metadata {
10188:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10189:     $uri=&declutter($uri);
10190:     # if it is a non metadata possible uri return quickly
10191:     if (($uri eq '') || 
10192: 	(($uri =~ m|^/*adm/|) && 
10193: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10194:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10195: 	return undef;
10196:     }
10197:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10198: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10199: 	return undef;
10200:     }
10201:     my $filename=$uri;
10202:     $uri=~s/\.meta$//;
10203: #
10204: # Is the metadata already cached?
10205: # Look at timestamp of caching
10206: # Everything is cached by the main uri, libraries are never directly cached
10207: #
10208:     if (!defined($liburi)) {
10209: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10210: 	if (defined($cached)) { return $result->{':'.$what}; }
10211:     }
10212:     {
10213: # Imported parts would go here
10214:         my %importedids=();
10215:         my @origfileimportpartids=();
10216:         my $importedparts=0;
10217: #
10218: # Is this a recursive call for a library?
10219: #
10220: #	if (! exists($metacache{$uri})) {
10221: #	    $metacache{$uri}={};
10222: #	}
10223: 	my $cachetime = 60*60;
10224:         if ($liburi) {
10225: 	    $liburi=&declutter($liburi);
10226:             $filename=$liburi;
10227:         } else {
10228: 	    &devalidate_cache_new('meta',$uri);
10229: 	    undef(%metaentry);
10230: 	}
10231:         my %metathesekeys=();
10232:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10233: 	my $metastring;
10234: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10235: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10236: 	    $metastring = 
10237: 		&Apache::lonnet::ssi_body($which,
10238: 					  ('grade_target' => 'meta'));
10239: 	    $cachetime = 1; # only want this cached in the child not long term
10240: 	} elsif (($uri !~ m -^(editupload)/-) && 
10241:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10242: 	    my $file=&filelocation('',&clutter($filename));
10243: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10244: 	    $metastring=&getfile($file);
10245: 	}
10246:         my $parser=HTML::LCParser->new(\$metastring);
10247:         my $token;
10248:         undef %metathesekeys;
10249:         while ($token=$parser->get_token) {
10250: 	    if ($token->[0] eq 'S') {
10251: 		if (defined($token->[2]->{'package'})) {
10252: #
10253: # This is a package - get package info
10254: #
10255: 		    my $package=$token->[2]->{'package'};
10256: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10257: 		    if (defined($token->[2]->{'id'})) { 
10258: 			$keyroot.='_'.$token->[2]->{'id'}; 
10259: 		    }
10260: 		    if ($metaentry{':packages'}) {
10261: 			$metaentry{':packages'}.=','.$package.$keyroot;
10262: 		    } else {
10263: 			$metaentry{':packages'}=$package.$keyroot;
10264: 		    }
10265: 		    foreach my $pack_entry (keys(%packagetab)) {
10266: 			my $part=$keyroot;
10267: 			$part=~s/^\_//;
10268: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10269: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10270: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10271: 			    # ignore package.tab specified default values
10272:                             # here &package_tab_default() will fetch those
10273: 			    if ($subp eq 'default') { next; }
10274: 			    my $value=$packagetab{$pack_entry};
10275: 			    my $unikey;
10276: 			    if ($pack =~ /_0$/) {
10277: 				$unikey='parameter_0_'.$name;
10278: 				$part=0;
10279: 			    } else {
10280: 				$unikey='parameter'.$keyroot.'_'.$name;
10281: 			    }
10282: 			    if ($subp eq 'display') {
10283: 				$value.=' [Part: '.$part.']';
10284: 			    }
10285: 			    $metaentry{':'.$unikey.'.part'}=$part;
10286: 			    $metathesekeys{$unikey}=1;
10287: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10288: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10289: 			    }
10290: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10291: 				$metaentry{':'.$unikey}=
10292: 				    $metaentry{':'.$unikey.'.default'};
10293: 			    }
10294: 			}
10295: 		    }
10296: 		} else {
10297: #
10298: # This is not a package - some other kind of start tag
10299: #
10300: 		    my $entry=$token->[1];
10301: 		    my $unikey='';
10302: 
10303: 		    if ($entry eq 'import') {
10304: #
10305: # Importing a library here
10306: #
10307:                         my $location=$parser->get_text('/import');
10308:                         my $dir=$filename;
10309:                         $dir=~s|[^/]*$||;
10310:                         $location=&filelocation($dir,$location);
10311:                        
10312:                         my $importmode=$token->[2]->{'importmode'};
10313:                         if ($importmode eq 'problem') {
10314: # Import as problem/response
10315:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10316:                         } elsif ($importmode eq 'part') {
10317: # Import as part(s)
10318:                            $importedparts=1;
10319: # We need to get the original file and the imported file to get the part order correct
10320: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10321: # Load and inspect original file
10322:                            if ($#origfileimportpartids<0) {
10323:                               undef(%importedpartids);
10324:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10325:                               my $origfile=&getfile($origfilelocation);
10326:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10327:                            }
10328: 
10329: # Load and inspect imported file
10330:                            my $impfile=&getfile($location);
10331:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10332:                            if ($#impfilepartids>=0) {
10333: # This problem had parts
10334:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10335:                            } else {
10336: # Importing by turning a single problem into a problem part
10337: # It gets the import-tags ID as part-ID
10338:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10339:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10340:                            }
10341:                         } else {
10342: # Normal import
10343:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10344:                            if (defined($token->[2]->{'id'})) {
10345:                               $unikey.='_'.$token->[2]->{'id'};
10346:                            }
10347:                         }
10348: 
10349: 			if ($depthcount<20) {
10350: 			    my $metadata = 
10351: 				&metadata($uri,'keys', $location,$unikey,
10352: 					  $depthcount+1);
10353: 			    foreach my $meta (split(',',$metadata)) {
10354: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10355: 				$metathesekeys{$meta}=1;
10356: 			    }
10357: 			
10358:                         }
10359: 		    } else {
10360: #
10361: # Not importing, some other kind of non-package, non-library start tag
10362: # 
10363:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10364:                         if (defined($token->[2]->{'id'})) {
10365:                             $unikey.='_'.$token->[2]->{'id'};
10366:                         }
10367: 			if (defined($token->[2]->{'name'})) { 
10368: 			    $unikey.='_'.$token->[2]->{'name'}; 
10369: 			}
10370: 			$metathesekeys{$unikey}=1;
10371: 			foreach my $param (@{$token->[3]}) {
10372: 			    $metaentry{':'.$unikey.'.'.$param} =
10373: 				$token->[2]->{$param};
10374: 			}
10375: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10376: 			my $default=$metaentry{':'.$unikey.'.default'};
10377: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10378: 		 # only ws inside the tag, and not in default, so use default
10379: 		 # as value
10380: 			    $metaentry{':'.$unikey}=$default;
10381: 			} elsif ( $internaltext =~ /\S/ ) {
10382: 		  # something interesting inside the tag
10383: 			    $metaentry{':'.$unikey}=$internaltext;
10384: 			} else {
10385: 		  # no interesting values, don't set a default
10386: 			}
10387: # end of not-a-package not-a-library import
10388: 		    }
10389: # end of not-a-package start tag
10390: 		}
10391: # the next is the end of "start tag"
10392: 	    }
10393: 	}
10394: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10395: 	$extension = lc($extension);
10396: 	if ($extension eq 'htm') { $extension='html'; }
10397: 
10398: 	foreach my $key (keys(%packagetab)) {
10399: 	    #no specific packages #how's our extension
10400: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10401: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10402: 					 \%metathesekeys);
10403: 	}
10404: 
10405: 	if (!exists($metaentry{':packages'})
10406: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10407: 	    foreach my $key (keys(%packagetab)) {
10408: 		#no specific packages well let's get default then
10409: 		if ($key!~/^default&/) { next; }
10410: 		&metadata_create_package_def($uri,$key,'default',
10411: 					     \%metathesekeys);
10412: 	    }
10413: 	}
10414: # are there custom rights to evaluate
10415: 	if ($metaentry{':copyright'} eq 'custom') {
10416: 
10417:     #
10418:     # Importing a rights file here
10419:     #
10420: 	    unless ($depthcount) {
10421: 		my $location=$metaentry{':customdistributionfile'};
10422: 		my $dir=$filename;
10423: 		$dir=~s|[^/]*$||;
10424: 		$location=&filelocation($dir,$location);
10425: 		my $rights_metadata =
10426: 		    &metadata($uri,'keys',$location,'_rights',
10427: 			      $depthcount+1);
10428: 		foreach my $rights (split(',',$rights_metadata)) {
10429: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10430: 		    $metathesekeys{$rights}=1;
10431: 		}
10432: 	    }
10433: 	}
10434: 	# uniqifiy package listing
10435: 	my %seen;
10436: 	my @uniq_packages =
10437: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10438: 	$metaentry{':packages'} = join(',',@uniq_packages);
10439: 
10440:         if ($importedparts) {
10441: # We had imported parts and need to rebuild partorder
10442:            $metaentry{':partorder'}='';
10443:            $metathesekeys{'partorder'}=1;
10444:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10445:                if ($origfileimportpartids[$index] eq 'part') {
10446: # original part, part of the problem
10447:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10448:                } else {
10449: # we have imported parts at this position
10450:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10451:                }
10452:            }
10453:            $metaentry{':partorder'}=~s/^\,//;
10454:         }
10455: 
10456: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10457: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10458: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10459: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10460: # this is the end of "was not already recently cached
10461:     }
10462:     return $metaentry{':'.$what};
10463: }
10464: 
10465: sub metadata_create_package_def {
10466:     my ($uri,$key,$package,$metathesekeys)=@_;
10467:     my ($pack,$name,$subp)=split(/\&/,$key);
10468:     if ($subp eq 'default') { next; }
10469:     
10470:     if (defined($metaentry{':packages'})) {
10471: 	$metaentry{':packages'}.=','.$package;
10472:     } else {
10473: 	$metaentry{':packages'}=$package;
10474:     }
10475:     my $value=$packagetab{$key};
10476:     my $unikey;
10477:     $unikey='parameter_0_'.$name;
10478:     $metaentry{':'.$unikey.'.part'}=0;
10479:     $$metathesekeys{$unikey}=1;
10480:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10481: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10482:     }
10483:     if (defined($metaentry{':'.$unikey.'.default'})) {
10484: 	$metaentry{':'.$unikey}=
10485: 	    $metaentry{':'.$unikey.'.default'};
10486:     }
10487: }
10488: 
10489: sub metadata_generate_part0 {
10490:     my ($metadata,$metacache,$uri) = @_;
10491:     my %allnames;
10492:     foreach my $metakey (keys(%$metadata)) {
10493: 	if ($metakey=~/^parameter\_(.*)/) {
10494: 	  my $part=$$metacache{':'.$metakey.'.part'};
10495: 	  my $name=$$metacache{':'.$metakey.'.name'};
10496: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10497: 	    $allnames{$name}=$part;
10498: 	  }
10499: 	}
10500:     }
10501:     foreach my $name (keys(%allnames)) {
10502:       $$metadata{"parameter_0_$name"}=1;
10503:       my $key=":parameter_0_$name";
10504:       $$metacache{"$key.part"}='0';
10505:       $$metacache{"$key.name"}=$name;
10506:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10507: 					   $allnames{$name}.'_'.$name.
10508: 					   '.type'};
10509:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10510: 			     '.display'};
10511:       my $expr='[Part: '.$allnames{$name}.']';
10512:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10513:       $$metacache{"$key.display"}=$olddis;
10514:     }
10515: }
10516: 
10517: # ------------------------------------------------------ Devalidate title cache
10518: 
10519: sub devalidate_title_cache {
10520:     my ($url)=@_;
10521:     if (!$env{'request.course.id'}) { return; }
10522:     my $symb=&symbread($url);
10523:     if (!$symb) { return; }
10524:     my $key=$env{'request.course.id'}."\0".$symb;
10525:     &devalidate_cache_new('title',$key);
10526: }
10527: 
10528: # ------------------------------------------------- Get the title of a course
10529: 
10530: sub current_course_title {
10531:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10532: }
10533: # ------------------------------------------------- Get the title of a resource
10534: 
10535: sub gettitle {
10536:     my $urlsymb=shift;
10537:     my $symb=&symbread($urlsymb);
10538:     if ($symb) {
10539: 	my $key=$env{'request.course.id'}."\0".$symb;
10540: 	my ($result,$cached)=&is_cached_new('title',$key);
10541: 	if (defined($cached)) { 
10542: 	    return $result;
10543: 	}
10544: 	my ($map,$resid,$url)=&decode_symb($symb);
10545: 	my $title='';
10546: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10547: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10548: 	} else {
10549: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10550: 		    &GDBM_READER(),0640)) {
10551: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10552: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10553: 		untie(%bighash);
10554: 	    }
10555: 	}
10556: 	$title=~s/\&colon\;/\:/gs;
10557: 	if ($title) {
10558: # Remember both $symb and $title for dynamic metadata
10559:             $accesshash{$symb.'___crstitle'}=$title;
10560:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10561: # Cache this title and then return it
10562: 	    return &do_cache_new('title',$key,$title,600);
10563: 	}
10564: 	$urlsymb=$url;
10565:     }
10566:     my $title=&metadata($urlsymb,'title');
10567:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10568:     return $title;
10569: }
10570: 
10571: sub get_slot {
10572:     my ($which,$cnum,$cdom)=@_;
10573:     if (!$cnum || !$cdom) {
10574: 	(undef,my $courseid)=&whichuser();
10575: 	$cdom=$env{'course.'.$courseid.'.domain'};
10576: 	$cnum=$env{'course.'.$courseid.'.num'};
10577:     }
10578:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10579:     my %slotinfo;
10580:     if (exists($remembered{$key})) {
10581: 	$slotinfo{$which} = $remembered{$key};
10582:     } else {
10583: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10584: 	&Apache::lonhomework::showhash(%slotinfo);
10585: 	my ($tmp)=keys(%slotinfo);
10586: 	if ($tmp=~/^error:/) { return (); }
10587: 	$remembered{$key} = $slotinfo{$which};
10588:     }
10589:     if (ref($slotinfo{$which}) eq 'HASH') {
10590: 	return %{$slotinfo{$which}};
10591:     }
10592:     return $slotinfo{$which};
10593: }
10594: 
10595: sub get_reservable_slots {
10596:     my ($cnum,$cdom,$uname,$udom) = @_;
10597:     my $now = time;
10598:     my $reservable_info;
10599:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10600:     if (exists($remembered{$key})) {
10601:         $reservable_info = $remembered{$key};
10602:     } else {
10603:         my %resv;
10604:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10605:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10606:         $reservable_info = \%resv;
10607:         $remembered{$key} = $reservable_info;
10608:     }
10609:     return $reservable_info;
10610: }
10611: 
10612: sub get_course_slots {
10613:     my ($cnum,$cdom) = @_;
10614:     my $hashid=$cnum.':'.$cdom;
10615:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10616:     if (defined($cached)) {
10617:         if (ref($result) eq 'HASH') {
10618:             return %{$result};
10619:         }
10620:     } else {
10621:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10622:         my ($tmp) = keys(%slots);
10623:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10624:             &do_cache_new('allslots',$hashid,\%slots,600);
10625:             return %slots;
10626:         }
10627:     }
10628:     return;
10629: }
10630: 
10631: sub devalidate_slots_cache {
10632:     my ($cnum,$cdom)=@_;
10633:     my $hashid=$cnum.':'.$cdom;
10634:     &devalidate_cache_new('allslots',$hashid);
10635: }
10636: 
10637: sub get_coursechange {
10638:     my ($cdom,$cnum) = @_;
10639:     if ($cdom eq '' || $cnum eq '') {
10640:         return unless ($env{'request.course.id'});
10641:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10642:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10643:     }
10644:     my $hashid=$cdom.'_'.$cnum;
10645:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10646:     if ((defined($cached)) && ($change ne '')) {
10647:         return $change;
10648:     } else {
10649:         my %crshash;
10650:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10651:         if ($crshash{'internal.contentchange'} eq '') {
10652:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10653:             if ($change eq '') {
10654:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10655:                 $change = $crshash{'internal.created'};
10656:             }
10657:         } else {
10658:             $change = $crshash{'internal.contentchange'};
10659:         }
10660:         my $cachetime = 600;
10661:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10662:     }
10663:     return $change;
10664: }
10665: 
10666: sub devalidate_coursechange_cache {
10667:     my ($cnum,$cdom)=@_;
10668:     my $hashid=$cnum.':'.$cdom;
10669:     &devalidate_cache_new('crschange',$hashid);
10670: }
10671: 
10672: # ------------------------------------------------- Update symbolic store links
10673: 
10674: sub symblist {
10675:     my ($mapname,%newhash)=@_;
10676:     $mapname=&deversion(&declutter($mapname));
10677:     my %hash;
10678:     if (($env{'request.course.fn'}) && (%newhash)) {
10679:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10680:                       &GDBM_WRCREAT(),0640)) {
10681: 	    foreach my $url (keys(%newhash)) {
10682: 		next if ($url eq 'last_known'
10683: 			 && $env{'form.no_update_last_known'});
10684: 		$hash{declutter($url)}=&encode_symb($mapname,
10685: 						    $newhash{$url}->[1],
10686: 						    $newhash{$url}->[0]);
10687:             }
10688:             if (untie(%hash)) {
10689: 		return 'ok';
10690:             }
10691:         }
10692:     }
10693:     return 'error';
10694: }
10695: 
10696: # --------------------------------------------------------------- Verify a symb
10697: 
10698: sub symbverify {
10699:     my ($symb,$thisurl,$encstate)=@_;
10700:     my $thisfn=$thisurl;
10701:     $thisfn=&declutter($thisfn);
10702: # direct jump to resource in page or to a sequence - will construct own symbs
10703:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10704: # check URL part
10705:     my ($map,$resid,$url)=&decode_symb($symb);
10706: 
10707:     unless ($url eq $thisfn) { return 0; }
10708: 
10709:     $symb=&symbclean($symb);
10710:     $thisurl=&deversion($thisurl);
10711:     $thisfn=&deversion($thisfn);
10712: 
10713:     my %bighash;
10714:     my $okay=0;
10715: 
10716:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10717:                             &GDBM_READER(),0640)) {
10718:         my $noclutter;
10719:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10720:             $thisurl =~ s/\?.+$//;
10721:             if ($map =~ m{^uploaded/.+\.page$}) {
10722:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10723:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10724:                 $noclutter = 1;
10725:             }
10726:         }
10727:         my $ids;
10728:         if ($noclutter) {
10729:             $ids=$bighash{'ids_'.$thisurl};
10730:         } else {
10731:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10732:         }
10733:         unless ($ids) {
10734:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10735:             $ids=$bighash{$idkey};
10736:         }
10737:         if ($ids) {
10738: # ------------------------------------------------------------------- Has ID(s)
10739:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10740:                 $symb =~ s/\?.+$//;
10741:             }
10742: 	    foreach my $id (split(/\,/,$ids)) {
10743: 	       my ($mapid,$resid)=split(/\./,$id);
10744:                if (
10745:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10746:    eq $symb) {
10747:                    if (ref($encstate)) {
10748:                        $$encstate = $bighash{'encrypted_'.$id};
10749:                    }
10750: 		   if (($env{'request.role.adv'}) ||
10751: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10752:                        ($thisurl eq '/adm/navmaps')) {
10753: 		       $okay=1;
10754:                        last;
10755: 		   }
10756: 	       }
10757: 	   }
10758:         }
10759: 	untie(%bighash);
10760:     }
10761:     return $okay;
10762: }
10763: 
10764: # --------------------------------------------------------------- Clean-up symb
10765: 
10766: sub symbclean {
10767:     my $symb=shift;
10768:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10769: # remove version from map
10770:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10771: 
10772: # remove version from URL
10773:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10774: 
10775: # remove wrapper
10776: 
10777:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10778:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10779:     return $symb;
10780: }
10781: 
10782: # ---------------------------------------------- Split symb to find map and url
10783: 
10784: sub encode_symb {
10785:     my ($map,$resid,$url)=@_;
10786:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10787: }
10788: 
10789: sub decode_symb {
10790:     my $symb=shift;
10791:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10792:     my ($map,$resid,$url)=split(/___/,$symb);
10793:     return (&fixversion($map),$resid,&fixversion($url));
10794: }
10795: 
10796: sub fixversion {
10797:     my $fn=shift;
10798:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10799:     my %bighash;
10800:     my $uri=&clutter($fn);
10801:     my $key=$env{'request.course.id'}.'_'.$uri;
10802: # is this cached?
10803:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10804:     if (defined($cached)) { return $result; }
10805: # unfortunately not cached, or expired
10806:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10807: 	    &GDBM_READER(),0640)) {
10808:  	if ($bighash{'version_'.$uri}) {
10809:  	    my $version=$bighash{'version_'.$uri};
10810:  	    unless (($version eq 'mostrecent') || 
10811: 		    ($version==&getversion($uri))) {
10812:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10813:  	    }
10814:  	}
10815:  	untie %bighash;
10816:     }
10817:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10818: }
10819: 
10820: sub deversion {
10821:     my $url=shift;
10822:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10823:     return $url;
10824: }
10825: 
10826: # ------------------------------------------------------ Return symb list entry
10827: 
10828: sub symbread {
10829:     my ($thisfn,$donotrecurse)=@_;
10830:     my $cache_str;
10831:     if ($thisfn ne '') {
10832:         $cache_str='request.symbread.cached.'.$thisfn;
10833:         if ($env{$cache_str} ne '') {
10834:             return $env{$cache_str};
10835:         }
10836:     } else {
10837: # no filename provided? try from environment
10838:         if ($env{'request.symb'}) {
10839: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10840: 	}
10841: 	$thisfn=$env{'request.filename'};
10842:     }
10843:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10844: # is that filename actually a symb? Verify, clean, and return
10845:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10846: 	if (&symbverify($thisfn,$1)) {
10847: 	    return $env{$cache_str}=&symbclean($thisfn);
10848: 	}
10849:     }
10850:     $thisfn=declutter($thisfn);
10851:     my %hash;
10852:     my %bighash;
10853:     my $syval='';
10854:     if (($env{'request.course.fn'}) && ($thisfn)) {
10855:         my $targetfn = $thisfn;
10856:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10857:             $targetfn = 'adm/wrapper/'.$thisfn;
10858:         }
10859: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10860: 	    $targetfn=$1;
10861: 	}
10862:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10863:                       &GDBM_READER(),0640)) {
10864: 	    $syval=$hash{$targetfn};
10865:             untie(%hash);
10866:         }
10867: # ---------------------------------------------------------- There was an entry
10868:         if ($syval) {
10869: 	    #unless ($syval=~/\_\d+$/) {
10870: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10871: 		    #&appenv({'request.ambiguous' => $thisfn});
10872: 		    #return $env{$cache_str}='';
10873: 		#}    
10874: 		#$syval.=$1;
10875: 	    #}
10876:         } else {
10877: # ------------------------------------------------------- Was not in symb table
10878:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10879:                             &GDBM_READER(),0640)) {
10880: # ---------------------------------------------- Get ID(s) for current resource
10881:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10882:               unless ($ids) { 
10883:                  $ids=$bighash{'ids_/'.$thisfn};
10884:               }
10885:               unless ($ids) {
10886: # alias?
10887: 		  $ids=$bighash{'mapalias_'.$thisfn};
10888:               }
10889:               if ($ids) {
10890: # ------------------------------------------------------------------- Has ID(s)
10891:                  my @possibilities=split(/\,/,$ids);
10892:                  if ($#possibilities==0) {
10893: # ----------------------------------------------- There is only one possibility
10894: 		     my ($mapid,$resid)=split(/\./,$ids);
10895: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10896: 						    $resid,$thisfn);
10897:                  } elsif (!$donotrecurse) {
10898: # ------------------------------------------ There is more than one possibility
10899:                      my $realpossible=0;
10900:                      foreach my $id (@possibilities) {
10901: 			 my $file=$bighash{'src_'.$id};
10902:                          if (&allowed('bre',$file)) {
10903:          		    my ($mapid,$resid)=split(/\./,$id);
10904:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10905: 				$realpossible++;
10906:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10907: 						    $resid,$thisfn);
10908:                             }
10909: 			 }
10910:                      }
10911: 		     if ($realpossible!=1) { $syval=''; }
10912:                  } else {
10913:                      $syval='';
10914:                  }
10915: 	      }
10916:               untie(%bighash)
10917:            }
10918:         }
10919:         if ($syval) {
10920: 	    return $env{$cache_str}=$syval;
10921:         }
10922:     }
10923:     &appenv({'request.ambiguous' => $thisfn});
10924:     return $env{$cache_str}='';
10925: }
10926: 
10927: # ---------------------------------------------------------- Return random seed
10928: 
10929: sub numval {
10930:     my $txt=shift;
10931:     $txt=~tr/A-J/0-9/;
10932:     $txt=~tr/a-j/0-9/;
10933:     $txt=~tr/K-T/0-9/;
10934:     $txt=~tr/k-t/0-9/;
10935:     $txt=~tr/U-Z/0-5/;
10936:     $txt=~tr/u-z/0-5/;
10937:     $txt=~s/\D//g;
10938:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10939:     return int($txt);
10940: }
10941: 
10942: sub numval2 {
10943:     my $txt=shift;
10944:     $txt=~tr/A-J/0-9/;
10945:     $txt=~tr/a-j/0-9/;
10946:     $txt=~tr/K-T/0-9/;
10947:     $txt=~tr/k-t/0-9/;
10948:     $txt=~tr/U-Z/0-5/;
10949:     $txt=~tr/u-z/0-5/;
10950:     $txt=~s/\D//g;
10951:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10952:     my $total;
10953:     foreach my $val (@txts) { $total+=$val; }
10954:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10955:     return int($total);
10956: }
10957: 
10958: sub numval3 {
10959:     use integer;
10960:     my $txt=shift;
10961:     $txt=~tr/A-J/0-9/;
10962:     $txt=~tr/a-j/0-9/;
10963:     $txt=~tr/K-T/0-9/;
10964:     $txt=~tr/k-t/0-9/;
10965:     $txt=~tr/U-Z/0-5/;
10966:     $txt=~tr/u-z/0-5/;
10967:     $txt=~s/\D//g;
10968:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10969:     my $total;
10970:     foreach my $val (@txts) { $total+=$val; }
10971:     if ($_64bit) { $total=(($total<<32)>>32); }
10972:     return $total;
10973: }
10974: 
10975: sub digest {
10976:     my ($data)=@_;
10977:     my $digest=&Digest::MD5::md5($data);
10978:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10979:     my ($e,$f);
10980:     {
10981:         use integer;
10982:         $e=($a+$b);
10983:         $f=($c+$d);
10984:         if ($_64bit) {
10985:             $e=(($e<<32)>>32);
10986:             $f=(($f<<32)>>32);
10987:         }
10988:     }
10989:     if (wantarray) {
10990: 	return ($e,$f);
10991:     } else {
10992: 	my $g;
10993: 	{
10994: 	    use integer;
10995: 	    $g=($e+$f);
10996: 	    if ($_64bit) {
10997: 		$g=(($g<<32)>>32);
10998: 	    }
10999: 	}
11000: 	return $g;
11001:     }
11002: }
11003: 
11004: sub latest_rnd_algorithm_id {
11005:     return '64bit5';
11006: }
11007: 
11008: sub get_rand_alg {
11009:     my ($courseid)=@_;
11010:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11011:     if ($courseid) {
11012: 	return $env{"course.$courseid.rndseed"};
11013:     }
11014:     return &latest_rnd_algorithm_id();
11015: }
11016: 
11017: sub validCODE {
11018:     my ($CODE)=@_;
11019:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11020:     return 0;
11021: }
11022: 
11023: sub getCODE {
11024:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11025:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11026: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11027: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11028: 	return $Apache::lonhomework::history{'resource.CODE'};
11029:     }
11030:     return undef;
11031: }
11032: #
11033: #  Determines the random seed for a specific context:
11034: #
11035: # parameters:
11036: #   symb      - in course context the symb for the seed.
11037: #   course_id - The course id of the form domain_coursenum.
11038: #   domain    - Domain for the user.
11039: #   course    - Course for the user.
11040: #   cenv      - environment of the course.
11041: #
11042: # NOTE:
11043: #   All parameters are picked out of the environment if missing
11044: #   or not defined.
11045: #   If a symb cannot be determined the current time is used instead.
11046: #
11047: #  For a given well defined symb, courside, domain, username,
11048: #  and course environment, the seed is reproducible.
11049: #
11050: sub rndseed {
11051:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11052:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11053:     if (!defined($symb)) {
11054: 	unless ($symb=$wsymb) { return time; }
11055:     }
11056:     if (!defined $courseid) { 
11057: 	$courseid=$wcourseid; 
11058:     }
11059:     if (!defined $domain) { $domain=$wdomain; }
11060:     if (!defined $username) { $username=$wusername }
11061: 
11062:     my $which;
11063:     if (defined($cenv->{'rndseed'})) {
11064: 	$which = $cenv->{'rndseed'};
11065:     } else {
11066: 	$which =&get_rand_alg($courseid);
11067:     }
11068:     if (defined(&getCODE())) {
11069: 
11070: 	if ($which eq '64bit5') {
11071: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11072: 	} elsif ($which eq '64bit4') {
11073: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11074: 	} else {
11075: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11076: 	}
11077:     } elsif ($which eq '64bit5') {
11078: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11079:     } elsif ($which eq '64bit4') {
11080: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11081:     } elsif ($which eq '64bit3') {
11082: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11083:     } elsif ($which eq '64bit2') {
11084: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11085:     } elsif ($which eq '64bit') {
11086: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11087:     }
11088:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11089: }
11090: 
11091: sub rndseed_32bit {
11092:     my ($symb,$courseid,$domain,$username)=@_;
11093:     {
11094: 	use integer;
11095: 	my $symbchck=unpack("%32C*",$symb) << 27;
11096: 	my $symbseed=numval($symb) << 22;
11097: 	my $namechck=unpack("%32C*",$username) << 17;
11098: 	my $nameseed=numval($username) << 12;
11099: 	my $domainseed=unpack("%32C*",$domain) << 7;
11100: 	my $courseseed=unpack("%32C*",$courseid);
11101: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11102: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11103: 	#&logthis("rndseed :$num:$symb");
11104: 	if ($_64bit) { $num=(($num<<32)>>32); }
11105: 	return $num;
11106:     }
11107: }
11108: 
11109: sub rndseed_64bit {
11110:     my ($symb,$courseid,$domain,$username)=@_;
11111:     {
11112: 	use integer;
11113: 	my $symbchck=unpack("%32S*",$symb) << 21;
11114: 	my $symbseed=numval($symb) << 10;
11115: 	my $namechck=unpack("%32S*",$username);
11116: 	
11117: 	my $nameseed=numval($username) << 21;
11118: 	my $domainseed=unpack("%32S*",$domain) << 10;
11119: 	my $courseseed=unpack("%32S*",$courseid);
11120: 	
11121: 	my $num1=$symbchck+$symbseed+$namechck;
11122: 	my $num2=$nameseed+$domainseed+$courseseed;
11123: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11124: 	#&logthis("rndseed :$num:$symb");
11125: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11126: 	return "$num1,$num2";
11127:     }
11128: }
11129: 
11130: sub rndseed_64bit2 {
11131:     my ($symb,$courseid,$domain,$username)=@_;
11132:     {
11133: 	use integer;
11134: 	# strings need to be an even # of cahracters long, it it is odd the
11135:         # last characters gets thrown away
11136: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11137: 	my $symbseed=numval($symb) << 10;
11138: 	my $namechck=unpack("%32S*",$username.' ');
11139: 	
11140: 	my $nameseed=numval($username) << 21;
11141: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11142: 	my $courseseed=unpack("%32S*",$courseid.' ');
11143: 	
11144: 	my $num1=$symbchck+$symbseed+$namechck;
11145: 	my $num2=$nameseed+$domainseed+$courseseed;
11146: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11147: 	#&logthis("rndseed :$num:$symb");
11148: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11149: 	return "$num1,$num2";
11150:     }
11151: }
11152: 
11153: sub rndseed_64bit3 {
11154:     my ($symb,$courseid,$domain,$username)=@_;
11155:     {
11156: 	use integer;
11157: 	# strings need to be an even # of cahracters long, it it is odd the
11158:         # last characters gets thrown away
11159: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11160: 	my $symbseed=numval2($symb) << 10;
11161: 	my $namechck=unpack("%32S*",$username.' ');
11162: 	
11163: 	my $nameseed=numval2($username) << 21;
11164: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11165: 	my $courseseed=unpack("%32S*",$courseid.' ');
11166: 	
11167: 	my $num1=$symbchck+$symbseed+$namechck;
11168: 	my $num2=$nameseed+$domainseed+$courseseed;
11169: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11170: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11171: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11172: 	
11173: 	return "$num1:$num2";
11174:     }
11175: }
11176: 
11177: sub rndseed_64bit4 {
11178:     my ($symb,$courseid,$domain,$username)=@_;
11179:     {
11180: 	use integer;
11181: 	# strings need to be an even # of cahracters long, it it is odd the
11182:         # last characters gets thrown away
11183: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11184: 	my $symbseed=numval3($symb) << 10;
11185: 	my $namechck=unpack("%32S*",$username.' ');
11186: 	
11187: 	my $nameseed=numval3($username) << 21;
11188: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11189: 	my $courseseed=unpack("%32S*",$courseid.' ');
11190: 	
11191: 	my $num1=$symbchck+$symbseed+$namechck;
11192: 	my $num2=$nameseed+$domainseed+$courseseed;
11193: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11194: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11195: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11196: 	
11197: 	return "$num1:$num2";
11198:     }
11199: }
11200: 
11201: sub rndseed_64bit5 {
11202:     my ($symb,$courseid,$domain,$username)=@_;
11203:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11204:     return "$num1:$num2";
11205: }
11206: 
11207: sub rndseed_CODE_64bit {
11208:     my ($symb,$courseid,$domain,$username)=@_;
11209:     {
11210: 	use integer;
11211: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11212: 	my $symbseed=numval2($symb);
11213: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11214: 	my $CODEseed=numval(&getCODE());
11215: 	my $courseseed=unpack("%32S*",$courseid.' ');
11216: 	my $num1=$symbseed+$CODEchck;
11217: 	my $num2=$CODEseed+$courseseed+$symbchck;
11218: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11219: 	#&logthis("rndseed :$num1:$num2:$symb");
11220: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11221: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11222: 	return "$num1:$num2";
11223:     }
11224: }
11225: 
11226: sub rndseed_CODE_64bit4 {
11227:     my ($symb,$courseid,$domain,$username)=@_;
11228:     {
11229: 	use integer;
11230: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11231: 	my $symbseed=numval3($symb);
11232: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11233: 	my $CODEseed=numval3(&getCODE());
11234: 	my $courseseed=unpack("%32S*",$courseid.' ');
11235: 	my $num1=$symbseed+$CODEchck;
11236: 	my $num2=$CODEseed+$courseseed+$symbchck;
11237: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11238: 	#&logthis("rndseed :$num1:$num2:$symb");
11239: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11240: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11241: 	return "$num1:$num2";
11242:     }
11243: }
11244: 
11245: sub rndseed_CODE_64bit5 {
11246:     my ($symb,$courseid,$domain,$username)=@_;
11247:     my $code = &getCODE();
11248:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11249:     return "$num1:$num2";
11250: }
11251: 
11252: sub setup_random_from_rndseed {
11253:     my ($rndseed)=@_;
11254:     if ($rndseed =~/([,:])/) {
11255: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11256: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11257:     } else {
11258: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11259:     }
11260: }
11261: 
11262: sub latest_receipt_algorithm_id {
11263:     return 'receipt3';
11264: }
11265: 
11266: sub recunique {
11267:     my $fucourseid=shift;
11268:     my $unique;
11269:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11270: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11271: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11272:     } else {
11273: 	$unique=$perlvar{'lonReceipt'};
11274:     }
11275:     return unpack("%32C*",$unique);
11276: }
11277: 
11278: sub recprefix {
11279:     my $fucourseid=shift;
11280:     my $prefix;
11281:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11282: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11283: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11284:     } else {
11285: 	$prefix=$perlvar{'lonHostID'};
11286:     }
11287:     return unpack("%32C*",$prefix);
11288: }
11289: 
11290: sub ireceipt {
11291:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11292: 
11293:     my $return =&recprefix($fucourseid).'-';
11294: 
11295:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11296: 	$env{'request.state'} eq 'construct') {
11297: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11298: 	return $return;
11299:     }
11300: 
11301:     my $cuname=unpack("%32C*",$funame);
11302:     my $cudom=unpack("%32C*",$fudom);
11303:     my $cucourseid=unpack("%32C*",$fucourseid);
11304:     my $cusymb=unpack("%32C*",$fusymb);
11305:     my $cunique=&recunique($fucourseid);
11306:     my $cpart=unpack("%32S*",$part);
11307:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11308: 
11309: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11310: 			       
11311: 	$return.= ($cunique%$cuname+
11312: 		   $cunique%$cudom+
11313: 		   $cusymb%$cuname+
11314: 		   $cusymb%$cudom+
11315: 		   $cucourseid%$cuname+
11316: 		   $cucourseid%$cudom+
11317: 		   $cpart%$cuname+
11318: 		   $cpart%$cudom);
11319:     } else {
11320: 	$return.= ($cunique%$cuname+
11321: 		   $cunique%$cudom+
11322: 		   $cusymb%$cuname+
11323: 		   $cusymb%$cudom+
11324: 		   $cucourseid%$cuname+
11325: 		   $cucourseid%$cudom);
11326:     }
11327:     return $return;
11328: }
11329: 
11330: sub receipt {
11331:     my ($part)=@_;
11332:     my ($symb,$courseid,$domain,$name) = &whichuser();
11333:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11334: }
11335: 
11336: sub whichuser {
11337:     my ($passedsymb)=@_;
11338:     my ($symb,$courseid,$domain,$name,$publicuser);
11339:     if (defined($env{'form.grade_symb'})) {
11340: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11341: 	my $allowed=&allowed('vgr',$tmp_courseid);
11342: 	if (!$allowed &&
11343: 	    exists($env{'request.course.sec'}) &&
11344: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11345: 	    $allowed=&allowed('vgr',$tmp_courseid.
11346: 			      '/'.$env{'request.course.sec'});
11347: 	}
11348: 	if ($allowed) {
11349: 	    ($symb)=&get_env_multiple('form.grade_symb');
11350: 	    $courseid=$tmp_courseid;
11351: 	    ($domain)=&get_env_multiple('form.grade_domain');
11352: 	    ($name)=&get_env_multiple('form.grade_username');
11353: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11354: 	}
11355:     }
11356:     if (!$passedsymb) {
11357: 	$symb=&symbread();
11358:     } else {
11359: 	$symb=$passedsymb;
11360:     }
11361:     $courseid=$env{'request.course.id'};
11362:     $domain=$env{'user.domain'};
11363:     $name=$env{'user.name'};
11364:     if ($name eq 'public' && $domain eq 'public') {
11365: 	if (!defined($env{'form.username'})) {
11366: 	    $env{'form.username'}.=time.rand(10000000);
11367: 	}
11368: 	$name.=$env{'form.username'};
11369:     }
11370:     return ($symb,$courseid,$domain,$name,$publicuser);
11371: 
11372: }
11373: 
11374: # ------------------------------------------------------------ Serves up a file
11375: # returns either the contents of the file or 
11376: # -1 if the file doesn't exist
11377: #
11378: # if the target is a file that was uploaded via DOCS, 
11379: # a check will be made to see if a current copy exists on the local server,
11380: # if it does this will be served, otherwise a copy will be retrieved from
11381: # the home server for the course and stored in /home/httpd/html/userfiles on
11382: # the local server.   
11383: 
11384: sub getfile {
11385:     my ($file) = @_;
11386:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11387:     &repcopy($file);
11388:     return &readfile($file);
11389: }
11390: 
11391: sub repcopy_userfile {
11392:     my ($file)=@_;
11393:     my $londocroot = $perlvar{'lonDocRoot'};
11394:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11395:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11396:     my ($cdom,$cnum,$filename) = 
11397: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11398:     my $uri="/uploaded/$cdom/$cnum/$filename";
11399:     if (-e "$file") {
11400: # we already have a local copy, check it out
11401: 	my @fileinfo = stat($file);
11402: 	my $rtncode;
11403: 	my $info;
11404: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11405: 	if ($lwpresp ne 'ok') {
11406: # there is no such file anymore, even though we had a local copy
11407: 	    if ($rtncode eq '404') {
11408: 		unlink($file);
11409: 	    }
11410: 	    return -1;
11411: 	}
11412: 	if ($info < $fileinfo[9]) {
11413: # nice, the file we have is up-to-date, just say okay
11414: 	    return 'ok';
11415: 	} else {
11416: # the file is outdated, get rid of it
11417: 	    unlink($file);
11418: 	}
11419:     }
11420: # one way or the other, at this point, we don't have the file
11421: # construct the correct path for the file
11422:     my @parts = ($cdom,$cnum); 
11423:     if ($filename =~ m|^(.+)/[^/]+$|) {
11424: 	push @parts, split(/\//,$1);
11425:     }
11426:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11427:     foreach my $part (@parts) {
11428: 	$path .= '/'.$part;
11429: 	if (!-e $path) {
11430: 	    mkdir($path,0770);
11431: 	}
11432:     }
11433: # now the path exists for sure
11434: # get a user agent
11435:     my $ua=new LWP::UserAgent;
11436:     my $transferfile=$file.'.in.transfer';
11437: # FIXME: this should flock
11438:     if (-e $transferfile) { return 'ok'; }
11439:     my $request;
11440:     $uri=~s/^\///;
11441:     my $homeserver = &homeserver($cnum,$cdom);
11442:     my $protocol = $protocol{$homeserver};
11443:     $protocol = 'http' if ($protocol ne 'https');
11444:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11445:     my $response=$ua->request($request,$transferfile);
11446: # did it work?
11447:     if ($response->is_error()) {
11448: 	unlink($transferfile);
11449: 	&logthis("Userfile repcopy failed for $uri");
11450: 	return -1;
11451:     }
11452: # worked, rename the transfer file
11453:     rename($transferfile,$file);
11454:     return 'ok';
11455: }
11456: 
11457: sub tokenwrapper {
11458:     my $uri=shift;
11459:     $uri=~s|^https?\://([^/]+)||;
11460:     $uri=~s|^/||;
11461:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11462:     my $token=$1;
11463:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11464:     if ($udom && $uname && $file) {
11465: 	$file=~s|(\?\.*)*$||;
11466:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11467:         my $homeserver = &homeserver($uname,$udom);
11468:         my $protocol = $protocol{$homeserver};
11469:         $protocol = 'http' if ($protocol ne 'https');
11470:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11471:                (($uri=~/\?/)?'&':'?').'token='.$token.
11472:                                '&tokenissued='.$perlvar{'lonHostID'};
11473:     } else {
11474:         return '/adm/notfound.html';
11475:     }
11476: }
11477: 
11478: # call with reqtype HEAD: get last modification time
11479: # call with reqtype GET: get the file contents
11480: # Do not call this with reqtype GET for large files! It loads everything into memory
11481: #
11482: sub getuploaded {
11483:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11484:     $uri=~s/^\///;
11485:     my $homeserver = &homeserver($cnum,$cdom);
11486:     my $protocol = $protocol{$homeserver};
11487:     $protocol = 'http' if ($protocol ne 'https');
11488:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11489:     my $ua=new LWP::UserAgent;
11490:     my $request=new HTTP::Request($reqtype,$uri);
11491:     my $response=$ua->request($request);
11492:     $$rtncode = $response->code;
11493:     if (! $response->is_success()) {
11494: 	return 'failed';
11495:     }      
11496:     if ($reqtype eq 'HEAD') {
11497: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11498:     } elsif ($reqtype eq 'GET') {
11499: 	$$info = $response->content;
11500:     }
11501:     return 'ok';
11502: }
11503: 
11504: sub readfile {
11505:     my $file = shift;
11506:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11507:     my $fh;
11508:     open($fh,"<$file");
11509:     my $a='';
11510:     while (my $line = <$fh>) { $a .= $line; }
11511:     return $a;
11512: }
11513: 
11514: sub filelocation {
11515:     my ($dir,$file) = @_;
11516:     my $location;
11517:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11518: 
11519:     if ($file =~ m-^/adm/-) {
11520: 	$file=~s-^/adm/wrapper/-/-;
11521: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11522:     }
11523: 
11524:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11525:         $location = $file;
11526:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11527:         my ($udom,$uname,$filename)=
11528:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11529:         my $home=&homeserver($uname,$udom);
11530:         my $is_me=0;
11531:         my @ids=&current_machine_ids();
11532:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11533:         if ($is_me) {
11534:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11535:         } else {
11536:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11537:   	      $udom.'/'.$uname.'/'.$filename;
11538:         }
11539:     } elsif ($file =~ m-^/adm/-) {
11540: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11541:     } else {
11542:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11543:         $file=~s:^/(res|priv)/:/:;
11544:         my $space=$1;
11545:         if ( !( $file =~ m:^/:) ) {
11546:             $location = $dir. '/'.$file;
11547:         } else {
11548:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11549:         }
11550:     }
11551:     $location=~s://+:/:g; # remove duplicate /
11552:     while ($location=~m{/\.\./}) {
11553: 	if ($location =~ m{/[^/]+/\.\./}) {
11554: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11555: 	} else {
11556: 	    $location=~ s{/\.\./}{/}g;
11557: 	}
11558:     } #remove dir/..
11559:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11560:     return $location;
11561: }
11562: 
11563: sub hreflocation {
11564:     my ($dir,$file)=@_;
11565:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11566: 	$file=filelocation($dir,$file);
11567:     } elsif ($file=~m-^/adm/-) {
11568: 	$file=~s-^/adm/wrapper/-/-;
11569: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11570:     }
11571:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11572: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11573:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11574: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11575: 	        {/uploaded/$1/$2/}x;
11576:     }
11577:     if ($file=~ m{^/userfiles/}) {
11578: 	$file =~ s{^/userfiles/}{/uploaded/};
11579:     }
11580:     return $file;
11581: }
11582: 
11583: 
11584: 
11585: 
11586: 
11587: sub current_machine_domains {
11588:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11589: }
11590: 
11591: sub machine_domains {
11592:     my ($hostname) = @_;
11593:     my @domains;
11594:     my %hostname = &all_hostnames();
11595:     while( my($id, $name) = each(%hostname)) {
11596: #	&logthis("-$id-$name-$hostname-");
11597: 	if ($hostname eq $name) {
11598: 	    push(@domains,&host_domain($id));
11599: 	}
11600:     }
11601:     return @domains;
11602: }
11603: 
11604: sub current_machine_ids {
11605:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11606: }
11607: 
11608: sub machine_ids {
11609:     my ($hostname) = @_;
11610:     $hostname ||= &hostname($perlvar{'lonHostID'});
11611:     my @ids;
11612:     my %name_to_host = &all_names();
11613:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11614: 	return @{ $name_to_host{$hostname} };
11615:     }
11616:     return;
11617: }
11618: 
11619: sub additional_machine_domains {
11620:     my @domains;
11621:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11622:     while( my $line = <$fh>) {
11623:         $line =~ s/\s//g;
11624:         push(@domains,$line);
11625:     }
11626:     return @domains;
11627: }
11628: 
11629: sub default_login_domain {
11630:     my $domain = $perlvar{'lonDefDomain'};
11631:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11632:     foreach my $posdom (&current_machine_domains(),
11633:                         &additional_machine_domains()) {
11634:         if (lc($posdom) eq lc($testdomain)) {
11635:             $domain=$posdom;
11636:             last;
11637:         }
11638:     }
11639:     return $domain;
11640: }
11641: 
11642: # ------------------------------------------------------------- Declutters URLs
11643: 
11644: sub declutter {
11645:     my $thisfn=shift;
11646:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11647:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11648:     $thisfn=~s/^\///;
11649:     $thisfn=~s|^adm/wrapper/||;
11650:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11651:     $thisfn=~s/^res\///;
11652:     $thisfn=~s/^priv\///;
11653:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11654:         $thisfn=~s/\?.+$//;
11655:     }
11656:     return $thisfn;
11657: }
11658: 
11659: # ------------------------------------------------------------- Clutter up URLs
11660: 
11661: sub clutter {
11662:     my $thisfn='/'.&declutter(shift);
11663:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11664: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11665:        $thisfn='/res'.$thisfn; 
11666:     }
11667:     if ($thisfn !~m|^/adm|) {
11668: 	if ($thisfn =~ m|^/ext/|) {
11669: 	    $thisfn='/adm/wrapper'.$thisfn;
11670: 	} else {
11671: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11672: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11673: 	    if ($embstyle eq 'ssi'
11674: 		|| ($embstyle eq 'hdn')
11675: 		|| ($embstyle eq 'rat')
11676: 		|| ($embstyle eq 'prv')
11677: 		|| ($embstyle eq 'ign')) {
11678: 		#do nothing with these
11679: 	    } elsif (($embstyle eq 'img') 
11680: 		|| ($embstyle eq 'emb')
11681: 		|| ($embstyle eq 'wrp')) {
11682: 		$thisfn='/adm/wrapper'.$thisfn;
11683: 	    } elsif ($embstyle eq 'unk'
11684: 		     && $thisfn!~/\.(sequence|page)$/) {
11685: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11686: 	    } else {
11687: #		&logthis("Got a blank emb style");
11688: 	    }
11689: 	}
11690:     }
11691:     return $thisfn;
11692: }
11693: 
11694: sub clutter_with_no_wrapper {
11695:     my $uri = &clutter(shift);
11696:     if ($uri =~ m-^/adm/-) {
11697: 	$uri =~ s-^/adm/wrapper/-/-;
11698: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11699:     }
11700:     return $uri;
11701: }
11702: 
11703: sub freeze_escape {
11704:     my ($value)=@_;
11705:     if (ref($value)) {
11706: 	$value=&nfreeze($value);
11707: 	return '__FROZEN__'.&escape($value);
11708:     }
11709:     return &escape($value);
11710: }
11711: 
11712: 
11713: sub thaw_unescape {
11714:     my ($value)=@_;
11715:     if ($value =~ /^__FROZEN__/) {
11716: 	substr($value,0,10,undef);
11717: 	$value=&unescape($value);
11718: 	return &thaw($value);
11719:     }
11720:     return &unescape($value);
11721: }
11722: 
11723: sub correct_line_ends {
11724:     my ($result)=@_;
11725:     $$result =~s/\r\n/\n/mg;
11726:     $$result =~s/\r/\n/mg;
11727: }
11728: # ================================================================ Main Program
11729: 
11730: sub goodbye {
11731:    &logthis("Starting Shut down");
11732: #not converted to using infrastruture and probably shouldn't be
11733:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11734: #converted
11735: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11736:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11737: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11738: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11739: #1.1 only
11740: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11741: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11742: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11743: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11744:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11745:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11746:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11747:    &flushcourselogs();
11748:    &logthis("Shutting down");
11749: }
11750: 
11751: sub get_dns {
11752:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11753:     if (!$ignore_cache) {
11754: 	my ($content,$cached)=
11755: 	    &Apache::lonnet::is_cached_new('dns',$url);
11756: 	if ($cached) {
11757: 	    &$func($content,$hashref);
11758: 	    return;
11759: 	}
11760:     }
11761: 
11762:     my %alldns;
11763:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11764:     foreach my $dns (<$config>) {
11765: 	next if ($dns !~ /^\^(\S*)/x);
11766:         my $line = $1;
11767:         my ($host,$protocol) = split(/:/,$line);
11768:         if ($protocol ne 'https') {
11769:             $protocol = 'http';
11770:         }
11771: 	$alldns{$host} = $protocol;
11772:     }
11773:     while (%alldns) {
11774: 	my ($dns) = keys(%alldns);
11775: 	my $ua=new LWP::UserAgent;
11776:         $ua->timeout(30);
11777: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11778: 	my $response=$ua->request($request);
11779:         delete($alldns{$dns});
11780: 	next if ($response->is_error());
11781: 	my @content = split("\n",$response->content);
11782: 	unless ($nocache) {
11783: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11784: 	}
11785: 	&$func(\@content,$hashref);
11786: 	return;
11787:     }
11788:     close($config);
11789:     my $which = (split('/',$url))[3];
11790:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11791:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11792:     my @content = <$config>;
11793:     &$func(\@content,$hashref);
11794:     return;
11795: }
11796: 
11797: # ------------------------------------------------------Get DNS checksums file
11798: sub parse_dns_checksums_tab {
11799:     my ($lines,$hashref) = @_;
11800:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11801:     my $loncaparev = &get_server_loncaparev($machine_dom);
11802:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11803:     my (%chksum,%revnum);
11804:     if (ref($lines) eq 'ARRAY') {
11805:         chomp(@{$lines});
11806:         my $version = shift(@{$lines});
11807:         if ($version eq $release) {  
11808:             foreach my $line (@{$lines}) {
11809:                 my ($file,$version,$shasum) = split(/,/,$line);
11810:                 $chksum{$file} = $shasum;
11811:                 $revnum{$file} = $version;
11812:             }
11813:             if (ref($hashref) eq 'HASH') {
11814:                 %{$hashref} = (
11815:                                 sums     => \%chksum,
11816:                                 versions => \%revnum,
11817:                               );
11818:             }
11819:         }
11820:     }
11821:     return;
11822: }
11823: 
11824: sub fetch_dns_checksums {
11825:     my %checksums;
11826:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11827:     my $loncaparev = &get_server_loncaparev($machine_dom);
11828:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11829:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11830:              \%checksums);
11831:     return \%checksums;
11832: }
11833: 
11834: # ------------------------------------------------------------ Read domain file
11835: {
11836:     my $loaded;
11837:     my %domain;
11838: 
11839:     sub parse_domain_tab {
11840: 	my ($lines) = @_;
11841: 	foreach my $line (@$lines) {
11842: 	    next if ($line =~ /^(\#|\s*$ )/x);
11843: 
11844: 	    chomp($line);
11845: 	    my ($name,@elements) = split(/:/,$line,9);
11846: 	    my %this_domain;
11847: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11848: 			       'lang_def', 'city', 'longi', 'lati',
11849: 			       'primary') {
11850: 		$this_domain{$field} = shift(@elements);
11851: 	    }
11852: 	    $domain{$name} = \%this_domain;
11853: 	}
11854:     }
11855: 
11856:     sub reset_domain_info {
11857: 	undef($loaded);
11858: 	undef(%domain);
11859:     }
11860: 
11861:     sub load_domain_tab {
11862: 	my ($ignore_cache) = @_;
11863: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11864: 	my $fh;
11865: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11866: 	    my @lines = <$fh>;
11867: 	    &parse_domain_tab(\@lines);
11868: 	}
11869: 	close($fh);
11870: 	$loaded = 1;
11871:     }
11872: 
11873:     sub domain {
11874: 	&load_domain_tab() if (!$loaded);
11875: 
11876: 	my ($name,$what) = @_;
11877: 	return if ( !exists($domain{$name}) );
11878: 
11879: 	if (!$what) {
11880: 	    return $domain{$name}{'description'};
11881: 	}
11882: 	return $domain{$name}{$what};
11883:     }
11884: 
11885:     sub domain_info {
11886:         &load_domain_tab() if (!$loaded);
11887:         return %domain;
11888:     }
11889: 
11890: }
11891: 
11892: 
11893: # ------------------------------------------------------------- Read hosts file
11894: {
11895:     my %hostname;
11896:     my %hostdom;
11897:     my %libserv;
11898:     my $loaded;
11899:     my %name_to_host;
11900:     my %internetdom;
11901:     my %LC_dns_serv;
11902: 
11903:     sub parse_hosts_tab {
11904: 	my ($file) = @_;
11905: 	foreach my $configline (@$file) {
11906: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11907:             chomp($configline);
11908: 	    if ($configline =~ /^\^/) {
11909:                 if ($configline =~ /^\^([\w.\-]+)/) {
11910:                     $LC_dns_serv{$1} = 1;
11911:                 }
11912:                 next;
11913:             }
11914: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11915: 	    $name=~s/\s//g;
11916: 	    if ($id && $domain && $role && $name) {
11917: 		$hostname{$id}=$name;
11918: 		push(@{$name_to_host{$name}}, $id);
11919: 		$hostdom{$id}=$domain;
11920: 		if ($role eq 'library') { $libserv{$id}=$name; }
11921:                 if (defined($protocol)) {
11922:                     if ($protocol eq 'https') {
11923:                         $protocol{$id} = $protocol;
11924:                     } else {
11925:                         $protocol{$id} = 'http'; 
11926:                     }
11927:                 } else {
11928:                     $protocol{$id} = 'http';
11929:                 }
11930:                 if (defined($intdom)) {
11931:                     $internetdom{$id} = $intdom;
11932:                 }
11933: 	    }
11934: 	}
11935:     }
11936:     
11937:     sub reset_hosts_info {
11938: 	&purge_remembered();
11939: 	&reset_domain_info();
11940: 	&reset_hosts_ip_info();
11941: 	undef(%name_to_host);
11942: 	undef(%hostname);
11943: 	undef(%hostdom);
11944: 	undef(%libserv);
11945: 	undef($loaded);
11946:     }
11947: 
11948:     sub load_hosts_tab {
11949: 	my ($ignore_cache) = @_;
11950: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11951: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11952: 	my @config = <$config>;
11953: 	&parse_hosts_tab(\@config);
11954: 	close($config);
11955: 	$loaded=1;
11956:     }
11957: 
11958:     sub hostname {
11959: 	&load_hosts_tab() if (!$loaded);
11960: 
11961: 	my ($lonid) = @_;
11962: 	return $hostname{$lonid};
11963:     }
11964: 
11965:     sub all_hostnames {
11966: 	&load_hosts_tab() if (!$loaded);
11967: 
11968: 	return %hostname;
11969:     }
11970: 
11971:     sub all_names {
11972: 	&load_hosts_tab() if (!$loaded);
11973: 
11974: 	return %name_to_host;
11975:     }
11976: 
11977:     sub all_host_domain {
11978:         &load_hosts_tab() if (!$loaded);
11979:         return %hostdom;
11980:     }
11981: 
11982:     sub is_library {
11983: 	&load_hosts_tab() if (!$loaded);
11984: 
11985: 	return exists($libserv{$_[0]});
11986:     }
11987: 
11988:     sub all_library {
11989: 	&load_hosts_tab() if (!$loaded);
11990: 
11991: 	return %libserv;
11992:     }
11993: 
11994:     sub unique_library {
11995: 	#2x reverse removes all hostnames that appear more than once
11996:         my %unique = reverse &all_library();
11997:         return reverse %unique;
11998:     }
11999: 
12000:     sub get_servers {
12001: 	&load_hosts_tab() if (!$loaded);
12002: 
12003: 	my ($domain,$type) = @_;
12004: 	my %possible_hosts = ($type eq 'library') ? %libserv
12005: 	                                          : %hostname;
12006: 	my %result;
12007: 	if (ref($domain) eq 'ARRAY') {
12008: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12009: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12010: 		    $result{$host} = $hostname;
12011: 		}
12012: 	    }
12013: 	} else {
12014: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12015: 		if ($hostdom{$host} eq $domain) {
12016: 		    $result{$host} = $hostname;
12017: 		}
12018: 	    }
12019: 	}
12020: 	return %result;
12021:     }
12022: 
12023:     sub get_unique_servers {
12024:         my %unique = reverse &get_servers(@_);
12025: 	return reverse %unique;
12026:     }
12027: 
12028:     sub host_domain {
12029: 	&load_hosts_tab() if (!$loaded);
12030: 
12031: 	my ($lonid) = @_;
12032: 	return $hostdom{$lonid};
12033:     }
12034: 
12035:     sub all_domains {
12036: 	&load_hosts_tab() if (!$loaded);
12037: 
12038: 	my %seen;
12039: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12040: 	return @uniq;
12041:     }
12042: 
12043:     sub internet_dom {
12044:         &load_hosts_tab() if (!$loaded);
12045: 
12046:         my ($lonid) = @_;
12047:         return $internetdom{$lonid};
12048:     }
12049: 
12050:     sub is_LC_dns {
12051:         &load_hosts_tab() if (!$loaded);
12052: 
12053:         my ($hostname) = @_;
12054:         return exists($LC_dns_serv{$hostname});
12055:     }
12056: 
12057: }
12058: 
12059: { 
12060:     my %iphost;
12061:     my %name_to_ip;
12062:     my %lonid_to_ip;
12063: 
12064:     sub get_hosts_from_ip {
12065: 	my ($ip) = @_;
12066: 	my %iphosts = &get_iphost();
12067: 	if (ref($iphosts{$ip})) {
12068: 	    return @{$iphosts{$ip}};
12069: 	}
12070: 	return;
12071:     }
12072:     
12073:     sub reset_hosts_ip_info {
12074: 	undef(%iphost);
12075: 	undef(%name_to_ip);
12076: 	undef(%lonid_to_ip);
12077:     }
12078: 
12079:     sub get_host_ip {
12080: 	my ($lonid) = @_;
12081: 	if (exists($lonid_to_ip{$lonid})) {
12082: 	    return $lonid_to_ip{$lonid};
12083: 	}
12084: 	my $name=&hostname($lonid);
12085:    	my $ip = gethostbyname($name);
12086: 	return if (!$ip || length($ip) ne 4);
12087: 	$ip=inet_ntoa($ip);
12088: 	$name_to_ip{$name}   = $ip;
12089: 	$lonid_to_ip{$lonid} = $ip;
12090: 	return $ip;
12091:     }
12092:     
12093:     sub get_iphost {
12094: 	my ($ignore_cache) = @_;
12095: 
12096: 	if (!$ignore_cache) {
12097: 	    if (%iphost) {
12098: 		return %iphost;
12099: 	    }
12100: 	    my ($ip_info,$cached)=
12101: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12102: 	    if ($cached) {
12103: 		%iphost      = %{$ip_info->[0]};
12104: 		%name_to_ip  = %{$ip_info->[1]};
12105: 		%lonid_to_ip = %{$ip_info->[2]};
12106: 		return %iphost;
12107: 	    }
12108: 	}
12109: 
12110: 	# get yesterday's info for fallback
12111: 	my %old_name_to_ip;
12112: 	my ($ip_info,$cached)=
12113: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12114: 	if ($cached) {
12115: 	    %old_name_to_ip = %{$ip_info->[1]};
12116: 	}
12117: 
12118: 	my %name_to_host = &all_names();
12119: 	foreach my $name (keys(%name_to_host)) {
12120: 	    my $ip;
12121: 	    if (!exists($name_to_ip{$name})) {
12122: 		$ip = gethostbyname($name);
12123: 		if (!$ip || length($ip) ne 4) {
12124: 		    if (defined($old_name_to_ip{$name})) {
12125: 			$ip = $old_name_to_ip{$name};
12126: 			&logthis("Can't find $name defaulting to old $ip");
12127: 		    } else {
12128: 			&logthis("Name $name no IP found");
12129: 			next;
12130: 		    }
12131: 		} else {
12132: 		    $ip=inet_ntoa($ip);
12133: 		}
12134: 		$name_to_ip{$name} = $ip;
12135: 	    } else {
12136: 		$ip = $name_to_ip{$name};
12137: 	    }
12138: 	    foreach my $id (@{ $name_to_host{$name} }) {
12139: 		$lonid_to_ip{$id} = $ip;
12140: 	    }
12141: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12142: 	}
12143: 	&do_cache_new('iphost','iphost',
12144: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12145: 		      48*60*60);
12146: 
12147: 	return %iphost;
12148:     }
12149: 
12150:     #
12151:     #  Given a DNS returns the loncapa host name for that DNS 
12152:     # 
12153:     sub host_from_dns {
12154:         my ($dns) = @_;
12155:         my @hosts;
12156:         my $ip;
12157: 
12158:         if (exists($name_to_ip{$dns})) {
12159:             $ip = $name_to_ip{$dns};
12160:         }
12161:         if (!$ip) {
12162:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12163:             if (length($ip) == 4) { 
12164: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12165:             }
12166:         }
12167:         if ($ip) {
12168: 	    @hosts = get_hosts_from_ip($ip);
12169: 	    return $hosts[0];
12170:         }
12171:         return undef;
12172:     }
12173: 
12174:     sub get_internet_names {
12175:         my ($lonid) = @_;
12176:         return if ($lonid eq '');
12177:         my ($idnref,$cached)=
12178:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12179:         if ($cached) {
12180:             return $idnref;
12181:         }
12182:         my $ip = &get_host_ip($lonid);
12183:         my @hosts = &get_hosts_from_ip($ip);
12184:         my %iphost = &get_iphost();
12185:         my (@idns,%seen);
12186:         foreach my $id (@hosts) {
12187:             my $dom = &host_domain($id);
12188:             my $prim_id = &domain($dom,'primary');
12189:             my $prim_ip = &get_host_ip($prim_id);
12190:             next if ($seen{$prim_ip});
12191:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12192:                 foreach my $id (@{$iphost{$prim_ip}}) {
12193:                     my $intdom = &internet_dom($id);
12194:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12195:                         push(@idns,$intdom);
12196:                     }
12197:                 }
12198:             }
12199:             $seen{$prim_ip} = 1;
12200:         }
12201:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12202:     }
12203: 
12204: }
12205: 
12206: sub all_loncaparevs {
12207:     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);
12208: }
12209: 
12210: # ---------------------------------------------------------- Read loncaparev table
12211: {
12212:     sub load_loncaparevs { 
12213:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12214:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12215:                 while (my $configline=<$config>) {
12216:                     chomp($configline);
12217:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12218:                     $loncaparevs{$hostid}=$loncaparev;
12219:                 }
12220:                 close($config);
12221:             }
12222:         }
12223:     }
12224: }
12225: 
12226: # ---------------------------------------------------------- Read serverhostID table
12227: {
12228:     sub load_serverhomeIDs {
12229:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12230:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12231:                 while (my $configline=<$config>) {
12232:                     chomp($configline);
12233:                     my ($name,$id)=split(/:/,$configline);
12234:                     $serverhomeIDs{$name}=$id;
12235:                 }
12236:                 close($config);
12237:             }
12238:         }
12239:     }
12240: }
12241: 
12242: 
12243: BEGIN {
12244: 
12245: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12246:     unless ($readit) {
12247: {
12248:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12249:     %perlvar = (%perlvar,%{$configvars});
12250: }
12251: 
12252: 
12253: # ------------------------------------------------------ Read spare server file
12254: {
12255:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12256: 
12257:     while (my $configline=<$config>) {
12258:        chomp($configline);
12259:        if ($configline) {
12260: 	   my ($host,$type) = split(':',$configline,2);
12261: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12262: 	   push(@{ $spareid{$type} }, $host);
12263:        }
12264:     }
12265:     close($config);
12266: }
12267: # ------------------------------------------------------------ Read permissions
12268: {
12269:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12270: 
12271:     while (my $configline=<$config>) {
12272: 	chomp($configline);
12273: 	if ($configline) {
12274: 	    my ($role,$perm)=split(/ /,$configline);
12275: 	    if ($perm ne '') { $pr{$role}=$perm; }
12276: 	}
12277:     }
12278:     close($config);
12279: }
12280: 
12281: # -------------------------------------------- Read plain texts for permissions
12282: {
12283:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12284: 
12285:     while (my $configline=<$config>) {
12286: 	chomp($configline);
12287: 	if ($configline) {
12288: 	    my ($short,@plain)=split(/:/,$configline);
12289:             %{$prp{$short}} = ();
12290: 	    if (@plain > 0) {
12291:                 $prp{$short}{'std'} = $plain[0];
12292:                 for (my $i=1; $i<@plain; $i++) {
12293:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12294:                 }
12295:             }
12296: 	}
12297:     }
12298:     close($config);
12299: }
12300: 
12301: # ---------------------------------------------------------- Read package table
12302: {
12303:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12304: 
12305:     while (my $configline=<$config>) {
12306: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12307: 	chomp($configline);
12308: 	my ($short,$plain)=split(/:/,$configline);
12309: 	my ($pack,$name)=split(/\&/,$short);
12310: 	if ($plain ne '') {
12311: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12312: 	    $packagetab{$short}=$plain; 
12313: 	}
12314:     }
12315:     close($config);
12316: }
12317: 
12318: # ---------------------------------------------------------- Read loncaparev table
12319: 
12320: &load_loncaparevs();
12321: 
12322: # ---------------------------------------------------------- Read serverhostID table
12323: 
12324: &load_serverhomeIDs();
12325: 
12326: # ---------------------------------------------------------- Read releaseslist XML
12327: {
12328:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12329:     if (-e $file) {
12330:         my $parser = HTML::LCParser->new($file);
12331:         while (my $token = $parser->get_token()) {
12332:             if ($token->[0] eq 'S') {
12333:                 my $item = $token->[1];
12334:                 my $name = $token->[2]{'name'};
12335:                 my $value = $token->[2]{'value'};
12336:                 if ($item ne '' && $name ne '' && $value ne '') {
12337:                     my $release = $parser->get_text();
12338:                     $release =~ s/(^\s*|\s*$ )//gx;
12339:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12340:                 }
12341:             }
12342:         }
12343:     }
12344: }
12345: 
12346: # ---------------------------------------------------------- Read managers table
12347: {
12348:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12349:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12350:             while (my $configline=<$config>) {
12351:                 chomp($configline);
12352:                 next if ($configline =~ /^\#/);
12353:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12354:                     $managerstab{$configline} = 1;
12355:                 }
12356:             }
12357:             close($config);
12358:         }
12359:     }
12360: }
12361: 
12362: # ------------- set up temporary directory
12363: {
12364:     $tmpdir = LONCAPA::tempdir();
12365: 
12366: }
12367: 
12368: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12369: 				'compress_threshold'=> 20_000,
12370:  			        });
12371: 
12372: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12373: $dumpcount=0;
12374: $locknum=0;
12375: 
12376: &logtouch();
12377: &logthis('<font color="yellow">INFO: Read configuration</font>');
12378: $readit=1;
12379:     {
12380: 	use integer;
12381: 	my $test=(2**32)+1;
12382: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12383: 	&logthis(" Detected 64bit platform ($_64bit)");
12384:     }
12385: }
12386: }
12387: 
12388: 1;
12389: __END__
12390: 
12391: =pod
12392: 
12393: =head1 NAME
12394: 
12395: Apache::lonnet - Subroutines to ask questions about things in the network.
12396: 
12397: =head1 SYNOPSIS
12398: 
12399: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12400: 
12401:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12402: 
12403: Common parameters:
12404: 
12405: =over 4
12406: 
12407: =item *
12408: 
12409: $uname : an internal username (if $cname expecting a course Id specifically)
12410: 
12411: =item *
12412: 
12413: $udom : a domain (if $cdom expecting a course's domain specifically)
12414: 
12415: =item *
12416: 
12417: $symb : a resource instance identifier
12418: 
12419: =item *
12420: 
12421: $namespace : the name of a .db file that contains the data needed or
12422: being set.
12423: 
12424: =back
12425: 
12426: =head1 OVERVIEW
12427: 
12428: lonnet provides subroutines which interact with the
12429: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12430: about classes, users, and resources.
12431: 
12432: For many of these objects you can also use this to store data about
12433: them or modify them in various ways.
12434: 
12435: =head2 Symbs
12436: 
12437: To identify a specific instance of a resource, LON-CAPA uses symbols
12438: or "symbs"X<symb>. These identifiers are built from the URL of the
12439: map, the resource number of the resource in the map, and the URL of
12440: the resource itself. The latter is somewhat redundant, but might help
12441: if maps change.
12442: 
12443: An example is
12444: 
12445:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12446: 
12447: The respective map entry is
12448: 
12449:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12450:   title="Problem 2">
12451:  </resource>
12452: 
12453: Symbs are used by the random number generator, as well as to store and
12454: restore data specific to a certain instance of for example a problem.
12455: 
12456: =head2 Storing And Retrieving Data
12457: 
12458: X<store()>X<cstore()>X<restore()>Three of the most important functions
12459: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12460: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12461: is is the non-critical message twin of cstore. These functions are for
12462: handlers to store a perl hash to a user's permanent data space in an
12463: easy manner, and to retrieve it again on another call. It is expected
12464: that a handler would use this once at the beginning to retrieve data,
12465: and then again once at the end to send only the new data back.
12466: 
12467: The data is stored in the user's data directory on the user's
12468: homeserver under the ID of the course.
12469: 
12470: The hash that is returned by restore will have all of the previous
12471: value for all of the elements of the hash.
12472: 
12473: Example:
12474: 
12475:  #creating a hash
12476:  my %hash;
12477:  $hash{'foo'}='bar';
12478: 
12479:  #storing it
12480:  &Apache::lonnet::cstore(\%hash);
12481: 
12482:  #changing a value
12483:  $hash{'foo'}='notbar';
12484: 
12485:  #adding a new value
12486:  $hash{'bar'}='foo';
12487:  &Apache::lonnet::cstore(\%hash);
12488: 
12489:  #retrieving the hash
12490:  my %history=&Apache::lonnet::restore();
12491: 
12492:  #print the hash
12493:  foreach my $key (sort(keys(%history))) {
12494:    print("\%history{$key} = $history{$key}");
12495:  }
12496: 
12497: Will print out:
12498: 
12499:  %history{1:foo} = bar
12500:  %history{1:keys} = foo:timestamp
12501:  %history{1:timestamp} = 990455579
12502:  %history{2:bar} = foo
12503:  %history{2:foo} = notbar
12504:  %history{2:keys} = foo:bar:timestamp
12505:  %history{2:timestamp} = 990455580
12506:  %history{bar} = foo
12507:  %history{foo} = notbar
12508:  %history{timestamp} = 990455580
12509:  %history{version} = 2
12510: 
12511: Note that the special hash entries C<keys>, C<version> and
12512: C<timestamp> were added to the hash. C<version> will be equal to the
12513: total number of versions of the data that have been stored. The
12514: C<timestamp> attribute will be the UNIX time the hash was
12515: stored. C<keys> is available in every historical section to list which
12516: keys were added or changed at a specific historical revision of a
12517: hash.
12518: 
12519: B<Warning>: do not store the hash that restore returns directly. This
12520: will cause a mess since it will restore the historical keys as if the
12521: were new keys. I.E. 1:foo will become 1:1:foo etc.
12522: 
12523: Calling convention:
12524: 
12525:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12526:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12527: 
12528: For more detailed information, see lonnet specific documentation.
12529: 
12530: =head1 RETURN MESSAGES
12531: 
12532: =over 4
12533: 
12534: =item * B<con_lost>: unable to contact remote host
12535: 
12536: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12537: when the connection is brought back up
12538: 
12539: =item * B<con_failed>: unable to contact remote host and unable to save message
12540: for later delivery
12541: 
12542: =item * B<error:>: an error a occurred, a description of the error follows the :
12543: 
12544: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12545: that was requested
12546: 
12547: =back
12548: 
12549: =head1 PUBLIC SUBROUTINES
12550: 
12551: =head2 Session Environment Functions
12552: 
12553: =over 4
12554: 
12555: =item * 
12556: X<appenv()>
12557: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12558: the user envirnoment file, and will be restored for each access this
12559: user makes during this session, also modifies the %env for the current
12560: process. Optional rolesarrayref - if defined contains a reference to an array
12561: of roles which are exempt from the restriction on modifying user.role entries 
12562: in the user's environment.db and in %env.    
12563: 
12564: =item *
12565: X<delenv()>
12566: B<delenv($delthis,$regexp)>: removes all items from the session
12567: environment file that begin with $delthis. If the 
12568: optional second arg - $regexp - is true, $delthis is treated as a 
12569: regular expression, otherwise \Q$delthis\E is used. 
12570: The values are also deleted from the current processes %env.
12571: 
12572: =item * get_env_multiple($name) 
12573: 
12574: gets $name from the %env hash, it seemlessly handles the cases where multiple
12575: values may be defined and end up as an array ref.
12576: 
12577: returns an array of values
12578: 
12579: =back
12580: 
12581: =head2 User Information
12582: 
12583: =over 4
12584: 
12585: =item *
12586: X<queryauthenticate()>
12587: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12588: authentication scheme
12589: 
12590: =item *
12591: X<authenticate()>
12592: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12593: authenticate user from domain's lib servers (first use the current
12594: one). C<$upass> should be the users password.
12595: $checkdefauth is optional (value is 1 if a check should be made to
12596:    authenticate user using default authentication method, and allow
12597:    account creation if username does not have account in the domain).
12598: $clientcancheckhost is optional (value is 1 if checking whether the
12599:    server can host will occur on the client side in lonauth.pm).   
12600: 
12601: =item *
12602: X<homeserver()>
12603: B<homeserver($uname,$udom)>: find the server which has
12604: the user's directory and files (there must be only one), this caches
12605: the answer, and also caches if there is a borken connection.
12606: 
12607: =item *
12608: X<idget()>
12609: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12610: (IDs are a unique resource in a domain, there must be only 1 ID per
12611: username, and only 1 username per ID in a specific domain) (returns
12612: hash: id=>name,id=>name)
12613: 
12614: =item *
12615: X<idrget()>
12616: B<idrget($udom,@unames)>: find the IDs behind a list of
12617: usernames (returns hash: name=>id,name=>id)
12618: 
12619: =item *
12620: X<idput()>
12621: B<idput($udom,%ids)>: store away a list of names and associated IDs
12622: 
12623: =item *
12624: X<rolesinit()>
12625: B<rolesinit($udom,$username)>: get user privileges.
12626: returns user role, first access and timer interval hashes
12627: 
12628: =item *
12629: X<privileged()>
12630: B<privileged($username,$domain)>: returns a true if user has a
12631: privileged and active role (i.e. su or dc), false otherwise.
12632: 
12633: =item *
12634: X<getsection()>
12635: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12636: course $cname, return section name/number or '' for "not in course"
12637: and '-1' for "no section"
12638: 
12639: =item *
12640: X<userenvironment()>
12641: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12642: passed in @what from the requested user's environment, returns a hash
12643: 
12644: =item * 
12645: X<userlog_query()>
12646: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12647: activity.log file. %filters defines filters applied when parsing the
12648: log file. These can be start or end timestamps, or the type of action
12649: - log to look for Login or Logout events, check for Checkin or
12650: Checkout, role for role selection. The response is in the form
12651: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12652: escaped strings of the action recorded in the activity.log file.
12653: 
12654: =back
12655: 
12656: =head2 User Roles
12657: 
12658: =over 4
12659: 
12660: =item *
12661: 
12662: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12663:  F: full access
12664:  U,I,K: authentication modes (cxx only)
12665:  '': forbidden
12666:  1: user needs to choose course
12667:  2: browse allowed
12668:  A: passphrase authentication needed
12669: 
12670: =item *
12671: 
12672: constructaccess($url,$setpriv) : check for access to construction space URL
12673: 
12674: See if the owner domain and name in the URL match those in the
12675: expected environment.  If so, return three element list
12676: ($ownername,$ownerdomain,$ownerhome).
12677: 
12678: Otherwise return the null string.
12679: 
12680: If second argument 'setpriv' is true, it assigns the privileges,
12681: and returns the same three element list, unless the owner has
12682: blocked "ad hoc" Domain Coordinator access to the Author Space,
12683: in which case the null string is returned.
12684: 
12685: =item *
12686: 
12687: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12688: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12689: and course level
12690: 
12691: =item *
12692: 
12693: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12694: (rolesplain.tab); plain text explanation of a user role term.
12695: $type is Course (default) or Community.
12696: If $forcedefault evaluates to true, text returned will be default 
12697: text for $type. Otherwise, if this is a course, the text returned 
12698: will be a custom name for the role (if defined in the course's 
12699: environment).  If no custom name is defined the default is returned.
12700:    
12701: =item *
12702: 
12703: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12704: All arguments are optional. Returns a hash of a roles, either for
12705: co-author/assistant author roles for a user's Construction Space
12706: (default), or if $context is 'userroles', roles for the user himself,
12707: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12708: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12709: For each key, value is set to colon-separated start and end times for
12710: the role.  If no username and domain are specified, will default to
12711: current user/domain. Types, roles, and roledoms are references to arrays
12712: of role statuses (active, future or previous), roles 
12713: (e.g., cc,in, st etc.) and domains of the roles which can be used
12714: to restrict the list of roles reported. If no array ref is 
12715: provided for types, will default to return only active roles.
12716: 
12717: =item *
12718: 
12719: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12720: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12721: 
12722: Additional optional arguments are: $type (if role checking is to be restricted 
12723: to certain user status types -- previous (expired roles), active (currently
12724: available roles) or future (roles available in the future), and
12725: $hideprivileged -- if true will not report course roles for users who
12726: have active Domain Coordinator role in course's domain or in additional
12727: domains (specified in 'Domains to check for privileged users' in course
12728: environment -- set via:  Course Settings -> Classlists and staff listing).
12729: 
12730: =item *
12731: 
12732: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12733: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12734: $possdomains and $possroles are optional array refs -- to domains to check and
12735: roles to check.  If $possdomains is not specified, a dump will be done of the
12736: users' roles.db to check for a dc or su role in any domain. This can be
12737: time consuming if &privileged is called repeatedly (e.g., when displaying a
12738: classlist), so in such cases, supplying a $possdomains array is preferred, as
12739: this then allows &privileged_by_domain() to be used, which caches the identity
12740: of privileged users, eliminating the need for repeated calls to &dump().
12741: 
12742: =item *
12743: 
12744: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12745: where the outer hash keys are domains specified in the $possdomains array ref,
12746: next inner hash keys are privileged roles specified in the $roles array ref,
12747: and the innermost hash contains key = value pairs for username:domain = end:start
12748: for active or future "privileged" users with that role in that domain. To avoid
12749: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12750: innerhash are cached using priv_$role and $dom as the identifiers.
12751: 
12752: =back
12753: 
12754: =head2 User Modification
12755: 
12756: =over 4
12757: 
12758: =item *
12759: 
12760: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12761: user for the level given by URL.  Optional start and end dates (leave empty
12762: string or zero for "no date")
12763: 
12764: =item *
12765: 
12766: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12767: change a users, password, possible return values are: ok,
12768: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12769: refused
12770: 
12771: =item *
12772: 
12773: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12774: 
12775: =item *
12776: 
12777: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12778:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12779: 
12780: will update user information (firstname,middlename,lastname,generation,
12781: permanentemail), and if forceid is true, student/employee ID also.
12782: A user's institutional affiliation(s) can also be updated.
12783: User information fields will not be overwritten with empty entries 
12784: unless the field is included in the $candelete array reference.
12785: This array is included when a single user is modified via "Manage Users",
12786: or when Autoupdate.pl is run by cron in a domain.
12787: 
12788: =item *
12789: 
12790: modifystudent
12791: 
12792: modify a student's enrollment and identification information.
12793: The course id is resolved based on the current user's environment.  
12794: This means the invoking user must be a course coordinator or otherwise
12795: associated with a course.
12796: 
12797: This call is essentially a wrapper for lonnet::modifyuser and
12798: lonnet::modify_student_enrollment
12799: 
12800: Inputs: 
12801: 
12802: =over 4
12803: 
12804: =item B<$udom> Student's loncapa domain
12805: 
12806: =item B<$uname> Student's loncapa login name
12807: 
12808: =item B<$uid> Student/Employee ID
12809: 
12810: =item B<$umode> Student's authentication mode
12811: 
12812: =item B<$upass> Student's password
12813: 
12814: =item B<$first> Student's first name
12815: 
12816: =item B<$middle> Student's middle name
12817: 
12818: =item B<$last> Student's last name
12819: 
12820: =item B<$gene> Student's generation
12821: 
12822: =item B<$usec> Student's section in course
12823: 
12824: =item B<$end> Unix time of the roles expiration
12825: 
12826: =item B<$start> Unix time of the roles start date
12827: 
12828: =item B<$forceid> If defined, allow $uid to be changed
12829: 
12830: =item B<$desiredhome> server to use as home server for student
12831: 
12832: =item B<$email> Student's permanent e-mail address
12833: 
12834: =item B<$type> Type of enrollment (auto or manual)
12835: 
12836: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12837: 
12838: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12839: 
12840: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12841: 
12842: =item B<$context> role change context (shown in User Management Logs display in a course)
12843: 
12844: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12845: 
12846: =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.
12847: 
12848: =back
12849: 
12850: =item *
12851: 
12852: modify_student_enrollment
12853: 
12854: Change a student's enrollment status in a class.  The environment variable
12855: 'role.request.course' must be defined for this function to proceed.
12856: 
12857: Inputs:
12858: 
12859: =over 4
12860: 
12861: =item $udom, student's domain
12862: 
12863: =item $uname, student's name
12864: 
12865: =item $uid, student's user id
12866: 
12867: =item $first, student's first name
12868: 
12869: =item $middle
12870: 
12871: =item $last
12872: 
12873: =item $gene
12874: 
12875: =item $usec
12876: 
12877: =item $end
12878: 
12879: =item $start
12880: 
12881: =item $type
12882: 
12883: =item $locktype
12884: 
12885: =item $cid
12886: 
12887: =item $selfenroll
12888: 
12889: =item $context
12890: 
12891: =item $credits, number of credits student will earn from this class
12892: 
12893: =back
12894: 
12895: 
12896: =item *
12897: 
12898: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12899: custom role; give a custom role to a user for the level given by URL.  Specify
12900: name and domain of role author, and role name
12901: 
12902: =item *
12903: 
12904: revokerole($udom,$uname,$url,$role) : revoke a role for url
12905: 
12906: =item *
12907: 
12908: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12909: 
12910: =back
12911: 
12912: =head2 Course Infomation
12913: 
12914: =over 4
12915: 
12916: =item *
12917: 
12918: coursedescription($courseid,$options) : returns a hash of information about the
12919: specified course id, including all environment settings for the
12920: course, the description of the course will be in the hash under the
12921: key 'description'
12922: 
12923: $options is an optional parameter that if supplied is a hash reference that controls
12924: what how this function works.  It has the following key/values:
12925: 
12926: =over 4
12927: 
12928: =item freshen_cache
12929: 
12930: If defined, and the environment cache for the course is valid, it is 
12931: returned in the returned hash.
12932: 
12933: =item one_time
12934: 
12935: If defined, the last cache time is set to _now_
12936: 
12937: =item user
12938: 
12939: If defined, the supplied username is used instead of the current user.
12940: 
12941: 
12942: =back
12943: 
12944: =item *
12945: 
12946: resdata($name,$domain,$type,@which) : request for current parameter
12947: setting for a specific $type, where $type is either 'course' or 'user',
12948: @what should be a list of parameters to ask about. This routine caches
12949: answers for 10 minutes.
12950: 
12951: =item *
12952: 
12953: get_courseresdata($courseid, $domain) : dump the entire course resource
12954: data base, returning a hash that is keyed by the resource name and has
12955: values that are the resource value.  I believe that the timestamps and
12956: versions are also returned.
12957: 
12958: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12959: supplemental content area. This routine caches the number of files for 
12960: 10 minutes.
12961: 
12962: =back
12963: 
12964: =head2 Course Modification
12965: 
12966: =over 4
12967: 
12968: =item *
12969: 
12970: writecoursepref($courseid,%prefs) : write preferences (environment
12971: database) for a course
12972: 
12973: =item *
12974: 
12975: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12976: 
12977: =item *
12978: 
12979: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12980: 
12981: =item *
12982: 
12983: is_course($courseid), is_course($cdom, $cnum)
12984: 
12985: Accepts either a combined $courseid (in the form of domain_courseid) or the
12986: two component version $cdom, $cnum. It checks if the specified course exists.
12987: 
12988: Returns:
12989:     undef if the course doesn't exist, otherwise
12990:     in scalar context the combined courseid.
12991:     in list context the two components of the course identifier, domain and 
12992:     courseid.    
12993: 
12994: =back
12995: 
12996: =head2 Resource Subroutines
12997: 
12998: =over 4
12999: 
13000: =item *
13001: 
13002: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13003: 
13004: =item *
13005: 
13006: repcopy($filename) : subscribes to the requested file, and attempts to
13007: replicate from the owning library server, Might return
13008: 'unavailable', 'not_found', 'forbidden', 'ok', or
13009: 'bad_request', also attempts to grab the metadata for the
13010: resource. Expects the local filesystem pathname
13011: (/home/httpd/html/res/....)
13012: 
13013: =back
13014: 
13015: =head2 Resource Information
13016: 
13017: =over 4
13018: 
13019: =item *
13020: 
13021: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13022: and returns the value of a variety of different possible values,
13023: $varname should be a request string, and the other parameters can be
13024: used to specify who and what one is asking about. Ordinarily, $cid 
13025: does not need to be specified, as it is retrived from 
13026: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13027: within lonuserstate::loadmap() when initializing a course, before
13028: $env{'request.course.id'} has been set, so it needs to be provided
13029: in that one case.
13030: 
13031: Possible values for $varname are environment.lastname (or other item
13032: from the envirnment hash), user.name (or someother aspect about the
13033: user), resource.0.maxtries (or some other part and parameter of a
13034: resource)
13035: 
13036: =item *
13037: 
13038: directcondval($number) : get current value of a condition; reads from a state
13039: string
13040: 
13041: =item *
13042: 
13043: condval($condidx) : value of condition index based on state
13044: 
13045: =item *
13046: 
13047: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13048: resource's metadata, $what should be either a specific key, or either
13049: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13050: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13051: 
13052: this function automatically caches all requests
13053: 
13054: =item *
13055: 
13056: metadata_query($query,$custom,$customshow) : make a metadata query against the
13057: network of library servers; returns file handle of where SQL and regex results
13058: will be stored for query
13059: 
13060: =item *
13061: 
13062: symbread($filename) : return symbolic list entry (filename argument optional);
13063: returns the data handle
13064: 
13065: =item *
13066: 
13067: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13068: and is a possible symb for the URL in $thisfn, and if is an encrypted
13069: resource that the user accessed using /enc/ returns a 1 on success, 0
13070: on failure, user must be in a course, as it assumes the existence of
13071: the course initial hash, and uses $env('request.course.id'}.  The third
13072: arg is an optional reference to a scalar.  If this arg is passed in the 
13073: call to symbverify, it will be set to 1 if the symb has been set to be 
13074: encrypted; otherwise it will be null.  
13075: 
13076: =item *
13077: 
13078: symbclean($symb) : removes versions numbers from a symb, returns the
13079: cleaned symb
13080: 
13081: =item *
13082: 
13083: is_on_map($uri) : checks if the $uri is somewhere on the current
13084: course map, user must be in a course for it to work.
13085: 
13086: =item *
13087: 
13088: numval($salt) : return random seed value (addend for rndseed)
13089: 
13090: =item *
13091: 
13092: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13093: a random seed, all arguments are optional, if they aren't sent it uses the
13094: environment to derive them. Note: if symb isn't sent and it can't get one
13095: from &symbread it will use the current time as its return value
13096: 
13097: =item *
13098: 
13099: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13100: unfakeable, receipt
13101: 
13102: =item *
13103: 
13104: receipt() : API to ireceipt working off of env values; given out to users
13105: 
13106: =item *
13107: 
13108: countacc($url) : count the number of accesses to a given URL
13109: 
13110: =item *
13111: 
13112: 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
13113: 
13114: =item *
13115: 
13116: 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)
13117: 
13118: =item *
13119: 
13120: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13121: 
13122: =item *
13123: 
13124: devalidate($symb) : devalidate temporary spreadsheet calculations,
13125: forcing spreadsheet to reevaluate the resource scores next time.
13126: 
13127: =item * 
13128: 
13129: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13130: when viewing in course context.
13131: 
13132:  input: six args -- filename (decluttered), course number, course domain,
13133:                     url, symb (if registered) and group (if this is a 
13134:                     group item -- e.g., bulletin board, group page etc.).
13135: 
13136:  output: array of five scalars --
13137:          $cfile -- url for file editing if editable on current server
13138:          $home -- homeserver of resource (i.e., for author if published,
13139:                                           or course if uploaded.).
13140:          $switchserver --  1 if server switch will be needed.
13141:          $forceedit -- 1 if icon/link should be to go to edit mode 
13142:          $forceview -- 1 if icon/link should be to go to view mode
13143: 
13144: =item *
13145: 
13146: is_course_upload($file,$cnum,$cdom)
13147: 
13148: Used in course context to determine if current file was uploaded to 
13149: the course (i.e., would be found in /userfiles/docs on the course's 
13150: homeserver.
13151: 
13152:   input: 3 args -- filename (decluttered), course number and course domain.
13153:   output: boolean -- 1 if file was uploaded.
13154: 
13155: =back
13156: 
13157: =head2 Storing/Retreiving Data
13158: 
13159: =over 4
13160: 
13161: =item *
13162: 
13163: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13164: for this url; hashref needs to be given and should be a \%hashname; the
13165: remaining args aren't required and if they aren't passed or are '' they will
13166: be derived from the env
13167: 
13168: =item *
13169: 
13170: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13171: uses critical subroutine
13172: 
13173: =item *
13174: 
13175: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13176: all args are optional
13177: 
13178: =item *
13179: 
13180: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13181: dumps the complete (or key matching regexp) namespace into a hash
13182: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13183: normally &store()ed into
13184: 
13185: $range should be either an integer '100' (give me the first 100
13186:                                            matching records)
13187:               or be  two integers sperated by a - with no spaces
13188:                  '30-50' (give me the 30th through the 50th matching
13189:                           records)
13190: 
13191: 
13192: =item *
13193: 
13194: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13195: replaces a &store() version of data with a replacement set of data
13196: for a particular resource in a namespace passed in the $storehash hash 
13197: reference
13198: 
13199: =item *
13200: 
13201: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13202: works very similar to store/cstore, but all data is stored in a
13203: temporary location and can be reset using tmpreset, $storehash should
13204: be a hash reference, returns nothing on success
13205: 
13206: =item *
13207: 
13208: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13209: similar to restore, but all data is stored in a temporary location and
13210: can be reset using tmpreset. Returns a hash of values on success,
13211: error string otherwise.
13212: 
13213: =item *
13214: 
13215: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13216: deltes all keys for $symb form the temporary storage hash.
13217: 
13218: =item *
13219: 
13220: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13221: reference filled in from namesp ($udom and $uname are optional)
13222: 
13223: =item *
13224: 
13225: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13226: namesp ($udom and $uname are optional)
13227: 
13228: =item *
13229: 
13230: dump($namespace,$udom,$uname,$regexp,$range) : 
13231: dumps the complete (or key matching regexp) namespace into a hash
13232: ($udom, $uname, $regexp, $range are optional)
13233: 
13234: $range should be either an integer '100' (give me the first 100
13235:                                            matching records)
13236:               or be  two integers sperated by a - with no spaces
13237:                  '30-50' (give me the 30th through the 50th matching
13238:                           records)
13239: =item *
13240: 
13241: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13242: $store can be a scalar, an array reference, or if the amount to be 
13243: incremented is > 1, a hash reference.
13244: 
13245: ($udom and $uname are optional)
13246: 
13247: =item *
13248: 
13249: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13250: ($udom and $uname are optional)
13251: 
13252: =item *
13253: 
13254: cput($namespace,$storehash,$udom,$uname) : critical put
13255: ($udom and $uname are optional)
13256: 
13257: =item *
13258: 
13259: newput($namespace,$storehash,$udom,$uname) :
13260: 
13261: Attempts to store the items in the $storehash, but only if they don't
13262: currently exist, if this succeeds you can be certain that you have 
13263: successfully created a new key value pair in the $namespace db.
13264: 
13265: 
13266: Args:
13267:  $namespace: name of database to store values to
13268:  $storehash: hashref to store to the db
13269:  $udom: (optional) domain of user containing the db
13270:  $uname: (optional) name of user caontaining the db
13271: 
13272: Returns:
13273:  'ok' -> succeeded in storing all keys of $storehash
13274:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13275:                         least <key> already existed in the db (other
13276:                         requested keys may also already exist)
13277:  'error: <msg>' -> unable to tie the DB or other error occurred
13278:  'con_lost' -> unable to contact request server
13279:  'refused' -> action was not allowed by remote machine
13280: 
13281: 
13282: =item *
13283: 
13284: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13285: reference filled in from namesp (encrypts the return communication)
13286: ($udom and $uname are optional)
13287: 
13288: =item *
13289: 
13290: log($udom,$name,$home,$message) : write to permanent log for user; use
13291: critical subroutine
13292: 
13293: =item *
13294: 
13295: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13296: array reference filled in from namespace found in domain level on either
13297: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13298: 
13299: =item *
13300: 
13301: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13302: domain level either on specified domain server ($uhome) or primary domain 
13303: server ($udom and $uhome are optional)
13304: 
13305: =item * 
13306: 
13307: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13308: for: authentication, language, quotas, timezone, date locale, and portal URL in
13309: the target domain.
13310: 
13311: May also include additional key => value pairs for the following groups:
13312: 
13313: =over
13314: 
13315: =item
13316: disk quotas (MB allocated by default to portfolios and authoring spaces).
13317: 
13318: =over
13319: 
13320: =item defaultquota, authorquota
13321: 
13322: =back
13323: 
13324: =item
13325: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13326: portfolio for users).
13327: 
13328: =over
13329: 
13330: =item
13331: aboutme, blog, webdav, portfolio
13332: 
13333: =back
13334: 
13335: =item
13336: requestcourses: ability to request courses, and how requests are processed.
13337: 
13338: =over
13339: 
13340: =item
13341: official, unofficial, community, textbook
13342: 
13343: =back
13344: 
13345: =item
13346: inststatus: types of institutional affiliation, and order in which they are displayed.
13347: 
13348: =over
13349: 
13350: =item
13351: inststatustypes, inststatusorder
13352: 
13353: =back
13354: 
13355: =item
13356: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13357: for course's uploaded content.
13358: 
13359: =over
13360: 
13361: =item
13362: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13363: communityquota, textbookquota
13364: 
13365: =back
13366: 
13367: =item
13368: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13369: on your servers.
13370: 
13371: =over
13372: 
13373: =item 
13374: remotesessions, hostedsessions
13375: 
13376: =back
13377: 
13378: =back
13379: 
13380: In cases where a domain coordinator has never used the "Set Domain Configuration"
13381: utility to create a configuration.db file on a domain's primary library server 
13382: only the following domain defaults: auth_def, auth_arg_def, lang_def
13383: -- corresponding values are authentication type (internal, krb4, krb5,
13384: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13385: will be available. Values are retrieved from cache (if current), unless the
13386: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13387: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13388: 
13389: Typical usage:
13390: 
13391: %domdefaults = &get_domain_defaults($target_domain);
13392: 
13393: =back
13394: 
13395: =head2 Network Status Functions
13396: 
13397: =over 4
13398: 
13399: =item *
13400: 
13401: dirlist() : return directory list based on URI (first arg).
13402: 
13403: Inputs: 1 required, 5 optional.
13404: 
13405: =over
13406: 
13407: =item 
13408: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13409: 
13410: =item
13411: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13412: 
13413: =item
13414: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13415: 
13416: =item
13417: $getpropath - boolean: 1 if prepend path using &propath(). 
13418: 
13419: =item
13420: $getuserdir - boolean: 1 if prepend path for "userfiles".
13421: 
13422: =item 
13423: $alternateRoot - path to prepend in place of path from $uri.
13424: 
13425: =back
13426: 
13427: Returns: Array of up to two items.
13428: 
13429: =over
13430: 
13431: a reference to an array of files/subdirectories
13432: 
13433: =over
13434: 
13435: Each element in the array of files/subdirectories is a & separated list of
13436: item name and the result of running stat on the item.  If dirlist was requested
13437: for a file instead of a directory, the item name will be ''. For a directory 
13438: listing, if the item is a metadata file, the element will end &N&M 
13439: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13440: default copyright set (1).  
13441: 
13442: =back
13443: 
13444: a scalar containing error condition (if encountered).
13445: 
13446: =over
13447: 
13448: =item 
13449: no_host (no homeserver identified for $username:$domain).
13450: 
13451: =item 
13452: no_such_host (server contacted for listing not identified as valid host).
13453: 
13454: =item 
13455: con_lost (connection to remote server failed).
13456: 
13457: =item 
13458: refused (invalid $username:$domain received on lond side).
13459: 
13460: =item 
13461: no_such_dir (directory at specified path on lond side does not exist). 
13462: 
13463: =item 
13464: empty (directory at specified path on lond side is empty).
13465: 
13466: =over
13467: 
13468: This is currently not encountered because the &ls3, &ls2, 
13469: &ls (_handler) routines on the lond side do not filter out
13470: . and .. from a directory listing. 
13471: 
13472: =back
13473: 
13474: =back
13475: 
13476: =back
13477: 
13478: =item *
13479: 
13480: spareserver() : find server with least workload from spare.tab
13481: 
13482: 
13483: =item *
13484: 
13485: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13486: if there is no corresponding loncapa host.
13487: 
13488: =back
13489: 
13490: 
13491: =head2 Apache Request
13492: 
13493: =over 4
13494: 
13495: =item *
13496: 
13497: ssi($url,%hash) : server side include, does a complete request cycle on url to
13498: localhost, posts hash
13499: 
13500: =back
13501: 
13502: =head2 Data to String to Data
13503: 
13504: =over 4
13505: 
13506: =item *
13507: 
13508: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13509: and '&' separators, supports elements that are arrayrefs and hashrefs
13510: 
13511: =item *
13512: 
13513: hashref2str($hashref) : convert a hashref into a string complete with
13514: escaping and '=' and '&' separators, supports elements that are
13515: arrayrefs and hashrefs
13516: 
13517: =item *
13518: 
13519: arrayref2str($arrayref) : convert an arrayref into a string complete
13520: with escaping and '&' separators, supports elements that are arrayrefs
13521: and hashrefs
13522: 
13523: =item *
13524: 
13525: str2hash($string) : convert string to hash using unescaping and
13526: splitting on '=' and '&', supports elements that are arrayrefs and
13527: hashrefs
13528: 
13529: =item *
13530: 
13531: str2array($string) : convert string to hash using unescaping and
13532: splitting on '&', supports elements that are arrayrefs and hashrefs
13533: 
13534: =back
13535: 
13536: =head2 Logging Routines
13537: 
13538: 
13539: These routines allow one to make log messages in the lonnet.log and
13540: lonnet.perm logfiles.
13541: 
13542: =over 4
13543: 
13544: =item *
13545: 
13546: logtouch() : make sure the logfile, lonnet.log, exists
13547: 
13548: =item *
13549: 
13550: logthis() : append message to the normal lonnet.log file, it gets
13551: preiodically rolled over and deleted.
13552: 
13553: =item *
13554: 
13555: logperm() : append a permanent message to lonnet.perm.log, this log
13556: file never gets deleted by any automated portion of the system, only
13557: messages of critical importance should go in here.
13558: 
13559: 
13560: =back
13561: 
13562: =head2 General File Helper Routines
13563: 
13564: =over 4
13565: 
13566: =item *
13567: 
13568: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13569: (a) files in /uploaded
13570:   (i) If a local copy of the file exists - 
13571:       compares modification date of local copy with last-modified date for 
13572:       definitive version stored on home server for course. If local copy is 
13573:       stale, requests a new version from the home server and stores it. 
13574:       If the original has been removed from the home server, then local copy 
13575:       is unlinked.
13576:   (ii) If local copy does not exist -
13577:       requests the file from the home server and stores it. 
13578:   
13579:   If $caller is 'uploadrep':  
13580:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13581:     for request for files originally uploaded via DOCS. 
13582:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13583:   
13584:   Otherwise:
13585:      This indicates a call from the content generation phase of the request.
13586:      -  returns the entire contents of the file or -1.
13587:      
13588: (b) files in /res
13589:    - returns the entire contents of a file or -1; 
13590:    it properly subscribes to and replicates the file if neccessary.
13591: 
13592: 
13593: =item *
13594: 
13595: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13596:                   reference
13597: 
13598: returns either a stat() list of data about the file or an empty list
13599: if the file doesn't exist or couldn't find out about it (connection
13600: problems or user unknown)
13601: 
13602: =item *
13603: 
13604: filelocation($dir,$file) : returns file system location of a file
13605: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13606: directory that relative $file lookups are to looked in ($dir of /a/dir
13607: and a file of ../bob will become /a/bob)
13608: 
13609: =item *
13610: 
13611: hreflocation($dir,$file) : returns file system location or a URL; same as
13612: filelocation except for hrefs
13613: 
13614: =item *
13615: 
13616: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13617: 
13618: =back
13619: 
13620: =head2 Usererfile file routines (/uploaded*)
13621: 
13622: =over 4
13623: 
13624: =item *
13625: 
13626: userfileupload(): main rotine for putting a file in a user or course's
13627:                   filespace, arguments are,
13628: 
13629:  formname - required - this is the name of the element in $env where the
13630:            filename, and the contents of the file to create/modifed exist
13631:            the filename is in $env{'form.'.$formname.'.filename'} and the
13632:            contents of the file is located in $env{'form.'.$formname}
13633:  context - if coursedoc, store the file in the course of the active role
13634:              of the current user; 
13635:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13636:            if 'canceloverwrite': delete file in tmp/overwrites directory
13637:  subdir - required - subdirectory to put the file in under ../userfiles/
13638:          if undefined, it will be placed in "unknown"
13639: 
13640:  (This routine calls clean_filename() to remove any dangerous
13641:  characters from the filename, and then calls finuserfileupload() to
13642:  complete the transaction)
13643: 
13644:  returns either the url of the uploaded file (/uploaded/....) if successful
13645:  and /adm/notfound.html if unsuccessful
13646: 
13647: =item *
13648: 
13649: clean_filename(): routine for cleaing a filename up for storage in
13650:                  userfile space, argument is:
13651: 
13652:  filename - proposed filename
13653: 
13654: returns: the new clean filename
13655: 
13656: =item *
13657: 
13658: finishuserfileupload(): routine that creates and sends the file to
13659: userspace, probably shouldn't be called directly
13660: 
13661:   docuname: username or courseid of destination for the file
13662:   docudom: domain of user/course of destination for the file
13663:   formname: same as for userfileupload()
13664:   fname: filename (including subdirectories) for the file
13665:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13666:   allfiles: reference to hash used to store objects found by parser
13667:   codebase: reference to hash used for codebases of java objects found by parser
13668:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13669:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13670:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13671:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13672:   context: if 'overwrite', will move the uploaded file from its temporary location to
13673:             userfiles to facilitate overwriting a previously uploaded file with same name.
13674:   mimetype: reference to scalar to accommodate mime type determined
13675:             from File::MMagic if $parser = parse.
13676: 
13677:  returns either the url of the uploaded file (/uploaded/....) if successful
13678:  and /adm/notfound.html if unsuccessful (or an error message if context 
13679:  was 'overwrite').
13680:  
13681: 
13682: =item *
13683: 
13684: renameuserfile(): renames an existing userfile to a new name
13685: 
13686:   Args:
13687:    docuname: username or courseid of destination for the file
13688:    docudom: domain of user/course of destination for the file
13689:    old: current file name (including any subdirs under userfiles)
13690:    new: desired file name (including any subdirs under userfiles)
13691: 
13692: =item *
13693: 
13694: mkdiruserfile(): creates a directory is a userfiles dir
13695: 
13696:   Args:
13697:    docuname: username or courseid of destination for the file
13698:    docudom: domain of user/course of destination for the file
13699:    dir: dir to create (including any subdirs under userfiles)
13700: 
13701: =item *
13702: 
13703: removeuserfile(): removes a file that exists in userfiles
13704: 
13705:   Args:
13706:    docuname: username or courseid of destination for the file
13707:    docudom: domain of user/course of destination for the file
13708:    fname: filname to delete (including any subdirs under userfiles)
13709: 
13710: =item *
13711: 
13712: removeuploadedurl(): convience function for removeuserfile()
13713: 
13714:   Args:
13715:    url:  a full /uploaded/... url to delete
13716: 
13717: =item * 
13718: 
13719: get_portfile_permissions():
13720:   Args:
13721:     domain: domain of user or course contain the portfolio files
13722:     user: name of user or num of course contain the portfolio files
13723:   Returns:
13724:     hashref of a dump of the proper file_permissions.db
13725:    
13726: 
13727: =item * 
13728: 
13729: get_access_controls():
13730: 
13731: Args:
13732:   current_permissions: the hash ref returned from get_portfile_permissions()
13733:   group: (optional) the group you want the files associated with
13734:   file: (optional) the file you want access info on
13735: 
13736: Returns:
13737:     a hash (keys are file names) of hashes containing
13738:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13739:         values are XML containing access control settings (see below) 
13740: 
13741: Internal notes:
13742: 
13743:  access controls are stored in file_permissions.db as key=value pairs.
13744:     key -> path to file/file_name\0uniqueID:scope_end_start
13745:         where scope -> public,guest,course,group,domains or users.
13746:               end -> UNIX time for end of access (0 -> no end date)
13747:               start -> UNIX time for start of access
13748: 
13749:     value -> XML description of access control
13750:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13751:             <start></start>
13752:             <end></end>
13753: 
13754:             <password></password>  for scope type = guest
13755: 
13756:             <domain></domain>     for scope type = course or group
13757:             <number></number>
13758:             <roles id="">
13759:              <role></role>
13760:              <access></access>
13761:              <section></section>
13762:              <group></group>
13763:             </roles>
13764: 
13765:             <dom></dom>         for scope type = domains
13766: 
13767:             <users>             for scope type = users
13768:              <user>
13769:               <uname></uname>
13770:               <udom></udom>
13771:              </user>
13772:             </users>
13773:            </scope> 
13774:               
13775:  Access data is also aggregated for each file in an additional key=value pair:
13776:  key -> path to file/file_name\0accesscontrol 
13777:  value -> reference to hash
13778:           hash contains key = value pairs
13779:           where key = uniqueID:scope_end_start
13780:                 value = UNIX time record was last updated
13781: 
13782:           Used to improve speed of look-ups of access controls for each file.  
13783:  
13784:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13785: 
13786: =item *
13787: 
13788: modify_access_controls():
13789: 
13790: Modifies access controls for a portfolio file
13791: Args
13792: 1. file name
13793: 2. reference to hash of required changes,
13794: 3. domain
13795: 4. username
13796:   where domain,username are the domain of the portfolio owner 
13797:   (either a user or a course) 
13798: 
13799: Returns:
13800: 1. result of additions or updates ('ok' or 'error', with error message). 
13801: 2. result of deletions ('ok' or 'error', with error message).
13802: 3. reference to hash of any new or updated access controls.
13803: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13804:    key = integer (inbound ID)
13805:    value = uniqueID
13806: 
13807: =item *
13808: 
13809: get_timebased_id():
13810: 
13811: Attempts to get a unique timestamp-based suffix for use with items added to a 
13812: course via the Course Editor (e.g., folders, composite pages, 
13813: group bulletin boards).
13814: 
13815: Args: (first three required; six others optional)
13816: 
13817: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13818:    docssequence, or name of group
13819: 
13820: 2. keyid (alphanumeric): name of temporary locking key in hash,
13821:    e.g., num, boardids
13822: 
13823: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13824:    file will be named nohist_namespace.db
13825: 
13826: 4. cdom: domain of course; default is current course domain from %env
13827: 
13828: 5. cnum: course number; default is current course number from %env
13829: 
13830: 6. idtype: set to concat if an additional digit is to be appended to the 
13831:    unix timestamp to form the suffix, if the plain timestamp is already
13832:    in use.  Default is to not do this, but simply increment the unix 
13833:    timestamp by 1 until a unique key is obtained.
13834: 
13835: 7. who: holder of locking key; defaults to user:domain for user.
13836: 
13837: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13838:    retrying); default is 3.
13839: 
13840: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13841: 
13842: Returns:
13843: 
13844: 1. suffix obtained (numeric)
13845: 
13846: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13847: 
13848: 3. error: contains (localized) error message if an error occurred.
13849: 
13850: 
13851: =back
13852: 
13853: =head2 HTTP Helper Routines
13854: 
13855: =over 4
13856: 
13857: =item *
13858: 
13859: escape() : unpack non-word characters into CGI-compatible hex codes
13860: 
13861: =item *
13862: 
13863: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13864: 
13865: =back
13866: 
13867: =head1 PRIVATE SUBROUTINES
13868: 
13869: =head2 Underlying communication routines (Shouldn't call)
13870: 
13871: =over 4
13872: 
13873: =item *
13874: 
13875: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13876: 
13877: =item *
13878: 
13879: reply() : uses subreply to send a message to remote machine, logs all failures
13880: 
13881: =item *
13882: 
13883: critical() : passes a critical message to another server; if cannot
13884: get through then place message in connection buffer directory and
13885: returns con_delayed, if incapable of saving message, returns
13886: con_failed
13887: 
13888: =item *
13889: 
13890: reconlonc() : tries to reconnect lonc client processes.
13891: 
13892: =back
13893: 
13894: =head2 Resource Access Logging
13895: 
13896: =over 4
13897: 
13898: =item *
13899: 
13900: flushcourselogs() : flush (save) buffer logs and access logs
13901: 
13902: =item *
13903: 
13904: courselog($what) : save message for course in hash
13905: 
13906: =item *
13907: 
13908: courseacclog($what) : save message for course using &courselog().  Perform
13909: special processing for specific resource types (problems, exams, quizzes, etc).
13910: 
13911: =item *
13912: 
13913: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13914: as a PerlChildExitHandler
13915: 
13916: =back
13917: 
13918: =head2 Other
13919: 
13920: =over 4
13921: 
13922: =item *
13923: 
13924: symblist($mapname,%newhash) : update symbolic storage links
13925: 
13926: =back
13927: 
13928: =cut
13929: 

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