File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1162: download - view: text, annotated - select for diffs
Sat Mar 31 23:10:55 2012 UTC (12 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6518
  - Exam blocks can also block access to specified folders and/or resources
    for the duration of an exam.
  - Start time for blocking can be based on activation of the timer for
    a specific timed quiz item (map or resource-specific). End time for
    blocking is then start time plus the duration of the timed interval.

lonnet.pm:
  - &rolesinit() now returns an array containing references to hashes
    for the following: userroles, firstaccenv, timerintenv.
  - New db file: timerinterval.db contains interval which applied when
    user activated timer for a map or resource for which time limit applied.
    - needed to determine end time for exam blocks which are triggered by
      timer activation.
   - New routine &get_comm_blocks() used to get communication/collaboration
     blocks from a course.  Now cached for 10 minutes in memcached.
   - New routine: &has_comm_blocking() used to determine if exam block
     applies to display of requested content item in a course. Used by
     &allowed().
   - new routine: &check_docs_block() used by &has_comm_blocking().

loncommon.pm:
   - new items added to user's environment by &init_user_environment()
      - $env{'course.courseid.firstaccess.symb'} and
        $env{'course.courseid.timerinterval.symb'} where symb is the symb
        of the resource or map which provides the activation-based block
        for access to specific content.

blockedaccess.pm:
  - now called when access to content is blocked by an exam block.
    duration, and setter of block now available in pop-up from:
    &loncommon::blocking_status() for this type of access control.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1162 2012/03/31 23:10:55 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: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   80:             %managerstab);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use File::MMagic;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: use LONCAPA::lonmetadata;
  100: 
  101: use File::Copy;
  102: 
  103: my $readit;
  104: my $max_connection_retries = 10;     # Or some such value.
  105: 
  106: require Exporter;
  107: 
  108: our @ISA = qw (Exporter);
  109: our @EXPORT = qw(%env);
  110: 
  111: 
  112: # --------------------------------------------------------------------- Logging
  113: {
  114:     my $logid;
  115:     sub instructor_log {
  116: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  117:         if (($cnum eq '') || ($cdom eq '')) {
  118:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  119:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  120:         }
  121: 	$logid++;
  122:         my $now = time();
  123: 	my $id=$now.'00000'.$$.'00000'.$logid;
  124: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  125: 				    { $id => {
  126: 					'exe_uname' => $env{'user.name'},
  127: 					'exe_udom'  => $env{'user.domain'},
  128: 					'exe_time'  => $now,
  129: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  130: 					'delflag'   => $delflag,
  131: 					'logentry'  => $storehash,
  132: 					'uname'     => $uname,
  133: 					'udom'      => $udom,
  134: 				    }
  135: 				  },$cdom,$cnum);
  136:     }
  137: }
  138: 
  139: sub logtouch {
  140:     my $execdir=$perlvar{'lonDaemons'};
  141:     unless (-e "$execdir/logs/lonnet.log") {	
  142: 	open(my $fh,">>$execdir/logs/lonnet.log");
  143: 	close $fh;
  144:     }
  145:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  146:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  147: }
  148: 
  149: sub logthis {
  150:     my $message=shift;
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     my $now=time;
  153:     my $local=localtime($now);
  154:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  155: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  156: 	print $fh $logstring;
  157: 	close($fh);
  158:     }
  159:     return 1;
  160: }
  161: 
  162: sub logperm {
  163:     my $message=shift;
  164:     my $execdir=$perlvar{'lonDaemons'};
  165:     my $now=time;
  166:     my $local=localtime($now);
  167:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  168: 	print $fh "$now:$message:$local\n";
  169: 	close($fh);
  170:     }
  171:     return 1;
  172: }
  173: 
  174: sub create_connection {
  175:     my ($hostname,$lonid) = @_;
  176:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  177: 				     Type    => SOCK_STREAM,
  178: 				     Timeout => 10);
  179:     return 0 if (!$client);
  180:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  181:     my $result = <$client>;
  182:     chomp($result);
  183:     return 1 if ($result eq 'done');
  184:     return 0;
  185: }
  186: 
  187: sub get_server_timezone {
  188:     my ($cnum,$cdom) = @_;
  189:     my $home=&homeserver($cnum,$cdom);
  190:     if ($home ne 'no_host') {
  191:         my $cachetime = 24*3600;
  192:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  193:         if (defined($cached)) {
  194:             return $timezone;
  195:         } else {
  196:             my $timezone = &reply('servertimezone',$home);
  197:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  198:         }
  199:     }
  200: }
  201: 
  202: sub get_server_distarch {
  203:     my ($lonhost,$ignore_cache) = @_;
  204:     if (defined($lonhost)) {
  205:         if (!defined(&hostname($lonhost))) {
  206:             return;
  207:         }
  208:         my $cachetime = 12*3600;
  209:         if (!$ignore_cache) {
  210:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  211:             if (defined($cached)) {
  212:                 return $distarch;
  213:             }
  214:         }
  215:         my $rep = &reply('serverdistarch',$lonhost);
  216:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  217:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  218:                 $rep eq '') {
  219:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  220:         }
  221:     }
  222:     return;
  223: }
  224: 
  225: sub get_server_loncaparev {
  226:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  227:     if (defined($lonhost)) {
  228:         if (!defined(&hostname($lonhost))) {
  229:             undef($lonhost);
  230:         }
  231:     }
  232:     if (!defined($lonhost)) {
  233:         if (defined(&domain($dom,'primary'))) {
  234:             $lonhost=&domain($dom,'primary');
  235:             if ($lonhost eq 'no_host') {
  236:                 undef($lonhost);
  237:             }
  238:         }
  239:     }
  240:     if (defined($lonhost)) {
  241:         my $cachetime = 12*3600;
  242:         if (!$ignore_cache) {
  243:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  244:             if (defined($cached)) {
  245:                 return $loncaparev;
  246:             }
  247:         }
  248:         my ($answer,$loncaparev);
  249:         my @ids=&current_machine_ids();
  250:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  251:             $answer = $perlvar{'lonVersion'};
  252:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  253:                 $loncaparev = $1;
  254:             }
  255:         } else {
  256:             $answer = &reply('serverloncaparev',$lonhost);
  257:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  258:                 if ($caller eq 'loncron') {
  259:                     my $ua=new LWP::UserAgent;
  260:                     $ua->timeout(4);
  261:                     my $protocol = $protocol{$lonhost};
  262:                     $protocol = 'http' if ($protocol ne 'https');
  263:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  264:                     my $request=new HTTP::Request('GET',$url);
  265:                     my $response=$ua->request($request);
  266:                     unless ($response->is_error()) {
  267:                         my $content = $response->content;
  268:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  269:                             $loncaparev = $1;
  270:                         }
  271:                     }
  272:                 } else {
  273:                     $loncaparev = $loncaparevs{$lonhost};
  274:                 }
  275:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  276:                 $loncaparev = $1;
  277:             }
  278:         }
  279:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  280:     }
  281: }
  282: 
  283: sub get_server_homeID {
  284:     my ($hostname,$ignore_cache,$caller) = @_;
  285:     unless ($ignore_cache) {
  286:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  287:         if (defined($cached)) {
  288:             return $serverhomeID;
  289:         }
  290:     }
  291:     my $cachetime = 12*3600;
  292:     my $serverhomeID;
  293:     if ($caller eq 'loncron') { 
  294:         my @machine_ids = &machine_ids($hostname);
  295:         foreach my $id (@machine_ids) {
  296:             my $response = &reply('serverhomeID',$id);
  297:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  298:                 $serverhomeID = $response;
  299:                 last;
  300:             }
  301:         }
  302:         if ($serverhomeID eq '') {
  303:             $serverhomeID = $machine_ids[-1];
  304:         }
  305:     } else {
  306:         $serverhomeID = $serverhomeIDs{$hostname};
  307:     }
  308:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  309: }
  310: 
  311: sub get_remote_globals {
  312:     my ($lonhost,$whathash,$ignore_cache) = @_;
  313:     my ($result,%returnhash,%whatneeded);
  314:     if (ref($whathash) eq 'HASH') {
  315:         foreach my $what (sort(keys(%{$whathash}))) {
  316:             my $hashid = $lonhost.'-'.$what;
  317:             my ($response,$cached);
  318:             unless ($ignore_cache) {
  319:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  320:             }
  321:             if (defined($cached)) {
  322:                 $returnhash{$what} = $response;
  323:             } else {
  324:                 $whatneeded{$what} = 1;
  325:             }
  326:         }
  327:         if (keys(%whatneeded) == 0) {
  328:             $result = 'ok';
  329:         } else {
  330:             my $requested = &freeze_escape(\%whatneeded);
  331:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  332:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  333:                 ($rep eq 'unknown_cmd')) {
  334:                 $result = $rep;
  335:             } else {
  336:                 $result = 'ok';
  337:                 my @pairs=split(/\&/,$rep);
  338:                 foreach my $item (@pairs) {
  339:                     my ($key,$value)=split(/=/,$item,2);
  340:                     my $what = &unescape($key);
  341:                     my $hashid = $lonhost.'-'.$what;
  342:                     $returnhash{$what}=&thaw_unescape($value);
  343:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  344:                 }
  345:             }
  346:         }
  347:     }
  348:     return ($result,\%returnhash);
  349: }
  350: 
  351: sub remote_devalidate_cache {
  352:     my ($lonhost,$name,$id) = @_;
  353:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  354:     return $response;
  355: }
  356: 
  357: # -------------------------------------------------- Non-critical communication
  358: sub subreply {
  359:     my ($cmd,$server)=@_;
  360:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  361:     #
  362:     #  With loncnew process trimming, there's a timing hole between lonc server
  363:     #  process exit and the master server picking up the listen on the AF_UNIX
  364:     #  socket.  In that time interval, a lock file will exist:
  365: 
  366:     my $lockfile=$peerfile.".lock";
  367:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  368: 	sleep(1);
  369:     }
  370:     # At this point, either a loncnew parent is listening or an old lonc
  371:     # or loncnew child is listening so we can connect or everything's dead.
  372:     #
  373:     #   We'll give the connection a few tries before abandoning it.  If
  374:     #   connection is not possible, we'll con_lost back to the client.
  375:     #   
  376:     my $client;
  377:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  378: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  379: 				      Type    => SOCK_STREAM,
  380: 				      Timeout => 10);
  381: 	if ($client) {
  382: 	    last;		# Connected!
  383: 	} else {
  384: 	    &create_connection(&hostname($server),$server);
  385: 	}
  386:         sleep(1);		# Try again later if failed connection.
  387:     }
  388:     my $answer;
  389:     if ($client) {
  390: 	print $client "sethost:$server:$cmd\n";
  391: 	$answer=<$client>;
  392: 	if (!$answer) { $answer="con_lost"; }
  393: 	chomp($answer);
  394:     } else {
  395: 	$answer = 'con_lost';	# Failed connection.
  396:     }
  397:     return $answer;
  398: }
  399: 
  400: sub reply {
  401:     my ($cmd,$server)=@_;
  402:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  403:     my $answer=subreply($cmd,$server);
  404:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  405:        &logthis("<font color=\"blue\">WARNING:".
  406:                 " $cmd to $server returned $answer</font>");
  407:     }
  408:     return $answer;
  409: }
  410: 
  411: # ----------------------------------------------------------- Send USR1 to lonc
  412: 
  413: sub reconlonc {
  414:     my ($lonid) = @_;
  415:     my $hostname = &hostname($lonid);
  416:     if ($lonid) {
  417: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  418: 	if ($hostname && -e $peerfile) {
  419: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  420: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  421: 					     Type    => SOCK_STREAM,
  422: 					     Timeout => 10);
  423: 	    if ($client) {
  424: 		print $client ("reset_retries\n");
  425: 		my $answer=<$client>;
  426: 		#reset just this one.
  427: 	    }
  428: 	}
  429: 	return;
  430:     }
  431: 
  432:     &logthis("Trying to reconnect lonc");
  433:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  434:     if (open(my $fh,"<$loncfile")) {
  435: 	my $loncpid=<$fh>;
  436:         chomp($loncpid);
  437:         if (kill 0 => $loncpid) {
  438: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  439:             kill USR1 => $loncpid;
  440:             sleep 1;
  441:          } else {
  442: 	    &logthis(
  443:                "<font color=\"blue\">WARNING:".
  444:                " lonc at pid $loncpid not responding, giving up</font>");
  445:         }
  446:     } else {
  447: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  448:     }
  449: }
  450: 
  451: # ------------------------------------------------------ Critical communication
  452: 
  453: sub critical {
  454:     my ($cmd,$server)=@_;
  455:     unless (&hostname($server)) {
  456:         &logthis("<font color=\"blue\">WARNING:".
  457:                " Critical message to unknown server ($server)</font>");
  458:         return 'no_such_host';
  459:     }
  460:     my $answer=reply($cmd,$server);
  461:     if ($answer eq 'con_lost') {
  462: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  463: 	my $answer=reply($cmd,$server);
  464:         if ($answer eq 'con_lost') {
  465:             my $now=time;
  466:             my $middlename=$cmd;
  467:             $middlename=substr($middlename,0,16);
  468:             $middlename=~s/\W//g;
  469:             my $dfilename=
  470:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  471:             $dumpcount++;
  472:             {
  473: 		my $dfh;
  474: 		if (open($dfh,">$dfilename")) {
  475: 		    print $dfh "$cmd\n"; 
  476: 		    close($dfh);
  477: 		}
  478:             }
  479:             sleep 2;
  480:             my $wcmd='';
  481:             {
  482: 		my $dfh;
  483: 		if (open($dfh,"<$dfilename")) {
  484: 		    $wcmd=<$dfh>; 
  485: 		    close($dfh);
  486: 		}
  487:             }
  488:             chomp($wcmd);
  489:             if ($wcmd eq $cmd) {
  490: 		&logthis("<font color=\"blue\">WARNING: ".
  491:                          "Connection buffer $dfilename: $cmd</font>");
  492:                 &logperm("D:$server:$cmd");
  493: 	        return 'con_delayed';
  494:             } else {
  495:                 &logthis("<font color=\"red\">CRITICAL:"
  496:                         ." Critical connection failed: $server $cmd</font>");
  497:                 &logperm("F:$server:$cmd");
  498:                 return 'con_failed';
  499:             }
  500:         }
  501:     }
  502:     return $answer;
  503: }
  504: 
  505: # ------------------------------------------- check if return value is an error
  506: 
  507: sub error {
  508:     my ($result) = @_;
  509:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  510: 	if ($2 == 2) { return undef; }
  511: 	return $1;
  512:     }
  513:     return undef;
  514: }
  515: 
  516: sub convert_and_load_session_env {
  517:     my ($lonidsdir,$handle)=@_;
  518:     my @profile;
  519:     {
  520: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  521: 	if (!$opened) {
  522: 	    return 0;
  523: 	}
  524: 	flock($idf,LOCK_SH);
  525: 	@profile=<$idf>;
  526: 	close($idf);
  527:     }
  528:     my %temp_env;
  529:     foreach my $line (@profile) {
  530: 	if ($line !~ m/=/) {
  531: 	    return 0;
  532: 	}
  533: 	chomp($line);
  534: 	my ($envname,$envvalue)=split(/=/,$line,2);
  535: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  536:     }
  537:     unlink("$lonidsdir/$handle.id");
  538:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  539: 	    0640)) {
  540: 	%disk_env = %temp_env;
  541: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  542: 	untie(%disk_env);
  543:     }
  544:     return 1;
  545: }
  546: 
  547: # ------------------------------------------- Transfer profile into environment
  548: my $env_loaded;
  549: sub transfer_profile_to_env {
  550:     my ($lonidsdir,$handle,$force_transfer) = @_;
  551:     if (!$force_transfer && $env_loaded) { return; } 
  552: 
  553:     if (!defined($lonidsdir)) {
  554: 	$lonidsdir = $perlvar{'lonIDsDir'};
  555:     }
  556:     if (!defined($handle)) {
  557:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  558:     }
  559: 
  560:     my $convert;
  561:     {
  562:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  563: 	if (!$opened) {
  564: 	    return;
  565: 	}
  566: 	flock($idf,LOCK_SH);
  567: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  568: 		&GDBM_READER(),0640)) {
  569: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  570: 	    untie(%disk_env);
  571: 	} else {
  572: 	    $convert = 1;
  573: 	}
  574:     }
  575:     if ($convert) {
  576: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  577: 	    &logthis("Failed to load session, or convert session.");
  578: 	}
  579:     }
  580: 
  581:     my %remove;
  582:     while ( my $envname = each(%env) ) {
  583:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  584:             if ($time < time-300) {
  585:                 $remove{$key}++;
  586:             }
  587:         }
  588:     }
  589: 
  590:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  591:     $env_loaded=1;
  592:     foreach my $expired_key (keys(%remove)) {
  593:         &delenv($expired_key);
  594:     }
  595: }
  596: 
  597: # ---------------------------------------------------- Check for valid session 
  598: sub check_for_valid_session {
  599:     my ($r,$name) = @_;
  600:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  601:     if ($name eq '') {
  602:         $name = 'lonID';
  603:     }
  604:     my $lonid=$cookies{$name};
  605:     return undef if (!$lonid);
  606: 
  607:     my $handle=&LONCAPA::clean_handle($lonid->value);
  608:     my $lonidsdir;
  609:     if ($name eq 'lonDAV') {
  610:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  611:     } else {
  612:         $lonidsdir=$r->dir_config('lonIDsDir');
  613:     }
  614:     return undef if (!-e "$lonidsdir/$handle.id");
  615: 
  616:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  617:     return undef if (!$opened);
  618: 
  619:     flock($idf,LOCK_SH);
  620:     my %disk_env;
  621:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  622: 	    &GDBM_READER(),0640)) {
  623: 	return undef;	
  624:     }
  625: 
  626:     if (!defined($disk_env{'user.name'})
  627: 	|| !defined($disk_env{'user.domain'})) {
  628: 	return undef;
  629:     }
  630:     return $handle;
  631: }
  632: 
  633: sub timed_flock {
  634:     my ($file,$lock_type) = @_;
  635:     my $failed=0;
  636:     eval {
  637: 	local $SIG{__DIE__}='DEFAULT';
  638: 	local $SIG{ALRM}=sub {
  639: 	    $failed=1;
  640: 	    die("failed lock");
  641: 	};
  642: 	alarm(13);
  643: 	flock($file,$lock_type);
  644: 	alarm(0);
  645:     };
  646:     if ($failed) {
  647: 	return undef;
  648:     } else {
  649: 	return 1;
  650:     }
  651: }
  652: 
  653: # ---------------------------------------------------------- Append Environment
  654: 
  655: sub appenv {
  656:     my ($newenv,$roles) = @_;
  657:     if (ref($newenv) eq 'HASH') {
  658:         foreach my $key (keys(%{$newenv})) {
  659:             my $refused = 0;
  660: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  661:                 $refused = 1;
  662:                 if (ref($roles) eq 'ARRAY') {
  663:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  664:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  665:                         $refused = 0;
  666:                     }
  667:                 }
  668:             }
  669:             if ($refused) {
  670:                 &logthis("<font color=\"blue\">WARNING: ".
  671:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  672:                          .'</font>');
  673: 	        delete($newenv->{$key});
  674:             } else {
  675:                 $env{$key}=$newenv->{$key};
  676:             }
  677:         }
  678:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  679:         if ($opened
  680: 	    && &timed_flock($env_file,LOCK_EX)
  681: 	    &&
  682: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  683: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  684: 	    while (my ($key,$value) = each(%{$newenv})) {
  685: 	        $disk_env{$key} = $value;
  686: 	    }
  687: 	    untie(%disk_env);
  688:         }
  689:     }
  690:     return 'ok';
  691: }
  692: # ----------------------------------------------------- Delete from Environment
  693: 
  694: sub delenv {
  695:     my ($delthis,$regexp,$roles) = @_;
  696:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  697:         my $refused = 1;
  698:         if (ref($roles) eq 'ARRAY') {
  699:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  700:             if (grep(/^\Q$role\E$/,@{$roles})) {
  701:                 $refused = 0;
  702:             }
  703:         }
  704:         if ($refused) {
  705:             &logthis("<font color=\"blue\">WARNING: ".
  706:                      "Attempt to delete from environment ".$delthis);
  707:             return 'error';
  708:         }
  709:     }
  710:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  711:     if ($opened
  712: 	&& &timed_flock($env_file,LOCK_EX)
  713: 	&&
  714: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  715: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  716: 	foreach my $key (keys(%disk_env)) {
  717: 	    if ($regexp) {
  718:                 if ($key=~/^$delthis/) {
  719:                     delete($env{$key});
  720:                     delete($disk_env{$key});
  721:                 } 
  722:             } else {
  723:                 if ($key=~/^\Q$delthis\E/) {
  724: 		    delete($env{$key});
  725: 		    delete($disk_env{$key});
  726: 	        }
  727:             }
  728: 	}
  729: 	untie(%disk_env);
  730:     }
  731:     return 'ok';
  732: }
  733: 
  734: sub get_env_multiple {
  735:     my ($name) = @_;
  736:     my @values;
  737:     if (defined($env{$name})) {
  738:         # exists is it an array
  739:         if (ref($env{$name})) {
  740:             @values=@{ $env{$name} };
  741:         } else {
  742:             $values[0]=$env{$name};
  743:         }
  744:     }
  745:     return(@values);
  746: }
  747: 
  748: # ------------------------------------------------------------------- Locking
  749: 
  750: sub set_lock {
  751:     my ($text)=@_;
  752:     $locknum++;
  753:     my $id=$$.'-'.$locknum;
  754:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  755:              'session.lock.'.$id => $text});
  756:     return $id;
  757: }
  758: 
  759: sub get_locks {
  760:     my $num=0;
  761:     my %texts=();
  762:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  763:        if ($lock=~/\w/) {
  764:           $num++;
  765:           $texts{$lock}=$env{'session.lock.'.$lock};
  766:        }
  767:    }
  768:    return ($num,%texts);
  769: }
  770: 
  771: sub remove_lock {
  772:     my ($id)=@_;
  773:     my $newlocks='';
  774:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  775:        if (($lock=~/\w/) && ($lock ne $id)) {
  776:           $newlocks.=','.$lock;
  777:        }
  778:     }
  779:     &appenv({'session.locks' => $newlocks});
  780:     &delenv('session.lock.'.$id);
  781: }
  782: 
  783: sub remove_all_locks {
  784:     my $activelocks=$env{'session.locks'};
  785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  786:        if ($lock=~/\w/) {
  787:           &remove_lock($lock);
  788:        }
  789:     }
  790: }
  791: 
  792: 
  793: # ------------------------------------------ Find out current server userload
  794: sub userload {
  795:     my $numusers=0;
  796:     {
  797: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  798: 	my $filename;
  799: 	my $curtime=time;
  800: 	while ($filename=readdir(LONIDS)) {
  801: 	    next if ($filename eq '.' || $filename eq '..');
  802: 	    next if ($filename =~ /publicuser_\d+\.id/);
  803: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  804: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  805: 	}
  806: 	closedir(LONIDS);
  807:     }
  808:     my $userloadpercent=0;
  809:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  810:     if ($maxuserload) {
  811: 	$userloadpercent=100*$numusers/$maxuserload;
  812:     }
  813:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  814:     return $userloadpercent;
  815: }
  816: 
  817: # ------------------------------ Find server with least workload from spare.tab
  818: 
  819: sub spareserver {
  820:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  821:     my $spare_server;
  822:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  823:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  824:                                                      :  $userloadpercent;
  825:     my ($uint_dom,$remotesessions);
  826:     if (($udom ne '') && (&domain($udom) ne '')) {
  827:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  828:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  829:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  830:         $remotesessions = $udomdefaults{'remotesessions'};
  831:     }
  832:     my $spareshash = &this_host_spares($udom);
  833:     if (ref($spareshash) eq 'HASH') {
  834:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  835:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  836:                 if ($uint_dom) {
  837:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  838:                                                  $try_server));
  839:                 }
  840: 	        ($spare_server, $lowest_load) =
  841: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  842:             }
  843:         }
  844: 
  845:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  846: 
  847:         if (!$found_server) {
  848:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  849: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  850:                     if ($uint_dom) {
  851:                         next unless (&spare_can_host($udom,$uint_dom,
  852:                                                      $remotesessions,$try_server));
  853:                     }
  854: 	            ($spare_server, $lowest_load) =
  855: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  856:                 }
  857: 	    }
  858:         }
  859:     }
  860: 
  861:     if (!$want_server_name) {
  862:         my $protocol = 'http';
  863:         if ($protocol{$spare_server} eq 'https') {
  864:             $protocol = $protocol{$spare_server};
  865:         }
  866:         if (defined($spare_server)) {
  867:             my $hostname = &hostname($spare_server);
  868:             if (defined($hostname)) {
  869: 	        $spare_server = $protocol.'://'.$hostname;
  870:             }
  871:         }
  872:     }
  873:     return $spare_server;
  874: }
  875: 
  876: sub compare_server_load {
  877:     my ($try_server, $spare_server, $lowest_load) = @_;
  878: 
  879:     my $loadans     = &reply('load',    $try_server);
  880:     my $userloadans = &reply('userload',$try_server);
  881: 
  882:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  883: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  884:     }
  885: 
  886:     my $load;
  887:     if ($loadans =~ /\d/) {
  888: 	if ($userloadans =~ /\d/) {
  889: 	    #both are numbers, pick the bigger one
  890: 	    $load = ($loadans > $userloadans) ? $loadans 
  891: 		                              : $userloadans;
  892: 	} else {
  893: 	    $load = $loadans;
  894: 	}
  895:     } else {
  896: 	$load = $userloadans;
  897:     }
  898: 
  899:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  900: 	$spare_server = $try_server;
  901: 	$lowest_load  = $load;
  902:     }
  903:     return ($spare_server,$lowest_load);
  904: }
  905: 
  906: # --------------------------- ask offload servers if user already has a session
  907: sub find_existing_session {
  908:     my ($udom,$uname) = @_;
  909:     my $spareshash = &this_host_spares($udom);
  910:     if (ref($spareshash) eq 'HASH') {
  911:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  912:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  913:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  914:             }
  915:         }
  916:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  917:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  918:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  919:             }
  920:         }
  921:     }
  922:     return;
  923: }
  924: 
  925: # -------------------------------- ask if server already has a session for user
  926: sub has_user_session {
  927:     my ($lonid,$udom,$uname) = @_;
  928:     my $result = &reply(join(':','userhassession',
  929: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  930:     return 1 if ($result eq 'ok');
  931: 
  932:     return 0;
  933: }
  934: 
  935: # --------- determine least loaded server in a user's domain which allows login
  936: 
  937: sub choose_server {
  938:     my ($udom,$checkloginvia) = @_;
  939:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  940:     my %servers = &get_servers($udom);
  941:     my $lowest_load = 30000;
  942:     my ($login_host,$hostname,$portal_path,$isredirect);
  943:     foreach my $lonhost (keys(%servers)) {
  944:         my $loginvia;
  945:         if ($checkloginvia) {
  946:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  947:             if ($loginvia) {
  948:                 my ($server,$path) = split(/:/,$loginvia);
  949:                 ($login_host, $lowest_load) =
  950:                     &compare_server_load($server, $login_host, $lowest_load);
  951:                 if ($login_host eq $server) {
  952:                     $portal_path = $path;
  953:                     $isredirect = 1;
  954:                 }
  955:             } else {
  956:                 ($login_host, $lowest_load) =
  957:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  958:                 if ($login_host eq $lonhost) {
  959:                     $portal_path = '';
  960:                     $isredirect = ''; 
  961:                 }
  962:             }
  963:         } else {
  964:             ($login_host, $lowest_load) =
  965:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  966:         }
  967:     }
  968:     if ($login_host ne '') {
  969:         $hostname = &hostname($login_host);
  970:     }
  971:     return ($login_host,$hostname,$portal_path,$isredirect);
  972: }
  973: 
  974: # --------------------------------------------- Try to change a user's password
  975: 
  976: sub changepass {
  977:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  978:     $currentpass = &escape($currentpass);
  979:     $newpass     = &escape($newpass);
  980:     my $lonhost = $perlvar{'lonHostID'};
  981:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  982: 		       $server);
  983:     if (! $answer) {
  984: 	&logthis("No reply on password change request to $server ".
  985: 		 "by $uname in domain $udom.");
  986:     } elsif ($answer =~ "^ok") {
  987:         &logthis("$uname in $udom successfully changed their password ".
  988: 		 "on $server.");
  989:     } elsif ($answer =~ "^pwchange_failure") {
  990: 	&logthis("$uname in $udom was unable to change their password ".
  991: 		 "on $server.  The action was blocked by either lcpasswd ".
  992: 		 "or pwchange");
  993:     } elsif ($answer =~ "^non_authorized") {
  994:         &logthis("$uname in $udom did not get their password correct when ".
  995: 		 "attempting to change it on $server.");
  996:     } elsif ($answer =~ "^auth_mode_error") {
  997:         &logthis("$uname in $udom attempted to change their password despite ".
  998: 		 "not being locally or internally authenticated on $server.");
  999:     } elsif ($answer =~ "^unknown_user") {
 1000:         &logthis("$uname in $udom attempted to change their password ".
 1001: 		 "on $server but were unable to because $server is not ".
 1002: 		 "their home server.");
 1003:     } elsif ($answer =~ "^refused") {
 1004: 	&logthis("$server refused to change $uname in $udom password because ".
 1005: 		 "it was sent an unencrypted request to change the password.");
 1006:     } elsif ($answer =~ "invalid_client") {
 1007:         &logthis("$server refused to change $uname in $udom password because ".
 1008:                  "it was a reset by e-mail originating from an invalid server.");
 1009:     }
 1010:     return $answer;
 1011: }
 1012: 
 1013: # ----------------------- Try to determine user's current authentication scheme
 1014: 
 1015: sub queryauthenticate {
 1016:     my ($uname,$udom)=@_;
 1017:     my $uhome=&homeserver($uname,$udom);
 1018:     if (!$uhome) {
 1019: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1020: 	return 'no_host';
 1021:     }
 1022:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1023:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1024: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1025:     }
 1026:     return $answer;
 1027: }
 1028: 
 1029: # --------- Try to authenticate user from domain's lib servers (first this one)
 1030: 
 1031: sub authenticate {
 1032:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1033:     $upass=&escape($upass);
 1034:     $uname= &LONCAPA::clean_username($uname);
 1035:     my $uhome=&homeserver($uname,$udom,1);
 1036:     my $newhome;
 1037:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1038: # Maybe the machine was offline and only re-appeared again recently?
 1039:         &reconlonc();
 1040: # One more
 1041: 	$uhome=&homeserver($uname,$udom,1);
 1042:         if (($uhome eq 'no_host') && $checkdefauth) {
 1043:             if (defined(&domain($udom,'primary'))) {
 1044:                 $newhome=&domain($udom,'primary');
 1045:             }
 1046:             if ($newhome ne '') {
 1047:                 $uhome = $newhome;
 1048:             }
 1049:         }
 1050: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1051: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1052: 	    return 'no_host';
 1053:         }
 1054:     }
 1055:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1056:     if ($answer eq 'authorized') {
 1057:         if ($newhome) {
 1058:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1059:             return 'no_account_on_host'; 
 1060:         } else {
 1061:             &logthis("User $uname at $udom authorized by $uhome");
 1062:             return $uhome;
 1063:         }
 1064:     }
 1065:     if ($answer eq 'non_authorized') {
 1066: 	&logthis("User $uname at $udom rejected by $uhome");
 1067: 	return 'no_host'; 
 1068:     }
 1069:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1070:     return 'no_host';
 1071: }
 1072: 
 1073: sub can_host_session {
 1074:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1075:     my $canhost = 1;
 1076:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1077:     if (ref($remotesessions) eq 'HASH') {
 1078:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1079:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1080:                 $canhost = 0;
 1081:             } else {
 1082:                 $canhost = 1;
 1083:             }
 1084:         }
 1085:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1087:                 $canhost = 1;
 1088:             } else {
 1089:                 $canhost = 0;
 1090:             }
 1091:         }
 1092:         if ($canhost) {
 1093:             if ($remotesessions->{'version'} ne '') {
 1094:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1095:                 if ($reqmajor ne '' && $reqminor ne '') {
 1096:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1097:                         my $major = $1;
 1098:                         my $minor = $2;
 1099:                         if (($major < $reqmajor ) ||
 1100:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1101:                             $canhost = 0;
 1102:                         }
 1103:                     } else {
 1104:                         $canhost = 0;
 1105:                     }
 1106:                 }
 1107:             }
 1108:         }
 1109:     }
 1110:     if ($canhost) {
 1111:         if (ref($hostedsessions) eq 'HASH') {
 1112:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1113:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1114:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1115:                 if (($uint_dom ne '') && 
 1116:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1117:                     $canhost = 0;
 1118:                 } else {
 1119:                     $canhost = 1;
 1120:                 }
 1121:             }
 1122:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1123:                 if (($uint_dom ne '') && 
 1124:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1125:                     $canhost = 1;
 1126:                 } else {
 1127:                     $canhost = 0;
 1128:                 }
 1129:             }
 1130:         }
 1131:     }
 1132:     return $canhost;
 1133: }
 1134: 
 1135: sub spare_can_host {
 1136:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1137:     my $canhost=1;
 1138:     my @intdoms;
 1139:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1140:     if (ref($internet_names) eq 'ARRAY') {
 1141:         @intdoms = @{$internet_names};
 1142:     }
 1143:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1144:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1145:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1146:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1147:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1148:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1149:                                      $remotesessions,
 1150:                                      $defdomdefaults{'hostedsessions'});
 1151:     }
 1152:     return $canhost;
 1153: }
 1154: 
 1155: sub this_host_spares {
 1156:     my ($dom) = @_;
 1157:     my ($dom_in_use,$lonhost_in_use,$result);
 1158:     my @hosts = &current_machine_ids();
 1159:     foreach my $lonhost (@hosts) {
 1160:         if (&host_domain($lonhost) eq $dom) {
 1161:             $dom_in_use = $dom;
 1162:             $lonhost_in_use = $lonhost;
 1163:             last;
 1164:         }
 1165:     }
 1166:     if ($dom_in_use ne '') {
 1167:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1168:     }
 1169:     if (ref($result) ne 'HASH') {
 1170:         $lonhost_in_use = $perlvar{'lonHostID'};
 1171:         $dom_in_use = &host_domain($lonhost_in_use);
 1172:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1173:         if (ref($result) ne 'HASH') {
 1174:             $result = \%spareid;
 1175:         }
 1176:     }
 1177:     return $result;
 1178: }
 1179: 
 1180: sub spares_for_offload  {
 1181:     my ($dom_in_use,$lonhost_in_use) = @_;
 1182:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1183:     if (defined($cached)) {
 1184:         return $result;
 1185:     } else {
 1186:         my $cachetime = 60*60*24;
 1187:         my %domconfig =
 1188:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1189:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1190:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1191:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1192:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1193:                 }
 1194:             }
 1195:         }
 1196:     }
 1197:     return;
 1198: }
 1199: 
 1200: sub get_lonbalancer_config {
 1201:     my ($servers) = @_;
 1202:     my ($currbalancer,$currtargets);
 1203:     if (ref($servers) eq 'HASH') {
 1204:         foreach my $server (keys(%{$servers})) {
 1205:             my %what = (
 1206:                          spareid => 1,
 1207:                          perlvar => 1,
 1208:                        );
 1209:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1210:             if ($result eq 'ok') {
 1211:                 if (ref($returnhash) eq 'HASH') {
 1212:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1213:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1214:                             $currbalancer = $server;
 1215:                             $currtargets = {};
 1216:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1217:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1218:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1219:                                 }
 1220:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1221:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1222:                                 }
 1223:                             }
 1224:                             last;
 1225:                         }
 1226:                     }
 1227:                 }
 1228:             }
 1229:         }
 1230:     }
 1231:     return ($currbalancer,$currtargets);
 1232: }
 1233: 
 1234: sub check_loadbalancing {
 1235:     my ($uname,$udom) = @_;
 1236:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1237:         $offloadto,$otherserver);
 1238:     my $lonhost = $perlvar{'lonHostID'};
 1239:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1240:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1241:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1242:     my $serverhomedom = &host_domain($lonhost);
 1243: 
 1244:     my $cachetime = 60*60*24;
 1245: 
 1246:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1247:         $dom_in_use = $udom;
 1248:         $homeintdom = 1;
 1249:     } else {
 1250:         $dom_in_use = $serverhomedom;
 1251:     }
 1252:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1253:     unless (defined($cached)) {
 1254:         my %domconfig =
 1255:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1256:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1257:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1258:         }
 1259:     }
 1260:     if (ref($result) eq 'HASH') {
 1261:         my $currbalancer = $result->{'lonhost'};
 1262:         my $currtargets = $result->{'targets'};
 1263:         my $currrules = $result->{'rules'};
 1264:         if ($currbalancer ne '') {
 1265:             my @hosts = &current_machine_ids();
 1266:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1267:                 $is_balancer = 1;
 1268:             }
 1269:         }
 1270:         if ($is_balancer) {
 1271:             if (ref($currrules) eq 'HASH') {
 1272:                 if ($homeintdom) {
 1273:                     if ($uname ne '') {
 1274:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1275:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1276:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1277:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1278:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1279:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1280:                             }
 1281:                         }
 1282:                         if ($rule_in_effect eq '') {
 1283:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1284:                             if ($userenv{'inststatus'} ne '') {
 1285:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1286:                                 my ($othertitle,$usertypes,$types) =
 1287:                                     &Apache::loncommon::sorted_inst_types($udom);
 1288:                                 if (ref($types) eq 'ARRAY') {
 1289:                                     foreach my $type (@{$types}) {
 1290:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1291:                                             if (exists($currrules->{$type})) {
 1292:                                                 $rule_in_effect = $currrules->{$type};
 1293:                                             }
 1294:                                         }
 1295:                                     }
 1296:                                 }
 1297:                             } else {
 1298:                                 if (exists($currrules->{'default'})) {
 1299:                                     $rule_in_effect = $currrules->{'default'};
 1300:                                 }
 1301:                             }
 1302:                         }
 1303:                     } else {
 1304:                         if (exists($currrules->{'default'})) {
 1305:                             $rule_in_effect = $currrules->{'default'};
 1306:                         }
 1307:                     }
 1308:                 } else {
 1309:                     if ($currrules->{'_LC_external'} ne '') {
 1310:                         $rule_in_effect = $currrules->{'_LC_external'};
 1311:                     }
 1312:                 }
 1313:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1314:                                                        $uname,$udom);
 1315:             }
 1316:         }
 1317:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1318:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1319:         unless (defined($cached)) {
 1320:             my %domconfig =
 1321:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1322:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1323:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1324:             }
 1325:         }
 1326:         if (ref($result) eq 'HASH') {
 1327:             my $currbalancer = $result->{'lonhost'};
 1328:             my $currtargets = $result->{'targets'};
 1329:             my $currrules = $result->{'rules'};
 1330: 
 1331:             if ($currbalancer eq $lonhost) {
 1332:                 $is_balancer = 1;
 1333:                 if (ref($currrules) eq 'HASH') {
 1334:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1335:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1336:                     }
 1337:                 }
 1338:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1339:                                                        $uname,$udom);
 1340:             }
 1341:         } else {
 1342:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1343:                 $is_balancer = 1;
 1344:                 $offloadto = &this_host_spares($dom_in_use);
 1345:             }
 1346:         }
 1347:     } else {
 1348:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1349:             $is_balancer = 1;
 1350:             $offloadto = &this_host_spares($dom_in_use);
 1351:         }
 1352:     }
 1353:     my $lowest_load = 30000;
 1354:     if (ref($offloadto) eq 'HASH') {
 1355:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1356:             foreach my $try_server (@{$offloadto->{'primary'}}) {
 1357:                 ($otherserver,$lowest_load) =
 1358:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1359:             }
 1360:         }
 1361:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1362: 
 1363:         if (!$found_server) {
 1364:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1365:                 foreach my $try_server (@{$offloadto->{'default'}}) {
 1366:                     ($otherserver,$lowest_load) =
 1367:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1368:                 }
 1369:             }
 1370:         }
 1371:     } elsif (ref($offloadto) eq 'ARRAY') {
 1372:         if (@{$offloadto} == 1) {
 1373:             $otherserver = $offloadto->[0];
 1374:         } elsif (@{$offloadto} > 1) {
 1375:             foreach my $try_server (@{$offloadto}) {
 1376:                 ($otherserver,$lowest_load) =
 1377:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1378:             }
 1379:         }
 1380:     }
 1381:     return ($is_balancer,$otherserver);
 1382: }
 1383: 
 1384: sub get_loadbalancer_targets {
 1385:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1386:     my $offloadto;
 1387:     if ($rule_in_effect eq '') {
 1388:         $offloadto = $currtargets;
 1389:     } else {
 1390:         if ($rule_in_effect eq 'homeserver') {
 1391:             my $homeserver = &homeserver($uname,$udom);
 1392:             if ($homeserver ne 'no_host') {
 1393:                 $offloadto = [$homeserver];
 1394:             }
 1395:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1396:             my %domconfig =
 1397:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1398:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1399:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1400:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1401:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1402:                     }
 1403:                 }
 1404:             } else {
 1405:                 my %servers = &dom_servers($udom);
 1406:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1407:                 if (&hostname($remotebalancer) ne '') {
 1408:                     $offloadto = [$remotebalancer];
 1409:                 }
 1410:             }
 1411:         } elsif (&hostname($rule_in_effect) ne '') {
 1412:             $offloadto = [$rule_in_effect];
 1413:         }
 1414:     }
 1415:     return $offloadto;
 1416: }
 1417: 
 1418: sub internet_dom_servers {
 1419:     my ($dom) = @_;
 1420:     my (%uniqservers,%servers);
 1421:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1422:     my @machinedoms = &machine_domains($primaryserver);
 1423:     foreach my $mdom (@machinedoms) {
 1424:         my %currservers = %servers;
 1425:         my %server = &get_servers($mdom);
 1426:         %servers = (%currservers,%server);
 1427:     }
 1428:     my %by_hostname;
 1429:     foreach my $id (keys(%servers)) {
 1430:         push(@{$by_hostname{$servers{$id}}},$id);
 1431:     }
 1432:     foreach my $hostname (sort(keys(%by_hostname))) {
 1433:         if (@{$by_hostname{$hostname}} > 1) {
 1434:             my $match = 0;
 1435:             foreach my $id (@{$by_hostname{$hostname}}) {
 1436:                 if (&host_domain($id) eq $dom) {
 1437:                     $uniqservers{$id} = $hostname;
 1438:                     $match = 1;
 1439:                 }
 1440:             }
 1441:             unless ($match) {
 1442:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1443:             }
 1444:         } else {
 1445:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1446:         }
 1447:     }
 1448:     return %uniqservers;
 1449: }
 1450: 
 1451: # ---------------------- Find the homebase for a user from domain's lib servers
 1452: 
 1453: my %homecache;
 1454: sub homeserver {
 1455:     my ($uname,$udom,$ignoreBadCache)=@_;
 1456:     my $index="$uname:$udom";
 1457: 
 1458:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1459: 
 1460:     my %servers = &get_servers($udom,'library');
 1461:     foreach my $tryserver (keys(%servers)) {
 1462:         next if ($ignoreBadCache ne 'true' && 
 1463: 		 exists($badServerCache{$tryserver}));
 1464: 
 1465: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1466: 	if ($answer eq 'found') {
 1467: 	    delete($badServerCache{$tryserver}); 
 1468: 	    return $homecache{$index}=$tryserver;
 1469: 	} elsif ($answer eq 'no_host') {
 1470: 	    $badServerCache{$tryserver}=1;
 1471: 	}
 1472:     }    
 1473:     return 'no_host';
 1474: }
 1475: 
 1476: # ------------------------------------- Find the usernames behind a list of IDs
 1477: 
 1478: sub idget {
 1479:     my ($udom,@ids)=@_;
 1480:     my %returnhash=();
 1481:     
 1482:     my %servers = &get_servers($udom,'library');
 1483:     foreach my $tryserver (keys(%servers)) {
 1484: 	my $idlist=join('&',@ids);
 1485: 	$idlist=~tr/A-Z/a-z/; 
 1486: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1487: 	my @answer=();
 1488: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1489: 	    @answer=split(/\&/,$reply);
 1490: 	}                    ;
 1491: 	my $i;
 1492: 	for ($i=0;$i<=$#ids;$i++) {
 1493: 	    if ($answer[$i]) {
 1494: 		$returnhash{$ids[$i]}=$answer[$i];
 1495: 	    } 
 1496: 	}
 1497:     } 
 1498:     return %returnhash;
 1499: }
 1500: 
 1501: # ------------------------------------- Find the IDs behind a list of usernames
 1502: 
 1503: sub idrget {
 1504:     my ($udom,@unames)=@_;
 1505:     my %returnhash=();
 1506:     foreach my $uname (@unames) {
 1507:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1508:     }
 1509:     return %returnhash;
 1510: }
 1511: 
 1512: # ------------------------------- Store away a list of names and associated IDs
 1513: 
 1514: sub idput {
 1515:     my ($udom,%ids)=@_;
 1516:     my %servers=();
 1517:     foreach my $uname (keys(%ids)) {
 1518: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1519:         my $uhom=&homeserver($uname,$udom);
 1520:         if ($uhom ne 'no_host') {
 1521:             my $id=&escape($ids{$uname});
 1522:             $id=~tr/A-Z/a-z/;
 1523:             my $esc_unam=&escape($uname);
 1524: 	    if ($servers{$uhom}) {
 1525: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1526:             } else {
 1527:                 $servers{$uhom}=$id.'='.$esc_unam;
 1528:             }
 1529:         }
 1530:     }
 1531:     foreach my $server (keys(%servers)) {
 1532:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1533:     }
 1534: }
 1535: 
 1536: # ------------------------------dump from db file owned by domainconfig user
 1537: sub dump_dom {
 1538:     my ($namespace,$udom,$regexp,$range)=@_;
 1539:     if (!$udom) {
 1540:         $udom=$env{'user.domain'};
 1541:     }
 1542:     my %returnhash;
 1543:     if ($udom) {
 1544:         my $uname = &get_domainconfiguser($udom);
 1545:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
 1546:     }
 1547:     return %returnhash;
 1548: }
 1549: 
 1550: # ------------------------------------------ get items from domain db files   
 1551: 
 1552: sub get_dom {
 1553:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1554:     my $items='';
 1555:     foreach my $item (@$storearr) {
 1556:         $items.=&escape($item).'&';
 1557:     }
 1558:     $items=~s/\&$//;
 1559:     if (!$udom) {
 1560:         $udom=$env{'user.domain'};
 1561:         if (defined(&domain($udom,'primary'))) {
 1562:             $uhome=&domain($udom,'primary');
 1563:         } else {
 1564:             undef($uhome);
 1565:         }
 1566:     } else {
 1567:         if (!$uhome) {
 1568:             if (defined(&domain($udom,'primary'))) {
 1569:                 $uhome=&domain($udom,'primary');
 1570:             }
 1571:         }
 1572:     }
 1573:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1574:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1575:         my %returnhash;
 1576:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1577:             return %returnhash;
 1578:         }
 1579:         my @pairs=split(/\&/,$rep);
 1580:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1581:             return @pairs;
 1582:         }
 1583:         my $i=0;
 1584:         foreach my $item (@$storearr) {
 1585:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1586:             $i++;
 1587:         }
 1588:         return %returnhash;
 1589:     } else {
 1590:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1591:     }
 1592: }
 1593: 
 1594: # -------------------------------------------- put items in domain db files 
 1595: 
 1596: sub put_dom {
 1597:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1598:     if (!$udom) {
 1599:         $udom=$env{'user.domain'};
 1600:         if (defined(&domain($udom,'primary'))) {
 1601:             $uhome=&domain($udom,'primary');
 1602:         } else {
 1603:             undef($uhome);
 1604:         }
 1605:     } else {
 1606:         if (!$uhome) {
 1607:             if (defined(&domain($udom,'primary'))) {
 1608:                 $uhome=&domain($udom,'primary');
 1609:             }
 1610:         }
 1611:     } 
 1612:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1613:         my $items='';
 1614:         foreach my $item (keys(%$storehash)) {
 1615:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1616:         }
 1617:         $items=~s/\&$//;
 1618:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1619:     } else {
 1620:         &logthis("put_dom failed - no homeserver and/or domain");
 1621:     }
 1622: }
 1623: 
 1624: # --------------------- newput for items in db file owned by domainconfig user
 1625: sub newput_dom {
 1626:     my ($namespace,$storehash,$udom) = @_;
 1627:     my $result;
 1628:     if (!$udom) {
 1629:         $udom=$env{'user.domain'};
 1630:     }
 1631:     if ($udom) {
 1632:         my $uname = &get_domainconfiguser($udom);
 1633:         $result = &newput($namespace,$storehash,$udom,$uname);
 1634:     }
 1635:     return $result;
 1636: }
 1637: 
 1638: # --------------------- delete for items in db file owned by domainconfig user
 1639: sub del_dom {
 1640:     my ($namespace,$storearr,$udom)=@_;
 1641:     if (ref($storearr) eq 'ARRAY') {
 1642:         if (!$udom) {
 1643:             $udom=$env{'user.domain'};
 1644:         }
 1645:         if ($udom) {
 1646:             my $uname = &get_domainconfiguser($udom); 
 1647:             return &del($namespace,$storearr,$udom,$uname);
 1648:         }
 1649:     }
 1650: }
 1651: 
 1652: # ----------------------------------construct domainconfig user for a domain 
 1653: sub get_domainconfiguser {
 1654:     my ($udom) = @_;
 1655:     return $udom.'-domainconfig';
 1656: }
 1657: 
 1658: sub retrieve_inst_usertypes {
 1659:     my ($udom) = @_;
 1660:     my (%returnhash,@order);
 1661:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1662:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1663:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1664:         %returnhash = %{$domdefs{'inststatustypes'}};
 1665:         @order = @{$domdefs{'inststatusorder'}};
 1666:     } else {
 1667:         if (defined(&domain($udom,'primary'))) {
 1668:             my $uhome=&domain($udom,'primary');
 1669:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1670:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1671:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1672:                 return (\%returnhash,\@order);
 1673:             }
 1674:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1675:             my @pairs=split(/\&/,$hashitems);
 1676:             foreach my $item (@pairs) {
 1677:                 my ($key,$value)=split(/=/,$item,2);
 1678:                 $key = &unescape($key);
 1679:                 next if ($key =~ /^error: 2 /);
 1680:                 $returnhash{$key}=&thaw_unescape($value);
 1681:             }
 1682:             my @esc_order = split(/\&/,$orderitems);
 1683:             foreach my $item (@esc_order) {
 1684:                 push(@order,&unescape($item));
 1685:             }
 1686:         } else {
 1687:             &logthis("get_dom failed - no primary domain server for $udom");
 1688:         }
 1689:     }
 1690:     return (\%returnhash,\@order);
 1691: }
 1692: 
 1693: sub is_domainimage {
 1694:     my ($url) = @_;
 1695:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1696:         if (&domain($1) ne '') {
 1697:             return '1';
 1698:         }
 1699:     }
 1700:     return;
 1701: }
 1702: 
 1703: sub inst_directory_query {
 1704:     my ($srch) = @_;
 1705:     my $udom = $srch->{'srchdomain'};
 1706:     my %results;
 1707:     my $homeserver = &domain($udom,'primary');
 1708:     my $outcome;
 1709:     if ($homeserver ne '') {
 1710: 	my $queryid=&reply("querysend:instdirsearch:".
 1711: 			   &escape($srch->{'srchby'}).':'.
 1712: 			   &escape($srch->{'srchterm'}).':'.
 1713: 			   &escape($srch->{'srchtype'}),$homeserver);
 1714: 	my $host=&hostname($homeserver);
 1715: 	if ($queryid !~/^\Q$host\E\_/) {
 1716: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1717: 	    return;
 1718: 	}
 1719: 	my $response = &get_query_reply($queryid);
 1720: 	my $maxtries = 5;
 1721: 	my $tries = 1;
 1722: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1723: 	    $response = &get_query_reply($queryid);
 1724: 	    $tries ++;
 1725: 	}
 1726: 
 1727:         if (!&error($response) && $response ne 'refused') {
 1728:             if ($response eq 'unavailable') {
 1729:                 $outcome = $response;
 1730:             } else {
 1731:                 $outcome = 'ok';
 1732:                 my @matches = split(/\n/,$response);
 1733:                 foreach my $match (@matches) {
 1734:                     my ($key,$value) = split(/=/,$match);
 1735:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1736:                 }
 1737:             }
 1738:         }
 1739:     }
 1740:     return ($outcome,%results);
 1741: }
 1742: 
 1743: sub usersearch {
 1744:     my ($srch) = @_;
 1745:     my $dom = $srch->{'srchdomain'};
 1746:     my %results;
 1747:     my %libserv = &all_library();
 1748:     my $query = 'usersearch';
 1749:     foreach my $tryserver (keys(%libserv)) {
 1750:         if (&host_domain($tryserver) eq $dom) {
 1751:             my $host=&hostname($tryserver);
 1752:             my $queryid=
 1753:                 &reply("querysend:".&escape($query).':'.
 1754:                        &escape($srch->{'srchby'}).':'.
 1755:                        &escape($srch->{'srchtype'}).':'.
 1756:                        &escape($srch->{'srchterm'}),$tryserver);
 1757:             if ($queryid !~/^\Q$host\E\_/) {
 1758:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1759:                 next;
 1760:             }
 1761:             my $reply = &get_query_reply($queryid);
 1762:             my $maxtries = 1;
 1763:             my $tries = 1;
 1764:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1765:                 $reply = &get_query_reply($queryid);
 1766:                 $tries ++;
 1767:             }
 1768:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1769:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1770:             } else {
 1771:                 my @matches;
 1772:                 if ($reply =~ /\n/) {
 1773:                     @matches = split(/\n/,$reply);
 1774:                 } else {
 1775:                     @matches = split(/\&/,$reply);
 1776:                 }
 1777:                 foreach my $match (@matches) {
 1778:                     my ($uname,$udom,%userhash);
 1779:                     foreach my $entry (split(/:/,$match)) {
 1780:                         my ($key,$value) =
 1781:                             map {&unescape($_);} split(/=/,$entry);
 1782:                         $userhash{$key} = $value;
 1783:                         if ($key eq 'username') {
 1784:                             $uname = $value;
 1785:                         } elsif ($key eq 'domain') {
 1786:                             $udom = $value;
 1787:                         }
 1788:                     }
 1789:                     $results{$uname.':'.$udom} = \%userhash;
 1790:                 }
 1791:             }
 1792:         }
 1793:     }
 1794:     return %results;
 1795: }
 1796: 
 1797: sub get_instuser {
 1798:     my ($udom,$uname,$id) = @_;
 1799:     my $homeserver = &domain($udom,'primary');
 1800:     my ($outcome,%results);
 1801:     if ($homeserver ne '') {
 1802:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1803:                            &escape($id).':'.&escape($udom),$homeserver);
 1804:         my $host=&hostname($homeserver);
 1805:         if ($queryid !~/^\Q$host\E\_/) {
 1806:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1807:             return;
 1808:         }
 1809:         my $response = &get_query_reply($queryid);
 1810:         my $maxtries = 5;
 1811:         my $tries = 1;
 1812:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1813:             $response = &get_query_reply($queryid);
 1814:             $tries ++;
 1815:         }
 1816:         if (!&error($response) && $response ne 'refused') {
 1817:             if ($response eq 'unavailable') {
 1818:                 $outcome = $response;
 1819:             } else {
 1820:                 $outcome = 'ok';
 1821:                 my @matches = split(/\n/,$response);
 1822:                 foreach my $match (@matches) {
 1823:                     my ($key,$value) = split(/=/,$match);
 1824:                     $results{&unescape($key)} = &thaw_unescape($value);
 1825:                 }
 1826:             }
 1827:         }
 1828:     }
 1829:     my %userinfo;
 1830:     if (ref($results{$uname}) eq 'HASH') {
 1831:         %userinfo = %{$results{$uname}};
 1832:     } 
 1833:     return ($outcome,%userinfo);
 1834: }
 1835: 
 1836: sub inst_rulecheck {
 1837:     my ($udom,$uname,$id,$item,$rules) = @_;
 1838:     my %returnhash;
 1839:     if ($udom ne '') {
 1840:         if (ref($rules) eq 'ARRAY') {
 1841:             @{$rules} = map {&escape($_);} (@{$rules});
 1842:             my $rulestr = join(':',@{$rules});
 1843:             my $homeserver=&domain($udom,'primary');
 1844:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1845:                 my $response;
 1846:                 if ($item eq 'username') {                
 1847:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1848:                                               ':'.&escape($uname).':'.$rulestr,
 1849:                                               $homeserver));
 1850:                 } elsif ($item eq 'id') {
 1851:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1852:                                               ':'.&escape($id).':'.$rulestr,
 1853:                                               $homeserver));
 1854:                 } elsif ($item eq 'selfcreate') {
 1855:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1856:                                                &escape($udom).':'.&escape($uname).
 1857:                                               ':'.$rulestr,$homeserver));
 1858:                 }
 1859:                 if ($response ne 'refused') {
 1860:                     my @pairs=split(/\&/,$response);
 1861:                     foreach my $item (@pairs) {
 1862:                         my ($key,$value)=split(/=/,$item,2);
 1863:                         $key = &unescape($key);
 1864:                         next if ($key =~ /^error: 2 /);
 1865:                         $returnhash{$key}=&thaw_unescape($value);
 1866:                     }
 1867:                 }
 1868:             }
 1869:         }
 1870:     }
 1871:     return %returnhash;
 1872: }
 1873: 
 1874: sub inst_userrules {
 1875:     my ($udom,$check) = @_;
 1876:     my (%ruleshash,@ruleorder);
 1877:     if ($udom ne '') {
 1878:         my $homeserver=&domain($udom,'primary');
 1879:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1880:             my $response;
 1881:             if ($check eq 'id') {
 1882:                 $response=&reply('instidrules:'.&escape($udom),
 1883:                                  $homeserver);
 1884:             } elsif ($check eq 'email') {
 1885:                 $response=&reply('instemailrules:'.&escape($udom),
 1886:                                  $homeserver);
 1887:             } else {
 1888:                 $response=&reply('instuserrules:'.&escape($udom),
 1889:                                  $homeserver);
 1890:             }
 1891:             if (($response ne 'refused') && ($response ne 'error') && 
 1892:                 ($response ne 'unknown_cmd') && 
 1893:                 ($response ne 'no_such_host')) {
 1894:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1895:                 my @pairs=split(/\&/,$hashitems);
 1896:                 foreach my $item (@pairs) {
 1897:                     my ($key,$value)=split(/=/,$item,2);
 1898:                     $key = &unescape($key);
 1899:                     next if ($key =~ /^error: 2 /);
 1900:                     $ruleshash{$key}=&thaw_unescape($value);
 1901:                 }
 1902:                 my @esc_order = split(/\&/,$orderitems);
 1903:                 foreach my $item (@esc_order) {
 1904:                     push(@ruleorder,&unescape($item));
 1905:                 }
 1906:             }
 1907:         }
 1908:     }
 1909:     return (\%ruleshash,\@ruleorder);
 1910: }
 1911: 
 1912: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1913: 
 1914: sub get_domain_defaults {
 1915:     my ($domain) = @_;
 1916:     my $cachetime = 60*60*24;
 1917:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1918:     if (defined($cached)) {
 1919:         if (ref($result) eq 'HASH') {
 1920:             return %{$result};
 1921:         }
 1922:     }
 1923:     my %domdefaults;
 1924:     my %domconfig =
 1925:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1926:                                   'requestcourses','inststatus',
 1927:                                   'coursedefaults','usersessions'],$domain);
 1928:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1929:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1930:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1931:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1932:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1933:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1934:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1935:     } else {
 1936:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1937:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1938:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1939:     }
 1940:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1941:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1942:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1943:         } else {
 1944:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1945:         } 
 1946:         my @usertools = ('aboutme','blog','portfolio');
 1947:         foreach my $item (@usertools) {
 1948:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1949:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1950:             }
 1951:         }
 1952:     }
 1953:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1954:         foreach my $item ('official','unofficial','community') {
 1955:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1956:         }
 1957:     }
 1958:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1959:         foreach my $item ('inststatustypes','inststatusorder') {
 1960:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1961:         }
 1962:     }
 1963:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1964:         foreach my $item ('canuse_pdfforms') {
 1965:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1966:         }
 1967:     }
 1968:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1969:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1970:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1971:         }
 1972:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1973:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1974:         }
 1975:     }
 1976:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1977:                                   $cachetime);
 1978:     return %domdefaults;
 1979: }
 1980: 
 1981: # --------------------------------------------------- Assign a key to a student
 1982: 
 1983: sub assign_access_key {
 1984: #
 1985: # a valid key looks like uname:udom#comments
 1986: # comments are being appended
 1987: #
 1988:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1989:     $kdom=
 1990:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1991:     $knum=
 1992:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1993:     $cdom=
 1994:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1995:     $cnum=
 1996:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1997:     $udom=$env{'user.name'} unless (defined($udom));
 1998:     $uname=$env{'user.domain'} unless (defined($uname));
 1999:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2000:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2001:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2002:                                                   # assigned to this person
 2003:                                                   # - this should not happen,
 2004:                                                   # unless something went wrong
 2005:                                                   # the first time around
 2006: # ready to assign
 2007:         $logentry=$1.'; '.$logentry;
 2008:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2009:                                                  $kdom,$knum) eq 'ok') {
 2010: # key now belongs to user
 2011: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2012:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2013:                 &appenv({'environment.'.$envkey => $ckey});
 2014:                 return 'ok';
 2015:             } else {
 2016:                 return 
 2017:   'error: Count not permanently assign key, will need to be re-entered later.';
 2018: 	    }
 2019:         } else {
 2020:             return 'error: Could not assign key, try again later.';
 2021:         }
 2022:     } elsif (!$existing{$ckey}) {
 2023: # the key does not exist
 2024: 	return 'error: The key does not exist';
 2025:     } else {
 2026: # the key is somebody else's
 2027: 	return 'error: The key is already in use';
 2028:     }
 2029: }
 2030: 
 2031: # ------------------------------------------ put an additional comment on a key
 2032: 
 2033: sub comment_access_key {
 2034: #
 2035: # a valid key looks like uname:udom#comments
 2036: # comments are being appended
 2037: #
 2038:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2039:     $cdom=
 2040:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2041:     $cnum=
 2042:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2043:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2044:     if ($existing{$ckey}) {
 2045:         $existing{$ckey}.='; '.$logentry;
 2046: # ready to assign
 2047:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2048:                                                  $cdom,$cnum) eq 'ok') {
 2049: 	    return 'ok';
 2050:         } else {
 2051: 	    return 'error: Count not store comment.';
 2052:         }
 2053:     } else {
 2054: # the key does not exist
 2055: 	return 'error: The key does not exist';
 2056:     }
 2057: }
 2058: 
 2059: # ------------------------------------------------------ Generate a set of keys
 2060: 
 2061: sub generate_access_keys {
 2062:     my ($number,$cdom,$cnum,$logentry)=@_;
 2063:     $cdom=
 2064:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2065:     $cnum=
 2066:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2067:     unless (&allowed('mky',$cdom)) { return 0; }
 2068:     unless (($cdom) && ($cnum)) { return 0; }
 2069:     if ($number>10000) { return 0; }
 2070:     sleep(2); # make sure don't get same seed twice
 2071:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2072:     my $total=0;
 2073:     for (my $i=1;$i<=$number;$i++) {
 2074:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2075:                   sprintf("%lx",int(100000*rand)).'-'.
 2076:                   sprintf("%lx",int(100000*rand));
 2077:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2078:        $newkey=~s/0/h/g; # and also 0 and O
 2079:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2080:        if ($existing{$newkey}) {
 2081:            $i--;
 2082:        } else {
 2083: 	  if (&put('accesskeys',
 2084:               { $newkey => '# generated '.localtime().
 2085:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2086:                            '; '.$logentry },
 2087: 		   $cdom,$cnum) eq 'ok') {
 2088:               $total++;
 2089: 	  }
 2090:        }
 2091:     }
 2092:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2093:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2094:     return $total;
 2095: }
 2096: 
 2097: # ------------------------------------------------------- Validate an accesskey
 2098: 
 2099: sub validate_access_key {
 2100:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2101:     $cdom=
 2102:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2103:     $cnum=
 2104:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2105:     $udom=$env{'user.domain'} unless (defined($udom));
 2106:     $uname=$env{'user.name'} unless (defined($uname));
 2107:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2108:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2109: }
 2110: 
 2111: # ------------------------------------- Find the section of student in a course
 2112: sub devalidate_getsection_cache {
 2113:     my ($udom,$unam,$courseid)=@_;
 2114:     my $hashid="$udom:$unam:$courseid";
 2115:     &devalidate_cache_new('getsection',$hashid);
 2116: }
 2117: 
 2118: sub courseid_to_courseurl {
 2119:     my ($courseid) = @_;
 2120:     #already url style courseid
 2121:     return $courseid if ($courseid =~ m{^/});
 2122: 
 2123:     if (exists($env{'course.'.$courseid.'.num'})) {
 2124: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2125: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2126: 	return "/$cdom/$cnum";
 2127:     }
 2128: 
 2129:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2130:     if (exists($courseinfo{'num'})) {
 2131: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2132:     }
 2133: 
 2134:     return undef;
 2135: }
 2136: 
 2137: sub getsection {
 2138:     my ($udom,$unam,$courseid)=@_;
 2139:     my $cachetime=1800;
 2140: 
 2141:     my $hashid="$udom:$unam:$courseid";
 2142:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2143:     if (defined($cached)) { return $result; }
 2144: 
 2145:     my %Pending; 
 2146:     my %Expired;
 2147:     #
 2148:     # Each role can either have not started yet (pending), be active, 
 2149:     #    or have expired.
 2150:     #
 2151:     # If there is an active role, we are done.
 2152:     #
 2153:     # If there is more than one role which has not started yet, 
 2154:     #     choose the one which will start sooner
 2155:     # If there is one role which has not started yet, return it.
 2156:     #
 2157:     # If there is more than one expired role, choose the one which ended last.
 2158:     # If there is a role which has expired, return it.
 2159:     #
 2160:     $courseid = &courseid_to_courseurl($courseid);
 2161:     my $extra = &freeze_escape({'skipcheck' => 1});
 2162:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
 2163:     foreach my $key (keys(%roleshash)) {
 2164:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2165:         my $section=$1;
 2166:         if ($key eq $courseid.'_st') { $section=''; }
 2167:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2168:         my $now=time;
 2169:         if (defined($end) && $end && ($now > $end)) {
 2170:             $Expired{$end}=$section;
 2171:             next;
 2172:         }
 2173:         if (defined($start) && $start && ($now < $start)) {
 2174:             $Pending{$start}=$section;
 2175:             next;
 2176:         }
 2177:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2178:     }
 2179:     #
 2180:     # Presumedly there will be few matching roles from the above
 2181:     # loop and the sorting time will be negligible.
 2182:     if (scalar(keys(%Pending))) {
 2183:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2184:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2185:     } 
 2186:     if (scalar(keys(%Expired))) {
 2187:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2188:         my $time = pop(@sorted);
 2189:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2190:     }
 2191:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2192: }
 2193: 
 2194: sub save_cache {
 2195:     &purge_remembered();
 2196:     #&Apache::loncommon::validate_page();
 2197:     undef(%env);
 2198:     undef($env_loaded);
 2199: }
 2200: 
 2201: my $to_remember=-1;
 2202: my %remembered;
 2203: my %accessed;
 2204: my $kicks=0;
 2205: my $hits=0;
 2206: sub make_key {
 2207:     my ($name,$id) = @_;
 2208:     if (length($id) > 65 
 2209: 	&& length(&escape($id)) > 200) {
 2210: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2211:     }
 2212:     return &escape($name.':'.$id);
 2213: }
 2214: 
 2215: sub devalidate_cache_new {
 2216:     my ($name,$id,$debug) = @_;
 2217:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2218:     $id=&make_key($name,$id);
 2219:     $memcache->delete($id);
 2220:     delete($remembered{$id});
 2221:     delete($accessed{$id});
 2222: }
 2223: 
 2224: sub is_cached_new {
 2225:     my ($name,$id,$debug) = @_;
 2226:     $id=&make_key($name,$id);
 2227:     if (exists($remembered{$id})) {
 2228: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2229: 	$accessed{$id}=[&gettimeofday()];
 2230: 	$hits++;
 2231: 	return ($remembered{$id},1);
 2232:     }
 2233:     my $value = $memcache->get($id);
 2234:     if (!(defined($value))) {
 2235: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2236: 	return (undef,undef);
 2237:     }
 2238:     if ($value eq '__undef__') {
 2239: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2240: 	$value=undef;
 2241:     }
 2242:     &make_room($id,$value,$debug);
 2243:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2244:     return ($value,1);
 2245: }
 2246: 
 2247: sub do_cache_new {
 2248:     my ($name,$id,$value,$time,$debug) = @_;
 2249:     $id=&make_key($name,$id);
 2250:     my $setvalue=$value;
 2251:     if (!defined($setvalue)) {
 2252: 	$setvalue='__undef__';
 2253:     }
 2254:     if (!defined($time) ) {
 2255: 	$time=600;
 2256:     }
 2257:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2258:     my $result = $memcache->set($id,$setvalue,$time);
 2259:     if (! $result) {
 2260: 	&logthis("caching of id -> $id  failed");
 2261: 	$memcache->disconnect_all();
 2262:     }
 2263:     # need to make a copy of $value
 2264:     &make_room($id,$value,$debug);
 2265:     return $value;
 2266: }
 2267: 
 2268: sub make_room {
 2269:     my ($id,$value,$debug)=@_;
 2270: 
 2271:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2272:                                     : $value;
 2273:     if ($to_remember<0) { return; }
 2274:     $accessed{$id}=[&gettimeofday()];
 2275:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2276:     my $to_kick;
 2277:     my $max_time=0;
 2278:     foreach my $other (keys(%accessed)) {
 2279: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2280: 	    $to_kick=$other;
 2281: 	    $max_time=&tv_interval($accessed{$other});
 2282: 	}
 2283:     }
 2284:     delete($remembered{$to_kick});
 2285:     delete($accessed{$to_kick});
 2286:     $kicks++;
 2287:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2288:     return;
 2289: }
 2290: 
 2291: sub purge_remembered {
 2292:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2293:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2294:     undef(%remembered);
 2295:     undef(%accessed);
 2296: }
 2297: # ------------------------------------- Read an entry from a user's environment
 2298: 
 2299: sub userenvironment {
 2300:     my ($udom,$unam,@what)=@_;
 2301:     my $items;
 2302:     foreach my $item (@what) {
 2303:         $items.=&escape($item).'&';
 2304:     }
 2305:     $items=~s/\&$//;
 2306:     my %returnhash=();
 2307:     my $uhome = &homeserver($unam,$udom);
 2308:     unless ($uhome eq 'no_host') {
 2309:         my @answer=split(/\&/, 
 2310:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2311:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2312:             return %returnhash;
 2313:         }
 2314:         my $i;
 2315:         for ($i=0;$i<=$#what;$i++) {
 2316: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2317:         }
 2318:     }
 2319:     return %returnhash;
 2320: }
 2321: 
 2322: # ---------------------------------------------------------- Get a studentphoto
 2323: sub studentphoto {
 2324:     my ($udom,$unam,$ext) = @_;
 2325:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2326:     if (defined($env{'request.course.id'})) {
 2327:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2328:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2329:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2330:             } else {
 2331:                 my ($result,$perm_reqd)=
 2332: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2333:                 if ($result eq 'ok') {
 2334:                     if (!($perm_reqd eq 'yes')) {
 2335:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2336:                     }
 2337:                 }
 2338:             }
 2339:         }
 2340:     } else {
 2341:         my ($result,$perm_reqd) = 
 2342: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2343:         if ($result eq 'ok') {
 2344:             if (!($perm_reqd eq 'yes')) {
 2345:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2346:             }
 2347:         }
 2348:     }
 2349:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2350: }
 2351: 
 2352: sub retrievestudentphoto {
 2353:     my ($udom,$unam,$ext,$type) = @_;
 2354:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2355:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2356:     if ($ret eq 'ok') {
 2357:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2358:         if ($type eq 'thumbnail') {
 2359:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2360:         }
 2361:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2362:         return $tokenurl;
 2363:     } else {
 2364:         if ($type eq 'thumbnail') {
 2365:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2366:         } else { 
 2367:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2368:         }
 2369:     }
 2370: }
 2371: 
 2372: # -------------------------------------------------------------------- New chat
 2373: 
 2374: sub chatsend {
 2375:     my ($newentry,$anon,$group)=@_;
 2376:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2377:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2378:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2379:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2380: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2381: 		   &escape($newentry)).':'.$group,$chome);
 2382: }
 2383: 
 2384: # ------------------------------------------ Find current version of a resource
 2385: 
 2386: sub getversion {
 2387:     my $fname=&clutter(shift);
 2388:     unless ($fname=~/^\/res\//) { return -1; }
 2389:     return &currentversion(&filelocation('',$fname));
 2390: }
 2391: 
 2392: sub currentversion {
 2393:     my $fname=shift;
 2394:     my $author=$fname;
 2395:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2396:     my ($udom,$uname)=split(/\//,$author);
 2397:     my $home=&homeserver($uname,$udom);
 2398:     if ($home eq 'no_host') { 
 2399:         return -1; 
 2400:     }
 2401:     my $answer=&reply("currentversion:$fname",$home);
 2402:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2403: 	return -1;
 2404:     }
 2405:     return $answer;
 2406: }
 2407: 
 2408: #
 2409: # Return special version number of resource if set by override, empty otherwise
 2410: #
 2411: sub usedversion {
 2412:     my $fname=shift;
 2413:     unless ($fname) { $fname=$env{'request.uri'}; }
 2414:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2415:     if ($urlversion) { return $urlversion; }
 2416:     return '';
 2417: }
 2418: 
 2419: # ----------------------------- Subscribe to a resource, return URL if possible
 2420: 
 2421: sub subscribe {
 2422:     my $fname=shift;
 2423:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2424:     $fname=~s/[\n\r]//g;
 2425:     my $author=$fname;
 2426:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2427:     my ($udom,$uname)=split(/\//,$author);
 2428:     my $home=homeserver($uname,$udom);
 2429:     if ($home eq 'no_host') {
 2430:         return 'not_found';
 2431:     }
 2432:     my $answer=reply("sub:$fname",$home);
 2433:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2434: 	$answer.=' by '.$home;
 2435:     }
 2436:     return $answer;
 2437: }
 2438:     
 2439: # -------------------------------------------------------------- Replicate file
 2440: 
 2441: sub repcopy {
 2442:     my $filename=shift;
 2443:     $filename=~s/\/+/\//g;
 2444:     my $londocroot = $perlvar{'lonDocRoot'};
 2445:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2446:     if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
 2447:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2448: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2449: 	return &repcopy_userfile($filename);
 2450:     }
 2451:     $filename=~s/[\n\r]//g;
 2452:     my $transname="$filename.in.transfer";
 2453: # FIXME: this should flock
 2454:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2455:     my $remoteurl=subscribe($filename);
 2456:     if ($remoteurl =~ /^con_lost by/) {
 2457: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2458:            return 'unavailable';
 2459:     } elsif ($remoteurl eq 'not_found') {
 2460: 	   #&logthis("Subscribe returned not_found: $filename");
 2461: 	   return 'not_found';
 2462:     } elsif ($remoteurl =~ /^rejected by/) {
 2463: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2464:            return 'forbidden';
 2465:     } elsif ($remoteurl eq 'directory') {
 2466:            return 'ok';
 2467:     } else {
 2468:         my $author=$filename;
 2469:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2470:         my ($udom,$uname)=split(/\//,$author);
 2471:         my $home=homeserver($uname,$udom);
 2472:         unless ($home eq $perlvar{'lonHostID'}) {
 2473:            my @parts=split(/\//,$filename);
 2474:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2475:            if ($path ne "$londocroot/res") {
 2476:                &logthis("Malconfiguration for replication: $filename");
 2477: 	       return 'bad_request';
 2478:            }
 2479:            my $count;
 2480:            for ($count=5;$count<$#parts;$count++) {
 2481:                $path.="/$parts[$count]";
 2482:                if ((-e $path)!=1) {
 2483: 		   mkdir($path,0777);
 2484:                }
 2485:            }
 2486:            my $ua=new LWP::UserAgent;
 2487:            my $request=new HTTP::Request('GET',"$remoteurl");
 2488:            my $response=$ua->request($request,$transname);
 2489:            if ($response->is_error()) {
 2490: 	       unlink($transname);
 2491:                my $message=$response->status_line;
 2492:                &logthis("<font color=\"blue\">WARNING:"
 2493:                        ." LWP get: $message: $filename</font>");
 2494:                return 'unavailable';
 2495:            } else {
 2496: 	       if ($remoteurl!~/\.meta$/) {
 2497:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2498:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2499:                   if ($mresponse->is_error()) {
 2500: 		      unlink($filename.'.meta');
 2501:                       &logthis(
 2502:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2503:                   }
 2504: 	       }
 2505:                rename($transname,$filename);
 2506:                return 'ok';
 2507:            }
 2508:        }
 2509:     }
 2510: }
 2511: 
 2512: # ------------------------------------------------ Get server side include body
 2513: sub ssi_body {
 2514:     my ($filelink,%form)=@_;
 2515:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2516:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2517:     }
 2518:     my $output='';
 2519:     my $response;
 2520:     if ($filelink=~/^https?\:/) {
 2521:        ($output,$response)=&externalssi($filelink);
 2522:     } else {
 2523:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2524:        $filelink .= 'inhibitmenu=yes';
 2525:        ($output,$response)=&ssi($filelink,%form);
 2526:     }
 2527:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2528:     $output=~s/^.*?\<body[^\>]*\>//si;
 2529:     $output=~s/\<\/body\s*\>.*?$//si;
 2530:     if (wantarray) {
 2531:         return ($output, $response);
 2532:     } else {
 2533:         return $output;
 2534:     }
 2535: }
 2536: 
 2537: # --------------------------------------------------------- Server Side Include
 2538: 
 2539: sub absolute_url {
 2540:     my ($host_name) = @_;
 2541:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2542:     if ($host_name eq '') {
 2543: 	$host_name = $ENV{'SERVER_NAME'};
 2544:     }
 2545:     return $protocol.$host_name;
 2546: }
 2547: 
 2548: #
 2549: #   Server side include.
 2550: # Parameters:
 2551: #  fn     Possibly encrypted resource name/id.
 2552: #  form   Hash that describes how the rendering should be done
 2553: #         and other things.
 2554: # Returns:
 2555: #   Scalar context: The content of the response.
 2556: #   Array context:  2 element list of the content and the full response object.
 2557: #     
 2558: sub ssi {
 2559: 
 2560:     my ($fn,%form)=@_;
 2561:     my $ua=new LWP::UserAgent;
 2562:     my $request;
 2563: 
 2564:     $form{'no_update_last_known'}=1;
 2565:     &Apache::lonenc::check_encrypt(\$fn);
 2566:     if (%form) {
 2567:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2568:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2569:     } else {
 2570:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2571:     }
 2572: 
 2573:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2574:     my $response=$ua->request($request);
 2575: 
 2576:     if (wantarray) {
 2577: 	return ($response->content, $response);
 2578:     } else {
 2579: 	return $response->content;
 2580:     }
 2581: }
 2582: 
 2583: sub externalssi {
 2584:     my ($url)=@_;
 2585:     my $ua=new LWP::UserAgent;
 2586:     my $request=new HTTP::Request('GET',$url);
 2587:     my $response=$ua->request($request);
 2588:     if (wantarray) {
 2589:         return ($response->content, $response);
 2590:     } else {
 2591:         return $response->content;
 2592:     }
 2593: }
 2594: 
 2595: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2596: 
 2597: sub allowuploaded {
 2598:     my ($srcurl,$url)=@_;
 2599:     $url=&clutter(&declutter($url));
 2600:     my $dir=$url;
 2601:     $dir=~s/\/[^\/]+$//;
 2602:     my %httpref=();
 2603:     my $httpurl=&hreflocation('',$url);
 2604:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2605:     &Apache::lonnet::appenv(\%httpref);
 2606: }
 2607: 
 2608: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2609: # input: action, courseID, current domain, intended
 2610: #        path to file, source of file, instruction to parse file for objects,
 2611: #        ref to hash for embedded objects,
 2612: #        ref to hash for codebase of java objects.
 2613: #        reference to scalar to accommodate mime type determined
 2614: #          from File::MMagic if $parser = parse.
 2615: #
 2616: # output: url to file (if action was uploaddoc), 
 2617: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2618: #
 2619: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2620: # course.
 2621: #
 2622: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2623: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2624: #          course's home server.
 2625: #
 2626: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2627: #          be copied from $source (current location) to 
 2628: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2629: #         and will then be copied to
 2630: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2631: #         course's home server.
 2632: #
 2633: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2634: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2635: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2636: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2637: #         in course's home server.
 2638: #
 2639: 
 2640: sub process_coursefile {
 2641:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2642:         $mimetype)=@_;
 2643:     my $fetchresult;
 2644:     my $home=&homeserver($docuname,$docudom);
 2645:     if ($action eq 'propagate') {
 2646:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2647: 			     $home);
 2648:     } else {
 2649:         my $fpath = '';
 2650:         my $fname = $file;
 2651:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2652:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2653:         my $filepath = &build_filepath($fpath);
 2654:         if ($action eq 'copy') {
 2655:             if ($source eq '') {
 2656:                 $fetchresult = 'no source file';
 2657:                 return $fetchresult;
 2658:             } else {
 2659:                 my $destination = $filepath.'/'.$fname;
 2660:                 rename($source,$destination);
 2661:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2662:                                  $home);
 2663:             }
 2664:         } elsif ($action eq 'uploaddoc') {
 2665:             open(my $fh,'>'.$filepath.'/'.$fname);
 2666:             print $fh $env{'form.'.$source};
 2667:             close($fh);
 2668:             if ($parser eq 'parse') {
 2669:                 my $mm = new File::MMagic;
 2670:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2671:                 if ($type eq 'text/html') {
 2672:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2673:                     unless ($parse_result eq 'ok') {
 2674:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2675:                     }
 2676:                 }
 2677:                 if (ref($mimetype)) {
 2678:                     $$mimetype = $type;
 2679:                 } 
 2680:             }
 2681:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2682:                                  $home);
 2683:             if ($fetchresult eq 'ok') {
 2684:                 return '/uploaded/'.$fpath.'/'.$fname;
 2685:             } else {
 2686:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2687:                         ' to host '.$home.': '.$fetchresult);
 2688:                 return '/adm/notfound.html';
 2689:             }
 2690:         }
 2691:     }
 2692:     unless ( $fetchresult eq 'ok') {
 2693:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2694:              ' to host '.$home.': '.$fetchresult);
 2695:     }
 2696:     return $fetchresult;
 2697: }
 2698: 
 2699: sub build_filepath {
 2700:     my ($fpath) = @_;
 2701:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2702:     unless ($fpath eq '') {
 2703:         my @parts=split('/',$fpath);
 2704:         foreach my $part (@parts) {
 2705:             $filepath.= '/'.$part;
 2706:             if ((-e $filepath)!=1) {
 2707:                 mkdir($filepath,0777);
 2708:             }
 2709:         }
 2710:     }
 2711:     return $filepath;
 2712: }
 2713: 
 2714: sub store_edited_file {
 2715:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2716:     my $file = $primary_url;
 2717:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2718:     my $fpath = '';
 2719:     my $fname = $file;
 2720:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2721:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2722:     my $filepath = &build_filepath($fpath);
 2723:     open(my $fh,'>'.$filepath.'/'.$fname);
 2724:     print $fh $content;
 2725:     close($fh);
 2726:     my $home=&homeserver($docuname,$docudom);
 2727:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2728: 			  $home);
 2729:     if ($$fetchresult eq 'ok') {
 2730:         return '/uploaded/'.$fpath.'/'.$fname;
 2731:     } else {
 2732:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2733: 		 ' to host '.$home.': '.$$fetchresult);
 2734:         return '/adm/notfound.html';
 2735:     }
 2736: }
 2737: 
 2738: sub clean_filename {
 2739:     my ($fname,$args)=@_;
 2740: # Replace Windows backslashes by forward slashes
 2741:     $fname=~s/\\/\//g;
 2742:     if (!$args->{'keep_path'}) {
 2743:         # Get rid of everything but the actual filename
 2744: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2745:     }
 2746: # Replace spaces by underscores
 2747:     $fname=~s/\s+/\_/g;
 2748: # Replace all other weird characters by nothing
 2749:     $fname=~s{[^/\w\.\-]}{}g;
 2750: # Replace all .\d. sequences with _\d. so they no longer look like version
 2751: # numbers
 2752:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2753:     return $fname;
 2754: }
 2755: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2756: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2757: # image with the same aspect ratio as the original, but with dimensions which do 
 2758: # not exceed $resizewidth and $resizeheight.
 2759:  
 2760: sub resizeImage {
 2761:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2762:     my $ima = Image::Magick->new;
 2763:     my $resized;
 2764:     if (-e $img_path) {
 2765:         $ima->Read($img_path);
 2766:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2767:             my $width = $ima->Get('width');
 2768:             my $height = $ima->Get('height');
 2769:             if ($width > $resizewidth) {
 2770: 	        my $factor = $width/$resizewidth;
 2771:                 my $newheight = $height/$factor;
 2772:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2773:                 $resized = 1;
 2774:             }
 2775:         }
 2776:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2777:             my $width = $ima->Get('width');
 2778:             my $height = $ima->Get('height');
 2779:             if ($height > $resizeheight) {
 2780:                 my $factor = $height/$resizeheight;
 2781:                 my $newwidth = $width/$factor;
 2782:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2783:                 $resized = 1;
 2784:             }
 2785:         }
 2786:         if ($resized) {
 2787:             $ima->Write($img_path);
 2788:         }
 2789:     }
 2790:     return;
 2791: }
 2792: 
 2793: # --------------- Take an uploaded file and put it into the userfiles directory
 2794: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2795: #                    the desired filename is in $env{"form.$formname.filename"}
 2796: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2797: #                                    canceloverwrite, or ''. 
 2798: #                   if 'coursedoc': upload to the current course
 2799: #                   if 'existingfile': write file to tmp/overwrites directory 
 2800: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2801: #                   $context is passed as argument to &finishuserfileupload
 2802: #        $subdir - directory in userfile to store the file into
 2803: #        $parser - instruction to parse file for objects ($parser = parse)    
 2804: #        $allfiles - reference to hash for embedded objects
 2805: #        $codebase - reference to hash for codebase of java objects
 2806: #        $desuname - username for permanent storage of uploaded file
 2807: #        $dsetudom - domain for permanaent storage of uploaded file
 2808: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2809: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2810: #        $resizewidth - width (pixels) to which to resize uploaded image
 2811: #        $resizeheight - height (pixels) to which to resize uploaded image
 2812: #        $mimetype - reference to scalar to accommodate mime type determined
 2813: #                    from File::MMagic.
 2814: # 
 2815: # output: url of file in userspace, or error: <message> 
 2816: #             or /adm/notfound.html if failure to upload occurse
 2817: 
 2818: sub userfileupload {
 2819:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2820:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2821:     if (!defined($subdir)) { $subdir='unknown'; }
 2822:     my $fname=$env{'form.'.$formname.'.filename'};
 2823:     $fname=&clean_filename($fname);
 2824:     # See if there is anything left
 2825:     unless ($fname) { return 'error: no uploaded file'; }
 2826:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2827:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2828:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2829:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2830:         my $now = time;
 2831:         my $filepath;
 2832:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2833:              $filepath = 'tmp/helprequests/'.$now;
 2834:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2835:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2836:                          '_'.$env{'user.domain'}.'/pending';
 2837:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2838:             my ($docuname,$docudom);
 2839:             if ($destudom) {
 2840:                 $docudom = $destudom;
 2841:             } else {
 2842:                 $docudom = $env{'user.domain'};
 2843:             }
 2844:             if ($destuname) {
 2845:                 $docuname = $destuname;
 2846:             } else {
 2847:                 $docuname = $env{'user.name'};
 2848:             }
 2849:             if (exists($env{'form.group'})) {
 2850:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2851:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2852:             }
 2853:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2854:             if ($context eq 'canceloverwrite') {
 2855:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2856:                 if (-e  $tempfile) {
 2857:                     my @info = stat($tempfile);
 2858:                     if ($info[9] eq $env{'form.timestamp'}) {
 2859:                         unlink($tempfile);
 2860:                     }
 2861:                 }
 2862:                 return;
 2863:             }
 2864:         }
 2865:         # Create the directory if not present
 2866:         my @parts=split(/\//,$filepath);
 2867:         my $fullpath = $perlvar{'lonDaemons'};
 2868:         for (my $i=0;$i<@parts;$i++) {
 2869:             $fullpath .= '/'.$parts[$i];
 2870:             if ((-e $fullpath)!=1) {
 2871:                 mkdir($fullpath,0777);
 2872:             }
 2873:         }
 2874:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2875:         print $fh $env{'form.'.$formname};
 2876:         close($fh);
 2877:         if ($context eq 'existingfile') {
 2878:             my @info = stat($fullpath.'/'.$fname);
 2879:             return ($fullpath.'/'.$fname,$info[9]);
 2880:         } else {
 2881:             return $fullpath.'/'.$fname;
 2882:         }
 2883:     }
 2884:     if ($subdir eq 'scantron') {
 2885:         $fname = 'scantron_orig_'.$fname;
 2886:     } else {
 2887:         $fname="$subdir/$fname";
 2888:     }
 2889:     if ($context eq 'coursedoc') {
 2890: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2891: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2892:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2893:             return &finishuserfileupload($docuname,$docudom,
 2894: 					 $formname,$fname,$parser,$allfiles,
 2895: 					 $codebase,$thumbwidth,$thumbheight,
 2896:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2897:         } else {
 2898:             $fname=$env{'form.folder'}.'/'.$fname;
 2899:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2900: 				       $fname,$formname,$parser,
 2901: 				       $allfiles,$codebase,$mimetype);
 2902:         }
 2903:     } elsif (defined($destuname)) {
 2904:         my $docuname=$destuname;
 2905:         my $docudom=$destudom;
 2906: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2907: 				     $parser,$allfiles,$codebase,
 2908:                                      $thumbwidth,$thumbheight,
 2909:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2910:     } else {
 2911:         my $docuname=$env{'user.name'};
 2912:         my $docudom=$env{'user.domain'};
 2913:         if (exists($env{'form.group'})) {
 2914:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2915:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2916:         }
 2917: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2918: 				     $parser,$allfiles,$codebase,
 2919:                                      $thumbwidth,$thumbheight,
 2920:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2921:     }
 2922: }
 2923: 
 2924: sub finishuserfileupload {
 2925:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2926:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2927:     my $path=$docudom.'/'.$docuname.'/';
 2928:     my $filepath=$perlvar{'lonDocRoot'};
 2929:   
 2930:     my ($fnamepath,$file,$fetchthumb);
 2931:     $file=$fname;
 2932:     if ($fname=~m|/|) {
 2933:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2934: 	$path.=$fnamepath.'/';
 2935:     }
 2936:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2937:     my $count;
 2938:     for ($count=4;$count<=$#parts;$count++) {
 2939:         $filepath.="/$parts[$count]";
 2940:         if ((-e $filepath)!=1) {
 2941: 	    mkdir($filepath,0777);
 2942:         }
 2943:     }
 2944: 
 2945: # Save the file
 2946:     {
 2947: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2948: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2949: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2950: 	    return '/adm/notfound.html';
 2951: 	}
 2952:         if ($context eq 'overwrite') {
 2953:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2954:             my $target = $filepath.'/'.$file;
 2955:             if (-e $source) {
 2956:                 my @info = stat($source);
 2957:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2958:                     unless (&File::Copy::move($source,$target)) {
 2959:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2960:                         return "Moving from $source failed";
 2961:                     }
 2962:                 } else {
 2963:                     return "Temporary file: $source had unexpected date/time for last modification";
 2964:                 }
 2965:             } else {
 2966:                 return "Temporary file: $source missing";
 2967:             }
 2968:         } elsif (!print FH ($env{'form.'.$formname})) {
 2969: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2970: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2971: 	    return '/adm/notfound.html';
 2972: 	}
 2973: 	close(FH);
 2974:         if ($resizewidth && $resizeheight) {
 2975:             my $mm = new File::MMagic;
 2976:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2977:             if ($mime_type =~ m{^image/}) {
 2978: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2979:             }  
 2980: 	}
 2981:     }
 2982:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 2983:         if (ref($mimetype)) {
 2984:             if ($$mimetype eq '') {
 2985:                 my $mm = new File::MMagic;
 2986:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 2987:                 $$mimetype = $type;
 2988:             }
 2989:         }
 2990:     }
 2991:     if ($parser eq 'parse') {
 2992:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 2993:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2994:                                                        $allfiles,$codebase);
 2995:             unless ($parse_result eq 'ok') {
 2996:                 &logthis('Failed to parse '.$filepath.$file.
 2997: 	   	         ' for embedded media: '.$parse_result); 
 2998:             }
 2999:         }
 3000:     }
 3001:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3002:         my $input = $filepath.'/'.$file;
 3003:         my $output = $filepath.'/'.'tn-'.$file;
 3004:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3005:         system("convert -sample $thumbsize $input $output");
 3006:         if (-e $filepath.'/'.'tn-'.$file) {
 3007:             $fetchthumb  = 1; 
 3008:         }
 3009:     }
 3010:  
 3011: # Notify homeserver to grep it
 3012: #
 3013:     my $docuhome=&homeserver($docuname,$docudom);	
 3014:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3015:     if ($fetchresult eq 'ok') {
 3016:         if ($fetchthumb) {
 3017:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3018:             if ($thumbresult ne 'ok') {
 3019:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3020:                          $docuhome.': '.$thumbresult);
 3021:             }
 3022:         }
 3023: #
 3024: # Return the URL to it
 3025:         return '/uploaded/'.$path.$file;
 3026:     } else {
 3027:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3028: 		 ': '.$fetchresult);
 3029:         return '/adm/notfound.html';
 3030:     }
 3031: }
 3032: 
 3033: sub extract_embedded_items {
 3034:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3035:     my @state = ();
 3036:     my %javafiles = (
 3037:                       codebase => '',
 3038:                       code => '',
 3039:                       archive => ''
 3040:                     );
 3041:     my %mediafiles = (
 3042:                       src => '',
 3043:                       movie => '',
 3044:                      );
 3045:     my $p;
 3046:     if ($content) {
 3047:         $p = HTML::LCParser->new($content);
 3048:     } else {
 3049:         $p = HTML::LCParser->new($fullpath);
 3050:     }
 3051:     while (my $t=$p->get_token()) {
 3052: 	if ($t->[0] eq 'S') {
 3053: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3054: 	    push(@state, $tagname);
 3055:             if (lc($tagname) eq 'allow') {
 3056:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3057:             }
 3058: 	    if (lc($tagname) eq 'img') {
 3059: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3060: 	    }
 3061: 	    if (lc($tagname) eq 'a') {
 3062: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3063: 	    }
 3064:             if (lc($tagname) eq 'script') {
 3065:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3066:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3067:                 } else {
 3068:                     &add_filetype($allfiles,$attr->{'src'},'src');
 3069:                 }
 3070:             }
 3071:             if (lc($tagname) eq 'link') {
 3072:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3073:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3074:                 }
 3075:             }
 3076: 	    if (lc($tagname) eq 'object' ||
 3077: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3078: 		foreach my $item (keys(%javafiles)) {
 3079: 		    $javafiles{$item} = '';
 3080: 		}
 3081: 	    }
 3082: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3083: 		my $name = lc($attr->{'name'});
 3084: 		foreach my $item (keys(%javafiles)) {
 3085: 		    if ($name eq $item) {
 3086: 			$javafiles{$item} = $attr->{'value'};
 3087: 			last;
 3088: 		    }
 3089: 		}
 3090: 		foreach my $item (keys(%mediafiles)) {
 3091: 		    if ($name eq $item) {
 3092: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 3093: 			last;
 3094: 		    }
 3095: 		}
 3096: 	    }
 3097: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3098: 		foreach my $item (keys(%javafiles)) {
 3099: 		    if ($attr->{$item}) {
 3100: 			$javafiles{$item} = $attr->{$item};
 3101: 			last;
 3102: 		    }
 3103: 		}
 3104: 		foreach my $item (keys(%mediafiles)) {
 3105: 		    if ($attr->{$item}) {
 3106: 			&add_filetype($allfiles,$attr->{$item},$item);
 3107: 			last;
 3108: 		    }
 3109: 		}
 3110: 	    }
 3111: 	} elsif ($t->[0] eq 'E') {
 3112: 	    my ($tagname) = ($t->[1]);
 3113: 	    if ($javafiles{'codebase'} ne '') {
 3114: 		$javafiles{'codebase'} .= '/';
 3115: 	    }  
 3116: 	    if (lc($tagname) eq 'applet' ||
 3117: 		lc($tagname) eq 'object' ||
 3118: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3119: 		) {
 3120: 		foreach my $item (keys(%javafiles)) {
 3121: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3122: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3123: 			&add_filetype($allfiles,$file,$item);
 3124: 		    }
 3125: 		}
 3126: 	    } 
 3127: 	    pop @state;
 3128: 	}
 3129:     }
 3130:     return 'ok';
 3131: }
 3132: 
 3133: sub add_filetype {
 3134:     my ($allfiles,$file,$type)=@_;
 3135:     if (exists($allfiles->{$file})) {
 3136: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3137: 	    push(@{$allfiles->{$file}}, &escape($type));
 3138: 	}
 3139:     } else {
 3140: 	@{$allfiles->{$file}} = (&escape($type));
 3141:     }
 3142: }
 3143: 
 3144: sub removeuploadedurl {
 3145:     my ($url)=@_;	
 3146:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3147:     return &removeuserfile($uname,$udom,$fname);
 3148: }
 3149: 
 3150: sub removeuserfile {
 3151:     my ($docuname,$docudom,$fname)=@_;
 3152:     my $home=&homeserver($docuname,$docudom);    
 3153:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3154:     if ($result eq 'ok') {	
 3155:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3156:             my $metafile = $fname.'.meta';
 3157:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3158: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3159:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3160:             my $sqlresult = 
 3161:                 &update_portfolio_table($docuname,$docudom,$file,
 3162:                                         'portfolio_metadata',$group,
 3163:                                         'delete');
 3164:         }
 3165:     }
 3166:     return $result;
 3167: }
 3168: 
 3169: sub mkdiruserfile {
 3170:     my ($docuname,$docudom,$dir)=@_;
 3171:     my $home=&homeserver($docuname,$docudom);
 3172:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3173: }
 3174: 
 3175: sub renameuserfile {
 3176:     my ($docuname,$docudom,$old,$new)=@_;
 3177:     my $home=&homeserver($docuname,$docudom);
 3178:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3179:                         &escape("$old").':'.&escape("$new"),$home);
 3180:     if ($result eq 'ok') {
 3181:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3182:             my $oldmeta = $old.'.meta';
 3183:             my $newmeta = $new.'.meta';
 3184:             my $metaresult = 
 3185:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3186: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3187:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3188:             my $sqlresult = 
 3189:                 &update_portfolio_table($docuname,$docudom,$file,
 3190:                                         'portfolio_metadata',$group,
 3191:                                         'delete');
 3192:         }
 3193:     }
 3194:     return $result;
 3195: }
 3196: 
 3197: # ------------------------------------------------------------------------- Log
 3198: 
 3199: sub log {
 3200:     my ($dom,$nam,$hom,$what)=@_;
 3201:     return critical("log:$dom:$nam:$what",$hom);
 3202: }
 3203: 
 3204: # ------------------------------------------------------------------ Course Log
 3205: #
 3206: # This routine flushes several buffers of non-mission-critical nature
 3207: #
 3208: 
 3209: sub flushcourselogs {
 3210:     &logthis('Flushing log buffers');
 3211: #
 3212: # course logs
 3213: # This is a log of all transactions in a course, which can be used
 3214: # for data mining purposes
 3215: #
 3216: # It also collects the courseid database, which lists last transaction
 3217: # times and course titles for all courseids
 3218: #
 3219:     my %courseidbuffer=();
 3220:     foreach my $crsid (keys(%courselogs)) {
 3221:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3222: 		          &escape($courselogs{$crsid}),
 3223: 		          $coursehombuf{$crsid}) eq 'ok') {
 3224: 	    delete $courselogs{$crsid};
 3225:         } else {
 3226:             &logthis('Failed to flush log buffer for '.$crsid);
 3227:             if (length($courselogs{$crsid})>40000) {
 3228:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3229:                         " exceeded maximum size, deleting.</font>");
 3230:                delete $courselogs{$crsid};
 3231:             }
 3232:         }
 3233:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3234:             'description' => $coursedescrbuf{$crsid},
 3235:             'inst_code'    => $courseinstcodebuf{$crsid},
 3236:             'type'        => $coursetypebuf{$crsid},
 3237:             'owner'       => $courseownerbuf{$crsid},
 3238:         };
 3239:     }
 3240: #
 3241: # Write course id database (reverse lookup) to homeserver of courses 
 3242: # Is used in pickcourse
 3243: #
 3244:     foreach my $crs_home (keys(%courseidbuffer)) {
 3245:         my $response = &courseidput(&host_domain($crs_home),
 3246:                                     $courseidbuffer{$crs_home},
 3247:                                     $crs_home,'timeonly');
 3248:     }
 3249: #
 3250: # File accesses
 3251: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3252: #
 3253:     foreach my $entry (keys(%accesshash)) {
 3254:         if ($entry =~ /___count$/) {
 3255:             my ($dom,$name);
 3256:             ($dom,$name,undef)=
 3257: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3258:             if (! defined($dom) || $dom eq '' || 
 3259:                 ! defined($name) || $name eq '') {
 3260:                 my $cid = $env{'request.course.id'};
 3261:                 $dom  = $env{'request.'.$cid.'.domain'};
 3262:                 $name = $env{'request.'.$cid.'.num'};
 3263:             }
 3264:             my $value = $accesshash{$entry};
 3265:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3266:             my %temphash=($url => $value);
 3267:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3268:             if ($result eq 'ok') {
 3269:                 delete $accesshash{$entry};
 3270:             }
 3271:         } else {
 3272:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3273:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3274:             my %temphash=($entry => $accesshash{$entry});
 3275:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3276:                 delete $accesshash{$entry};
 3277:             }
 3278:         }
 3279:     }
 3280: #
 3281: # Roles
 3282: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3283: #
 3284:     foreach my $entry (keys(%userrolehash)) {
 3285:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3286: 	    split(/\:/,$entry);
 3287:         if (&Apache::lonnet::put('nohist_userroles',
 3288:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3289:                 $rudom,$runame) eq 'ok') {
 3290: 	    delete $userrolehash{$entry};
 3291:         }
 3292:     }
 3293: #
 3294: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3295: #
 3296:     my %domrolebuffer = ();
 3297:     foreach my $entry (keys(%domainrolehash)) {
 3298:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3299:         if ($domrolebuffer{$rudom}) {
 3300:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3301:                       '='.&escape($domainrolehash{$entry});
 3302:         } else {
 3303:             $domrolebuffer{$rudom}.=&escape($entry).
 3304:                       '='.&escape($domainrolehash{$entry});
 3305:         }
 3306:         delete $domainrolehash{$entry};
 3307:     }
 3308:     foreach my $dom (keys(%domrolebuffer)) {
 3309: 	my %servers = &get_servers($dom,'library');
 3310: 	foreach my $tryserver (keys(%servers)) {
 3311: 	    unless (&reply('domroleput:'.$dom.':'.
 3312: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3313: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3314: 	    }
 3315:         }
 3316:     }
 3317:     $dumpcount++;
 3318: }
 3319: 
 3320: sub courselog {
 3321:     my $what=shift;
 3322:     $what=time.':'.$what;
 3323:     unless ($env{'request.course.id'}) { return ''; }
 3324:     $coursedombuf{$env{'request.course.id'}}=
 3325:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3326:     $coursenumbuf{$env{'request.course.id'}}=
 3327:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3328:     $coursehombuf{$env{'request.course.id'}}=
 3329:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3330:     $coursedescrbuf{$env{'request.course.id'}}=
 3331:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3332:     $courseinstcodebuf{$env{'request.course.id'}}=
 3333:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3334:     $courseownerbuf{$env{'request.course.id'}}=
 3335:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3336:     $coursetypebuf{$env{'request.course.id'}}=
 3337:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3338:     if (defined $courselogs{$env{'request.course.id'}}) {
 3339: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3340:     } else {
 3341: 	$courselogs{$env{'request.course.id'}}.=$what;
 3342:     }
 3343:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3344: 	&flushcourselogs();
 3345:     }
 3346: }
 3347: 
 3348: sub courseacclog {
 3349:     my $fnsymb=shift;
 3350:     unless ($env{'request.course.id'}) { return ''; }
 3351:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3352:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3353:         $what.=':POST';
 3354:         # FIXME: Probably ought to escape things....
 3355: 	foreach my $key (keys(%env)) {
 3356:             if ($key=~/^form\.(.*)/) {
 3357:                 my $formitem = $1;
 3358:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3359:                     $what.=':'.$formitem.'='.$env{$key};
 3360:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3361:                     $what.=':'.$formitem.'='.$env{$key};
 3362:                 }
 3363:             }
 3364:         }
 3365:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3366:         # FIXME: We should not be depending on a form parameter that someone
 3367:         # editing lonsearchcat.pm might change in the future.
 3368:         if ($env{'form.phase'} eq 'course_search') {
 3369:             $what.= ':POST';
 3370:             # FIXME: Probably ought to escape things....
 3371:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3372:                                  'crsdiscuss') {
 3373:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3374:             }
 3375:         }
 3376:     }
 3377:     &courselog($what);
 3378: }
 3379: 
 3380: sub countacc {
 3381:     my $url=&declutter(shift);
 3382:     return if (! defined($url) || $url eq '');
 3383:     unless ($env{'request.course.id'}) { return ''; }
 3384: #
 3385: # Mark that this url was used in this course
 3386: #
 3387:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3388: #
 3389: # Increase the access count for this resource in this child process
 3390: #
 3391:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3392:     $accesshash{$key}++;
 3393: }
 3394: 
 3395: sub linklog {
 3396:     my ($from,$to)=@_;
 3397:     $from=&declutter($from);
 3398:     $to=&declutter($to);
 3399:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3400:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3401: }
 3402: 
 3403: sub statslog {
 3404:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3405:     if ($users<2) { return; }
 3406:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3407:             'course'       => $env{'request.course.id'},
 3408:             'sections'     => '"all"',
 3409:             'num_students' => $users,
 3410:             'part'         => $part,
 3411:             'symb'         => $symb,
 3412:             'mean_tries'   => $av_attempts,
 3413:             'deg_of_diff'  => $degdiff});
 3414:     foreach my $key (keys(%dynstore)) {
 3415:         $accesshash{$key}=$dynstore{$key};
 3416:     }
 3417: }
 3418:   
 3419: sub userrolelog {
 3420:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3421:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 3422:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 3423:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 3424:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 3425:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3426:        $userrolehash
 3427:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3428:                     =$tend.':'.$tstart;
 3429:     }
 3430:     if (($env{'request.role'} =~ /dc\./) &&
 3431: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 3432: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 3433: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 3434:          ($trole=~/^co/))) {
 3435:        $userrolehash
 3436:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3437:                     =$tend.':'.$tstart;
 3438:     }
 3439:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 3440:         ($trole=~/^li/) || ($trole=~/^li/) ||
 3441:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 3442:         ($trole=~/^sc/)) {
 3443:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3444:        $domainrolehash
 3445:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3446:                     = $tend.':'.$tstart;
 3447:     }
 3448: }
 3449: 
 3450: sub courserolelog {
 3451:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3452:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3453:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3454:         ($trole eq 'ta') || ($trole eq 'st') ||
 3455:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3456:         ($trole eq 'co')) {
 3457:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3458:             my $cdom = $1;
 3459:             my $cnum = $2;
 3460:             my $sec = $3;
 3461:             my $namespace = 'rolelog';
 3462:             my %storehash = (
 3463:                                role    => $trole,
 3464:                                start   => $tstart,
 3465:                                end     => $tend,
 3466:                                selfenroll => $selfenroll,
 3467:                                context    => $context,
 3468:                             );
 3469:             if ($trole eq 'gr') {
 3470:                 $namespace = 'groupslog';
 3471:                 $storehash{'group'} = $sec;
 3472:             } else {
 3473:                 $storehash{'section'} = $sec;
 3474:             }
 3475:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3476:             if (($trole ne 'st') || ($sec ne '')) {
 3477:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3478:             }
 3479:         }
 3480:     }
 3481:     return;
 3482: }
 3483: 
 3484: sub get_course_adv_roles {
 3485:     my ($cid,$codes) = @_;
 3486:     $cid=$env{'request.course.id'} unless (defined($cid));
 3487:     my %coursehash=&coursedescription($cid);
 3488:     my $crstype = &Apache::loncommon::course_type($cid);
 3489:     my %nothide=();
 3490:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3491:         if ($user !~ /:/) {
 3492: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3493:         } else {
 3494:             $nothide{$user}=1;
 3495:         }
 3496:     }
 3497:     my %returnhash=();
 3498:     my %dumphash=
 3499:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3500:     my $now=time;
 3501:     my %privileged;
 3502:     foreach my $entry (keys(%dumphash)) {
 3503: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3504:         if (($tstart) && ($tstart<0)) { next; }
 3505:         if (($tend) && ($tend<$now)) { next; }
 3506:         if (($tstart) && ($now<$tstart)) { next; }
 3507:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3508: 	if ($username eq '' || $domain eq '') { next; }
 3509:         unless (ref($privileged{$domain}) eq 'HASH') {
 3510:             my %dompersonnel =
 3511:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3512:             $privileged{$domain} = {};
 3513:             foreach my $server (keys(%dompersonnel)) {
 3514:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3515:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3516:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3517:                         $privileged{$udom}{$uname} = 1;
 3518:                     }
 3519:                 }
 3520:             }
 3521:         }
 3522:         if ((exists($privileged{$domain}{$username})) && 
 3523:             (!$nothide{$username.':'.$domain})) { next; }
 3524: 	if ($role eq 'cr') { next; }
 3525:         if ($codes) {
 3526:             if ($section) { $role .= ':'.$section; }
 3527:             if ($returnhash{$role}) {
 3528:                 $returnhash{$role}.=','.$username.':'.$domain;
 3529:             } else {
 3530:                 $returnhash{$role}=$username.':'.$domain;
 3531:             }
 3532:         } else {
 3533:             my $key=&plaintext($role,$crstype);
 3534:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3535:             if ($returnhash{$key}) {
 3536: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3537:             } else {
 3538:                 $returnhash{$key}=$username.':'.$domain;
 3539:             }
 3540:         }
 3541:     }
 3542:     return %returnhash;
 3543: }
 3544: 
 3545: sub get_my_roles {
 3546:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3547:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3548:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3549:     my (%dumphash,%nothide);
 3550:     if ($context eq 'userroles') {
 3551:         my $extra = &freeze_escape({'skipcheck' => 1});
 3552:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
 3553:     } else {
 3554:         %dumphash=
 3555:             &dump('nohist_userroles',$udom,$uname);
 3556:         if ($hidepriv) {
 3557:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3558:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3559:                 if ($user !~ /:/) {
 3560:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3561:                 } else {
 3562:                     $nothide{$user} = 1;
 3563:                 }
 3564:             }
 3565:         }
 3566:     }
 3567:     my %returnhash=();
 3568:     my $now=time;
 3569:     my %privileged;
 3570:     foreach my $entry (keys(%dumphash)) {
 3571:         my ($role,$tend,$tstart);
 3572:         if ($context eq 'userroles') {
 3573:             next if ($entry =~ /^rolesdef/);
 3574: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3575:         } else {
 3576:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3577:         }
 3578:         if (($tstart) && ($tstart<0)) { next; }
 3579:         my $status = 'active';
 3580:         if (($tend) && ($tend<=$now)) {
 3581:             $status = 'previous';
 3582:         } 
 3583:         if (($tstart) && ($now<$tstart)) {
 3584:             $status = 'future';
 3585:         }
 3586:         if (ref($types) eq 'ARRAY') {
 3587:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3588:                 next;
 3589:             } 
 3590:         } else {
 3591:             if ($status ne 'active') {
 3592:                 next;
 3593:             }
 3594:         }
 3595:         my ($rolecode,$username,$domain,$section,$area);
 3596:         if ($context eq 'userroles') {
 3597:             ($area,$rolecode) = split(/_/,$entry);
 3598:             (undef,$domain,$username,$section) = split(/\//,$area);
 3599:         } else {
 3600:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3601:         }
 3602:         if (ref($roledoms) eq 'ARRAY') {
 3603:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3604:                 next;
 3605:             }
 3606:         }
 3607:         if (ref($roles) eq 'ARRAY') {
 3608:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3609:                 if ($role =~ /^cr\//) {
 3610:                     if (!grep(/^cr$/,@{$roles})) {
 3611:                         next;
 3612:                     }
 3613:                 } elsif ($role =~ /^gr\//) {
 3614:                     if (!grep(/^gr$/,@{$roles})) {
 3615:                         next;
 3616:                     }
 3617:                 } else {
 3618:                     next;
 3619:                 }
 3620:             }
 3621:         }
 3622:         if ($hidepriv) {
 3623:             if ($context eq 'userroles') {
 3624:                 if ((&privileged($username,$domain)) &&
 3625:                     (!$nothide{$username.':'.$domain})) {
 3626:                     next;
 3627:                 }
 3628:             } else {
 3629:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3630:                     my %dompersonnel =
 3631:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3632:                     $privileged{$domain} = {};
 3633:                     if (keys(%dompersonnel)) {
 3634:                         foreach my $server (keys(%dompersonnel)) {
 3635:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3636:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3637:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3638:                                     $privileged{$udom}{$uname} = $trole;
 3639:                                 }
 3640:                             }
 3641:                         }
 3642:                     }
 3643:                 }
 3644:                 if (exists($privileged{$domain}{$username})) {
 3645:                     if (!$nothide{$username.':'.$domain}) {
 3646:                         next;
 3647:                     }
 3648:                 }
 3649:             }
 3650:         }
 3651:         if ($withsec) {
 3652:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3653:                 $tstart.':'.$tend;
 3654:         } else {
 3655:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3656:         }
 3657:     }
 3658:     return %returnhash;
 3659: }
 3660: 
 3661: # ----------------------------------------------------- Frontpage Announcements
 3662: #
 3663: #
 3664: 
 3665: sub postannounce {
 3666:     my ($server,$text)=@_;
 3667:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3668:     unless ($text=~/\w/) { $text=''; }
 3669:     return &reply('setannounce:'.&escape($text),$server);
 3670: }
 3671: 
 3672: sub getannounce {
 3673: 
 3674:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3675: 	my $announcement='';
 3676: 	while (my $line = <$fh>) { $announcement .= $line; }
 3677: 	close($fh);
 3678: 	if ($announcement=~/\w/) { 
 3679: 	    return 
 3680:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3681:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3682: 	} else {
 3683: 	    return '';
 3684: 	}
 3685:     } else {
 3686: 	return '';
 3687:     }
 3688: }
 3689: 
 3690: # ---------------------------------------------------------- Course ID routines
 3691: # Deal with domain's nohist_courseid.db files
 3692: #
 3693: 
 3694: sub courseidput {
 3695:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3696:     return unless (ref($storehash) eq 'HASH');
 3697:     my $outcome;
 3698:     if ($caller eq 'timeonly') {
 3699:         my $cids = '';
 3700:         foreach my $item (keys(%$storehash)) {
 3701:             $cids.=&escape($item).'&';
 3702:         }
 3703:         $cids=~s/\&$//;
 3704:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3705:                           $coursehome);       
 3706:     } else {
 3707:         my $items = '';
 3708:         foreach my $item (keys(%$storehash)) {
 3709:             $items.= &escape($item).'='.
 3710:                      &freeze_escape($$storehash{$item}).'&';
 3711:         }
 3712:         $items=~s/\&$//;
 3713:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3714:                           $coursehome);
 3715:     }
 3716:     if ($outcome eq 'unknown_cmd') {
 3717:         my $what;
 3718:         foreach my $cid (keys(%$storehash)) {
 3719:             $what .= &escape($cid).'=';
 3720:             foreach my $item ('description','inst_code','owner','type') {
 3721:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3722:             }
 3723:             $what =~ s/\:$/&/;
 3724:         }
 3725:         $what =~ s/\&$//;  
 3726:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3727:     } else {
 3728:         return $outcome;
 3729:     }
 3730: }
 3731: 
 3732: sub courseiddump {
 3733:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3734:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3735:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3736:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3737:     my $as_hash = 1;
 3738:     my %returnhash;
 3739:     if (!$domfilter) { $domfilter=''; }
 3740:     my %libserv = &all_library();
 3741:     foreach my $tryserver (keys(%libserv)) {
 3742:         if ( (  $hostidflag == 1 
 3743: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3744: 	     || (!defined($hostidflag)) ) {
 3745: 
 3746: 	    if (($domfilter eq '') ||
 3747: 		(&host_domain($tryserver) eq $domfilter)) {
 3748:                 my $rep = 
 3749:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3750:                          $sincefilter.':'.&escape($descfilter).':'.
 3751:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3752:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3753:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3754:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3755:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3756:                          &escape($cc_clone).':'.$cloneonly.':'.
 3757:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3758:                          &escape($creationcontext).':'.$domcloner,
 3759:                          $tryserver);
 3760:                 my @pairs=split(/\&/,$rep);
 3761:                 foreach my $item (@pairs) {
 3762:                     my ($key,$value)=split(/\=/,$item,2);
 3763:                     $key = &unescape($key);
 3764:                     next if ($key =~ /^error: 2 /);
 3765:                     my $result = &thaw_unescape($value);
 3766:                     if (ref($result) eq 'HASH') {
 3767:                         $returnhash{$key}=$result;
 3768:                     } else {
 3769:                         my @responses = split(/:/,$value);
 3770:                         my @items = ('description','inst_code','owner','type');
 3771:                         for (my $i=0; $i<@responses; $i++) {
 3772:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3773:                         }
 3774:                     }
 3775:                 }
 3776:             }
 3777:         }
 3778:     }
 3779:     return %returnhash;
 3780: }
 3781: 
 3782: sub courselastaccess {
 3783:     my ($cdom,$cnum,$hostidref) = @_;
 3784:     my %returnhash;
 3785:     if ($cdom && $cnum) {
 3786:         my $chome = &homeserver($cnum,$cdom);
 3787:         if ($chome ne 'no_host') {
 3788:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3789:             &extract_lastaccess(\%returnhash,$rep);
 3790:         }
 3791:     } else {
 3792:         if (!$cdom) { $cdom=''; }
 3793:         my %libserv = &all_library();
 3794:         foreach my $tryserver (keys(%libserv)) {
 3795:             if (ref($hostidref) eq 'ARRAY') {
 3796:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3797:             } 
 3798:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3799:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3800:                 &extract_lastaccess(\%returnhash,$rep);
 3801:             }
 3802:         }
 3803:     }
 3804:     return %returnhash;
 3805: }
 3806: 
 3807: sub extract_lastaccess {
 3808:     my ($returnhash,$rep) = @_;
 3809:     if (ref($returnhash) eq 'HASH') {
 3810:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3811:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3812:                  $rep eq '') {
 3813:             my @pairs=split(/\&/,$rep);
 3814:             foreach my $item (@pairs) {
 3815:                 my ($key,$value)=split(/\=/,$item,2);
 3816:                 $key = &unescape($key);
 3817:                 next if ($key =~ /^error: 2 /);
 3818:                 $returnhash->{$key} = &thaw_unescape($value);
 3819:             }
 3820:         }
 3821:     }
 3822:     return;
 3823: }
 3824: 
 3825: # ---------------------------------------------------------- DC e-mail
 3826: 
 3827: sub dcmailput {
 3828:     my ($domain,$msgid,$message,$server)=@_;
 3829:     my $status = &Apache::lonnet::critical(
 3830:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3831:        &escape($message),$server);
 3832:     return $status;
 3833: }
 3834: 
 3835: sub dcmaildump {
 3836:     my ($dom,$startdate,$enddate,$senders) = @_;
 3837:     my %returnhash=();
 3838: 
 3839:     if (defined(&domain($dom,'primary'))) {
 3840:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3841:                                                          &escape($enddate).':';
 3842: 	my @esc_senders=map { &escape($_)} @$senders;
 3843: 	$cmd.=&escape(join('&',@esc_senders));
 3844: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3845:             my ($key,$value) = split(/\=/,$line,2);
 3846:             if (($key) && ($value)) {
 3847:                 $returnhash{&unescape($key)} = &unescape($value);
 3848:             }
 3849:         }
 3850:     }
 3851:     return %returnhash;
 3852: }
 3853: # ---------------------------------------------------------- Domain roles
 3854: 
 3855: sub get_domain_roles {
 3856:     my ($dom,$roles,$startdate,$enddate)=@_;
 3857:     if ((!defined($startdate)) || ($startdate eq '')) {
 3858:         $startdate = '.';
 3859:     }
 3860:     if ((!defined($enddate)) || ($enddate eq '')) {
 3861:         $enddate = '.';
 3862:     }
 3863:     my $rolelist;
 3864:     if (ref($roles) eq 'ARRAY') {
 3865:         $rolelist = join(':',@{$roles});
 3866:     }
 3867:     my %personnel = ();
 3868: 
 3869:     my %servers = &get_servers($dom,'library');
 3870:     foreach my $tryserver (keys(%servers)) {
 3871: 	%{$personnel{$tryserver}}=();
 3872: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3873: 					    &escape($startdate).':'.
 3874: 					    &escape($enddate).':'.
 3875: 					    &escape($rolelist), $tryserver))) {
 3876: 	    my ($key,$value) = split(/\=/,$line,2);
 3877: 	    if (($key) && ($value)) {
 3878: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3879: 	    }
 3880: 	}
 3881:     }
 3882:     return %personnel;
 3883: }
 3884: 
 3885: # ----------------------------------------------------------- Interval timing 
 3886: 
 3887: {
 3888: # Caches needed for speedup of navmaps
 3889: # We don't want to cache this for very long at all (5 seconds at most)
 3890: # 
 3891: # The user for whom we cache
 3892: my $cachedkey='';
 3893: # The cached times for this user
 3894: my %cachedtimes=();
 3895: # When this was last done
 3896: my $cachedtime=();
 3897: 
 3898: sub load_all_first_access {
 3899:     my ($uname,$udom)=@_;
 3900:     if (($cachedkey eq $uname.':'.$udom) &&
 3901:         (abs($cachedtime-time)<5)) {
 3902:         return;
 3903:     }
 3904:     $cachedtime=time;
 3905:     $cachedkey=$uname.':'.$udom;
 3906:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 3907: }
 3908: 
 3909: sub get_first_access {
 3910:     my ($type,$argsymb,$argmap)=@_;
 3911:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3912:     if ($argsymb) { $symb=$argsymb; }
 3913:     my ($map,$id,$res)=&decode_symb($symb);
 3914:     if ($argmap) { $map = $argmap; }
 3915:     if ($type eq 'course') {
 3916: 	$res='course';
 3917:     } elsif ($type eq 'map') {
 3918: 	$res=&symbread($map);
 3919:     } else {
 3920: 	$res=$symb;
 3921:     }
 3922:     &load_all_first_access($uname,$udom);
 3923:     return $cachedtimes{"$courseid\0$res"};
 3924: }
 3925: 
 3926: sub set_first_access {
 3927:     my ($type,$interval)=@_;
 3928:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3929:     my ($map,$id,$res)=&decode_symb($symb);
 3930:     if ($type eq 'course') {
 3931: 	$res='course';
 3932:     } elsif ($type eq 'map') {
 3933: 	$res=&symbread($map);
 3934:     } else {
 3935: 	$res=$symb;
 3936:     }
 3937:     $cachedkey='';
 3938:     my $firstaccess=&get_first_access($type,$symb,$map);
 3939:     if (!$firstaccess) {
 3940:         my $start = time;
 3941: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 3942:                           $udom,$uname);
 3943:         if ($putres eq 'ok') {
 3944:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 3945:                  $udom,$uname); 
 3946:             &appenv(
 3947:                      {
 3948:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 3949:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 3950:                      }
 3951:                   );
 3952:         }
 3953:         return $putres;
 3954:     }
 3955:     return 'already_set';
 3956: }
 3957: }
 3958: # --------------------------------------------- Set Expire Date for Spreadsheet
 3959: 
 3960: sub expirespread {
 3961:     my ($uname,$udom,$stype,$usymb)=@_;
 3962:     my $cid=$env{'request.course.id'}; 
 3963:     if ($cid) {
 3964:        my $now=time;
 3965:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3966:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3967:                             $env{'course.'.$cid.'.num'}.
 3968: 	        	    ':nohist_expirationdates:'.
 3969:                             &escape($key).'='.$now,
 3970:                             $env{'course.'.$cid.'.home'})
 3971:     }
 3972:     return 'ok';
 3973: }
 3974: 
 3975: # ----------------------------------------------------- Devalidate Spreadsheets
 3976: 
 3977: sub devalidate {
 3978:     my ($symb,$uname,$udom)=@_;
 3979:     my $cid=$env{'request.course.id'}; 
 3980:     if ($cid) {
 3981:         # delete the stored spreadsheets for
 3982:         # - the student level sheet of this user in course's homespace
 3983:         # - the assessment level sheet for this resource 
 3984:         #   for this user in user's homespace
 3985: 	# - current conditional state info
 3986: 	my $key=$uname.':'.$udom.':';
 3987:         my $status=
 3988: 	    &del('nohist_calculatedsheets',
 3989: 		 [$key.'studentcalc:'],
 3990: 		 $env{'course.'.$cid.'.domain'},
 3991: 		 $env{'course.'.$cid.'.num'})
 3992: 		.' '.
 3993: 	    &del('nohist_calculatedsheets_'.$cid,
 3994: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3995:         unless ($status eq 'ok ok') {
 3996:            &logthis('Could not devalidate spreadsheet '.
 3997:                     $uname.' at '.$udom.' for '.
 3998: 		    $symb.': '.$status);
 3999:         }
 4000: 	&delenv('user.state.'.$cid);
 4001:     }
 4002: }
 4003: 
 4004: sub get_scalar {
 4005:     my ($string,$end) = @_;
 4006:     my $value;
 4007:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4008: 	$value = $1;
 4009:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4010: 	$value = $1;
 4011:     }
 4012:     return &unescape($value);
 4013: }
 4014: 
 4015: sub array2str {
 4016:   my (@array) = @_;
 4017:   my $result=&arrayref2str(\@array);
 4018:   $result=~s/^__ARRAY_REF__//;
 4019:   $result=~s/__END_ARRAY_REF__$//;
 4020:   return $result;
 4021: }
 4022: 
 4023: sub arrayref2str {
 4024:   my ($arrayref) = @_;
 4025:   my $result='__ARRAY_REF__';
 4026:   foreach my $elem (@$arrayref) {
 4027:     if(ref($elem) eq 'ARRAY') {
 4028:       $result.=&arrayref2str($elem).'&';
 4029:     } elsif(ref($elem) eq 'HASH') {
 4030:       $result.=&hashref2str($elem).'&';
 4031:     } elsif(ref($elem)) {
 4032:       #print("Got a ref of ".(ref($elem))." skipping.");
 4033:     } else {
 4034:       $result.=&escape($elem).'&';
 4035:     }
 4036:   }
 4037:   $result=~s/\&$//;
 4038:   $result .= '__END_ARRAY_REF__';
 4039:   return $result;
 4040: }
 4041: 
 4042: sub hash2str {
 4043:   my (%hash) = @_;
 4044:   my $result=&hashref2str(\%hash);
 4045:   $result=~s/^__HASH_REF__//;
 4046:   $result=~s/__END_HASH_REF__$//;
 4047:   return $result;
 4048: }
 4049: 
 4050: sub hashref2str {
 4051:   my ($hashref)=@_;
 4052:   my $result='__HASH_REF__';
 4053:   foreach my $key (sort(keys(%$hashref))) {
 4054:     if (ref($key) eq 'ARRAY') {
 4055:       $result.=&arrayref2str($key).'=';
 4056:     } elsif (ref($key) eq 'HASH') {
 4057:       $result.=&hashref2str($key).'=';
 4058:     } elsif (ref($key)) {
 4059:       $result.='=';
 4060:       #print("Got a ref of ".(ref($key))." skipping.");
 4061:     } else {
 4062: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4063:     }
 4064: 
 4065:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4066:       $result.=&arrayref2str($hashref->{$key}).'&';
 4067:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4068:       $result.=&hashref2str($hashref->{$key}).'&';
 4069:     } elsif(ref($hashref->{$key})) {
 4070:        $result.='&';
 4071:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4072:     } else {
 4073:       $result.=&escape($hashref->{$key}).'&';
 4074:     }
 4075:   }
 4076:   $result=~s/\&$//;
 4077:   $result .= '__END_HASH_REF__';
 4078:   return $result;
 4079: }
 4080: 
 4081: sub str2hash {
 4082:     my ($string)=@_;
 4083:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4084:     return %$hash;
 4085: }
 4086: 
 4087: sub str2hashref {
 4088:   my ($string) = @_;
 4089: 
 4090:   my %hash;
 4091: 
 4092:   if($string !~ /^__HASH_REF__/) {
 4093:       if (! ($string eq '' || !defined($string))) {
 4094: 	  $hash{'error'}='Not hash reference';
 4095:       }
 4096:       return (\%hash, $string);
 4097:   }
 4098: 
 4099:   $string =~ s/^__HASH_REF__//;
 4100: 
 4101:   while($string !~ /^__END_HASH_REF__/) {
 4102:       #key
 4103:       my $key='';
 4104:       if($string =~ /^__HASH_REF__/) {
 4105:           ($key, $string)=&str2hashref($string);
 4106:           if(defined($key->{'error'})) {
 4107:               $hash{'error'}='Bad data';
 4108:               return (\%hash, $string);
 4109:           }
 4110:       } elsif($string =~ /^__ARRAY_REF__/) {
 4111:           ($key, $string)=&str2arrayref($string);
 4112:           if($key->[0] eq 'Array reference error') {
 4113:               $hash{'error'}='Bad data';
 4114:               return (\%hash, $string);
 4115:           }
 4116:       } else {
 4117:           $string =~ s/^(.*?)=//;
 4118: 	  $key=&unescape($1);
 4119:       }
 4120:       $string =~ s/^=//;
 4121: 
 4122:       #value
 4123:       my $value='';
 4124:       if($string =~ /^__HASH_REF__/) {
 4125:           ($value, $string)=&str2hashref($string);
 4126:           if(defined($value->{'error'})) {
 4127:               $hash{'error'}='Bad data';
 4128:               return (\%hash, $string);
 4129:           }
 4130:       } elsif($string =~ /^__ARRAY_REF__/) {
 4131:           ($value, $string)=&str2arrayref($string);
 4132:           if($value->[0] eq 'Array reference error') {
 4133:               $hash{'error'}='Bad data';
 4134:               return (\%hash, $string);
 4135:           }
 4136:       } else {
 4137: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4138:       }
 4139:       $string =~ s/^&//;
 4140: 
 4141:       $hash{$key}=$value;
 4142:   }
 4143: 
 4144:   $string =~ s/^__END_HASH_REF__//;
 4145: 
 4146:   return (\%hash, $string);
 4147: }
 4148: 
 4149: sub str2array {
 4150:     my ($string)=@_;
 4151:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4152:     return @$array;
 4153: }
 4154: 
 4155: sub str2arrayref {
 4156:   my ($string) = @_;
 4157:   my @array;
 4158: 
 4159:   if($string !~ /^__ARRAY_REF__/) {
 4160:       if (! ($string eq '' || !defined($string))) {
 4161: 	  $array[0]='Array reference error';
 4162:       }
 4163:       return (\@array, $string);
 4164:   }
 4165: 
 4166:   $string =~ s/^__ARRAY_REF__//;
 4167: 
 4168:   while($string !~ /^__END_ARRAY_REF__/) {
 4169:       my $value='';
 4170:       if($string =~ /^__HASH_REF__/) {
 4171:           ($value, $string)=&str2hashref($string);
 4172:           if(defined($value->{'error'})) {
 4173:               $array[0] ='Array reference error';
 4174:               return (\@array, $string);
 4175:           }
 4176:       } elsif($string =~ /^__ARRAY_REF__/) {
 4177:           ($value, $string)=&str2arrayref($string);
 4178:           if($value->[0] eq 'Array reference error') {
 4179:               $array[0] ='Array reference error';
 4180:               return (\@array, $string);
 4181:           }
 4182:       } else {
 4183: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4184:       }
 4185:       $string =~ s/^&//;
 4186: 
 4187:       push(@array, $value);
 4188:   }
 4189: 
 4190:   $string =~ s/^__END_ARRAY_REF__//;
 4191: 
 4192:   return (\@array, $string);
 4193: }
 4194: 
 4195: # -------------------------------------------------------------------Temp Store
 4196: 
 4197: sub tmpreset {
 4198:   my ($symb,$namespace,$domain,$stuname) = @_;
 4199:   if (!$symb) {
 4200:     $symb=&symbread();
 4201:     if (!$symb) { $symb= $env{'request.url'}; }
 4202:   }
 4203:   $symb=escape($symb);
 4204: 
 4205:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4206:   $namespace=~s/\//\_/g;
 4207:   $namespace=~s/\W//g;
 4208: 
 4209:   if (!$domain) { $domain=$env{'user.domain'}; }
 4210:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4211:   if ($domain eq 'public' && $stuname eq 'public') {
 4212:       $stuname=$ENV{'REMOTE_ADDR'};
 4213:   }
 4214:   my $path=LONCAPA::tempdir();
 4215:   my %hash;
 4216:   if (tie(%hash,'GDBM_File',
 4217: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4218: 	  &GDBM_WRCREAT(),0640)) {
 4219:     foreach my $key (keys(%hash)) {
 4220:       if ($key=~ /:$symb/) {
 4221: 	delete($hash{$key});
 4222:       }
 4223:     }
 4224:   }
 4225: }
 4226: 
 4227: sub tmpstore {
 4228:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4229: 
 4230:   if (!$symb) {
 4231:     $symb=&symbread();
 4232:     if (!$symb) { $symb= $env{'request.url'}; }
 4233:   }
 4234:   $symb=escape($symb);
 4235: 
 4236:   if (!$namespace) {
 4237:     # I don't think we would ever want to store this for a course.
 4238:     # it seems this will only be used if we don't have a course.
 4239:     #$namespace=$env{'request.course.id'};
 4240:     #if (!$namespace) {
 4241:       $namespace=$env{'request.state'};
 4242:     #}
 4243:   }
 4244:   $namespace=~s/\//\_/g;
 4245:   $namespace=~s/\W//g;
 4246:   if (!$domain) { $domain=$env{'user.domain'}; }
 4247:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4248:   if ($domain eq 'public' && $stuname eq 'public') {
 4249:       $stuname=$ENV{'REMOTE_ADDR'};
 4250:   }
 4251:   my $now=time;
 4252:   my %hash;
 4253:   my $path=LONCAPA::tempdir();
 4254:   if (tie(%hash,'GDBM_File',
 4255: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4256: 	  &GDBM_WRCREAT(),0640)) {
 4257:     $hash{"version:$symb"}++;
 4258:     my $version=$hash{"version:$symb"};
 4259:     my $allkeys=''; 
 4260:     foreach my $key (keys(%$storehash)) {
 4261:       $allkeys.=$key.':';
 4262:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4263:     }
 4264:     $hash{"$version:$symb:timestamp"}=$now;
 4265:     $allkeys.='timestamp';
 4266:     $hash{"$version:keys:$symb"}=$allkeys;
 4267:     if (untie(%hash)) {
 4268:       return 'ok';
 4269:     } else {
 4270:       return "error:$!";
 4271:     }
 4272:   } else {
 4273:     return "error:$!";
 4274:   }
 4275: }
 4276: 
 4277: # -----------------------------------------------------------------Temp Restore
 4278: 
 4279: sub tmprestore {
 4280:   my ($symb,$namespace,$domain,$stuname) = @_;
 4281: 
 4282:   if (!$symb) {
 4283:     $symb=&symbread();
 4284:     if (!$symb) { $symb= $env{'request.url'}; }
 4285:   }
 4286:   $symb=escape($symb);
 4287: 
 4288:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4289: 
 4290:   if (!$domain) { $domain=$env{'user.domain'}; }
 4291:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4292:   if ($domain eq 'public' && $stuname eq 'public') {
 4293:       $stuname=$ENV{'REMOTE_ADDR'};
 4294:   }
 4295:   my %returnhash;
 4296:   $namespace=~s/\//\_/g;
 4297:   $namespace=~s/\W//g;
 4298:   my %hash;
 4299:   my $path=LONCAPA::tempdir();
 4300:   if (tie(%hash,'GDBM_File',
 4301: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4302: 	  &GDBM_READER(),0640)) {
 4303:     my $version=$hash{"version:$symb"};
 4304:     $returnhash{'version'}=$version;
 4305:     my $scope;
 4306:     for ($scope=1;$scope<=$version;$scope++) {
 4307:       my $vkeys=$hash{"$scope:keys:$symb"};
 4308:       my @keys=split(/:/,$vkeys);
 4309:       my $key;
 4310:       $returnhash{"$scope:keys"}=$vkeys;
 4311:       foreach $key (@keys) {
 4312: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4313: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4314:       }
 4315:     }
 4316:     if (!(untie(%hash))) {
 4317:       return "error:$!";
 4318:     }
 4319:   } else {
 4320:     return "error:$!";
 4321:   }
 4322:   return %returnhash;
 4323: }
 4324: 
 4325: # ----------------------------------------------------------------------- Store
 4326: 
 4327: sub store {
 4328:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4329:     my $home='';
 4330: 
 4331:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4332: 
 4333:     $symb=&symbclean($symb);
 4334:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4335: 
 4336:     if (!$domain) { $domain=$env{'user.domain'}; }
 4337:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4338: 
 4339:     &devalidate($symb,$stuname,$domain);
 4340: 
 4341:     $symb=escape($symb);
 4342:     if (!$namespace) { 
 4343:        unless ($namespace=$env{'request.course.id'}) { 
 4344:           return ''; 
 4345:        } 
 4346:     }
 4347:     if (!$home) { $home=$env{'user.home'}; }
 4348: 
 4349:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4350:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4351: 
 4352:     my $namevalue='';
 4353:     foreach my $key (keys(%$storehash)) {
 4354:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4355:     }
 4356:     $namevalue=~s/\&$//;
 4357:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4358:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4359: }
 4360: 
 4361: # -------------------------------------------------------------- Critical Store
 4362: 
 4363: sub cstore {
 4364:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4365:     my $home='';
 4366: 
 4367:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4368: 
 4369:     $symb=&symbclean($symb);
 4370:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4371: 
 4372:     if (!$domain) { $domain=$env{'user.domain'}; }
 4373:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4374: 
 4375:     &devalidate($symb,$stuname,$domain);
 4376: 
 4377:     $symb=escape($symb);
 4378:     if (!$namespace) { 
 4379:        unless ($namespace=$env{'request.course.id'}) { 
 4380:           return ''; 
 4381:        } 
 4382:     }
 4383:     if (!$home) { $home=$env{'user.home'}; }
 4384: 
 4385:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4386:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4387: 
 4388:     my $namevalue='';
 4389:     foreach my $key (keys(%$storehash)) {
 4390:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4391:     }
 4392:     $namevalue=~s/\&$//;
 4393:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4394:     return critical
 4395:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4396: }
 4397: 
 4398: # --------------------------------------------------------------------- Restore
 4399: 
 4400: sub restore {
 4401:     my ($symb,$namespace,$domain,$stuname) = @_;
 4402:     my $home='';
 4403: 
 4404:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4405: 
 4406:     if (!$symb) {
 4407:       unless ($symb=escape(&symbread())) { return ''; }
 4408:     } else {
 4409:       $symb=&escape(&symbclean($symb));
 4410:     }
 4411:     if (!$namespace) { 
 4412:        unless ($namespace=$env{'request.course.id'}) { 
 4413:           return ''; 
 4414:        } 
 4415:     }
 4416:     if (!$domain) { $domain=$env{'user.domain'}; }
 4417:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4418:     if (!$home) { $home=$env{'user.home'}; }
 4419:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4420: 
 4421:     my %returnhash=();
 4422:     foreach my $line (split(/\&/,$answer)) {
 4423: 	my ($name,$value)=split(/\=/,$line);
 4424:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4425:     }
 4426:     my $version;
 4427:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4428:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4429:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4430:        }
 4431:     }
 4432:     return %returnhash;
 4433: }
 4434: 
 4435: # ---------------------------------------------------------- Course Description
 4436: #
 4437: #  
 4438: 
 4439: sub coursedescription {
 4440:     my ($courseid,$args)=@_;
 4441:     $courseid=~s/^\///;
 4442:     $courseid=~s/\_/\//g;
 4443:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4444:     my $chome=&homeserver($cnum,$cdomain);
 4445:     my $normalid=$cdomain.'_'.$cnum;
 4446:     # need to always cache even if we get errors otherwise we keep 
 4447:     # trying and trying and trying to get the course description.
 4448:     my %envhash=();
 4449:     my %returnhash=();
 4450:     
 4451:     my $expiretime=600;
 4452:     if ($env{'request.course.id'} eq $normalid) {
 4453: 	$expiretime=120;
 4454:     }
 4455: 
 4456:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4457:     if (!$args->{'freshen_cache'}
 4458: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4459: 	foreach my $key (keys(%env)) {
 4460: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4461: 	    my ($setting) = $1;
 4462: 	    $returnhash{$setting} = $env{$key};
 4463: 	}
 4464: 	return %returnhash;
 4465:     }
 4466: 
 4467:     # get the data again
 4468: 
 4469:     if (!$args->{'one_time'}) {
 4470: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4471:     }
 4472: 
 4473:     if ($chome ne 'no_host') {
 4474:        %returnhash=&dump('environment',$cdomain,$cnum);
 4475:        if (!exists($returnhash{'con_lost'})) {
 4476: 	   my $username = $env{'user.name'}; # Defult username
 4477: 	   if(defined $args->{'user'}) {
 4478: 	       $username = $args->{'user'};
 4479: 	   }
 4480:            $returnhash{'home'}= $chome;
 4481: 	   $returnhash{'domain'} = $cdomain;
 4482: 	   $returnhash{'num'} = $cnum;
 4483:            if (!defined($returnhash{'type'})) {
 4484:                $returnhash{'type'} = 'Course';
 4485:            }
 4486:            while (my ($name,$value) = each %returnhash) {
 4487:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4488:            }
 4489:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4490:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4491: 	       $username.'_'.$cdomain.'_'.$cnum;
 4492:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4493:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4494:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4495:        }
 4496:     }
 4497:     if (!$args->{'one_time'}) {
 4498: 	&appenv(\%envhash);
 4499:     }
 4500:     return %returnhash;
 4501: }
 4502: 
 4503: sub update_released_required {
 4504:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4505:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4506:         $cid = $env{'request.course.id'};
 4507:         $cdom = $env{'course.'.$cid.'.domain'};
 4508:         $cnum = $env{'course.'.$cid.'.num'};
 4509:         $chome = $env{'course.'.$cid.'.home'};
 4510:     }
 4511:     if ($needsrelease) {
 4512:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4513:         my $needsupdate;
 4514:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4515:             $needsupdate = 1;
 4516:         } else {
 4517:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4518:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4519:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4520:                 $needsupdate = 1;
 4521:             }
 4522:         }
 4523:         if ($needsupdate) {
 4524:             my %needshash = (
 4525:                              'internal.releaserequired' => $needsrelease,
 4526:                             );
 4527:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4528:             if ($putresult eq 'ok') {
 4529:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4530:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4531:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4532:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4533:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4534:                 }
 4535:             }
 4536:         }
 4537:     }
 4538:     return;
 4539: }
 4540: 
 4541: # -------------------------------------------------See if a user is privileged
 4542: 
 4543: sub privileged {
 4544:     my ($username,$domain)=@_;
 4545:     my $rolesdump=&reply("dump:$domain:$username:roles",
 4546: 			&homeserver($username,$domain));
 4547:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4548:         ($rolesdump =~ /^error:/)) {
 4549:         return 0;
 4550:     }
 4551:     my $now=time;
 4552:     if ($rolesdump ne '') {
 4553:         foreach my $entry (split(/&/,$rolesdump)) {
 4554: 	    if ($entry!~/^rolesdef_/) {
 4555: 		my ($area,$role)=split(/=/,$entry);
 4556: 		$area=~s/\_\w\w$//;
 4557: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 4558: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 4559: 		    my $active=1;
 4560: 		    if ($tend) {
 4561: 			if ($tend<$now) { $active=0; }
 4562: 		    }
 4563: 		    if ($tstart) {
 4564: 			if ($tstart>$now) { $active=0; }
 4565: 		    }
 4566: 		    if ($active) { return 1; }
 4567: 		}
 4568: 	    }
 4569: 	}
 4570:     }
 4571:     return 0;
 4572: }
 4573: 
 4574: # -------------------------------------------------------- Get user privileges
 4575: 
 4576: sub rolesinit {
 4577:     my ($domain,$username,$authhost)=@_;
 4578:     my $now=time;
 4579:     my %userroles = ('user.login.time' => $now);
 4580:     my $extra = &freeze_escape({'skipcheck' => 1});
 4581:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
 4582:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4583:         ($rolesdump =~ /^error:/)) {
 4584:         return \%userroles;
 4585:     }
 4586:     my %firstaccess = &dump('firstaccesstimes',$domain,$username);
 4587:     my %timerinterval = &dump('timerinterval',$domain,$username);
 4588:     my (%coursetimerstarts,%firstaccchk,%firstaccenv,
 4589:         %coursetimerintervals,%timerintchk,%timerintenv);
 4590:     foreach my $key (keys(%firstaccess)) {
 4591:         my ($cid,$rest) = split(/\0/,$key);
 4592:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4593:     }
 4594:     foreach my $key (keys(%timerinterval)) {
 4595:         my ($cid,$rest) = split(/\0/,$key);
 4596:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4597:     }
 4598:     my %allroles=();
 4599:     my %allgroups=();
 4600: 
 4601:     if ($rolesdump ne '') {
 4602:         foreach my $entry (split(/&/,$rolesdump)) {
 4603: 	  if ($entry!~/^rolesdef_/) {
 4604:             my ($area,$role)=split(/=/,$entry);
 4605: 	    $area=~s/\_\w\w$//;
 4606:             my ($trole,$tend,$tstart,$group_privs);
 4607: 	    if ($role=~/^cr/) { 
 4608: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4609: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 4610: 		    ($tend,$tstart)=split('_',$trest);
 4611: 		} else {
 4612: 		    $trole=$role;
 4613: 		}
 4614:             } elsif ($role =~ m|^gr/|) {
 4615:                 ($trole,$tend,$tstart) = split(/_/,$role);
 4616:                 next if ($tstart eq '-1');
 4617:                 ($trole,$group_privs) = split(/\//,$trole);
 4618:                 $group_privs = &unescape($group_privs);
 4619: 	    } else {
 4620: 		($trole,$tend,$tstart)=split(/_/,$role);
 4621: 	    }
 4622: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4623: 					 $username);
 4624: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4625:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 4626:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 4627:             if (($area ne '') && ($trole ne '')) {
 4628: 		my $spec=$trole.'.'.$area;
 4629: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 4630: 		if ($trole =~ /^cr\//) {
 4631:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4632:                 } elsif ($trole eq 'gr') {
 4633:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4634: 		} else {
 4635:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4636: 		}
 4637:                 if ($trole ne 'gr') {
 4638:                     my $cid = $tdomain.'_'.$trest;
 4639:                     unless ($firstaccchk{$cid}) {
 4640:                         if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4641:                             foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4642:                                 $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4643:                                     $coursetimerstarts{$cid}{$item}; 
 4644:                             }
 4645:                         }
 4646:                         $firstaccchk{$cid} = 1;
 4647:                     }
 4648:                     unless ($timerintchk{$cid}) {
 4649:                         if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4650:                             foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4651:                                 $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4652:                                    $coursetimerintervals{$cid}{$item};
 4653:                             }
 4654:                         }
 4655:                         $timerintchk{$cid} = 1;
 4656:                     }
 4657:                 }
 4658:             }
 4659:           }
 4660:         }
 4661:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4662:         $userroles{'user.adv'}    = $adv;
 4663: 	$userroles{'user.author'} = $author;
 4664:         $env{'user.adv'}=$adv;
 4665:     }
 4666:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4667: }
 4668: 
 4669: sub set_arearole {
 4670:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4671: # log the associated role with the area
 4672:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4673:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4674: }
 4675: 
 4676: sub custom_roleprivs {
 4677:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4678:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4679:     my $homsvr=homeserver($rauthor,$rdomain);
 4680:     if (&hostname($homsvr) ne '') {
 4681:         my ($rdummy,$roledef)=
 4682:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4683:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4684:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4685:             if (defined($syspriv)) {
 4686:                 if ($trest =~ /^$match_community$/) {
 4687:                     $syspriv =~ s/bre\&S//; 
 4688:                 }
 4689:                 $$allroles{'cm./'}.=':'.$syspriv;
 4690:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4691:             }
 4692:             if ($tdomain ne '') {
 4693:                 if (defined($dompriv)) {
 4694:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4695:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4696:                 }
 4697:                 if (($trest ne '') && (defined($coursepriv))) {
 4698:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4699:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4700:                 }
 4701:             }
 4702:         }
 4703:     }
 4704: }
 4705: 
 4706: sub group_roleprivs {
 4707:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4708:     my $access = 1;
 4709:     my $now = time;
 4710:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4711:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4712:     if ($access) {
 4713:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4714:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4715:     }
 4716: }
 4717: 
 4718: sub standard_roleprivs {
 4719:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4720:     if (defined($pr{$trole.':s'})) {
 4721:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4722:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4723:     }
 4724:     if ($tdomain ne '') {
 4725:         if (defined($pr{$trole.':d'})) {
 4726:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4727:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4728:         }
 4729:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4730:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4731:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4732:         }
 4733:     }
 4734: }
 4735: 
 4736: sub set_userprivs {
 4737:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4738:     my $author=0;
 4739:     my $adv=0;
 4740:     my %grouproles = ();
 4741:     if (keys(%{$allgroups}) > 0) {
 4742:         my @groupkeys; 
 4743:         foreach my $role (keys(%{$allroles})) {
 4744:             push(@groupkeys,$role);
 4745:         }
 4746:         if (ref($groups_roles) eq 'HASH') {
 4747:             foreach my $key (keys(%{$groups_roles})) {
 4748:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4749:                     push(@groupkeys,$key);
 4750:                 }
 4751:             }
 4752:         }
 4753:         if (@groupkeys > 0) {
 4754:             foreach my $role (@groupkeys) {
 4755:                 my ($trole,$area,$sec,$extendedarea);
 4756:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4757:                     $trole = $1;
 4758:                     $area = $2;
 4759:                     $sec = $3;
 4760:                     $extendedarea = $area.$sec;
 4761:                     if (exists($$allgroups{$area})) {
 4762:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4763:                             my $spec = $trole.'.'.$extendedarea;
 4764:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4765:                                                 $$allgroups{$area}{$group};
 4766:                         }
 4767:                     }
 4768:                 }
 4769:             }
 4770:         }
 4771:     }
 4772:     foreach my $group (keys(%grouproles)) {
 4773:         $$allroles{$group} = $grouproles{$group};
 4774:     }
 4775:     foreach my $role (keys(%{$allroles})) {
 4776:         my %thesepriv;
 4777:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4778:         foreach my $item (split(/:/,$$allroles{$role})) {
 4779:             if ($item ne '') {
 4780:                 my ($privilege,$restrictions)=split(/&/,$item);
 4781:                 if ($restrictions eq '') {
 4782:                     $thesepriv{$privilege}='F';
 4783:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4784:                     $thesepriv{$privilege}.=$restrictions;
 4785:                 }
 4786:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4787:             }
 4788:         }
 4789:         my $thesestr='';
 4790:         foreach my $priv (sort(keys(%thesepriv))) {
 4791: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4792: 	}
 4793:         $userroles->{'user.priv.'.$role} = $thesestr;
 4794:     }
 4795:     return ($author,$adv);
 4796: }
 4797: 
 4798: sub role_status {
 4799:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4800:     my @pwhere = ();
 4801:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4802:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4803:         unless (!defined($$role) || $$role eq '') {
 4804:             $$where=join('.',@pwhere);
 4805:             $$trolecode=$$role.'.'.$$where;
 4806:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4807:             $$tstatus='is';
 4808:             if ($$tstart && $$tstart>$update) {
 4809:                 $$tstatus='future';
 4810:                 if ($$tstart<$now) {
 4811:                     if ($$tstart && $$tstart>$refresh) {
 4812:                         if (($$where ne '') && ($$role ne '')) {
 4813:                             my (%allroles,%allgroups,$group_privs,
 4814:                                 %groups_roles,@rolecodes);
 4815:                             my %userroles = (
 4816:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4817:                             );
 4818:                             @rolecodes = ('cm'); 
 4819:                             my $spec=$$role.'.'.$$where;
 4820:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4821:                             if ($$role =~ /^cr\//) {
 4822:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4823:                                 push(@rolecodes,'cr');
 4824:                             } elsif ($$role eq 'gr') {
 4825:                                 push(@rolecodes,$$role);
 4826:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4827:                                                     $env{'user.name'});
 4828:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4829:                                 (undef,my $group_privs) = split(/\//,$trole);
 4830:                                 $group_privs = &unescape($group_privs);
 4831:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4832:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4833:                                 &get_groups_roles($tdomain,$trest,
 4834:                                                   \%course_roles,\@rolecodes,
 4835:                                                   \%groups_roles);
 4836:                             } else {
 4837:                                 push(@rolecodes,$$role);
 4838:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4839:                             }
 4840:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4841:                             &appenv(\%userroles,\@rolecodes);
 4842:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4843:                         }
 4844:                     }
 4845:                     $$tstatus = 'is';
 4846:                 }
 4847:             }
 4848:             if ($$tend) {
 4849:                 if ($$tend<$update) {
 4850:                     $$tstatus='expired';
 4851:                 } elsif ($$tend<$now) {
 4852:                     $$tstatus='will_not';
 4853:                 }
 4854:             }
 4855:         }
 4856:     }
 4857: }
 4858: 
 4859: sub get_groups_roles {
 4860:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4861:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4862:                   (ref($rolecodes) eq 'ARRAY') && 
 4863:                   (ref($groups_roles) eq 'HASH')); 
 4864:     if (keys(%{$cdom_courseroles}) > 0) {
 4865:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4866:         if ($cdom ne '' && $cnum ne '') {
 4867:             foreach my $key (keys(%{$cdom_courseroles})) {
 4868:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4869:                     my $crsrole = $1;
 4870:                     my $crssec = $2;
 4871:                     if ($crsrole =~ /^cr/) {
 4872:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4873:                             push(@{$rolecodes},'cr');
 4874:                         }
 4875:                     } else {
 4876:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4877:                             push(@{$rolecodes},$crsrole);
 4878:                         }
 4879:                     }
 4880:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4881:                     if ($crssec ne '') {
 4882:                         $rolekey .= "/$crssec";
 4883:                     }
 4884:                     $rolekey .= './';
 4885:                     $groups_roles->{$rolekey} = $rolecodes;
 4886:                 }
 4887:             }
 4888:         }
 4889:     }
 4890:     return;
 4891: }
 4892: 
 4893: sub delete_env_groupprivs {
 4894:     my ($where,$courseroles,$possroles) = @_;
 4895:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4896:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4897:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4898:         %{$courseroles->{$udom}} =
 4899:             &get_my_roles('','','userroles',['active'],
 4900:                           $possroles,[$udom],1);
 4901:     }
 4902:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4903:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4904:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4905:             my $area = '/'.$cdom.'/'.$cnum;
 4906:             my $privkey = "user.priv.$crsrole.$area";
 4907:             if ($crssec ne '') {
 4908:                 $privkey .= '/'.$crssec;
 4909:             }
 4910:             $privkey .= ".$area/$group";
 4911:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4912:         }
 4913:     }
 4914:     return;
 4915: }
 4916: 
 4917: sub check_adhoc_privs {
 4918:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4919:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4920:     if ($env{$cckey}) {
 4921:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4922:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4923:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4924:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4925:         }
 4926:     } else {
 4927:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4928:     }
 4929: }
 4930: 
 4931: sub set_adhoc_privileges {
 4932: # role can be cc or ca
 4933:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 4934:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4935:     my $spec = $role.'.'.$area;
 4936:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4937:                                   $env{'user.name'});
 4938:     my %ccrole = ();
 4939:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4940:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4941:     &appenv(\%userroles,[$role,'cm']);
 4942:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4943:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 4944:         &appenv( {'request.role'        => $spec,
 4945:                   'request.role.domain' => $dcdom,
 4946:                   'request.course.sec'  => ''
 4947:                  }
 4948:                );
 4949:         my $tadv=0;
 4950:         if (&allowed('adv') eq 'F') { $tadv=1; }
 4951:         &appenv({'request.role.adv'    => $tadv});
 4952:     }
 4953: }
 4954: 
 4955: # --------------------------------------------------------------- get interface
 4956: 
 4957: sub get {
 4958:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4959:    my $items='';
 4960:    foreach my $item (@$storearr) {
 4961:        $items.=&escape($item).'&';
 4962:    }
 4963:    $items=~s/\&$//;
 4964:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4965:    if (!$uname) { $uname=$env{'user.name'}; }
 4966:    my $uhome=&homeserver($uname,$udomain);
 4967: 
 4968:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4969:    my @pairs=split(/\&/,$rep);
 4970:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4971:      return @pairs;
 4972:    }
 4973:    my %returnhash=();
 4974:    my $i=0;
 4975:    foreach my $item (@$storearr) {
 4976:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4977:       $i++;
 4978:    }
 4979:    return %returnhash;
 4980: }
 4981: 
 4982: # --------------------------------------------------------------- del interface
 4983: 
 4984: sub del {
 4985:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4986:    my $items='';
 4987:    foreach my $item (@$storearr) {
 4988:        $items.=&escape($item).'&';
 4989:    }
 4990: 
 4991:    $items=~s/\&$//;
 4992:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4993:    if (!$uname) { $uname=$env{'user.name'}; }
 4994:    my $uhome=&homeserver($uname,$udomain);
 4995:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4996: }
 4997: 
 4998: # -------------------------------------------------------------- dump interface
 4999: 
 5000: sub dump {
 5001:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
 5002:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5003:     if (!$uname) { $uname=$env{'user.name'}; }
 5004:     my $uhome=&homeserver($uname,$udomain);
 5005:     if ($regexp) {
 5006: 	$regexp=&escape($regexp);
 5007:     } else {
 5008: 	$regexp='.';
 5009:     }
 5010:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
 5011:     my @pairs=split(/\&/,$rep);
 5012:     my %returnhash=();
 5013:     if (!($rep =~ /^error/ )) {
 5014: 	foreach my $item (@pairs) {
 5015: 	    my ($key,$value)=split(/=/,$item,2);
 5016: 	    $key = &unescape($key);
 5017: 	    next if ($key =~ /^error: 2 /);
 5018: 	    $returnhash{$key}=&thaw_unescape($value);
 5019: 	}
 5020:     }
 5021:     return %returnhash;
 5022: }
 5023: 
 5024: 
 5025: # --------------------------------------------------------- dumpstore interface
 5026: 
 5027: sub dumpstore {
 5028:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5029:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5030:    if (!$uname) { $uname=$env{'user.name'}; }
 5031:    my $uhome=&homeserver($uname,$udomain);
 5032:    if ($regexp) {
 5033:        $regexp=&escape($regexp);
 5034:    } else {
 5035:        $regexp='.';
 5036:    }
 5037:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5038:    my @pairs=split(/\&/,$rep);
 5039:    my %returnhash=();
 5040:    foreach my $item (@pairs) {
 5041:        my ($key,$value)=split(/=/,$item,2);
 5042:        next if ($key =~ /^error: 2 /);
 5043:        $returnhash{$key}=&thaw_unescape($value);
 5044:    }
 5045:    return %returnhash;
 5046: }
 5047: 
 5048: # -------------------------------------------------------------- keys interface
 5049: 
 5050: sub getkeys {
 5051:    my ($namespace,$udomain,$uname)=@_;
 5052:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5053:    if (!$uname) { $uname=$env{'user.name'}; }
 5054:    my $uhome=&homeserver($uname,$udomain);
 5055:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5056:    my @keyarray=();
 5057:    foreach my $key (split(/\&/,$rep)) {
 5058:       next if ($key =~ /^error: 2 /);
 5059:       push(@keyarray,&unescape($key));
 5060:    }
 5061:    return @keyarray;
 5062: }
 5063: 
 5064: # --------------------------------------------------------------- currentdump
 5065: sub currentdump {
 5066:    my ($courseid,$sdom,$sname)=@_;
 5067:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5068:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5069:    $sname    = $env{'user.name'}         if (! defined($sname));
 5070:    my $uhome = &homeserver($sname,$sdom);
 5071:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5072:    return if ($rep =~ /^(error:|no_such_host)/);
 5073:    #
 5074:    my %returnhash=();
 5075:    #
 5076:    if ($rep eq "unknown_cmd") { 
 5077:        # an old lond will not know currentdump
 5078:        # Do a dump and make it look like a currentdump
 5079:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5080:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5081:        my %hash = @tmp;
 5082:        @tmp=();
 5083:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5084:    } else {
 5085:        my @pairs=split(/\&/,$rep);
 5086:        foreach my $pair (@pairs) {
 5087:            my ($key,$value)=split(/=/,$pair,2);
 5088:            my ($symb,$param) = split(/:/,$key);
 5089:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5090:                                                         &thaw_unescape($value);
 5091:        }
 5092:    }
 5093:    return %returnhash;
 5094: }
 5095: 
 5096: sub convert_dump_to_currentdump{
 5097:     my %hash = %{shift()};
 5098:     my %returnhash;
 5099:     # Code ripped from lond, essentially.  The only difference
 5100:     # here is the unescaping done by lonnet::dump().  Conceivably
 5101:     # we might run in to problems with parameter names =~ /^v\./
 5102:     while (my ($key,$value) = each(%hash)) {
 5103:         my ($v,$symb,$param) = split(/:/,$key);
 5104: 	$symb  = &unescape($symb);
 5105: 	$param = &unescape($param);
 5106:         next if ($v eq 'version' || $symb eq 'keys');
 5107:         next if (exists($returnhash{$symb}) &&
 5108:                  exists($returnhash{$symb}->{$param}) &&
 5109:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5110:         $returnhash{$symb}->{$param}=$value;
 5111:         $returnhash{$symb}->{'v.'.$param}=$v;
 5112:     }
 5113:     #
 5114:     # Remove all of the keys in the hashes which keep track of
 5115:     # the version of the parameter.
 5116:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5117:         # use a foreach because we are going to delete from the hash.
 5118:         foreach my $key (keys(%$param_hash)) {
 5119:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5120:         }
 5121:     }
 5122:     return \%returnhash;
 5123: }
 5124: 
 5125: # ------------------------------------------------------ critical inc interface
 5126: 
 5127: sub cinc {
 5128:     return &inc(@_,'critical');
 5129: }
 5130: 
 5131: # --------------------------------------------------------------- inc interface
 5132: 
 5133: sub inc {
 5134:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5135:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5136:     if (!$uname) { $uname=$env{'user.name'}; }
 5137:     my $uhome=&homeserver($uname,$udomain);
 5138:     my $items='';
 5139:     if (! ref($store)) {
 5140:         # got a single value, so use that instead
 5141:         $items = &escape($store).'=&';
 5142:     } elsif (ref($store) eq 'SCALAR') {
 5143:         $items = &escape($$store).'=&';        
 5144:     } elsif (ref($store) eq 'ARRAY') {
 5145:         $items = join('=&',map {&escape($_);} @{$store});
 5146:     } elsif (ref($store) eq 'HASH') {
 5147:         while (my($key,$value) = each(%{$store})) {
 5148:             $items.= &escape($key).'='.&escape($value).'&';
 5149:         }
 5150:     }
 5151:     $items=~s/\&$//;
 5152:     if ($critical) {
 5153: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5154:     } else {
 5155: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5156:     }
 5157: }
 5158: 
 5159: # --------------------------------------------------------------- put interface
 5160: 
 5161: sub put {
 5162:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5163:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5164:    if (!$uname) { $uname=$env{'user.name'}; }
 5165:    my $uhome=&homeserver($uname,$udomain);
 5166:    my $items='';
 5167:    foreach my $item (keys(%$storehash)) {
 5168:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5169:    }
 5170:    $items=~s/\&$//;
 5171:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5172: }
 5173: 
 5174: # ------------------------------------------------------------ newput interface
 5175: 
 5176: sub newput {
 5177:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5178:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5179:    if (!$uname) { $uname=$env{'user.name'}; }
 5180:    my $uhome=&homeserver($uname,$udomain);
 5181:    my $items='';
 5182:    foreach my $key (keys(%$storehash)) {
 5183:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5184:    }
 5185:    $items=~s/\&$//;
 5186:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5187: }
 5188: 
 5189: # ---------------------------------------------------------  putstore interface
 5190: 
 5191: sub putstore {
 5192:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5193:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5194:    if (!$uname) { $uname=$env{'user.name'}; }
 5195:    my $uhome=&homeserver($uname,$udomain);
 5196:    my $items='';
 5197:    foreach my $key (keys(%$storehash)) {
 5198:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5199:    }
 5200:    $items=~s/\&$//;
 5201:    my $esc_symb=&escape($symb);
 5202:    my $esc_v=&escape($version);
 5203:    my $reply =
 5204:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5205: 	      $uhome);
 5206:    if ($reply eq 'unknown_cmd') {
 5207:        # gfall back to way things use to be done
 5208:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5209: 			    $uname);
 5210:    }
 5211:    return $reply;
 5212: }
 5213: 
 5214: sub old_putstore {
 5215:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5216:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5217:     if (!$uname) { $uname=$env{'user.name'}; }
 5218:     my $uhome=&homeserver($uname,$udomain);
 5219:     my %newstorehash;
 5220:     foreach my $item (keys(%$storehash)) {
 5221: 	my $key = $version.':'.&escape($symb).':'.$item;
 5222: 	$newstorehash{$key} = $storehash->{$item};
 5223:     }
 5224:     my $items='';
 5225:     my %allitems = ();
 5226:     foreach my $item (keys(%newstorehash)) {
 5227: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5228: 	    my $key = $1.':keys:'.$2;
 5229: 	    $allitems{$key} .= $3.':';
 5230: 	}
 5231: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5232:     }
 5233:     foreach my $item (keys(%allitems)) {
 5234: 	$allitems{$item} =~ s/\:$//;
 5235: 	$items.= $item.'='.$allitems{$item}.'&';
 5236:     }
 5237:     $items=~s/\&$//;
 5238:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5239: }
 5240: 
 5241: # ------------------------------------------------------ critical put interface
 5242: 
 5243: sub cput {
 5244:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5245:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5246:    if (!$uname) { $uname=$env{'user.name'}; }
 5247:    my $uhome=&homeserver($uname,$udomain);
 5248:    my $items='';
 5249:    foreach my $item (keys(%$storehash)) {
 5250:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5251:    }
 5252:    $items=~s/\&$//;
 5253:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5254: }
 5255: 
 5256: # -------------------------------------------------------------- eget interface
 5257: 
 5258: sub eget {
 5259:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5260:    my $items='';
 5261:    foreach my $item (@$storearr) {
 5262:        $items.=&escape($item).'&';
 5263:    }
 5264:    $items=~s/\&$//;
 5265:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5266:    if (!$uname) { $uname=$env{'user.name'}; }
 5267:    my $uhome=&homeserver($uname,$udomain);
 5268:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5269:    my @pairs=split(/\&/,$rep);
 5270:    my %returnhash=();
 5271:    my $i=0;
 5272:    foreach my $item (@$storearr) {
 5273:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5274:       $i++;
 5275:    }
 5276:    return %returnhash;
 5277: }
 5278: 
 5279: # ------------------------------------------------------------ tmpput interface
 5280: sub tmpput {
 5281:     my ($storehash,$server,$context)=@_;
 5282:     my $items='';
 5283:     foreach my $item (keys(%$storehash)) {
 5284: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5285:     }
 5286:     $items=~s/\&$//;
 5287:     if (defined($context)) {
 5288:         $items .= ':'.&escape($context);
 5289:     }
 5290:     return &reply("tmpput:$items",$server);
 5291: }
 5292: 
 5293: # ------------------------------------------------------------ tmpget interface
 5294: sub tmpget {
 5295:     my ($token,$server)=@_;
 5296:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5297:     my $rep=&reply("tmpget:$token",$server);
 5298:     my %returnhash;
 5299:     foreach my $item (split(/\&/,$rep)) {
 5300: 	my ($key,$value)=split(/=/,$item);
 5301:         next if ($key =~ /^error: 2 /);
 5302: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5303:     }
 5304:     return %returnhash;
 5305: }
 5306: 
 5307: # ------------------------------------------------------------ tmpdel interface
 5308: sub tmpdel {
 5309:     my ($token,$server)=@_;
 5310:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5311:     return &reply("tmpdel:$token",$server);
 5312: }
 5313: 
 5314: # -------------------------------------------------- portfolio access checking
 5315: 
 5316: sub portfolio_access {
 5317:     my ($requrl) = @_;
 5318:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5319:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5320:     if ($result) {
 5321:         my %setters;
 5322:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5323:             my ($startblock,$endblock) =
 5324:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5325:             if ($startblock && $endblock) {
 5326:                 return 'B';
 5327:             }
 5328:         } else {
 5329:             my ($startblock,$endblock) =
 5330:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5331:             if ($startblock && $endblock) {
 5332:                 return 'B';
 5333:             }
 5334:         }
 5335:     }
 5336:     if ($result eq 'ok') {
 5337:        return 'F';
 5338:     } elsif ($result =~ /^[^:]+:guest_/) {
 5339:        return 'A';
 5340:     }
 5341:     return '';
 5342: }
 5343: 
 5344: sub get_portfolio_access {
 5345:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5346: 
 5347:     if (!ref($access_hash)) {
 5348: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5349: 	my %access_controls = &get_access_controls($current_perms,$group,
 5350: 						   $file_name);
 5351: 	$access_hash = $access_controls{$file_name};
 5352:     }
 5353: 
 5354:     my ($public,$guest,@domains,@users,@courses,@groups);
 5355:     my $now = time;
 5356:     if (ref($access_hash) eq 'HASH') {
 5357:         foreach my $key (keys(%{$access_hash})) {
 5358:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5359:             if ($start > $now) {
 5360:                 next;
 5361:             }
 5362:             if ($end && $end<$now) {
 5363:                 next;
 5364:             }
 5365:             if ($scope eq 'public') {
 5366:                 $public = $key;
 5367:                 last;
 5368:             } elsif ($scope eq 'guest') {
 5369:                 $guest = $key;
 5370:             } elsif ($scope eq 'domains') {
 5371:                 push(@domains,$key);
 5372:             } elsif ($scope eq 'users') {
 5373:                 push(@users,$key);
 5374:             } elsif ($scope eq 'course') {
 5375:                 push(@courses,$key);
 5376:             } elsif ($scope eq 'group') {
 5377:                 push(@groups,$key);
 5378:             }
 5379:         }
 5380:         if ($public) {
 5381:             return 'ok';
 5382:         }
 5383:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5384:             if ($guest) {
 5385:                 return $guest;
 5386:             }
 5387:         } else {
 5388:             if (@domains > 0) {
 5389:                 foreach my $domkey (@domains) {
 5390:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5391:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5392:                             return 'ok';
 5393:                         }
 5394:                     }
 5395:                 }
 5396:             }
 5397:             if (@users > 0) {
 5398:                 foreach my $userkey (@users) {
 5399:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5400:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5401:                             if (ref($item) eq 'HASH') {
 5402:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5403:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5404:                                     return 'ok';
 5405:                                 }
 5406:                             }
 5407:                         }
 5408:                     } 
 5409:                 }
 5410:             }
 5411:             my %roleshash;
 5412:             my @courses_and_groups = @courses;
 5413:             push(@courses_and_groups,@groups); 
 5414:             if (@courses_and_groups > 0) {
 5415:                 my (%allgroups,%allroles); 
 5416:                 my ($start,$end,$role,$sec,$group);
 5417:                 foreach my $envkey (%env) {
 5418:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5419:                         my $cid = $2.'_'.$3; 
 5420:                         if ($1 eq 'gr') {
 5421:                             $group = $4;
 5422:                             $allgroups{$cid}{$group} = $env{$envkey};
 5423:                         } else {
 5424:                             if ($4 eq '') {
 5425:                                 $sec = 'none';
 5426:                             } else {
 5427:                                 $sec = $4;
 5428:                             }
 5429:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5430:                         }
 5431:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5432:                         my $cid = $2.'_'.$3;
 5433:                         if ($4 eq '') {
 5434:                             $sec = 'none';
 5435:                         } else {
 5436:                             $sec = $4;
 5437:                         }
 5438:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5439:                     }
 5440:                 }
 5441:                 if (keys(%allroles) == 0) {
 5442:                     return;
 5443:                 }
 5444:                 foreach my $key (@courses_and_groups) {
 5445:                     my %content = %{$$access_hash{$key}};
 5446:                     my $cnum = $content{'number'};
 5447:                     my $cdom = $content{'domain'};
 5448:                     my $cid = $cdom.'_'.$cnum;
 5449:                     if (!exists($allroles{$cid})) {
 5450:                         next;
 5451:                     }    
 5452:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5453:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5454:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5455:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5456:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5457:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5458:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5459:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5460:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5461:                                         if (grep/^all$/,@sections) {
 5462:                                             return 'ok';
 5463:                                         } else {
 5464:                                             if (grep/^$sec$/,@sections) {
 5465:                                                 return 'ok';
 5466:                                             }
 5467:                                         }
 5468:                                     }
 5469:                                 }
 5470:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5471:                                     if (grep/^none$/,@groups) {
 5472:                                         return 'ok';
 5473:                                     }
 5474:                                 } else {
 5475:                                     if (grep/^all$/,@groups) {
 5476:                                         return 'ok';
 5477:                                     } 
 5478:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5479:                                         if (grep/^$group$/,@groups) {
 5480:                                             return 'ok';
 5481:                                         }
 5482:                                     }
 5483:                                 } 
 5484:                             }
 5485:                         }
 5486:                     }
 5487:                 }
 5488:             }
 5489:             if ($guest) {
 5490:                 return $guest;
 5491:             }
 5492:         }
 5493:     }
 5494:     return;
 5495: }
 5496: 
 5497: sub course_group_datechecker {
 5498:     my ($dates,$now,$status) = @_;
 5499:     my ($start,$end) = split(/\./,$dates);
 5500:     if (!$start && !$end) {
 5501:         return 'ok';
 5502:     }
 5503:     if (grep/^active$/,@{$status}) {
 5504:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5505:             return 'ok';
 5506:         }
 5507:     }
 5508:     if (grep/^previous$/,@{$status}) {
 5509:         if ($end > $now ) {
 5510:             return 'ok';
 5511:         }
 5512:     }
 5513:     if (grep/^future$/,@{$status}) {
 5514:         if ($start > $now) {
 5515:             return 'ok';
 5516:         }
 5517:     }
 5518:     return; 
 5519: }
 5520: 
 5521: sub parse_portfolio_url {
 5522:     my ($url) = @_;
 5523: 
 5524:     my ($type,$udom,$unum,$group,$file_name);
 5525:     
 5526:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5527: 	$type = 1;
 5528:         $udom = $1;
 5529:         $unum = $2;
 5530:         $file_name = $3;
 5531:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5532: 	$type = 2;
 5533:         $udom = $1;
 5534:         $unum = $2;
 5535:         $group = $3;
 5536:         $file_name = $3.'/'.$4;
 5537:     }
 5538:     if (wantarray) {
 5539: 	return ($type,$udom,$unum,$file_name,$group);
 5540:     }
 5541:     return $type;
 5542: }
 5543: 
 5544: sub is_portfolio_url {
 5545:     my ($url) = @_;
 5546:     return scalar(&parse_portfolio_url($url));
 5547: }
 5548: 
 5549: sub is_portfolio_file {
 5550:     my ($file) = @_;
 5551:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5552:         return 1;
 5553:     }
 5554:     return;
 5555: }
 5556: 
 5557: sub usertools_access {
 5558:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5559:     my ($access,%tools);
 5560:     if ($context eq '') {
 5561:         $context = 'tools';
 5562:     }
 5563:     if ($context eq 'requestcourses') {
 5564:         %tools = (
 5565:                       official   => 1,
 5566:                       unofficial => 1,
 5567:                       community  => 1,
 5568:                  );
 5569:     } else {
 5570:         %tools = (
 5571:                       aboutme   => 1,
 5572:                       blog      => 1,
 5573:                       portfolio => 1,
 5574:                  );
 5575:     }
 5576:     return if (!defined($tools{$tool}));
 5577: 
 5578:     if ((!defined($udom)) || (!defined($uname))) {
 5579:         $udom = $env{'user.domain'};
 5580:         $uname = $env{'user.name'};
 5581:     }
 5582: 
 5583:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5584:         if ($action ne 'reload') {
 5585:             if ($context eq 'requestcourses') {
 5586:                 return $env{'environment.canrequest.'.$tool};
 5587:             } else {
 5588:                 return $env{'environment.availabletools.'.$tool};
 5589:             }
 5590:         }
 5591:     }
 5592: 
 5593:     my ($toolstatus,$inststatus);
 5594: 
 5595:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5596:          ($action ne 'reload')) {
 5597:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5598:         $inststatus = $env{'environment.inststatus'};
 5599:     } else {
 5600:         if (ref($userenvref) eq 'HASH') {
 5601:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5602:             $inststatus = $userenvref->{'inststatus'};
 5603:         } else {
 5604:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5605:             $toolstatus = $userenv{$context.'.'.$tool};
 5606:             $inststatus = $userenv{'inststatus'};
 5607:         }
 5608:     }
 5609: 
 5610:     if ($toolstatus ne '') {
 5611:         if ($toolstatus) {
 5612:             $access = 1;
 5613:         } else {
 5614:             $access = 0;
 5615:         }
 5616:         return $access;
 5617:     }
 5618: 
 5619:     my ($is_adv,%domdef);
 5620:     if (ref($is_advref) eq 'HASH') {
 5621:         $is_adv = $is_advref->{'is_adv'};
 5622:     } else {
 5623:         $is_adv = &is_advanced_user($udom,$uname);
 5624:     }
 5625:     if (ref($domdefref) eq 'HASH') {
 5626:         %domdef = %{$domdefref};
 5627:     } else {
 5628:         %domdef = &get_domain_defaults($udom);
 5629:     }
 5630:     if (ref($domdef{$tool}) eq 'HASH') {
 5631:         if ($is_adv) {
 5632:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5633:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5634:                     $access = 1;
 5635:                 } else {
 5636:                     $access = 0;
 5637:                 }
 5638:                 return $access;
 5639:             }
 5640:         }
 5641:         if ($inststatus ne '') {
 5642:             my ($hasaccess,$hasnoaccess);
 5643:             foreach my $affiliation (split(/:/,$inststatus)) {
 5644:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5645:                     if ($domdef{$tool}{$affiliation}) {
 5646:                         $hasaccess = 1;
 5647:                     } else {
 5648:                         $hasnoaccess = 1;
 5649:                     }
 5650:                 }
 5651:             }
 5652:             if ($hasaccess || $hasnoaccess) {
 5653:                 if ($hasaccess) {
 5654:                     $access = 1;
 5655:                 } elsif ($hasnoaccess) {
 5656:                     $access = 0; 
 5657:                 }
 5658:                 return $access;
 5659:             }
 5660:         } else {
 5661:             if ($domdef{$tool}{'default'} ne '') {
 5662:                 if ($domdef{$tool}{'default'}) {
 5663:                     $access = 1;
 5664:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5665:                     $access = 0;
 5666:                 }
 5667:                 return $access;
 5668:             }
 5669:         }
 5670:     } else {
 5671:         if ($context eq 'tools') {
 5672:             $access = 1;
 5673:         } else {
 5674:             $access = 0;
 5675:         }
 5676:         return $access;
 5677:     }
 5678: }
 5679: 
 5680: sub is_course_owner {
 5681:     my ($cdom,$cnum,$udom,$uname) = @_;
 5682:     if (($udom eq '') || ($uname eq '')) {
 5683:         $udom = $env{'user.domain'};
 5684:         $uname = $env{'user.name'};
 5685:     }
 5686:     unless (($udom eq '') || ($uname eq '')) {
 5687:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5688:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5689:                 return 1;
 5690:             } else {
 5691:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5692:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5693:                     return 1;
 5694:                 }
 5695:             }
 5696:         }
 5697:     }
 5698:     return;
 5699: }
 5700: 
 5701: sub is_advanced_user {
 5702:     my ($udom,$uname) = @_;
 5703:     if ($udom ne '' && $uname ne '') {
 5704:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5705:             if (wantarray) {
 5706:                 return ($env{'user.adv'},$env{'user.author'});
 5707:             } else {
 5708:                 return $env{'user.adv'};
 5709:             }
 5710:         }
 5711:     }
 5712:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5713:     my %allroles;
 5714:     my ($is_adv,$is_author);
 5715:     foreach my $role (keys(%roleshash)) {
 5716:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5717:         my $area = '/'.$tdomain.'/'.$trest;
 5718:         if ($sec ne '') {
 5719:             $area .= '/'.$sec;
 5720:         }
 5721:         if (($area ne '') && ($trole ne '')) {
 5722:             my $spec=$trole.'.'.$area;
 5723:             if ($trole =~ /^cr\//) {
 5724:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5725:             } elsif ($trole ne 'gr') {
 5726:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5727:             }
 5728:             if ($trole eq 'au') {
 5729:                 $is_author = 1;
 5730:             }
 5731:         }
 5732:     }
 5733:     foreach my $role (keys(%allroles)) {
 5734:         last if ($is_adv);
 5735:         foreach my $item (split(/:/,$allroles{$role})) {
 5736:             if ($item ne '') {
 5737:                 my ($privilege,$restrictions)=split(/&/,$item);
 5738:                 if ($privilege eq 'adv') {
 5739:                     $is_adv = 1;
 5740:                     last;
 5741:                 }
 5742:             }
 5743:         }
 5744:     }
 5745:     if (wantarray) {
 5746:         return ($is_adv,$is_author);
 5747:     }
 5748:     return $is_adv;
 5749: }
 5750: 
 5751: sub check_can_request {
 5752:     my ($dom,$can_request,$request_domains) = @_;
 5753:     my $canreq = 0;
 5754:     my ($types,$typename) = &Apache::loncommon::course_types();
 5755:     my @options = ('approval','validate','autolimit');
 5756:     my $optregex = join('|',@options);
 5757:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5758:         foreach my $type (@{$types}) {
 5759:             if (&usertools_access($env{'user.name'},
 5760:                                   $env{'user.domain'},
 5761:                                   $type,undef,'requestcourses')) {
 5762:                 $canreq ++;
 5763:                 if (ref($request_domains) eq 'HASH') {
 5764:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5765:                 }
 5766:                 if ($dom eq $env{'user.domain'}) {
 5767:                     $can_request->{$type} = 1;
 5768:                 }
 5769:             }
 5770:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5771:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5772:                 if (@curr > 0) {
 5773:                     foreach my $item (@curr) {
 5774:                         if (ref($request_domains) eq 'HASH') {
 5775:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5776:                             if ($otherdom ne '') {
 5777:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5778:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5779:                                         push(@{$request_domains->{$type}},$otherdom);
 5780:                                     }
 5781:                                 } else {
 5782:                                     push(@{$request_domains->{$type}},$otherdom);
 5783:                                 }
 5784:                             }
 5785:                         }
 5786:                     }
 5787:                     unless($dom eq $env{'user.domain'}) {
 5788:                         $canreq ++;
 5789:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5790:                             $can_request->{$type} = 1;
 5791:                         }
 5792:                     }
 5793:                 }
 5794:             }
 5795:         }
 5796:     }
 5797:     return $canreq;
 5798: }
 5799: 
 5800: # ---------------------------------------------- Custom access rule evaluation
 5801: 
 5802: sub customaccess {
 5803:     my ($priv,$uri)=@_;
 5804:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5805:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5806:     $udom = &LONCAPA::clean_domain($udom);
 5807:     $ucrs = &LONCAPA::clean_username($ucrs);
 5808:     my $access=0;
 5809:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5810: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5811: 	if ($type eq 'user') {
 5812: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5813: 		my ($tdom,$tuname)=split(m{/},$scope);
 5814: 		if ($tdom) {
 5815: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5816: 		}
 5817: 		if ($tuname) {
 5818: 		    if ($tuname ne $env{'user.name'}) { next; }
 5819: 		}
 5820: 		$access=($effect eq 'allow');
 5821: 		last;
 5822: 	    }
 5823: 	} else {
 5824: 	    if ($role) {
 5825: 		if ($role ne $urole) { next; }
 5826: 	    }
 5827: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5828: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5829: 		if ($tdom) {
 5830: 		    if ($tdom ne $udom) { next; }
 5831: 		}
 5832: 		if ($tcrs) {
 5833: 		    if ($tcrs ne $ucrs) { next; }
 5834: 		}
 5835: 		if ($tsec) {
 5836: 		    if ($tsec ne $usec) { next; }
 5837: 		}
 5838: 		$access=($effect eq 'allow');
 5839: 		last;
 5840: 	    }
 5841: 	    if ($realm eq '' && $role eq '') {
 5842: 		$access=($effect eq 'allow');
 5843: 	    }
 5844: 	}
 5845:     }
 5846:     return $access;
 5847: }
 5848: 
 5849: # ------------------------------------------------- Check for a user privilege
 5850: 
 5851: sub allowed {
 5852:     my ($priv,$uri,$symb,$role)=@_;
 5853:     my $ver_orguri=$uri;
 5854:     $uri=&deversion($uri);
 5855:     my $orguri=$uri;
 5856:     $uri=&declutter($uri);
 5857: 
 5858:     if ($priv eq 'evb') {
 5859: # Evade communication block restrictions for specified role in a course
 5860:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5861:             return $1;
 5862:         } else {
 5863:             return;
 5864:         }
 5865:     }
 5866: 
 5867:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5868: # Free bre access to adm and meta resources
 5869:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5870: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5871: 	&& ($priv eq 'bre')) {
 5872: 	return 'F';
 5873:     }
 5874: 
 5875: # Free bre access to user's own portfolio contents
 5876:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5877:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5878: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5879:         my %setters;
 5880:         my ($startblock,$endblock) = 
 5881:             &Apache::loncommon::blockcheck(\%setters,'port');
 5882:         if ($startblock && $endblock) {
 5883:             return 'B';
 5884:         } else {
 5885:             return 'F';
 5886:         }
 5887:     }
 5888: 
 5889: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5890:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5891:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5892:         if (exists($env{'request.course.id'})) {
 5893:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5894:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5895:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5896:                 my $courseprivid=$env{'request.course.id'};
 5897:                 $courseprivid=~s/\_/\//;
 5898:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5899:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5900:                     return $1; 
 5901:                 } else {
 5902:                     if ($env{'request.course.sec'}) {
 5903:                         $courseprivid.='/'.$env{'request.course.sec'};
 5904:                     }
 5905:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5906:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5907:                         return $2;
 5908:                     }
 5909:                 }
 5910:             }
 5911:         }
 5912:     }
 5913: 
 5914: # Free bre to public access
 5915: 
 5916:     if ($priv eq 'bre') {
 5917:         my $copyright=&metadata($uri,'copyright');
 5918: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5919:            return 'F'; 
 5920:         }
 5921:         if ($copyright eq 'priv') {
 5922:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5923: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5924: 		return '';
 5925:             }
 5926:         }
 5927:         if ($copyright eq 'domain') {
 5928:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5929: 	    unless (($env{'user.domain'} eq $1) ||
 5930:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5931: 		return '';
 5932:             }
 5933:         }
 5934:         if ($env{'request.role'}=~ /li\.\//) {
 5935:             # Library role, so allow browsing of resources in this domain.
 5936:             return 'F';
 5937:         }
 5938:         if ($copyright eq 'custom') {
 5939: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5940:         }
 5941:     }
 5942:     # Domain coordinator is trying to create a course
 5943:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5944:         # uri is the requested domain in this case.
 5945:         # comparison to 'request.role.domain' shows if the user has selected
 5946:         # a role of dc for the domain in question.
 5947:         return 'F' if ($uri eq $env{'request.role.domain'});
 5948:     }
 5949: 
 5950:     my $thisallowed='';
 5951:     my $statecond=0;
 5952:     my $courseprivid='';
 5953: 
 5954:     my $ownaccess;
 5955:     # Community Coordinator or Assistant Co-author browsing resource space.
 5956:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5957:         if ($uri eq '') {
 5958:             $ownaccess = 1;
 5959:         } else {
 5960:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5961:                 my $udom = $env{'user.domain'};
 5962:                 my $uname = $env{'user.name'};
 5963:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5964:                     $ownaccess = 1;
 5965:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5966:                     unless ($uri =~ m{\.\./}) {
 5967:                         $ownaccess = 1;
 5968:                     }
 5969:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5970:                     my $now = time;
 5971:                     if ($uri =~ m{^([^/]+)/?$}) {
 5972:                         my $adom = $1;
 5973:                         foreach my $key (keys(%env)) {
 5974:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5975:                                 my ($start,$end) = split('.',$env{$key});
 5976:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5977:                                     $ownaccess = 1;
 5978:                                     last;
 5979:                                 }
 5980:                             }
 5981:                         }
 5982:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5983:                         my $adom = $1;
 5984:                         my $aname = $2;
 5985:                         foreach my $role ('ca','aa') { 
 5986:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5987:                                 my ($start,$end) =
 5988:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5989:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5990:                                     $ownaccess = 1;
 5991:                                     last;
 5992:                                 }
 5993:                             }
 5994:                         }
 5995:                     }
 5996:                 }
 5997:             }
 5998:         }
 5999:     }
 6000: 
 6001: # Course
 6002: 
 6003:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6004:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6005:             $thisallowed.=$1;
 6006:         }
 6007:     }
 6008: 
 6009: # Domain
 6010: 
 6011:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6012:        =~/\Q$priv\E\&([^\:]*)/) {
 6013:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6014:             $thisallowed.=$1;
 6015:         }
 6016:     }
 6017: 
 6018: # User who is not author or co-author might still be able to edit
 6019: # resource of an author in the domain (e.g., if Domain Coordinator).
 6020:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6021:         (&allowed('mdc',$env{'request.course.id'}))) {
 6022:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6023:             $thisallowed.=$1;
 6024:         }
 6025:     }
 6026: 
 6027: # Course: uri itself is a course
 6028:     my $courseuri=$uri;
 6029:     $courseuri=~s/\_(\d)/\/$1/;
 6030:     $courseuri=~s/^([^\/])/\/$1/;
 6031: 
 6032:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6033:        =~/\Q$priv\E\&([^\:]*)/) {
 6034:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6035:             $thisallowed.=$1;
 6036:         }
 6037:     }
 6038: 
 6039: # URI is an uploaded document for this course, default permissions don't matter
 6040: # not allowing 'edit' access (editupload) to uploaded course docs
 6041:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6042: 	$thisallowed='';
 6043:         my ($match)=&is_on_map($uri);
 6044:         if ($match) {
 6045:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6046:                   =~/\Q$priv\E\&([^\:]*)/) {
 6047:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6048:                 if (@blockers > 0) {
 6049:                     $thisallowed = 'B';
 6050:                 } else {
 6051:                     $thisallowed.=$1;
 6052:                 }
 6053:             }
 6054:         } else {
 6055:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6056:             if ($refuri) {
 6057:                 if ($refuri =~ m|^/adm/|) {
 6058:                     $thisallowed='F';
 6059:                 } else {
 6060:                     $refuri=&declutter($refuri);
 6061:                     my ($match) = &is_on_map($refuri);
 6062:                     if ($match) {
 6063:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6064:                         if (@blockers > 0) {
 6065:                             $thisallowed = 'B';
 6066:                         } else {
 6067:                             $thisallowed='F';
 6068:                         }
 6069:                     }
 6070:                 }
 6071:             }
 6072:         }
 6073:     }
 6074: 
 6075:     if ($priv eq 'bre'
 6076: 	&& $thisallowed ne 'F' 
 6077: 	&& $thisallowed ne '2'
 6078: 	&& &is_portfolio_url($uri)) {
 6079: 	$thisallowed = &portfolio_access($uri);
 6080:     }
 6081:     
 6082: # Full access at system, domain or course-wide level? Exit.
 6083:     if ($thisallowed=~/F/) {
 6084: 	return 'F';
 6085:     }
 6086: 
 6087: # If this is generating or modifying users, exit with special codes
 6088: 
 6089:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6090: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6091: 	    my ($audom,$auname)=split('/',$uri);
 6092: # no author name given, so this just checks on the general right to make a co-author in this domain
 6093: 	    unless ($auname) { return $thisallowed; }
 6094: # an author name is given, so we are about to actually make a co-author for a certain account
 6095: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6096: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6097: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6098: 	}
 6099: 	return $thisallowed;
 6100:     }
 6101: #
 6102: # Gathered so far: system, domain and course wide privileges
 6103: #
 6104: # Course: See if uri or referer is an individual resource that is part of 
 6105: # the course
 6106: 
 6107:     if ($env{'request.course.id'}) {
 6108: 
 6109:        $courseprivid=$env{'request.course.id'};
 6110:        if ($env{'request.course.sec'}) {
 6111:           $courseprivid.='/'.$env{'request.course.sec'};
 6112:        }
 6113:        $courseprivid=~s/\_/\//;
 6114:        my $checkreferer=1;
 6115:        my ($match,$cond)=&is_on_map($uri);
 6116:        if ($match) {
 6117:            $statecond=$cond;
 6118:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6119:                =~/\Q$priv\E\&([^\:]*)/) {
 6120:                my $value = $1;
 6121:                if ($priv eq 'bre') {
 6122:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6123:                    if (@blockers > 0) {
 6124:                        $thisallowed = 'B';
 6125:                    } else {
 6126:                        $thisallowed.=$value;
 6127:                    }
 6128:                } else {
 6129:                    $thisallowed.=$value;
 6130:                }
 6131:                $checkreferer=0;
 6132:            }
 6133:        }
 6134:        
 6135:        if ($checkreferer) {
 6136: 	  my $refuri=$env{'httpref.'.$orguri};
 6137:             unless ($refuri) {
 6138:                 foreach my $key (keys(%env)) {
 6139: 		    if ($key=~/^httpref\..*\*/) {
 6140: 			my $pattern=$key;
 6141:                         $pattern=~s/^httpref\.\/res\///;
 6142:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6143:                         $pattern=~s/\//\\\//g;
 6144:                         if ($orguri=~/$pattern/) {
 6145: 			    $refuri=$env{$key};
 6146:                         }
 6147:                     }
 6148:                 }
 6149:             }
 6150: 
 6151:          if ($refuri) { 
 6152: 	  $refuri=&declutter($refuri);
 6153:           my ($match,$cond)=&is_on_map($refuri);
 6154:             if ($match) {
 6155:               my $refstatecond=$cond;
 6156:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6157:                   =~/\Q$priv\E\&([^\:]*)/) {
 6158:                   my $value = $1;
 6159:                   if ($priv eq 'bre') {
 6160:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6161:                       if (@blockers > 0) {
 6162:                           $thisallowed = 'B';
 6163:                       } else {
 6164:                           $thisallowed.=$value;
 6165:                       }
 6166:                   } else {
 6167:                       $thisallowed.=$value;
 6168:                   }
 6169:                   $uri=$refuri;
 6170:                   $statecond=$refstatecond;
 6171:               }
 6172:           }
 6173:         }
 6174:        }
 6175:    }
 6176: 
 6177: #
 6178: # Gathered now: all privileges that could apply, and condition number
 6179: # 
 6180: #
 6181: # Full or no access?
 6182: #
 6183: 
 6184:     if ($thisallowed=~/F/) {
 6185: 	return 'F';
 6186:     }
 6187: 
 6188:     unless ($thisallowed) {
 6189:         return '';
 6190:     }
 6191: 
 6192: # Restrictions exist, deal with them
 6193: #
 6194: #   C:according to course preferences
 6195: #   R:according to resource settings
 6196: #   L:unless locked
 6197: #   X:according to user session state
 6198: #
 6199: 
 6200: # Possibly locked functionality, check all courses
 6201: # Locks might take effect only after 10 minutes cache expiration for other
 6202: # courses, and 2 minutes for current course
 6203: 
 6204:     my $envkey;
 6205:     if ($thisallowed=~/L/) {
 6206:         foreach $envkey (keys(%env)) {
 6207:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6208:                my $courseid=$2;
 6209:                my $roleid=$1.'.'.$2;
 6210:                $courseid=~s/^\///;
 6211:                my $expiretime=600;
 6212:                if ($env{'request.role'} eq $roleid) {
 6213: 		  $expiretime=120;
 6214:                }
 6215: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6216:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6217:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6218: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6219:                }
 6220:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6221:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6222: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6223:                        &log($env{'user.domain'},$env{'user.name'},
 6224:                             $env{'user.home'},
 6225:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6226:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6227:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6228: 		       return '';
 6229:                    }
 6230:                }
 6231:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6232:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6233: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6234:                        &log($env{'user.domain'},$env{'user.name'},
 6235:                             $env{'user.home'},
 6236:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6237:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6238:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6239: 		       return '';
 6240:                    }
 6241:                }
 6242: 	   }
 6243:        }
 6244:     }
 6245:    
 6246: #
 6247: # Rest of the restrictions depend on selected course
 6248: #
 6249: 
 6250:     unless ($env{'request.course.id'}) {
 6251: 	if ($thisallowed eq 'A') {
 6252: 	    return 'A';
 6253:         } elsif ($thisallowed eq 'B') {
 6254:             return 'B';
 6255: 	} else {
 6256: 	    return '1';
 6257: 	}
 6258:     }
 6259: 
 6260: #
 6261: # Now user is definitely in a course
 6262: #
 6263: 
 6264: 
 6265: # Course preferences
 6266: 
 6267:    if ($thisallowed=~/C/) {
 6268:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6269:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6270:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6271: 	   =~/\Q$rolecode\E/) {
 6272: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6273: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6274: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6275: 			$env{'request.course.id'});
 6276: 	   }
 6277:            return '';
 6278:        }
 6279: 
 6280:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6281: 	   =~/\Q$unamedom\E/) {
 6282: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6283: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6284: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6285: 			$env{'request.course.id'});
 6286: 	   }
 6287:            return '';
 6288:        }
 6289:    }
 6290: 
 6291: # Resource preferences
 6292: 
 6293:    if ($thisallowed=~/R/) {
 6294:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6295:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6296: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6297: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6298: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6299: 	   }
 6300: 	   return '';
 6301:        }
 6302:    }
 6303: 
 6304: # Restricted by state or randomout?
 6305: 
 6306:    if ($thisallowed=~/X/) {
 6307:       if ($env{'acc.randomout'}) {
 6308: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6309:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6310:             return ''; 
 6311:          }
 6312:       }
 6313:       if (&condval($statecond)) {
 6314: 	 return '2';
 6315:       } else {
 6316:          return '';
 6317:       }
 6318:    }
 6319: 
 6320:     if ($thisallowed eq 'A') {
 6321: 	return 'A';
 6322:     } elsif ($thisallowed eq 'B') {
 6323:         return 'B';
 6324:     }
 6325:    return 'F';
 6326: }
 6327: 
 6328: sub get_comm_blocks {
 6329:     my ($cdom,$cnum) = @_;
 6330:     if ($cdom eq '' || $cnum eq '') {
 6331:         return unless ($env{'request.course.id'});
 6332:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6333:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6334:     }
 6335:     my %commblocks;
 6336:     my $hashid=$cdom.'_'.$cnum;
 6337:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6338:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6339:         %commblocks = %{$blocksref};
 6340:     } else {
 6341:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6342:         my $cachetime = 600;
 6343:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6344:     }
 6345:     return %commblocks;
 6346: }
 6347: 
 6348: sub has_comm_blocking {
 6349:     my ($priv,$symb,$uri,$blocks) = @_;
 6350:     return unless ($env{'request.course.id'});
 6351:     return unless ($priv eq 'bre');
 6352:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6353:     my %commblocks;
 6354:     if (ref($blocks) eq 'HASH') {
 6355:         %commblocks = %{$blocks};
 6356:     } else {
 6357:         %commblocks = &get_comm_blocks();
 6358:     }
 6359:     return unless (keys(%commblocks) > 0);
 6360:     if (!$symb) { $symb=&symbread($uri,1); }
 6361:     my ($map,$resid,undef)=&decode_symb($symb);
 6362:     my %tocheck = (
 6363:                     maps      => $map,
 6364:                     resources => $symb,
 6365:                   );
 6366:     my @blockers;
 6367:     my $now = time;
 6368:     foreach my $block (keys(%commblocks)) {
 6369:         if ($block =~ /^(\d+)____(\d+)$/) {
 6370:             my ($start,$end) = ($1,$2);
 6371:             if ($start <= $now && $end >= $now) {
 6372:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6373:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6374:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6375:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6376:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6377:                                     push(@blockers,$block);
 6378:                                 }
 6379:                             }
 6380:                         }
 6381:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6382:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6383:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6384:                                     push(@blockers,$block);
 6385:                                 }
 6386:                             }
 6387:                         }
 6388:                     }
 6389:                 }
 6390:             }
 6391:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6392:             my $item = $1;
 6393:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6394:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6395:                     my $check_interval;
 6396:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6397:                         my @interval;
 6398:                         my $type = 'map';
 6399:                         if ($item eq 'course') {
 6400:                             $type = 'course';
 6401:                             @interval=&EXT("resource.0.interval");
 6402:                         } else {
 6403:                             if ($item =~ /___\d+___/) {
 6404:                                 $type = 'resource';
 6405:                                 @interval=&EXT("resource.0.interval",$item);
 6406:                             } else {
 6407:                                 my $mapsymb = &symbread($item,1);
 6408:                                 if ($mapsymb) {
 6409:                                     my $navmap = Apache::lonnavmaps::navmap->new();
 6410:                                     if (ref($navmap)) {
 6411:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6412:                                         my @resources = $mapres->retrieveResources($mapres,undef,0,1);
 6413:                                         foreach my $res (@resources) {
 6414:                                             my $symb = $res->symb();
 6415:                                             next if ($symb eq $mapsymb);
 6416:                                             if ($symb ne '') {
 6417:                                                 @interval=&EXT("resource.0.interval",$symb);
 6418:                                                 last;
 6419:                                             }
 6420:                                         }
 6421:                                     }
 6422:                                 }
 6423:                             }
 6424:                         }
 6425:                         if ($interval[0] =~ /\d+/) {
 6426:                             my $first_access;
 6427:                             if ($type eq 'resource') {
 6428:                                 $first_access=&get_first_access($interval[1],$item);
 6429:                             } elsif ($type eq 'map') {
 6430:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6431:                             } else {
 6432:                                 $first_access=&get_first_access($interval[1]);
 6433:                             }
 6434:                             if ($first_access) {
 6435:                                 my $timesup = $first_access+$interval[0];
 6436:                                 if ($timesup > $now) {
 6437:                                     unless (grep(/^\Q$block\E$/,@blockers)) {
 6438:                                         push(@blockers,$block);
 6439:                                     }
 6440:                                 }
 6441:                             }
 6442:                         }
 6443:                     }
 6444:                 }
 6445:             }
 6446:         }
 6447:     }
 6448:     return @blockers;
 6449: }
 6450: 
 6451: sub check_docs_block {
 6452:     my ($docsblock,$tocheck) =@_;
 6453:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6454:         return;
 6455:     }
 6456:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6457:         if ($tocheck->{'maps'}) {
 6458:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6459:                 return 1;
 6460:             }
 6461:         }
 6462:     }
 6463:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6464:         if ($tocheck->{'resources'}) {
 6465:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6466:                 return 1;
 6467:             }
 6468:         }
 6469:     }
 6470:     return;
 6471: }
 6472: 
 6473: #
 6474: #   Removes the versino from a URI and
 6475: #   splits it in to its filename and path to the filename.
 6476: #   Seems like File::Basename could have done this more clearly.
 6477: #   Parameters:
 6478: #      $uri   - input URI
 6479: #   Returns:
 6480: #     Two element list consisting of 
 6481: #     $pathname  - the URI up to and excluding the trailing /
 6482: #     $filename  - The part of the URI following the last /
 6483: #  NOTE:
 6484: #    Another realization of this is simply:
 6485: #    use File::Basename;
 6486: #    ...
 6487: #    $uri = shift;
 6488: #    $filename = basename($uri);
 6489: #    $path     = dirname($uri);
 6490: #    return ($filename, $path);
 6491: #
 6492: #     The implementation below is probably faster however.
 6493: #
 6494: sub split_uri_for_cond {
 6495:     my $uri=&deversion(&declutter(shift));
 6496:     my @uriparts=split(/\//,$uri);
 6497:     my $filename=pop(@uriparts);
 6498:     my $pathname=join('/',@uriparts);
 6499:     return ($pathname,$filename);
 6500: }
 6501: # --------------------------------------------------- Is a resource on the map?
 6502: 
 6503: sub is_on_map {
 6504:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6505:     #Trying to find the conditional for the file
 6506:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6507: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6508:     if ($match) {
 6509: 	return (1,$1);
 6510:     } else {
 6511: 	return (0,0);
 6512:     }
 6513: }
 6514: 
 6515: # --------------------------------------------------------- Get symb from alias
 6516: 
 6517: sub get_symb_from_alias {
 6518:     my $symb=shift;
 6519:     my ($map,$resid,$url)=&decode_symb($symb);
 6520: # Already is a symb
 6521:     if ($url) { return $symb; }
 6522: # Must be an alias
 6523:     my $aliassymb='';
 6524:     my %bighash;
 6525:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6526:                             &GDBM_READER(),0640)) {
 6527:         my $rid=$bighash{'mapalias_'.$symb};
 6528: 	if ($rid) {
 6529: 	    my ($mapid,$resid)=split(/\./,$rid);
 6530: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6531: 				    $resid,$bighash{'src_'.$rid});
 6532: 	}
 6533:         untie %bighash;
 6534:     }
 6535:     return $aliassymb;
 6536: }
 6537: 
 6538: # ----------------------------------------------------------------- Define Role
 6539: 
 6540: sub definerole {
 6541:   if (allowed('mcr','/')) {
 6542:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6543:     foreach my $role (split(':',$sysrole)) {
 6544: 	my ($crole,$cqual)=split(/\&/,$role);
 6545:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6546:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6547: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6548:                return "refused:s:$crole&$cqual"; 
 6549:             }
 6550:         }
 6551:     }
 6552:     foreach my $role (split(':',$domrole)) {
 6553: 	my ($crole,$cqual)=split(/\&/,$role);
 6554:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6555:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6556: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6557:                return "refused:d:$crole&$cqual"; 
 6558:             }
 6559:         }
 6560:     }
 6561:     foreach my $role (split(':',$courole)) {
 6562: 	my ($crole,$cqual)=split(/\&/,$role);
 6563:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6564:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6565: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6566:                return "refused:c:$crole&$cqual"; 
 6567:             }
 6568:         }
 6569:     }
 6570:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6571:                 "$env{'user.domain'}:$env{'user.name'}:".
 6572: 	        "rolesdef_$rolename=".
 6573:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6574:     return reply($command,$env{'user.home'});
 6575:   } else {
 6576:     return 'refused';
 6577:   }
 6578: }
 6579: 
 6580: # ---------------- Make a metadata query against the network of library servers
 6581: 
 6582: sub metadata_query {
 6583:     my ($query,$custom,$customshow,$server_array)=@_;
 6584:     my %rhash;
 6585:     my %libserv = &all_library();
 6586:     my @server_list = (defined($server_array) ? @$server_array
 6587:                                               : keys(%libserv) );
 6588:     for my $server (@server_list) {
 6589: 	unless ($custom or $customshow) {
 6590: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6591: 	    $rhash{$server}=$reply;
 6592: 	}
 6593: 	else {
 6594: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6595: 			     &escape($custom).':'.&escape($customshow),
 6596: 			     $server);
 6597: 	    $rhash{$server}=$reply;
 6598: 	}
 6599:     }
 6600:     return \%rhash;
 6601: }
 6602: 
 6603: # ----------------------------------------- Send log queries and wait for reply
 6604: 
 6605: sub log_query {
 6606:     my ($uname,$udom,$query,%filters)=@_;
 6607:     my $uhome=&homeserver($uname,$udom);
 6608:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6609:     my $uhost=&hostname($uhome);
 6610:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6611:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6612:                        $uhome);
 6613:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6614:     return get_query_reply($queryid);
 6615: }
 6616: 
 6617: # -------------------------- Update MySQL table for portfolio file
 6618: 
 6619: sub update_portfolio_table {
 6620:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6621:     if ($group ne '') {
 6622:         $file_name =~s /^\Q$group\E//;
 6623:     }
 6624:     my $homeserver = &homeserver($uname,$udom);
 6625:     my $queryid=
 6626:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6627:                ':'.&escape($file_name).':'.$action,$homeserver);
 6628:     my $reply = &get_query_reply($queryid);
 6629:     return $reply;
 6630: }
 6631: 
 6632: # -------------------------- Update MySQL allusers table
 6633: 
 6634: sub update_allusers_table {
 6635:     my ($uname,$udom,$names) = @_;
 6636:     my $homeserver = &homeserver($uname,$udom);
 6637:     my $queryid=
 6638:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6639:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6640:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6641:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6642:                'generation='.&escape($names->{'generation'}).'%%'.
 6643:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6644:                'id='.&escape($names->{'id'}),$homeserver);
 6645:     return;
 6646: }
 6647: 
 6648: # ------- Request retrieval of institutional classlists for course(s)
 6649: 
 6650: sub fetch_enrollment_query {
 6651:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6652:     my $homeserver;
 6653:     my $maxtries = 1;
 6654:     if ($context eq 'automated') {
 6655:         $homeserver = $perlvar{'lonHostID'};
 6656:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6657:     } else {
 6658:         $homeserver = &homeserver($cnum,$dom);
 6659:     }
 6660:     my $host=&hostname($homeserver);
 6661:     my $cmd = '';
 6662:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6663:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6664:     }
 6665:     $cmd =~ s/%%$//;
 6666:     $cmd = &escape($cmd);
 6667:     my $query = 'fetchenrollment';
 6668:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6669:     unless ($queryid=~/^\Q$host\E\_/) { 
 6670:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6671:         return 'error: '.$queryid;
 6672:     }
 6673:     my $reply = &get_query_reply($queryid);
 6674:     my $tries = 1;
 6675:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6676:         $reply = &get_query_reply($queryid);
 6677:         $tries ++;
 6678:     }
 6679:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6680:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6681:     } else {
 6682:         my @responses = split(/:/,$reply);
 6683:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6684:             foreach my $line (@responses) {
 6685:                 my ($key,$value) = split(/=/,$line,2);
 6686:                 $$replyref{$key} = $value;
 6687:             }
 6688:         } else {
 6689:             my $pathname = LONCAPA::tempdir();
 6690:             foreach my $line (@responses) {
 6691:                 my ($key,$value) = split(/=/,$line);
 6692:                 $$replyref{$key} = $value;
 6693:                 if ($value > 0) {
 6694:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6695:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6696:                         my $destname = $pathname.'/'.$filename;
 6697:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6698:                         if ($xml_classlist =~ /^error/) {
 6699:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6700:                         } else {
 6701:                             if ( open(FILE,">$destname") ) {
 6702:                                 print FILE &unescape($xml_classlist);
 6703:                                 close(FILE);
 6704:                             } else {
 6705:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6706:                             }
 6707:                         }
 6708:                     }
 6709:                 }
 6710:             }
 6711:         }
 6712:         return 'ok';
 6713:     }
 6714:     return 'error';
 6715: }
 6716: 
 6717: sub get_query_reply {
 6718:     my $queryid=shift;
 6719:     my $replyfile=LONCAPA::tempdir().$queryid;
 6720:     my $reply='';
 6721:     for (1..100) {
 6722: 	sleep 2;
 6723:         if (-e $replyfile.'.end') {
 6724: 	    if (open(my $fh,$replyfile)) {
 6725: 		$reply = join('',<$fh>);
 6726: 		close($fh);
 6727: 	   } else { return 'error: reply_file_error'; }
 6728:            return &unescape($reply);
 6729: 	}
 6730:     }
 6731:     return 'timeout:'.$queryid;
 6732: }
 6733: 
 6734: sub courselog_query {
 6735: #
 6736: # possible filters:
 6737: # url: url or symb
 6738: # username
 6739: # domain
 6740: # action: view, submit, grade
 6741: # start: timestamp
 6742: # end: timestamp
 6743: #
 6744:     my (%filters)=@_;
 6745:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6746:     if ($filters{'url'}) {
 6747: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6748:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6749:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6750:     }
 6751:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6752:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6753:     return &log_query($cname,$cdom,'courselog',%filters);
 6754: }
 6755: 
 6756: sub userlog_query {
 6757: #
 6758: # possible filters:
 6759: # action: log check role
 6760: # start: timestamp
 6761: # end: timestamp
 6762: #
 6763:     my ($uname,$udom,%filters)=@_;
 6764:     return &log_query($uname,$udom,'userlog',%filters);
 6765: }
 6766: 
 6767: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6768: 
 6769: sub auto_run {
 6770:     my ($cnum,$cdom) = @_;
 6771:     my $response = 0;
 6772:     my $settings;
 6773:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6774:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6775:         $settings = $domconfig{'autoenroll'};
 6776:         if ($settings->{'run'} eq '1') {
 6777:             $response = 1;
 6778:         }
 6779:     } else {
 6780:         my $homeserver;
 6781:         if (&is_course($cdom,$cnum)) {
 6782:             $homeserver = &homeserver($cnum,$cdom);
 6783:         } else {
 6784:             $homeserver = &domain($cdom,'primary');
 6785:         }
 6786:         if ($homeserver ne 'no_host') {
 6787:             $response = &reply('autorun:'.$cdom,$homeserver);
 6788:         }
 6789:     }
 6790:     return $response;
 6791: }
 6792: 
 6793: sub auto_get_sections {
 6794:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6795:     my $homeserver;
 6796:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6797:         $homeserver = &homeserver($cnum,$cdom);
 6798:     }
 6799:     if (!defined($homeserver)) { 
 6800:         if ($cdom =~ /^$match_domain$/) {
 6801:             $homeserver = &domain($cdom,'primary');
 6802:         }
 6803:     }
 6804:     my @secs;
 6805:     if (defined($homeserver)) {
 6806:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6807:         unless ($response eq 'refused') {
 6808:             @secs = split(/:/,$response);
 6809:         }
 6810:     }
 6811:     return @secs;
 6812: }
 6813: 
 6814: sub auto_new_course {
 6815:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6816:     my $homeserver = &homeserver($cnum,$cdom);
 6817:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6818:     return $response;
 6819: }
 6820: 
 6821: sub auto_validate_courseID {
 6822:     my ($cnum,$cdom,$inst_course_id) = @_;
 6823:     my $homeserver = &homeserver($cnum,$cdom);
 6824:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6825:     return $response;
 6826: }
 6827: 
 6828: sub auto_validate_instcode {
 6829:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6830:     my ($homeserver,$response);
 6831:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6832:         $homeserver = &homeserver($cnum,$cdom);
 6833:     }
 6834:     if (!defined($homeserver)) {
 6835:         if ($cdom =~ /^$match_domain$/) {
 6836:             $homeserver = &domain($cdom,'primary');
 6837:         }
 6838:     }
 6839:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6840:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6841:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6842:     return ($outcome,$description);
 6843: }
 6844: 
 6845: sub auto_create_password {
 6846:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6847:     my ($homeserver,$response);
 6848:     my $create_passwd = 0;
 6849:     my $authchk = '';
 6850:     if ($udom =~ /^$match_domain$/) {
 6851:         $homeserver = &domain($udom,'primary');
 6852:     }
 6853:     if ($homeserver eq '') {
 6854:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6855:             $homeserver = &homeserver($cnum,$cdom);
 6856:         }
 6857:     }
 6858:     if ($homeserver eq '') {
 6859:         $authchk = 'nodomain';
 6860:     } else {
 6861:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6862:         if ($response eq 'refused') {
 6863:             $authchk = 'refused';
 6864:         } else {
 6865:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6866:         }
 6867:     }
 6868:     return ($authparam,$create_passwd,$authchk);
 6869: }
 6870: 
 6871: sub auto_photo_permission {
 6872:     my ($cnum,$cdom,$students) = @_;
 6873:     my $homeserver = &homeserver($cnum,$cdom);
 6874:     my ($outcome,$perm_reqd,$conditions) = 
 6875: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6876:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6877: 	return (undef,undef);
 6878:     }
 6879:     return ($outcome,$perm_reqd,$conditions);
 6880: }
 6881: 
 6882: sub auto_checkphotos {
 6883:     my ($uname,$udom,$pid) = @_;
 6884:     my $homeserver = &homeserver($uname,$udom);
 6885:     my ($result,$resulttype);
 6886:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6887: 				   &escape($uname).':'.&escape($pid),
 6888: 				   $homeserver));
 6889:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6890: 	return (undef,undef);
 6891:     }
 6892:     if ($outcome) {
 6893:         ($result,$resulttype) = split(/:/,$outcome);
 6894:     } 
 6895:     return ($result,$resulttype);
 6896: }
 6897: 
 6898: sub auto_photochoice {
 6899:     my ($cnum,$cdom) = @_;
 6900:     my $homeserver = &homeserver($cnum,$cdom);
 6901:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6902: 						       &escape($cdom),
 6903: 						       $homeserver)));
 6904:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6905: 	return (undef,undef);
 6906:     }
 6907:     return ($update,$comment);
 6908: }
 6909: 
 6910: sub auto_photoupdate {
 6911:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6912:     my $homeserver = &homeserver($cnum,$dom);
 6913:     my $host=&hostname($homeserver);
 6914:     my $cmd = '';
 6915:     my $maxtries = 1;
 6916:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6917:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6918:     }
 6919:     $cmd =~ s/%%$//;
 6920:     $cmd = &escape($cmd);
 6921:     my $query = 'institutionalphotos';
 6922:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 6923:     unless ($queryid=~/^\Q$host\E\_/) {
 6924:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 6925:         return 'error: '.$queryid;
 6926:     }
 6927:     my $reply = &get_query_reply($queryid);
 6928:     my $tries = 1;
 6929:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6930:         $reply = &get_query_reply($queryid);
 6931:         $tries ++;
 6932:     }
 6933:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6934:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6935:     } else {
 6936:         my @responses = split(/:/,$reply);
 6937:         my $outcome = shift(@responses); 
 6938:         foreach my $item (@responses) {
 6939:             my ($key,$value) = split(/=/,$item);
 6940:             $$photo{$key} = $value;
 6941:         }
 6942:         return $outcome;
 6943:     }
 6944:     return 'error';
 6945: }
 6946: 
 6947: sub auto_instcode_format {
 6948:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 6949: 	$cat_order) = @_;
 6950:     my $courses = '';
 6951:     my @homeservers;
 6952:     if ($caller eq 'global') {
 6953: 	my %servers = &get_servers($codedom,'library');
 6954: 	foreach my $tryserver (keys(%servers)) {
 6955: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6956: 		push(@homeservers,$tryserver);
 6957: 	    }
 6958:         }
 6959:     } elsif ($caller eq 'requests') {
 6960:         if ($codedom =~ /^$match_domain$/) {
 6961:             my $chome = &domain($codedom,'primary');
 6962:             unless ($chome eq 'no_host') {
 6963:                 push(@homeservers,$chome);
 6964:             }
 6965:         }
 6966:     } else {
 6967:         push(@homeservers,&homeserver($caller,$codedom));
 6968:     }
 6969:     foreach my $code (keys(%{$instcodes})) {
 6970:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 6971:     }
 6972:     chop($courses);
 6973:     my $ok_response = 0;
 6974:     my $response;
 6975:     while (@homeservers > 0 && $ok_response == 0) {
 6976:         my $server = shift(@homeservers); 
 6977:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 6978:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 6979:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 6980: 		split(/:/,$response);
 6981:             %{$codes} = (%{$codes},&str2hash($codes_str));
 6982:             push(@{$codetitles},&str2array($codetitles_str));
 6983:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 6984:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 6985:             $ok_response = 1;
 6986:         }
 6987:     }
 6988:     if ($ok_response) {
 6989:         return 'ok';
 6990:     } else {
 6991:         return $response;
 6992:     }
 6993: }
 6994: 
 6995: sub auto_instcode_defaults {
 6996:     my ($domain,$returnhash,$code_order) = @_;
 6997:     my @homeservers;
 6998: 
 6999:     my %servers = &get_servers($domain,'library');
 7000:     foreach my $tryserver (keys(%servers)) {
 7001: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7002: 	    push(@homeservers,$tryserver);
 7003: 	}
 7004:     }
 7005: 
 7006:     my $response;
 7007:     foreach my $server (@homeservers) {
 7008:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7009:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7010: 	
 7011: 	foreach my $pair (split(/\&/,$response)) {
 7012: 	    my ($name,$value)=split(/\=/,$pair);
 7013: 	    if ($name eq 'code_order') {
 7014: 		@{$code_order} = split(/\&/,&unescape($value));
 7015: 	    } else {
 7016: 		$returnhash->{&unescape($name)}=&unescape($value);
 7017: 	    }
 7018: 	}
 7019: 	return 'ok';
 7020:     }
 7021: 
 7022:     return $response;
 7023: }
 7024: 
 7025: sub auto_possible_instcodes {
 7026:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7027:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7028:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7029:         return;
 7030:     }
 7031:     my (@homeservers,$uhome);
 7032:     if (defined(&domain($domain,'primary'))) {
 7033:         $uhome=&domain($domain,'primary');
 7034:         push(@homeservers,&domain($domain,'primary'));
 7035:     } else {
 7036:         my %servers = &get_servers($domain,'library');
 7037:         foreach my $tryserver (keys(%servers)) {
 7038:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7039:                 push(@homeservers,$tryserver);
 7040:             }
 7041:         }
 7042:     }
 7043:     my $response;
 7044:     foreach my $server (@homeservers) {
 7045:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7046:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7047:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7048:             split(':',$response);
 7049:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7050:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7051:         foreach my $item (split('&',$cat_title)) {   
 7052:             my ($name,$value)=split('=',$item);
 7053:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7054:         }
 7055:         foreach my $item (split('&',$cat_order)) {
 7056:             my ($name,$value)=split('=',$item);
 7057:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7058:         }
 7059:         return 'ok';
 7060:     }
 7061:     return $response;
 7062: }
 7063: 
 7064: sub auto_courserequest_checks {
 7065:     my ($dom) = @_;
 7066:     my ($homeserver,%validations);
 7067:     if ($dom =~ /^$match_domain$/) {
 7068:         $homeserver = &domain($dom,'primary');
 7069:     }
 7070:     unless ($homeserver eq 'no_host') {
 7071:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7072:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7073:             my @items = split(/&/,$response);
 7074:             foreach my $item (@items) {
 7075:                 my ($key,$value) = split('=',$item);
 7076:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7077:             }
 7078:         }
 7079:     }
 7080:     return %validations; 
 7081: }
 7082: 
 7083: sub auto_courserequest_validation {
 7084:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7085:     my ($homeserver,$response);
 7086:     if ($dom =~ /^$match_domain$/) {
 7087:         $homeserver = &domain($dom,'primary');
 7088:     }
 7089:     unless ($homeserver eq 'no_host') {  
 7090:           
 7091:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7092:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7093:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7094:                                     $homeserver));
 7095:     }
 7096:     return $response;
 7097: }
 7098: 
 7099: sub auto_validate_class_sec {
 7100:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7101:     my $homeserver = &homeserver($cnum,$cdom);
 7102:     my $ownerlist;
 7103:     if (ref($owners) eq 'ARRAY') {
 7104:         $ownerlist = join(',',@{$owners});
 7105:     } else {
 7106:         $ownerlist = $owners;
 7107:     }
 7108:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7109:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7110:     return $response;
 7111: }
 7112: 
 7113: # ------------------------------------------------------- Course Group routines
 7114: 
 7115: sub get_coursegroups {
 7116:     my ($cdom,$cnum,$group,$namespace) = @_;
 7117:     return(&dump($namespace,$cdom,$cnum,$group));
 7118: }
 7119: 
 7120: sub modify_coursegroup {
 7121:     my ($cdom,$cnum,$groupsettings) = @_;
 7122:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7123: }
 7124: 
 7125: sub toggle_coursegroup_status {
 7126:     my ($cdom,$cnum,$group,$action) = @_;
 7127:     my ($from_namespace,$to_namespace);
 7128:     if ($action eq 'delete') {
 7129:         $from_namespace = 'coursegroups';
 7130:         $to_namespace = 'deleted_groups';
 7131:     } else {
 7132:         $from_namespace = 'deleted_groups';
 7133:         $to_namespace = 'coursegroups';
 7134:     }
 7135:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7136:     if (my $tmp = &error(%curr_group)) {
 7137:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7138:         return ('read error',$tmp);
 7139:     } else {
 7140:         my %savedsettings = %curr_group; 
 7141:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7142:         my $deloutcome;
 7143:         if ($result eq 'ok') {
 7144:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7145:         } else {
 7146:             return ('write error',$result);
 7147:         }
 7148:         if ($deloutcome eq 'ok') {
 7149:             return 'ok';
 7150:         } else {
 7151:             return ('delete error',$deloutcome);
 7152:         }
 7153:     }
 7154: }
 7155: 
 7156: sub modify_group_roles {
 7157:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7158:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7159:     my $role = 'gr/'.&escape($userprivs);
 7160:     my ($uname,$udom) = split(/:/,$user);
 7161:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7162:     if ($result eq 'ok') {
 7163:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7164:     }
 7165:     return $result;
 7166: }
 7167: 
 7168: sub modify_coursegroup_membership {
 7169:     my ($cdom,$cnum,$membership) = @_;
 7170:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7171:     return $result;
 7172: }
 7173: 
 7174: sub get_active_groups {
 7175:     my ($udom,$uname,$cdom,$cnum) = @_;
 7176:     my $now = time;
 7177:     my %groups = ();
 7178:     foreach my $key (keys(%env)) {
 7179:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7180:             my ($start,$end) = split(/\./,$env{$key});
 7181:             if (($end!=0) && ($end<$now)) { next; }
 7182:             if (($start!=0) && ($start>$now)) { next; }
 7183:             if ($1 eq $cdom && $2 eq $cnum) {
 7184:                 $groups{$3} = $env{$key} ;
 7185:             }
 7186:         }
 7187:     }
 7188:     return %groups;
 7189: }
 7190: 
 7191: sub get_group_membership {
 7192:     my ($cdom,$cnum,$group) = @_;
 7193:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7194: }
 7195: 
 7196: sub get_users_groups {
 7197:     my ($udom,$uname,$courseid) = @_;
 7198:     my @usersgroups;
 7199:     my $cachetime=1800;
 7200: 
 7201:     my $hashid="$udom:$uname:$courseid";
 7202:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7203:     if (defined($cached)) {
 7204:         @usersgroups = split(/:/,$grouplist);
 7205:     } else {  
 7206:         $grouplist = '';
 7207:         my $courseurl = &courseid_to_courseurl($courseid);
 7208:         my $extra = &freeze_escape({'skipcheck' => 1});
 7209:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
 7210:         my $access_end = $env{'course.'.$courseid.
 7211:                               '.default_enrollment_end_date'};
 7212:         my $now = time;
 7213:         foreach my $key (keys(%roleshash)) {
 7214:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7215:                 my $group = $1;
 7216:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7217:                     my $start = $2;
 7218:                     my $end = $1;
 7219:                     if ($start == -1) { next; } # deleted from group
 7220:                     if (($start!=0) && ($start>$now)) { next; }
 7221:                     if (($end!=0) && ($end<$now)) {
 7222:                         if ($access_end && $access_end < $now) {
 7223:                             if ($access_end - $end < 86400) {
 7224:                                 push(@usersgroups,$group);
 7225:                             }
 7226:                         }
 7227:                         next;
 7228:                     }
 7229:                     push(@usersgroups,$group);
 7230:                 }
 7231:             }
 7232:         }
 7233:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7234:         $grouplist = join(':',@usersgroups);
 7235:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7236:     }
 7237:     return @usersgroups;
 7238: }
 7239: 
 7240: sub devalidate_getgroups_cache {
 7241:     my ($udom,$uname,$cdom,$cnum)=@_;
 7242:     my $courseid = $cdom.'_'.$cnum;
 7243: 
 7244:     my $hashid="$udom:$uname:$courseid";
 7245:     &devalidate_cache_new('getgroups',$hashid);
 7246: }
 7247: 
 7248: # ------------------------------------------------------------------ Plain Text
 7249: 
 7250: sub plaintext {
 7251:     my ($short,$type,$cid,$forcedefault) = @_;
 7252:     if ($short =~ m{^cr/}) {
 7253: 	return (split('/',$short))[-1];
 7254:     }
 7255:     if (!defined($cid)) {
 7256:         $cid = $env{'request.course.id'};
 7257:     }
 7258:     my %rolenames = (
 7259:                       Course    => 'std',
 7260:                       Community => 'alt1',
 7261:                     );
 7262:     if ($cid ne '') {
 7263:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7264:             unless ($forcedefault) {
 7265:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7266:                 &Apache::lonlocal::mt_escape(\$roletext);
 7267:                 return &Apache::lonlocal::mt($roletext);
 7268:             }
 7269:         }
 7270:     }
 7271:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7272:         (defined($rolenames{$type})) && 
 7273:         (defined($prp{$short}{$rolenames{$type}}))) {
 7274:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7275:     } elsif ($cid ne '') {
 7276:         my $crstype = $env{'course.'.$cid.'.type'};
 7277:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7278:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7279:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7280:         }
 7281:     }
 7282:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7283: }
 7284: 
 7285: # ----------------------------------------------------------------- Assign Role
 7286: 
 7287: sub assignrole {
 7288:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7289:         $context)=@_;
 7290:     my $mrole;
 7291:     if ($role =~ /^cr\//) {
 7292:         my $cwosec=$url;
 7293:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7294: 	unless (&allowed('ccr',$cwosec)) {
 7295:            my $refused = 1;
 7296:            if ($context eq 'requestcourses') {
 7297:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7298:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7299:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7300:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7301:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7302:                            if ($crsenv{'internal.courseowner'} eq
 7303:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7304:                                $refused = '';
 7305:                            }
 7306:                        }
 7307:                    }
 7308:                }
 7309:            }
 7310:            if ($refused) {
 7311:                &logthis('Refused custom assignrole: '.
 7312:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7313:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7314:                return 'refused';
 7315:            }
 7316:         }
 7317:         $mrole='cr';
 7318:     } elsif ($role =~ /^gr\//) {
 7319:         my $cwogrp=$url;
 7320:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7321:         unless (&allowed('mdg',$cwogrp)) {
 7322:             &logthis('Refused group assignrole: '.
 7323:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7324:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7325:             return 'refused';
 7326:         }
 7327:         $mrole='gr';
 7328:     } else {
 7329:         my $cwosec=$url;
 7330:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7331:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7332:             my $refused;
 7333:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7334:                 if (!(&allowed('c'.$role,$url))) {
 7335:                     $refused = 1;
 7336:                 }
 7337:             } else {
 7338:                 $refused = 1;
 7339:             }
 7340:             if ($refused) {
 7341:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7342:                 if (!$selfenroll && $context eq 'course') {
 7343:                     my %crsenv;
 7344:                     if ($role eq 'cc' || $role eq 'co') {
 7345:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7346:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7347:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7348:                                 if ($crsenv{'internal.courseowner'} eq 
 7349:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7350:                                     $refused = '';
 7351:                                 }
 7352:                             }
 7353:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7354:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7355:                                 if ($crsenv{'internal.courseowner'} eq 
 7356:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7357:                                     $refused = '';
 7358:                                 }
 7359:                             }
 7360:                         }
 7361:                     }
 7362:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7363:                     $refused = '';
 7364:                 } elsif ($context eq 'requestcourses') {
 7365:                     my @possroles = ('st','ta','ep','in','cc','co');
 7366:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7367:                         my $wrongcc;
 7368:                         if ($cnum =~ /^$match_community$/) {
 7369:                             $wrongcc = 1 if ($role eq 'cc');
 7370:                         } else {
 7371:                             $wrongcc = 1 if ($role eq 'co');
 7372:                         }
 7373:                         unless ($wrongcc) {
 7374:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7375:                             if ($crsenv{'internal.courseowner'} eq 
 7376:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7377:                                 $refused = '';
 7378:                             }
 7379:                         }
 7380:                     }
 7381:                 }
 7382:                 if ($refused) {
 7383:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7384:                              ' '.$role.' '.$end.' '.$start.' by '.
 7385: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7386:                     return 'refused';
 7387:                 }
 7388:             }
 7389:         } elsif ($role eq 'au') {
 7390:             if ($url ne '/'.$udom.'/') {
 7391:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7392:                          ' to assign author role for '.$uname.':'.$udom.
 7393:                          ' in domain: '.$url.' refused (wrong domain).');
 7394:                 return 'refused';
 7395:             }
 7396:         }
 7397:         $mrole=$role;
 7398:     }
 7399:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7400:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7401:     if ($end) { $command.='_'.$end; }
 7402:     if ($start) {
 7403: 	if ($end) { 
 7404:            $command.='_'.$start; 
 7405:         } else {
 7406:            $command.='_0_'.$start;
 7407:         }
 7408:     }
 7409:     my $origstart = $start;
 7410:     my $origend = $end;
 7411:     my $delflag;
 7412: # actually delete
 7413:     if ($deleteflag) {
 7414: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7415: # modify command to delete the role
 7416:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7417:                 "$udom:$uname:$url".'_'."$mrole";
 7418: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7419: # set start and finish to negative values for userrolelog
 7420:            $start=-1;
 7421:            $end=-1;
 7422:            $delflag = 1;
 7423:         }
 7424:     }
 7425: # send command
 7426:     my $answer=&reply($command,&homeserver($uname,$udom));
 7427: # log new user role if status is ok
 7428:     if ($answer eq 'ok') {
 7429: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7430: # for course roles, perform group memberships changes triggered by role change.
 7431:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7432:         unless ($role =~ /^gr/) {
 7433:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7434:                                              $origstart,$selfenroll,$context);
 7435:         }
 7436:         if ($role eq 'cc') {
 7437:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7438:         }
 7439:     }
 7440:     return $answer;
 7441: }
 7442: 
 7443: sub autoupdate_coowners {
 7444:     my ($url,$end,$start,$uname,$udom) = @_;
 7445:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7446:     if (($cdom ne '') && ($cnum ne '')) {
 7447:         my $now = time;
 7448:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7449:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7450:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7451:             my $instcode = $coursehash{'internal.coursecode'};
 7452:             if ($instcode ne '') {
 7453:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7454:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7455:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7456:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7457:                         if ($result eq 'valid') {
 7458:                             if ($coursehash{'internal.co-owners'}) {
 7459:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7460:                                     push(@newcoowners,$coowner);
 7461:                                 }
 7462:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7463:                                     push(@newcoowners,$uname.':'.$udom);
 7464:                                 }
 7465:                                 @newcoowners = sort(@newcoowners);
 7466:                             } else {
 7467:                                 push(@newcoowners,$uname.':'.$udom);
 7468:                             }
 7469:                         } else {
 7470:                             if ($coursehash{'internal.co-owners'}) {
 7471:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7472:                                     unless ($coowner eq $uname.':'.$udom) {
 7473:                                         push(@newcoowners,$coowner);
 7474:                                     }
 7475:                                 }
 7476:                                 unless (@newcoowners > 0) {
 7477:                                     $delcoowners = 1;
 7478:                                     $coowners = '';
 7479:                                 }
 7480:                             }
 7481:                         }
 7482:                         if (@newcoowners || $delcoowners) {
 7483:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7484:                                             $delcoowners,@newcoowners);
 7485:                         }
 7486:                     }
 7487:                 }
 7488:             }
 7489:         }
 7490:     }
 7491: }
 7492: 
 7493: sub store_coowners {
 7494:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7495:     my $cid = $cdom.'_'.$cnum;
 7496:     my ($coowners,$delresult,$putresult);
 7497:     if (@newcoowners) {
 7498:         $coowners = join(',',@newcoowners);
 7499:         my %coownershash = (
 7500:                             'internal.co-owners' => $coowners,
 7501:                            );
 7502:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7503:         if ($putresult eq 'ok') {
 7504:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7505:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7506:             }
 7507:         }
 7508:     }
 7509:     if ($delcoowners) {
 7510:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7511:         if ($delresult eq 'ok') {
 7512:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7513:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7514:             }
 7515:         }
 7516:     }
 7517:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7518:         my %crsinfo =
 7519:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7520:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7521:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7522:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7523:         }
 7524:     }
 7525: }
 7526: 
 7527: # -------------------------------------------------- Modify user authentication
 7528: # Overrides without validation
 7529: 
 7530: sub modifyuserauth {
 7531:     my ($udom,$uname,$umode,$upass)=@_;
 7532:     my $uhome=&homeserver($uname,$udom);
 7533:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7534:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7535:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7536:              ' in domain '.$env{'request.role.domain'});  
 7537:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7538: 		     &escape($upass),$uhome);
 7539:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7540:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7541:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7542:     &log($udom,,$uname,$uhome,
 7543:         'Authentication changed by '.$env{'user.domain'}.', '.
 7544:                                      $env{'user.name'}.', '.$umode.
 7545:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7546:     unless ($reply eq 'ok') {
 7547:         &logthis('Authentication mode error: '.$reply);
 7548: 	return 'error: '.$reply;
 7549:     }   
 7550:     return 'ok';
 7551: }
 7552: 
 7553: # --------------------------------------------------------------- Modify a user
 7554: 
 7555: sub modifyuser {
 7556:     my ($udom,    $uname, $uid,
 7557:         $umode,   $upass, $first,
 7558:         $middle,  $last,  $gene,
 7559:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7560:     $udom= &LONCAPA::clean_domain($udom);
 7561:     $uname=&LONCAPA::clean_username($uname);
 7562:     my $showcandelete = 'none';
 7563:     if (ref($candelete) eq 'ARRAY') {
 7564:         if (@{$candelete} > 0) {
 7565:             $showcandelete = join(', ',@{$candelete});
 7566:         }
 7567:     }
 7568:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7569:              $umode.', '.$first.', '.$middle.', '.
 7570: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7571:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7572:                                      ' desiredhome not specified'). 
 7573:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7574:              ' in domain '.$env{'request.role.domain'});
 7575:     my $uhome=&homeserver($uname,$udom,'true');
 7576:     my $newuser;
 7577:     if ($uhome eq 'no_host') {
 7578:         $newuser = 1;
 7579:     }
 7580: # ----------------------------------------------------------------- Create User
 7581:     if (($uhome eq 'no_host') && 
 7582: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7583:         my $unhome='';
 7584:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7585:             $unhome = $desiredhome;
 7586: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7587: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7588:         } else { # load balancing routine for determining $unhome
 7589:             my $loadm=10000000;
 7590: 	    my %servers = &get_servers($udom,'library');
 7591: 	    foreach my $tryserver (keys(%servers)) {
 7592: 		my $answer=reply('load',$tryserver);
 7593: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7594: 		    $loadm=$answer;
 7595: 		    $unhome=$tryserver;
 7596: 		}
 7597: 	    }
 7598:         }
 7599:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7600: 	    return 'error: unable to find a home server for '.$uname.
 7601:                    ' in domain '.$udom;
 7602:         }
 7603:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7604:                          &escape($upass),$unhome);
 7605: 	unless ($reply eq 'ok') {
 7606:             return 'error: '.$reply;
 7607:         }   
 7608:         $uhome=&homeserver($uname,$udom,'true');
 7609:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7610: 	    return 'error: unable verify users home machine.';
 7611:         }
 7612:     }   # End of creation of new user
 7613: # ---------------------------------------------------------------------- Add ID
 7614:     if ($uid) {
 7615:        $uid=~tr/A-Z/a-z/;
 7616:        my %uidhash=&idrget($udom,$uname);
 7617:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7618:          && (!$forceid)) {
 7619: 	  unless ($uid eq $uidhash{$uname}) {
 7620: 	      return 'error: user id "'.$uid.'" does not match '.
 7621:                   'current user id "'.$uidhash{$uname}.'".';
 7622:           }
 7623:        } else {
 7624: 	  &idput($udom,($uname => $uid));
 7625:        }
 7626:     }
 7627: # -------------------------------------------------------------- Add names, etc
 7628:     my @tmp=&get('environment',
 7629: 		   ['firstname','middlename','lastname','generation','id',
 7630:                     'permanentemail','inststatus'],
 7631: 		   $udom,$uname);
 7632:     my (%names,%oldnames);
 7633:     if ($tmp[0] =~ m/^error:.*/) { 
 7634:         %names=(); 
 7635:     } else {
 7636:         %names = @tmp;
 7637:         %oldnames = %names;
 7638:     }
 7639: #
 7640: # If name, email and/or uid are blank (e.g., because an uploaded file
 7641: # of users did not contain them), do not overwrite existing values
 7642: # unless field is in $candelete array ref.  
 7643: #
 7644: 
 7645:     my @fields = ('firstname','middlename','lastname','generation',
 7646:                   'permanentemail','id');
 7647:     my %newvalues;
 7648:     if (ref($candelete) eq 'ARRAY') {
 7649:         foreach my $field (@fields) {
 7650:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7651:                 if ($field eq 'firstname') {
 7652:                     $names{$field} = $first;
 7653:                 } elsif ($field eq 'middlename') {
 7654:                     $names{$field} = $middle;
 7655:                 } elsif ($field eq 'lastname') {
 7656:                     $names{$field} = $last;
 7657:                 } elsif ($field eq 'generation') { 
 7658:                     $names{$field} = $gene;
 7659:                 } elsif ($field eq 'permanentemail') {
 7660:                     $names{$field} = $email;
 7661:                 } elsif ($field eq 'id') {
 7662:                     $names{$field}  = $uid;
 7663:                 }
 7664:             }
 7665:         }
 7666:     }
 7667:     if ($first)  { $names{'firstname'}  = $first; }
 7668:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7669:     if ($last)   { $names{'lastname'}   = $last; }
 7670:     if (defined($gene))   { $names{'generation'} = $gene; }
 7671:     if ($email) {
 7672:        $email=~s/[^\w\@\.\-\,]//gs;
 7673:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7674:     }
 7675:     if ($uid) { $names{'id'}  = $uid; }
 7676:     if (defined($inststatus)) {
 7677:         $names{'inststatus'} = '';
 7678:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7679:         if (ref($usertypes) eq 'HASH') {
 7680:             my @okstatuses; 
 7681:             foreach my $item (split(/:/,$inststatus)) {
 7682:                 if (defined($usertypes->{$item})) {
 7683:                     push(@okstatuses,$item);  
 7684:                 }
 7685:             }
 7686:             if (@okstatuses) {
 7687:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7688:             }
 7689:         }
 7690:     }
 7691:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7692:                  $umode.', '.$first.', '.$middle.', '.
 7693:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7694:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7695:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7696:     } else {
 7697:         $logmsg .= ' during self creation';
 7698:     }
 7699:     my $changed;
 7700:     if ($newuser) {
 7701:         $changed = 1;
 7702:     } else {
 7703:         foreach my $field (@fields) {
 7704:             if ($names{$field} ne $oldnames{$field}) {
 7705:                 $changed = 1;
 7706:                 last;
 7707:             }
 7708:         }
 7709:     }
 7710:     unless ($changed) {
 7711:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7712:         &logthis($logmsg);
 7713:         return 'ok';
 7714:     }
 7715:     my $reply = &put('environment', \%names, $udom,$uname);
 7716:     if ($reply ne 'ok') { 
 7717:         return 'error: '.$reply;
 7718:     }
 7719:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7720:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7721:     }
 7722:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7723:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7724:     $logmsg = 'Success modifying user '.$logmsg;
 7725:     &logthis($logmsg);
 7726:     return 'ok';
 7727: }
 7728: 
 7729: # -------------------------------------------------------------- Modify student
 7730: 
 7731: sub modifystudent {
 7732:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7733:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7734:         $selfenroll,$context,$inststatus)=@_;
 7735:     if (!$cid) {
 7736: 	unless ($cid=$env{'request.course.id'}) {
 7737: 	    return 'not_in_class';
 7738: 	}
 7739:     }
 7740: # --------------------------------------------------------------- Make the user
 7741:     my $reply=&modifyuser
 7742: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7743:          $desiredhome,$email,$inststatus);
 7744:     unless ($reply eq 'ok') { return $reply; }
 7745:     # This will cause &modify_student_enrollment to get the uid from the
 7746:     # students environment
 7747:     $uid = undef if (!$forceid);
 7748:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7749: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7750:     return $reply;
 7751: }
 7752: 
 7753: sub modify_student_enrollment {
 7754:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7755:     my ($cdom,$cnum,$chome);
 7756:     if (!$cid) {
 7757: 	unless ($cid=$env{'request.course.id'}) {
 7758: 	    return 'not_in_class';
 7759: 	}
 7760: 	$cdom=$env{'course.'.$cid.'.domain'};
 7761: 	$cnum=$env{'course.'.$cid.'.num'};
 7762:     } else {
 7763: 	($cdom,$cnum)=split(/_/,$cid);
 7764:     }
 7765:     $chome=$env{'course.'.$cid.'.home'};
 7766:     if (!$chome) {
 7767: 	$chome=&homeserver($cnum,$cdom);
 7768:     }
 7769:     if (!$chome) { return 'unknown_course'; }
 7770:     # Make sure the user exists
 7771:     my $uhome=&homeserver($uname,$udom);
 7772:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7773: 	return 'error: no such user';
 7774:     }
 7775:     # Get student data if we were not given enough information
 7776:     if (!defined($first)  || $first  eq '' || 
 7777:         !defined($last)   || $last   eq '' || 
 7778:         !defined($uid)    || $uid    eq '' || 
 7779:         !defined($middle) || $middle eq '' || 
 7780:         !defined($gene)   || $gene   eq '') {
 7781:         # They did not supply us with enough data to enroll the student, so
 7782:         # we need to pick up more information.
 7783:         my %tmp = &get('environment',
 7784:                        ['firstname','middlename','lastname', 'generation','id']
 7785:                        ,$udom,$uname);
 7786: 
 7787:         #foreach my $key (keys(%tmp)) {
 7788:         #    &logthis("key $key = ".$tmp{$key});
 7789:         #}
 7790:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7791:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7792:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7793:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7794:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7795:     }
 7796:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7797:     my $user = "$uname:$udom";
 7798:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7799:     my $reply=cput('classlist',
 7800: 		   {$user => 
 7801: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7802: 		   $cdom,$cnum);
 7803:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7804:         &devalidate_getsection_cache($udom,$uname,$cid);
 7805:     } else { 
 7806: 	return 'error: '.$reply;
 7807:     }
 7808:     # Add student role to user
 7809:     my $uurl='/'.$cid;
 7810:     $uurl=~s/\_/\//g;
 7811:     if ($usec) {
 7812: 	$uurl.='/'.$usec;
 7813:     }
 7814:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7815:                              $selfenroll,$context);
 7816:     if ($result ne 'ok') {
 7817:         if ($old_entry{$user} ne '') {
 7818:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7819:         } else {
 7820:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7821:         }
 7822:     }
 7823:     return $result; 
 7824: }
 7825: 
 7826: sub format_name {
 7827:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7828:     my $name;
 7829:     if ($first ne 'lastname') {
 7830: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7831:     } else {
 7832: 	if ($lastname=~/\S/) {
 7833: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7834: 	    $name=~s/\s+,/,/;
 7835: 	} else {
 7836: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7837: 	}
 7838:     }
 7839:     $name=~s/^\s+//;
 7840:     $name=~s/\s+$//;
 7841:     $name=~s/\s+/ /g;
 7842:     return $name;
 7843: }
 7844: 
 7845: # ------------------------------------------------- Write to course preferences
 7846: 
 7847: sub writecoursepref {
 7848:     my ($courseid,%prefs)=@_;
 7849:     $courseid=~s/^\///;
 7850:     $courseid=~s/\_/\//g;
 7851:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7852:     my $chome=homeserver($cnum,$cdomain);
 7853:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7854: 	return 'error: no such course';
 7855:     }
 7856:     my $cstring='';
 7857:     foreach my $pref (keys(%prefs)) {
 7858: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7859:     }
 7860:     $cstring=~s/\&$//;
 7861:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7862: }
 7863: 
 7864: # ---------------------------------------------------------- Make/modify course
 7865: 
 7866: sub createcourse {
 7867:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7868:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7869:     $url=&declutter($url);
 7870:     my $cid='';
 7871:     if ($context eq 'requestcourses') {
 7872:         my $can_create = 0;
 7873:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7874:         if ($udom eq $ownerdom) {
 7875:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7876:                                   $context)) {
 7877:                 $can_create = 1;
 7878:             }
 7879:         } else {
 7880:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7881:                                            $category);
 7882:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7883:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7884:                 if (@curr > 0) {
 7885:                     my @options = qw(approval validate autolimit);
 7886:                     my $optregex = join('|',@options);
 7887:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7888:                         $can_create = 1;
 7889:                     }
 7890:                 }
 7891:             }
 7892:         }
 7893:         if ($can_create) {
 7894:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7895:                 unless (&allowed('ccc',$udom)) {
 7896:                     return 'refused'; 
 7897:                 }
 7898:             }
 7899:         } else {
 7900:             return 'refused';
 7901:         }
 7902:     } elsif (!&allowed('ccc',$udom)) {
 7903:         return 'refused';
 7904:     }
 7905: # --------------------------------------------------------------- Get Unique ID
 7906:     my $uname;
 7907:     if ($cnum =~ /^$match_courseid$/) {
 7908:         my $chome=&homeserver($cnum,$udom,'true');
 7909:         if (($chome eq '') || ($chome eq 'no_host')) {
 7910:             $uname = $cnum;
 7911:         } else {
 7912:             $uname = &generate_coursenum($udom,$crstype);
 7913:         }
 7914:     } else {
 7915:         $uname = &generate_coursenum($udom,$crstype);
 7916:     }
 7917:     return $uname if ($uname =~ /^error/);
 7918: # -------------------------------------------------- Check supplied server name
 7919:     if (!defined($course_server)) {
 7920:         if (defined(&domain($udom,'primary'))) {
 7921:             $course_server = &domain($udom,'primary');
 7922:         } else {
 7923:             $course_server = $env{'user.home'}; 
 7924:         }
 7925:     }
 7926:     my %host_servers =
 7927:         &Apache::lonnet::get_servers($udom,'library');
 7928:     unless ($host_servers{$course_server}) {
 7929:         return 'error: invalid home server for course: '.$course_server;
 7930:     }
 7931: # ------------------------------------------------------------- Make the course
 7932:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 7933:                       $course_server);
 7934:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 7935:     my $uhome=&homeserver($uname,$udom,'true');
 7936:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7937: 	return 'error: no such course';
 7938:     }
 7939: # ----------------------------------------------------------------- Course made
 7940: # log existence
 7941:     my $now = time;
 7942:     my $newcourse = {
 7943:                     $udom.'_'.$uname => {
 7944:                                      description => $description,
 7945:                                      inst_code   => $inst_code,
 7946:                                      owner       => $course_owner,
 7947:                                      type        => $crstype,
 7948:                                      creator     => $env{'user.name'}.':'.
 7949:                                                     $env{'user.domain'},
 7950:                                      created     => $now,
 7951:                                      context     => $context,
 7952:                                                 },
 7953:                     };
 7954:     &courseidput($udom,$newcourse,$uhome,'notime');
 7955: # set toplevel url
 7956:     my $topurl=$url;
 7957:     unless ($nonstandard) {
 7958: # ------------------------------------------ For standard courses, make top url
 7959:         my $mapurl=&clutter($url);
 7960:         if ($mapurl eq '/res/') { $mapurl=''; }
 7961:         $env{'form.initmap'}=(<<ENDINITMAP);
 7962: <map>
 7963: <resource id="1" type="start"></resource>
 7964: <resource id="2" src="$mapurl"></resource>
 7965: <resource id="3" type="finish"></resource>
 7966: <link index="1" from="1" to="2"></link>
 7967: <link index="2" from="2" to="3"></link>
 7968: </map>
 7969: ENDINITMAP
 7970:         $topurl=&declutter(
 7971:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 7972:                           );
 7973:     }
 7974: # ----------------------------------------------------------- Write preferences
 7975:     &writecoursepref($udom.'_'.$uname,
 7976:                      ('description'              => $description,
 7977:                       'url'                      => $topurl,
 7978:                       'internal.creator'         => $env{'user.name'}.':'.
 7979:                                                     $env{'user.domain'},
 7980:                       'internal.created'         => $now,
 7981:                       'internal.creationcontext' => $context)
 7982:                     );
 7983:     return '/'.$udom.'/'.$uname;
 7984: }
 7985: 
 7986: # ------------------------------------------------------------------- Create ID
 7987: sub generate_coursenum {
 7988:     my ($udom,$crstype) = @_;
 7989:     my $domdesc = &domain($udom);
 7990:     return 'error: invalid domain' if ($domdesc eq '');
 7991:     my $first;
 7992:     if ($crstype eq 'Community') {
 7993:         $first = '0';
 7994:     } else {
 7995:         $first = int(1+rand(9)); 
 7996:     } 
 7997:     my $uname=$first.
 7998:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7999:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8000:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8001: # ----------------------------------------------- Make sure that does not exist
 8002:     my $uhome=&homeserver($uname,$udom,'true');
 8003:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8004:         if ($crstype eq 'Community') {
 8005:             $first = '0';
 8006:         } else {
 8007:             $first = int(1+rand(9));
 8008:         }
 8009:         $uname=$first.
 8010:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8011:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8012:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8013:         $uhome=&homeserver($uname,$udom,'true');
 8014:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8015:             return 'error: unable to generate unique course-ID';
 8016:         }
 8017:     }
 8018:     return $uname;
 8019: }
 8020: 
 8021: sub is_course {
 8022:     my ($cdom,$cnum) = @_;
 8023:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 8024: 				undef,'.');
 8025:     if (exists($courses{$cdom.'_'.$cnum})) {
 8026:         return 1;
 8027:     }
 8028:     return 0;
 8029: }
 8030: 
 8031: sub store_userdata {
 8032:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8033:     my $result;
 8034:     if ($datakey ne '') {
 8035:         if (ref($storehash) eq 'HASH') {
 8036:             if ($udom eq '' || $uname eq '') {
 8037:                 $udom = $env{'user.domain'};
 8038:                 $uname = $env{'user.name'};
 8039:             }
 8040:             my $uhome=&homeserver($uname,$udom);
 8041:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8042:                 $result = 'error: no_host';
 8043:             } else {
 8044:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8045:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8046: 
 8047:                 my $namevalue='';
 8048:                 foreach my $key (keys(%{$storehash})) {
 8049:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8050:                 }
 8051:                 $namevalue=~s/\&$//;
 8052:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8053:                                   $namevalue,$uhome);
 8054:             }
 8055:         } else {
 8056:             $result = 'error: data to store was not a hash reference'; 
 8057:         }
 8058:     } else {
 8059:         $result= 'error: invalid requestkey'; 
 8060:     }
 8061:     return $result;
 8062: }
 8063: 
 8064: # ---------------------------------------------------------- Assign Custom Role
 8065: 
 8066: sub assigncustomrole {
 8067:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8068:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8069:                        $end,$start,$deleteflag,$selfenroll,$context);
 8070: }
 8071: 
 8072: # ----------------------------------------------------------------- Revoke Role
 8073: 
 8074: sub revokerole {
 8075:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8076:     my $now=time;
 8077:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8078: }
 8079: 
 8080: # ---------------------------------------------------------- Revoke Custom Role
 8081: 
 8082: sub revokecustomrole {
 8083:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8084:     my $now=time;
 8085:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8086:            $deleteflag,$selfenroll,$context);
 8087: }
 8088: 
 8089: # ------------------------------------------------------------ Disk usage
 8090: sub diskusage {
 8091:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8092:     $directorypath =~ s/\/$//;
 8093:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8094:                        .&escape($getpropath).':'.&escape($uname).':'
 8095:                        .&escape($udom),homeserver($uname,$udom));
 8096:     if ($listing eq 'unknown_cmd') {
 8097:         if ($getpropath) {
 8098:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8099:         }
 8100:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8101:     }
 8102:     return $listing;
 8103: }
 8104: 
 8105: sub is_locked {
 8106:     my ($file_name, $domain, $user, $which) = @_;
 8107:     my @check;
 8108:     my $is_locked;
 8109:     push (@check,$file_name);
 8110:     my %locked = &get('file_permissions',\@check,
 8111: 		      $env{'user.domain'},$env{'user.name'});
 8112:     my ($tmp)=keys(%locked);
 8113:     if ($tmp=~/^error:/) { undef(%locked); }
 8114:     
 8115:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8116:         $is_locked = 'false';
 8117:         foreach my $entry (@{$locked{$file_name}}) {
 8118:            if (ref($entry) eq 'ARRAY') {
 8119:                $is_locked = 'true';
 8120:                if (ref($which) eq 'ARRAY') {
 8121:                    push(@{$which},$entry);
 8122:                } else {
 8123:                    last;
 8124:                }
 8125:            }
 8126:        }
 8127:     } else {
 8128:         $is_locked = 'false';
 8129:     }
 8130:     return $is_locked;
 8131: }
 8132: 
 8133: sub declutter_portfile {
 8134:     my ($file) = @_;
 8135:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8136:     return $file;
 8137: }
 8138: 
 8139: # ------------------------------------------------------------- Mark as Read Only
 8140: 
 8141: sub mark_as_readonly {
 8142:     my ($domain,$user,$files,$what) = @_;
 8143:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8144:     my ($tmp)=keys(%current_permissions);
 8145:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8146:     foreach my $file (@{$files}) {
 8147: 	$file = &declutter_portfile($file);
 8148:         push(@{$current_permissions{$file}},$what);
 8149:     }
 8150:     &put('file_permissions',\%current_permissions,$domain,$user);
 8151:     return;
 8152: }
 8153: 
 8154: # ------------------------------------------------------------Save Selected Files
 8155: 
 8156: sub save_selected_files {
 8157:     my ($user, $path, @files) = @_;
 8158:     my $filename = $user."savedfiles";
 8159:     my @other_files = &files_not_in_path($user, $path);
 8160:     open (OUT, '>'.$tmpdir.$filename);
 8161:     foreach my $file (@files) {
 8162:         print (OUT $env{'form.currentpath'}.$file."\n");
 8163:     }
 8164:     foreach my $file (@other_files) {
 8165:         print (OUT $file."\n");
 8166:     }
 8167:     close (OUT);
 8168:     return 'ok';
 8169: }
 8170: 
 8171: sub clear_selected_files {
 8172:     my ($user) = @_;
 8173:     my $filename = $user."savedfiles";
 8174:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8175:     print (OUT undef);
 8176:     close (OUT);
 8177:     return ("ok");    
 8178: }
 8179: 
 8180: sub files_in_path {
 8181:     my ($user, $path) = @_;
 8182:     my $filename = $user."savedfiles";
 8183:     my %return_files;
 8184:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8185:     while (my $line_in = <IN>) {
 8186:         chomp ($line_in);
 8187:         my @paths_and_file = split (m!/!, $line_in);
 8188:         my $file_part = pop (@paths_and_file);
 8189:         my $path_part = join ('/', @paths_and_file);
 8190:         $path_part.='/';
 8191:         my $path_and_file = $path_part.$file_part;
 8192:         if ($path_part eq $path) {
 8193:             $return_files{$file_part}= 'selected';
 8194:         }
 8195:     }
 8196:     close (IN);
 8197:     return (\%return_files);
 8198: }
 8199: 
 8200: # called in portfolio select mode, to show files selected NOT in current directory
 8201: sub files_not_in_path {
 8202:     my ($user, $path) = @_;
 8203:     my $filename = $user."savedfiles";
 8204:     my @return_files;
 8205:     my $path_part;
 8206:     open(IN, '<'.LONCAPA::.$filename);
 8207:     while (my $line = <IN>) {
 8208:         #ok, I know it's clunky, but I want it to work
 8209:         my @paths_and_file = split(m|/|, $line);
 8210:         my $file_part = pop(@paths_and_file);
 8211:         chomp($file_part);
 8212:         my $path_part = join('/', @paths_and_file);
 8213:         $path_part .= '/';
 8214:         my $path_and_file = $path_part.$file_part;
 8215:         if ($path_part ne $path) {
 8216:             push(@return_files, ($path_and_file));
 8217:         }
 8218:     }
 8219:     close(OUT);
 8220:     return (@return_files);
 8221: }
 8222: 
 8223: #----------------------------------------------Get portfolio file permissions
 8224: 
 8225: sub get_portfile_permissions {
 8226:     my ($domain,$user) = @_;
 8227:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8228:     my ($tmp)=keys(%current_permissions);
 8229:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8230:     return \%current_permissions;
 8231: }
 8232: 
 8233: #---------------------------------------------Get portfolio file access controls
 8234: 
 8235: sub get_access_controls {
 8236:     my ($current_permissions,$group,$file) = @_;
 8237:     my %access;
 8238:     my $real_file = $file;
 8239:     $file =~ s/\.meta$//;
 8240:     if (defined($file)) {
 8241:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8242:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8243:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8244:             }
 8245:         }
 8246:     } else {
 8247:         foreach my $key (keys(%{$current_permissions})) {
 8248:             if ($key =~ /\0accesscontrol$/) {
 8249:                 if (defined($group)) {
 8250:                     if ($key !~ m-^\Q$group\E/-) {
 8251:                         next;
 8252:                     }
 8253:                 }
 8254:                 my ($fullpath) = split(/\0/,$key);
 8255:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8256:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8257:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8258:                     }
 8259:                 }
 8260:             }
 8261:         }
 8262:     }
 8263:     return %access;
 8264: }
 8265: 
 8266: sub modify_access_controls {
 8267:     my ($file_name,$changes,$domain,$user)=@_;
 8268:     my ($outcome,$deloutcome);
 8269:     my %store_permissions;
 8270:     my %new_values;
 8271:     my %new_control;
 8272:     my %translation;
 8273:     my @deletions = ();
 8274:     my $now = time;
 8275:     if (exists($$changes{'activate'})) {
 8276:         if (ref($$changes{'activate'}) eq 'HASH') {
 8277:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8278:             my $numnew = scalar(@newitems);
 8279:             for (my $i=0; $i<$numnew; $i++) {
 8280:                 my $newkey = $newitems[$i];
 8281:                 my $newid = &Apache::loncommon::get_cgi_id();
 8282:                 if ($newkey =~ /^\d+:/) { 
 8283:                     $newkey =~ s/^(\d+)/$newid/;
 8284:                     $translation{$1} = $newid;
 8285:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8286:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8287:                     $translation{$1} = $newid;
 8288:                 }
 8289:                 $new_values{$file_name."\0".$newkey} = 
 8290:                                           $$changes{'activate'}{$newitems[$i]};
 8291:                 $new_control{$newkey} = $now;
 8292:             }
 8293:         }
 8294:     }
 8295:     my %todelete;
 8296:     my %changed_items;
 8297:     foreach my $action ('delete','update') {
 8298:         if (exists($$changes{$action})) {
 8299:             if (ref($$changes{$action}) eq 'HASH') {
 8300:                 foreach my $key (keys(%{$$changes{$action}})) {
 8301:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8302:                     if ($action eq 'delete') { 
 8303:                         $todelete{$itemnum} = 1;
 8304:                     } else {
 8305:                         $changed_items{$itemnum} = $key;
 8306:                     }
 8307:                 }
 8308:             }
 8309:         }
 8310:     }
 8311:     # get lock on access controls for file.
 8312:     my $lockhash = {
 8313:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8314:                                                        ':'.$env{'user.domain'},
 8315:                    }; 
 8316:     my $tries = 0;
 8317:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8318:    
 8319:     while (($gotlock ne 'ok') && $tries <3) {
 8320:         $tries ++;
 8321:         sleep 1;
 8322:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8323:     }
 8324:     if ($gotlock eq 'ok') {
 8325:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8326:         my ($tmp)=keys(%curr_permissions);
 8327:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8328:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8329:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8330:             if (ref($curr_controls) eq 'HASH') {
 8331:                 foreach my $control_item (keys(%{$curr_controls})) {
 8332:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8333:                     if (defined($todelete{$itemnum})) {
 8334:                         push(@deletions,$file_name."\0".$control_item);
 8335:                     } else {
 8336:                         if (defined($changed_items{$itemnum})) {
 8337:                             $new_control{$changed_items{$itemnum}} = $now;
 8338:                             push(@deletions,$file_name."\0".$control_item);
 8339:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8340:                         } else {
 8341:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8342:                         }
 8343:                     }
 8344:                 }
 8345:             }
 8346:         }
 8347:         my ($group);
 8348:         if (&is_course($domain,$user)) {
 8349:             ($group,my $file) = split(/\//,$file_name,2);
 8350:         }
 8351:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8352:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8353:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8354:         #  remove lock
 8355:         my @del_lock = ($file_name."\0".'locked_access_records');
 8356:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8357:         my $sqlresult =
 8358:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8359:                                     $group);
 8360:     } else {
 8361:         $outcome = "error: could not obtain lockfile\n";  
 8362:     }
 8363:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8364: }
 8365: 
 8366: sub make_public_indefinitely {
 8367:     my ($requrl) = @_;
 8368:     my $now = time;
 8369:     my $action = 'activate';
 8370:     my $aclnum = 0;
 8371:     if (&is_portfolio_url($requrl)) {
 8372:         my (undef,$udom,$unum,$file_name,$group) =
 8373:             &parse_portfolio_url($requrl);
 8374:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8375:         my %access_controls = &get_access_controls($current_perms,
 8376:                                                    $group,$file_name);
 8377:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8378:             my ($num,$scope,$end,$start) = 
 8379:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8380:             if ($scope eq 'public') {
 8381:                 if ($start <= $now && $end == 0) {
 8382:                     $action = 'none';
 8383:                 } else {
 8384:                     $action = 'update';
 8385:                     $aclnum = $num;
 8386:                 }
 8387:                 last;
 8388:             }
 8389:         }
 8390:         if ($action eq 'none') {
 8391:              return 'ok';
 8392:         } else {
 8393:             my %changes;
 8394:             my $newend = 0;
 8395:             my $newstart = $now;
 8396:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8397:             $changes{$action}{$newkey} = {
 8398:                 type => 'public',
 8399:                 time => {
 8400:                     start => $newstart,
 8401:                     end   => $newend,
 8402:                 },
 8403:             };
 8404:             my ($outcome,$deloutcome,$new_values,$translation) =
 8405:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8406:             return $outcome;
 8407:         }
 8408:     } else {
 8409:         return 'invalid';
 8410:     }
 8411: }
 8412: 
 8413: #------------------------------------------------------Get Marked as Read Only
 8414: 
 8415: sub get_marked_as_readonly {
 8416:     my ($domain,$user,$what,$group) = @_;
 8417:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8418:     my @readonly_files;
 8419:     my $cmp1=$what;
 8420:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8421:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8422:         if (defined($group)) {
 8423:             if ($file_name !~ m-^\Q$group\E/-) {
 8424:                 next;
 8425:             }
 8426:         }
 8427:         if (ref($value) eq "ARRAY"){
 8428:             foreach my $stored_what (@{$value}) {
 8429:                 my $cmp2=$stored_what;
 8430:                 if (ref($stored_what) eq 'ARRAY') {
 8431:                     $cmp2=join('',@{$stored_what});
 8432:                 }
 8433:                 if ($cmp1 eq $cmp2) {
 8434:                     push(@readonly_files, $file_name);
 8435:                     last;
 8436:                 } elsif (!defined($what)) {
 8437:                     push(@readonly_files, $file_name);
 8438:                     last;
 8439:                 }
 8440:             }
 8441:         }
 8442:     }
 8443:     return @readonly_files;
 8444: }
 8445: #-----------------------------------------------------------Get Marked as Read Only Hash
 8446: 
 8447: sub get_marked_as_readonly_hash {
 8448:     my ($current_permissions,$group,$what) = @_;
 8449:     my %readonly_files;
 8450:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8451:         if (defined($group)) {
 8452:             if ($file_name !~ m-^\Q$group\E/-) {
 8453:                 next;
 8454:             }
 8455:         }
 8456:         if (ref($value) eq "ARRAY"){
 8457:             foreach my $stored_what (@{$value}) {
 8458:                 if (ref($stored_what) eq 'ARRAY') {
 8459:                     foreach my $lock_descriptor(@{$stored_what}) {
 8460:                         if ($lock_descriptor eq 'graded') {
 8461:                             $readonly_files{$file_name} = 'graded';
 8462:                         } elsif ($lock_descriptor eq 'handback') {
 8463:                             $readonly_files{$file_name} = 'handback';
 8464:                         } else {
 8465:                             if (!exists($readonly_files{$file_name})) {
 8466:                                 $readonly_files{$file_name} = 'locked';
 8467:                             }
 8468:                         }
 8469:                     }
 8470:                 } 
 8471:             }
 8472:         } 
 8473:     }
 8474:     return %readonly_files;
 8475: }
 8476: # ------------------------------------------------------------ Unmark as Read Only
 8477: 
 8478: sub unmark_as_readonly {
 8479:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8480:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8481:     my ($domain,$user,$what,$file_name,$group) = @_;
 8482:     $file_name = &declutter_portfile($file_name);
 8483:     my $symb_crs = $what;
 8484:     if (ref($what)) { $symb_crs=join('',@$what); }
 8485:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8486:     my ($tmp)=keys(%current_permissions);
 8487:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8488:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8489:     foreach my $file (@readonly_files) {
 8490: 	my $clean_file = &declutter_portfile($file);
 8491: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8492: 	my $current_locks = $current_permissions{$file};
 8493:         my @new_locks;
 8494:         my @del_keys;
 8495:         if (ref($current_locks) eq "ARRAY"){
 8496:             foreach my $locker (@{$current_locks}) {
 8497:                 my $compare=$locker;
 8498:                 if (ref($locker) eq 'ARRAY') {
 8499:                     $compare=join('',@{$locker});
 8500:                     if ($compare ne $symb_crs) {
 8501:                         push(@new_locks, $locker);
 8502:                     }
 8503:                 }
 8504:             }
 8505:             if (scalar(@new_locks) > 0) {
 8506:                 $current_permissions{$file} = \@new_locks;
 8507:             } else {
 8508:                 push(@del_keys, $file);
 8509:                 &del('file_permissions',\@del_keys, $domain, $user);
 8510:                 delete($current_permissions{$file});
 8511:             }
 8512:         }
 8513:     }
 8514:     &put('file_permissions',\%current_permissions,$domain,$user);
 8515:     return;
 8516: }
 8517: 
 8518: # ------------------------------------------------------------ Directory lister
 8519: 
 8520: sub dirlist {
 8521:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8522:     $uri=~s/^\///;
 8523:     $uri=~s/\/$//;
 8524:     my ($udom, $uname);
 8525:     if ($getuserdir) {
 8526:         $udom = $userdomain;
 8527:         $uname = $username;
 8528:     } else {
 8529:         (undef,$udom,$uname)=split(/\//,$uri);
 8530:         if(defined($userdomain)) {
 8531:             $udom = $userdomain;
 8532:         }
 8533:         if(defined($username)) {
 8534:             $uname = $username;
 8535:         }
 8536:     }
 8537:     my ($dirRoot,$listing,@listing_results);
 8538: 
 8539:     $dirRoot = $perlvar{'lonDocRoot'};
 8540:     if (defined($getpropath)) {
 8541:         $dirRoot = &propath($udom,$uname);
 8542:         $dirRoot =~ s/\/$//;
 8543:     } elsif (defined($getuserdir)) {
 8544:         my $subdir=$uname.'__';
 8545:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8546:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8547:                    ."/$udom/$subdir/$uname";
 8548:     } elsif (defined($alternateRoot)) {
 8549:         $dirRoot = $alternateRoot;
 8550:     }
 8551: 
 8552:     if($udom) {
 8553:         if($uname) {
 8554:             my $uhome = &homeserver($uname,$udom);
 8555:             if ($uhome eq 'no_host') {
 8556:                 return ([],'no_host');
 8557:             }
 8558:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8559:                               .$getuserdir.':'.&escape($dirRoot)
 8560:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8561:             if ($listing eq 'unknown_cmd') {
 8562:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8563:             } else {
 8564:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8565:             }
 8566:             if ($listing eq 'unknown_cmd') {
 8567:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8568:                 @listing_results = split(/:/,$listing);
 8569:             } else {
 8570:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8571:             }
 8572:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8573:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8574:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8575:                 return ([],$listing);
 8576:             } else {
 8577:                 return (\@listing_results);
 8578:             }
 8579:         } elsif(!$alternateRoot) {
 8580:             my (%allusers,%listerror);
 8581: 	    my %servers = &get_servers($udom,'library');
 8582:  	    foreach my $tryserver (keys(%servers)) {
 8583:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8584:                                   &escape($udom),$tryserver);
 8585:                 if ($listing eq 'unknown_cmd') {
 8586: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8587: 				      $udom, $tryserver);
 8588:                 } else {
 8589:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8590:                 }
 8591: 		if ($listing eq 'unknown_cmd') {
 8592: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8593: 				      $udom, $tryserver);
 8594: 		    @listing_results = split(/:/,$listing);
 8595: 		} else {
 8596: 		    @listing_results =
 8597: 			map { &unescape($_); } split(/:/,$listing);
 8598: 		}
 8599:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8600:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8601:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8602:                     $listerror{$tryserver} = $listing;
 8603:                 } else {
 8604: 		    foreach my $line (@listing_results) {
 8605: 			my ($entry) = split(/&/,$line,2);
 8606: 			$allusers{$entry} = 1;
 8607: 		    }
 8608: 		}
 8609:             }
 8610:             my @alluserslist=();
 8611:             foreach my $user (sort(keys(%allusers))) {
 8612:                 push(@alluserslist,$user.'&user');
 8613:             }
 8614:             return (\@alluserslist);
 8615:         } else {
 8616:             return ([],'missing username');
 8617:         }
 8618:     } elsif(!defined($getpropath)) {
 8619:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8620:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8621:         return (\@all_domains);
 8622:     } else {
 8623:         return ([],'missing domain');
 8624:     }
 8625: }
 8626: 
 8627: # --------------------------------------------- GetFileTimestamp
 8628: # This function utilizes dirlist and returns the date stamp for
 8629: # when it was last modified.  It will also return an error of -1
 8630: # if an error occurs
 8631: 
 8632: sub GetFileTimestamp {
 8633:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8634:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8635:     $studentName   = &LONCAPA::clean_username($studentName);
 8636:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8637:                                     undef,$getuserdir);
 8638:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8639:         return -1;
 8640:     }
 8641:     if (ref($fileref) eq 'ARRAY') {
 8642:         my @stats = split('&',$fileref->[0]);
 8643:         # @stats contains first the filename, then the stat output
 8644:         return $stats[10]; # so this is 10 instead of 9.
 8645:     } else {
 8646:         return -1;
 8647:     }
 8648: }
 8649: 
 8650: sub stat_file {
 8651:     my ($uri) = @_;
 8652:     $uri = &clutter_with_no_wrapper($uri);
 8653: 
 8654:     my ($udom,$uname,$file);
 8655:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8656: 	($udom,$uname,$file) =
 8657: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8658: 	$file = 'userfiles/'.$file;
 8659:     }
 8660:     if ($uri =~ m-^/res/-) {
 8661: 	($udom,$uname) = 
 8662: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8663: 	$file = $uri;
 8664:     }
 8665: 
 8666:     if (!$udom || !$uname || !$file) {
 8667: 	# unable to handle the uri
 8668: 	return ();
 8669:     }
 8670:     my $getpropath;
 8671:     if ($file =~ /^userfiles\//) {
 8672:         $getpropath = 1;
 8673:     }
 8674:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8675:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8676:         return ();
 8677:     } else {
 8678:         if (ref($listref) eq 'ARRAY') {
 8679:             my @stats = split('&',$listref->[0]);
 8680: 	    shift(@stats); #filename is first
 8681: 	    return @stats;
 8682:         }
 8683:     }
 8684:     return ();
 8685: }
 8686: 
 8687: # -------------------------------------------------------- Value of a Condition
 8688: 
 8689: # gets the value of a specific preevaluated condition
 8690: #    stored in the string  $env{user.state.<cid>}
 8691: # or looks up a condition reference in the bighash and if if hasn't
 8692: # already been evaluated recurses into docondval to get the value of
 8693: # the condition, then memoizing it to 
 8694: #   $env{user.state.<cid>.<condition>}
 8695: sub directcondval {
 8696:     my $number=shift;
 8697:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8698: 	&Apache::lonuserstate::evalstate();
 8699:     }
 8700:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8701: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8702:     } elsif ($number =~ /^_/) {
 8703: 	my $sub_condition;
 8704: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8705: 		&GDBM_READER(),0640)) {
 8706: 	    $sub_condition=$bighash{'conditions'.$number};
 8707: 	    untie(%bighash);
 8708: 	}
 8709: 	my $value = &docondval($sub_condition);
 8710: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8711: 	return $value;
 8712:     }
 8713:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8714:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8715:     } else {
 8716:        return 2;
 8717:     }
 8718: }
 8719: 
 8720: # get the collection of conditions for this resource
 8721: sub condval {
 8722:     my $condidx=shift;
 8723:     my $allpathcond='';
 8724:     foreach my $cond (split(/\|/,$condidx)) {
 8725: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8726: 	    $allpathcond.=
 8727: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8728: 	}
 8729:     }
 8730:     $allpathcond=~s/\|$//;
 8731:     return &docondval($allpathcond);
 8732: }
 8733: 
 8734: #evaluates an expression of conditions
 8735: sub docondval {
 8736:     my ($allpathcond) = @_;
 8737:     my $result=0;
 8738:     if ($env{'request.course.id'}
 8739: 	&& defined($allpathcond)) {
 8740: 	my $operand='|';
 8741: 	my @stack;
 8742: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8743: 	    if ($chunk eq '(') {
 8744: 		push @stack,($operand,$result);
 8745: 	    } elsif ($chunk eq ')') {
 8746: 		my $before=pop @stack;
 8747: 		if (pop @stack eq '&') {
 8748: 		    $result=$result>$before?$before:$result;
 8749: 		} else {
 8750: 		    $result=$result>$before?$result:$before;
 8751: 		}
 8752: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8753: 		$operand=$chunk;
 8754: 	    } else {
 8755: 		my $new=directcondval($chunk);
 8756: 		if ($operand eq '&') {
 8757: 		    $result=$result>$new?$new:$result;
 8758: 		} else {
 8759: 		    $result=$result>$new?$result:$new;
 8760: 		}
 8761: 	    }
 8762: 	}
 8763:     }
 8764:     return $result;
 8765: }
 8766: 
 8767: # ---------------------------------------------------- Devalidate courseresdata
 8768: 
 8769: sub devalidatecourseresdata {
 8770:     my ($coursenum,$coursedomain)=@_;
 8771:     my $hashid=$coursenum.':'.$coursedomain;
 8772:     &devalidate_cache_new('courseres',$hashid);
 8773: }
 8774: 
 8775: 
 8776: # --------------------------------------------------- Course Resourcedata Query
 8777: #
 8778: #  Parameters:
 8779: #      $coursenum    - Number of the course.
 8780: #      $coursedomain - Domain at which the course was created.
 8781: #  Returns:
 8782: #     A hash of the course parameters along (I think) with timestamps
 8783: #     and version info.
 8784: 
 8785: sub get_courseresdata {
 8786:     my ($coursenum,$coursedomain)=@_;
 8787:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8788:     my $hashid=$coursenum.':'.$coursedomain;
 8789:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8790:     my %dumpreply;
 8791:     unless (defined($cached)) {
 8792: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8793: 	$result=\%dumpreply;
 8794: 	my ($tmp) = keys(%dumpreply);
 8795: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8796: 	    &do_cache_new('courseres',$hashid,$result,600);
 8797: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8798: 	    return $tmp;
 8799: 	} elsif ($tmp =~ /^(error)/) {
 8800: 	    $result=undef;
 8801: 	    &do_cache_new('courseres',$hashid,$result,600);
 8802: 	}
 8803:     }
 8804:     return $result;
 8805: }
 8806: 
 8807: sub devalidateuserresdata {
 8808:     my ($uname,$udom)=@_;
 8809:     my $hashid="$udom:$uname";
 8810:     &devalidate_cache_new('userres',$hashid);
 8811: }
 8812: 
 8813: sub get_userresdata {
 8814:     my ($uname,$udom)=@_;
 8815:     #most student don\'t have any data set, check if there is some data
 8816:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8817: 
 8818:     my $hashid="$udom:$uname";
 8819:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8820:     if (!defined($cached)) {
 8821: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8822: 	$result=\%resourcedata;
 8823: 	&do_cache_new('userres',$hashid,$result,600);
 8824:     }
 8825:     my ($tmp)=keys(%$result);
 8826:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8827: 	return $result;
 8828:     }
 8829:     #error 2 occurs when the .db doesn't exist
 8830:     if ($tmp!~/error: 2 /) {
 8831: 	&logthis("<font color=\"blue\">WARNING:".
 8832: 		 " Trying to get resource data for ".
 8833: 		 $uname." at ".$udom.": ".
 8834: 		 $tmp."</font>");
 8835:     } elsif ($tmp=~/error: 2 /) {
 8836: 	#&EXT_cache_set($udom,$uname);
 8837: 	&do_cache_new('userres',$hashid,undef,600);
 8838: 	undef($tmp); # not really an error so don't send it back
 8839:     }
 8840:     return $tmp;
 8841: }
 8842: #----------------------------------------------- resdata - return resource data
 8843: #  Purpose:
 8844: #    Return resource data for either users or for a course.
 8845: #  Parameters:
 8846: #     $name      - Course/user name.
 8847: #     $domain    - Name of the domain the user/course is registered on.
 8848: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8849: #     @which     - Array of names of resources desired.
 8850: #  Returns:
 8851: #     The value of the first reasource in @which that is found in the
 8852: #     resource hash.
 8853: #  Exceptional Conditions:
 8854: #     If the $type passed in is not valid (not the string 'course' or 
 8855: #     'user', an undefined  reference is returned.
 8856: #     If none of the resources are found, an undef is returned
 8857: sub resdata {
 8858:     my ($name,$domain,$type,@which)=@_;
 8859:     my $result;
 8860:     if ($type eq 'course') {
 8861: 	$result=&get_courseresdata($name,$domain);
 8862:     } elsif ($type eq 'user') {
 8863: 	$result=&get_userresdata($name,$domain);
 8864:     }
 8865:     if (!ref($result)) { return $result; }    
 8866:     foreach my $item (@which) {
 8867: 	if (defined($result->{$item->[0]})) {
 8868: 	    return [$result->{$item->[0]},$item->[1]];
 8869: 	}
 8870:     }
 8871:     return undef;
 8872: }
 8873: 
 8874: #
 8875: # EXT resource caching routines
 8876: #
 8877: 
 8878: sub clear_EXT_cache_status {
 8879:     &delenv('cache.EXT.');
 8880: }
 8881: 
 8882: sub EXT_cache_status {
 8883:     my ($target_domain,$target_user) = @_;
 8884:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8885:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8886:         # We know already the user has no data
 8887:         return 1;
 8888:     } else {
 8889:         return 0;
 8890:     }
 8891: }
 8892: 
 8893: sub EXT_cache_set {
 8894:     my ($target_domain,$target_user) = @_;
 8895:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8896:     #&appenv({$cachename => time});
 8897: }
 8898: 
 8899: # --------------------------------------------------------- Value of a Variable
 8900: sub EXT {
 8901: 
 8902:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8903:     unless ($varname) { return ''; }
 8904:     #get real user name/domain, courseid and symb
 8905:     my $courseid;
 8906:     my $publicuser;
 8907:     if ($symbparm) {
 8908: 	$symbparm=&get_symb_from_alias($symbparm);
 8909:     }
 8910:     if (!($uname && $udom)) {
 8911:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8912:       if (!$symbparm) {	$symbparm=$cursymb; }
 8913:     } else {
 8914: 	$courseid=$env{'request.course.id'};
 8915:     }
 8916:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 8917:     my $rest;
 8918:     if (defined($therest[0])) {
 8919:        $rest=join('.',@therest);
 8920:     } else {
 8921:        $rest='';
 8922:     }
 8923: 
 8924:     my $qualifierrest=$qualifier;
 8925:     if ($rest) { $qualifierrest.='.'.$rest; }
 8926:     my $spacequalifierrest=$space;
 8927:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 8928:     if ($realm eq 'user') {
 8929: # --------------------------------------------------------------- user.resource
 8930: 	if ($space eq 'resource') {
 8931: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 8932: 		  || defined($Apache::lonhomework::parsing_a_task))
 8933: 		 &&
 8934: 		 ($symbparm eq &symbread()) ) {	
 8935: 		# if we are in the middle of processing the resource the
 8936: 		# get the value we are planning on committing
 8937:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 8938:                     return $Apache::lonhomework::results{$qualifierrest};
 8939:                 } else {
 8940:                     return $Apache::lonhomework::history{$qualifierrest};
 8941:                 }
 8942: 	    } else {
 8943: 		my %restored;
 8944: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 8945: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 8946: 		} else {
 8947: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 8948: 		}
 8949: 		return $restored{$qualifierrest};
 8950: 	    }
 8951: # ----------------------------------------------------------------- user.access
 8952:         } elsif ($space eq 'access') {
 8953: 	    # FIXME - not supporting calls for a specific user
 8954:             return &allowed($qualifier,$rest);
 8955: # ------------------------------------------ user.preferences, user.environment
 8956:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 8957: 	    if (($uname eq $env{'user.name'}) &&
 8958: 		($udom eq $env{'user.domain'})) {
 8959: 		return $env{join('.',('environment',$qualifierrest))};
 8960: 	    } else {
 8961: 		my %returnhash;
 8962: 		if (!$publicuser) {
 8963: 		    %returnhash=&userenvironment($udom,$uname,
 8964: 						 $qualifierrest);
 8965: 		}
 8966: 		return $returnhash{$qualifierrest};
 8967: 	    }
 8968: # ----------------------------------------------------------------- user.course
 8969:         } elsif ($space eq 'course') {
 8970: 	    # FIXME - not supporting calls for a specific user
 8971:             return $env{join('.',('request.course',$qualifier))};
 8972: # ------------------------------------------------------------------- user.role
 8973:         } elsif ($space eq 'role') {
 8974: 	    # FIXME - not supporting calls for a specific user
 8975:             my ($role,$where)=split(/\./,$env{'request.role'});
 8976:             if ($qualifier eq 'value') {
 8977: 		return $role;
 8978:             } elsif ($qualifier eq 'extent') {
 8979:                 return $where;
 8980:             }
 8981: # ----------------------------------------------------------------- user.domain
 8982:         } elsif ($space eq 'domain') {
 8983:             return $udom;
 8984: # ------------------------------------------------------------------- user.name
 8985:         } elsif ($space eq 'name') {
 8986:             return $uname;
 8987: # ---------------------------------------------------- Any other user namespace
 8988:         } else {
 8989: 	    my %reply;
 8990: 	    if (!$publicuser) {
 8991: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 8992: 	    }
 8993: 	    return $reply{$qualifierrest};
 8994:         }
 8995:     } elsif ($realm eq 'query') {
 8996: # ---------------------------------------------- pull stuff out of query string
 8997:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 8998: 						[$spacequalifierrest]);
 8999: 	return $env{'form.'.$spacequalifierrest}; 
 9000:    } elsif ($realm eq 'request') {
 9001: # ------------------------------------------------------------- request.browser
 9002:         if ($space eq 'browser') {
 9003:             return $env{'browser.'.$qualifier};
 9004: # ------------------------------------------------------------ request.filename
 9005:         } else {
 9006:             return $env{'request.'.$spacequalifierrest};
 9007:         }
 9008:     } elsif ($realm eq 'course') {
 9009: # ---------------------------------------------------------- course.description
 9010:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9011:     } elsif ($realm eq 'resource') {
 9012: 
 9013: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9014: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9015: 	}
 9016: 
 9017: 	if ($space eq 'title') {
 9018: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9019: 	    return &gettitle($symbparm);
 9020: 	}
 9021: 	
 9022: 	if ($space eq 'map') {
 9023: 	    my ($map) = &decode_symb($symbparm);
 9024: 	    return &symbread($map);
 9025: 	}
 9026: 	if ($space eq 'filename') {
 9027: 	    if ($symbparm) {
 9028: 		return &clutter((&decode_symb($symbparm))[2]);
 9029: 	    }
 9030: 	    return &hreflocation('',$env{'request.filename'});
 9031: 	}
 9032: 
 9033: 	my ($section, $group, @groups);
 9034: 	my ($courselevelm,$courselevel);
 9035: 	if ($symbparm && defined($courseid) && 
 9036: 	    $courseid eq $env{'request.course.id'}) {
 9037: 
 9038: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9039: 
 9040: # ----------------------------------------------------- Cascading lookup scheme
 9041: 	    my $symbp=$symbparm;
 9042: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9043: 
 9044: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9045: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9046: 
 9047: 	    if (($env{'user.name'} eq $uname) &&
 9048: 		($env{'user.domain'} eq $udom)) {
 9049: 		$section=$env{'request.course.sec'};
 9050:                 @groups = split(/:/,$env{'request.course.groups'});  
 9051:                 @groups=&sort_course_groups($courseid,@groups); 
 9052: 	    } else {
 9053: 		if (! defined($usection)) {
 9054: 		    $section=&getsection($udom,$uname,$courseid);
 9055: 		} else {
 9056: 		    $section = $usection;
 9057: 		}
 9058:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9059: 	    }
 9060: 
 9061: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9062: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9063: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9064: 
 9065: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9066: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9067: 	    $courselevelm=$courseid.'.'.$mapparm;
 9068: 
 9069: # ----------------------------------------------------------- first, check user
 9070: 
 9071: 	    my $userreply=&resdata($uname,$udom,'user',
 9072: 				       ([$courselevelr,'resource'],
 9073: 					[$courselevelm,'map'     ],
 9074: 					[$courselevel, 'course'  ]));
 9075: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9076: 
 9077: # ------------------------------------------------ second, check some of course
 9078:             my $coursereply;
 9079:             if (@groups > 0) {
 9080:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9081:                                        $mapparm,$spacequalifierrest);
 9082:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9083:             }
 9084: 
 9085: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9086: 				  $env{'course.'.$courseid.'.domain'},
 9087: 				  'course',
 9088: 				  ([$seclevelr,   'resource'],
 9089: 				   [$seclevelm,   'map'     ],
 9090: 				   [$seclevel,    'course'  ],
 9091: 				   [$courselevelr,'resource']));
 9092: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9093: 
 9094: # ------------------------------------------------------ third, check map parms
 9095: 	    my %parmhash=();
 9096: 	    my $thisparm='';
 9097: 	    if (tie(%parmhash,'GDBM_File',
 9098: 		    $env{'request.course.fn'}.'_parms.db',
 9099: 		    &GDBM_READER(),0640)) {
 9100: 		$thisparm=$parmhash{$symbparm};
 9101: 		untie(%parmhash);
 9102: 	    }
 9103: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9104: 	}
 9105: # ------------------------------------------ fourth, look in resource metadata
 9106: 
 9107: 	$spacequalifierrest=~s/\./\_/;
 9108: 	my $filename;
 9109: 	if (!$symbparm) { $symbparm=&symbread(); }
 9110: 	if ($symbparm) {
 9111: 	    $filename=(&decode_symb($symbparm))[2];
 9112: 	} else {
 9113: 	    $filename=$env{'request.filename'};
 9114: 	}
 9115: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9116: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9117: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9118: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9119: 
 9120: # ---------------------------------------------- fourth, look in rest of course
 9121: 	if ($symbparm && defined($courseid) && 
 9122: 	    $courseid eq $env{'request.course.id'}) {
 9123: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9124: 				     $env{'course.'.$courseid.'.domain'},
 9125: 				     'course',
 9126: 				     ([$courselevelm,'map'   ],
 9127: 				      [$courselevel, 'course']));
 9128: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9129: 	}
 9130: # ------------------------------------------------------------------ Cascade up
 9131: 	unless ($space eq '0') {
 9132: 	    my @parts=split(/_/,$space);
 9133: 	    my $id=pop(@parts);
 9134: 	    my $part=join('_',@parts);
 9135: 	    if ($part eq '') { $part='0'; }
 9136: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9137: 				 $symbparm,$udom,$uname,$section,1);
 9138: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9139: 	}
 9140: 	if ($recurse) { return undef; }
 9141: 	my $pack_def=&packages_tab_default($filename,$varname);
 9142: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9143: # ---------------------------------------------------- Any other user namespace
 9144:     } elsif ($realm eq 'environment') {
 9145: # ----------------------------------------------------------------- environment
 9146: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9147: 	    return $env{'environment.'.$spacequalifierrest};
 9148: 	} else {
 9149: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9150: 		return '';
 9151: 	    }
 9152: 	    my %returnhash=&userenvironment($udom,$uname,
 9153: 					    $spacequalifierrest);
 9154: 	    return $returnhash{$spacequalifierrest};
 9155: 	}
 9156:     } elsif ($realm eq 'system') {
 9157: # ----------------------------------------------------------------- system.time
 9158: 	if ($space eq 'time') {
 9159: 	    return time;
 9160:         }
 9161:     } elsif ($realm eq 'server') {
 9162: # ----------------------------------------------------------------- system.time
 9163: 	if ($space eq 'name') {
 9164: 	    return $ENV{'SERVER_NAME'};
 9165:         }
 9166:     }
 9167:     return '';
 9168: }
 9169: 
 9170: sub get_reply {
 9171:     my ($reply_value) = @_;
 9172:     if (ref($reply_value) eq 'ARRAY') {
 9173:         if (wantarray) {
 9174: 	    return @$reply_value;
 9175:         }
 9176:         return $reply_value->[0];
 9177:     } else {
 9178:         return $reply_value;
 9179:     }
 9180: }
 9181: 
 9182: sub check_group_parms {
 9183:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9184:     my @groupitems = ();
 9185:     my $resultitem;
 9186:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9187:     foreach my $group (@{$groups}) {
 9188:         foreach my $level (@levels) {
 9189:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9190:              push(@groupitems,[$item,$level->[1]]);
 9191:         }
 9192:     }
 9193:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9194:                             $env{'course.'.$courseid.'.domain'},
 9195:                                      'course',@groupitems);
 9196:     return $coursereply;
 9197: }
 9198: 
 9199: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9200:     my ($courseid,@groups) = @_;
 9201:     @groups = sort(@groups);
 9202:     return @groups;
 9203: }
 9204: 
 9205: sub packages_tab_default {
 9206:     my ($uri,$varname)=@_;
 9207:     my (undef,$part,$name)=split(/\./,$varname);
 9208: 
 9209:     my (@extension,@specifics,$do_default);
 9210:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9211: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9212: 	if ($pack_type eq 'default') {
 9213: 	    $do_default=1;
 9214: 	} elsif ($pack_type eq 'extension') {
 9215: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9216: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9217: 	    # only look at packages defaults for packages that this id is
 9218: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9219: 	}
 9220:     }
 9221:     # first look for a package that matches the requested part id
 9222:     foreach my $package (@specifics) {
 9223: 	my (undef,$pack_type,$pack_part)=@{$package};
 9224: 	next if ($pack_part ne $part);
 9225: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9226: 	    return $packagetab{"$pack_type&$name&default"};
 9227: 	}
 9228:     }
 9229:     # look for any possible matching non extension_ package
 9230:     foreach my $package (@specifics) {
 9231: 	my (undef,$pack_type,$pack_part)=@{$package};
 9232: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9233: 	    return $packagetab{"$pack_type&$name&default"};
 9234: 	}
 9235: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9236: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9237: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9238: 	}
 9239:     }
 9240:     # look for any posible extension_ match
 9241:     foreach my $package (@extension) {
 9242: 	my ($package,$pack_type)=@{$package};
 9243: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9244: 	    return $packagetab{"$pack_type&$name&default"};
 9245: 	}
 9246: 	if (defined($packagetab{$package."&$name&default"})) {
 9247: 	    return $packagetab{$package."&$name&default"};
 9248: 	}
 9249:     }
 9250:     # look for a global default setting
 9251:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9252: 	return $packagetab{"default&$name&default"};
 9253:     }
 9254:     return undef;
 9255: }
 9256: 
 9257: sub add_prefix_and_part {
 9258:     my ($prefix,$part)=@_;
 9259:     my $keyroot;
 9260:     if (defined($prefix) && $prefix !~ /^__/) {
 9261: 	# prefix that has a part already
 9262: 	$keyroot=$prefix;
 9263:     } elsif (defined($prefix)) {
 9264: 	# prefix that is missing a part
 9265: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9266:     } else {
 9267: 	# no prefix at all
 9268: 	if (defined($part)) { $keyroot='_'.$part; }
 9269:     }
 9270:     return $keyroot;
 9271: }
 9272: 
 9273: # ---------------------------------------------------------------- Get metadata
 9274: 
 9275: my %metaentry;
 9276: my %importedpartids;
 9277: sub metadata {
 9278:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9279:     $uri=&declutter($uri);
 9280:     # if it is a non metadata possible uri return quickly
 9281:     if (($uri eq '') || 
 9282: 	(($uri =~ m|^/*adm/|) && 
 9283: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9284:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9285: 	return undef;
 9286:     }
 9287:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9288: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9289: 	return undef;
 9290:     }
 9291:     my $filename=$uri;
 9292:     $uri=~s/\.meta$//;
 9293: #
 9294: # Is the metadata already cached?
 9295: # Look at timestamp of caching
 9296: # Everything is cached by the main uri, libraries are never directly cached
 9297: #
 9298:     if (!defined($liburi)) {
 9299: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9300: 	if (defined($cached)) { return $result->{':'.$what}; }
 9301:     }
 9302:     {
 9303: # Imported parts would go here
 9304:         my %importedids=();
 9305:         my @origfileimportpartids=();
 9306:         my $importedparts=0;
 9307: #
 9308: # Is this a recursive call for a library?
 9309: #
 9310: #	if (! exists($metacache{$uri})) {
 9311: #	    $metacache{$uri}={};
 9312: #	}
 9313: 	my $cachetime = 60*60;
 9314:         if ($liburi) {
 9315: 	    $liburi=&declutter($liburi);
 9316:             $filename=$liburi;
 9317:         } else {
 9318: 	    &devalidate_cache_new('meta',$uri);
 9319: 	    undef(%metaentry);
 9320: 	}
 9321:         my %metathesekeys=();
 9322:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9323: 	my $metastring;
 9324: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9325: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9326: 	    $metastring = 
 9327: 		&Apache::lonnet::ssi_body($which,
 9328: 					  ('grade_target' => 'meta'));
 9329: 	    $cachetime = 1; # only want this cached in the child not long term
 9330: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9331:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9332: 	    my $file=&filelocation('',&clutter($filename));
 9333: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9334: 	    $metastring=&getfile($file);
 9335: 	}
 9336:         my $parser=HTML::LCParser->new(\$metastring);
 9337:         my $token;
 9338:         undef %metathesekeys;
 9339:         while ($token=$parser->get_token) {
 9340: 	    if ($token->[0] eq 'S') {
 9341: 		if (defined($token->[2]->{'package'})) {
 9342: #
 9343: # This is a package - get package info
 9344: #
 9345: 		    my $package=$token->[2]->{'package'};
 9346: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9347: 		    if (defined($token->[2]->{'id'})) { 
 9348: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9349: 		    }
 9350: 		    if ($metaentry{':packages'}) {
 9351: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9352: 		    } else {
 9353: 			$metaentry{':packages'}=$package.$keyroot;
 9354: 		    }
 9355: 		    foreach my $pack_entry (keys(%packagetab)) {
 9356: 			my $part=$keyroot;
 9357: 			$part=~s/^\_//;
 9358: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9359: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9360: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9361: 			    # ignore package.tab specified default values
 9362:                             # here &package_tab_default() will fetch those
 9363: 			    if ($subp eq 'default') { next; }
 9364: 			    my $value=$packagetab{$pack_entry};
 9365: 			    my $unikey;
 9366: 			    if ($pack =~ /_0$/) {
 9367: 				$unikey='parameter_0_'.$name;
 9368: 				$part=0;
 9369: 			    } else {
 9370: 				$unikey='parameter'.$keyroot.'_'.$name;
 9371: 			    }
 9372: 			    if ($subp eq 'display') {
 9373: 				$value.=' [Part: '.$part.']';
 9374: 			    }
 9375: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9376: 			    $metathesekeys{$unikey}=1;
 9377: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9378: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9379: 			    }
 9380: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9381: 				$metaentry{':'.$unikey}=
 9382: 				    $metaentry{':'.$unikey.'.default'};
 9383: 			    }
 9384: 			}
 9385: 		    }
 9386: 		} else {
 9387: #
 9388: # This is not a package - some other kind of start tag
 9389: #
 9390: 		    my $entry=$token->[1];
 9391: 		    my $unikey='';
 9392: 
 9393: 		    if ($entry eq 'import') {
 9394: #
 9395: # Importing a library here
 9396: #
 9397:                         my $location=$parser->get_text('/import');
 9398:                         my $dir=$filename;
 9399:                         $dir=~s|[^/]*$||;
 9400:                         $location=&filelocation($dir,$location);
 9401:                        
 9402:                         my $importmode=$token->[2]->{'importmode'};
 9403:                         if ($importmode eq 'problem') {
 9404: # Import as problem/response
 9405:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9406:                         } elsif ($importmode eq 'part') {
 9407: # Import as part(s)
 9408:                            $importedparts=1;
 9409: # We need to get the original file and the imported file to get the part order correct
 9410: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9411: # Load and inspect original file
 9412:                            if ($#origfileimportpartids<0) {
 9413:                               undef(%importedpartids);
 9414:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9415:                               my $origfile=&getfile($origfilelocation);
 9416:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9417:                            }
 9418: 
 9419: # Load and inspect imported file
 9420:                            my $impfile=&getfile($location);
 9421:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9422:                            if ($#impfilepartids>=0) {
 9423: # This problem had parts
 9424:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9425:                            } else {
 9426: # Importing by turning a single problem into a problem part
 9427: # It gets the import-tags ID as part-ID
 9428:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9429:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9430:                            }
 9431:                         } else {
 9432: # Normal import
 9433:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9434:                            if (defined($token->[2]->{'id'})) {
 9435:                               $unikey.='_'.$token->[2]->{'id'};
 9436:                            }
 9437:                         }
 9438: 
 9439: 			if ($depthcount<20) {
 9440: 			    my $metadata = 
 9441: 				&metadata($uri,'keys', $location,$unikey,
 9442: 					  $depthcount+1);
 9443: 			    foreach my $meta (split(',',$metadata)) {
 9444: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9445: 				$metathesekeys{$meta}=1;
 9446: 			    }
 9447: 			
 9448:                         }
 9449: 		    } else {
 9450: #
 9451: # Not importing, some other kind of non-package, non-library start tag
 9452: # 
 9453:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9454:                         if (defined($token->[2]->{'id'})) {
 9455:                             $unikey.='_'.$token->[2]->{'id'};
 9456:                         }
 9457: 			if (defined($token->[2]->{'name'})) { 
 9458: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9459: 			}
 9460: 			$metathesekeys{$unikey}=1;
 9461: 			foreach my $param (@{$token->[3]}) {
 9462: 			    $metaentry{':'.$unikey.'.'.$param} =
 9463: 				$token->[2]->{$param};
 9464: 			}
 9465: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9466: 			my $default=$metaentry{':'.$unikey.'.default'};
 9467: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9468: 		 # only ws inside the tag, and not in default, so use default
 9469: 		 # as value
 9470: 			    $metaentry{':'.$unikey}=$default;
 9471: 			} elsif ( $internaltext =~ /\S/ ) {
 9472: 		  # something interesting inside the tag
 9473: 			    $metaentry{':'.$unikey}=$internaltext;
 9474: 			} else {
 9475: 		  # no interesting values, don't set a default
 9476: 			}
 9477: # end of not-a-package not-a-library import
 9478: 		    }
 9479: # end of not-a-package start tag
 9480: 		}
 9481: # the next is the end of "start tag"
 9482: 	    }
 9483: 	}
 9484: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9485: 	$extension = lc($extension);
 9486: 	if ($extension eq 'htm') { $extension='html'; }
 9487: 
 9488: 	foreach my $key (keys(%packagetab)) {
 9489: 	    #no specific packages #how's our extension
 9490: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9491: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9492: 					 \%metathesekeys);
 9493: 	}
 9494: 
 9495: 	if (!exists($metaentry{':packages'})
 9496: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9497: 	    foreach my $key (keys(%packagetab)) {
 9498: 		#no specific packages well let's get default then
 9499: 		if ($key!~/^default&/) { next; }
 9500: 		&metadata_create_package_def($uri,$key,'default',
 9501: 					     \%metathesekeys);
 9502: 	    }
 9503: 	}
 9504: # are there custom rights to evaluate
 9505: 	if ($metaentry{':copyright'} eq 'custom') {
 9506: 
 9507:     #
 9508:     # Importing a rights file here
 9509:     #
 9510: 	    unless ($depthcount) {
 9511: 		my $location=$metaentry{':customdistributionfile'};
 9512: 		my $dir=$filename;
 9513: 		$dir=~s|[^/]*$||;
 9514: 		$location=&filelocation($dir,$location);
 9515: 		my $rights_metadata =
 9516: 		    &metadata($uri,'keys',$location,'_rights',
 9517: 			      $depthcount+1);
 9518: 		foreach my $rights (split(',',$rights_metadata)) {
 9519: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9520: 		    $metathesekeys{$rights}=1;
 9521: 		}
 9522: 	    }
 9523: 	}
 9524: 	# uniqifiy package listing
 9525: 	my %seen;
 9526: 	my @uniq_packages =
 9527: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9528: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9529: 
 9530:         if ($importedparts) {
 9531: # We had imported parts and need to rebuild partorder
 9532:            $metaentry{':partorder'}='';
 9533:            $metathesekeys{'partorder'}=1;
 9534:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9535:                if ($origfileimportpartids[$index] eq 'part') {
 9536: # original part, part of the problem
 9537:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9538:                } else {
 9539: # we have imported parts at this position
 9540:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9541:                }
 9542:            }
 9543:            $metaentry{':partorder'}=~s/^\,//;
 9544:         }
 9545: 
 9546: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9547: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9548: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9549: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9550: # this is the end of "was not already recently cached
 9551:     }
 9552:     return $metaentry{':'.$what};
 9553: }
 9554: 
 9555: sub metadata_create_package_def {
 9556:     my ($uri,$key,$package,$metathesekeys)=@_;
 9557:     my ($pack,$name,$subp)=split(/\&/,$key);
 9558:     if ($subp eq 'default') { next; }
 9559:     
 9560:     if (defined($metaentry{':packages'})) {
 9561: 	$metaentry{':packages'}.=','.$package;
 9562:     } else {
 9563: 	$metaentry{':packages'}=$package;
 9564:     }
 9565:     my $value=$packagetab{$key};
 9566:     my $unikey;
 9567:     $unikey='parameter_0_'.$name;
 9568:     $metaentry{':'.$unikey.'.part'}=0;
 9569:     $$metathesekeys{$unikey}=1;
 9570:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9571: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9572:     }
 9573:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9574: 	$metaentry{':'.$unikey}=
 9575: 	    $metaentry{':'.$unikey.'.default'};
 9576:     }
 9577: }
 9578: 
 9579: sub metadata_generate_part0 {
 9580:     my ($metadata,$metacache,$uri) = @_;
 9581:     my %allnames;
 9582:     foreach my $metakey (keys(%$metadata)) {
 9583: 	if ($metakey=~/^parameter\_(.*)/) {
 9584: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9585: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9586: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9587: 	    $allnames{$name}=$part;
 9588: 	  }
 9589: 	}
 9590:     }
 9591:     foreach my $name (keys(%allnames)) {
 9592:       $$metadata{"parameter_0_$name"}=1;
 9593:       my $key=":parameter_0_$name";
 9594:       $$metacache{"$key.part"}='0';
 9595:       $$metacache{"$key.name"}=$name;
 9596:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9597: 					   $allnames{$name}.'_'.$name.
 9598: 					   '.type'};
 9599:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9600: 			     '.display'};
 9601:       my $expr='[Part: '.$allnames{$name}.']';
 9602:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9603:       $$metacache{"$key.display"}=$olddis;
 9604:     }
 9605: }
 9606: 
 9607: # ------------------------------------------------------ Devalidate title cache
 9608: 
 9609: sub devalidate_title_cache {
 9610:     my ($url)=@_;
 9611:     if (!$env{'request.course.id'}) { return; }
 9612:     my $symb=&symbread($url);
 9613:     if (!$symb) { return; }
 9614:     my $key=$env{'request.course.id'}."\0".$symb;
 9615:     &devalidate_cache_new('title',$key);
 9616: }
 9617: 
 9618: # ------------------------------------------------- Get the title of a course
 9619: 
 9620: sub current_course_title {
 9621:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9622: }
 9623: # ------------------------------------------------- Get the title of a resource
 9624: 
 9625: sub gettitle {
 9626:     my $urlsymb=shift;
 9627:     my $symb=&symbread($urlsymb);
 9628:     if ($symb) {
 9629: 	my $key=$env{'request.course.id'}."\0".$symb;
 9630: 	my ($result,$cached)=&is_cached_new('title',$key);
 9631: 	if (defined($cached)) { 
 9632: 	    return $result;
 9633: 	}
 9634: 	my ($map,$resid,$url)=&decode_symb($symb);
 9635: 	my $title='';
 9636: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9637: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9638: 	} else {
 9639: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9640: 		    &GDBM_READER(),0640)) {
 9641: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9642: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9643: 		untie(%bighash);
 9644: 	    }
 9645: 	}
 9646: 	$title=~s/\&colon\;/\:/gs;
 9647: 	if ($title) {
 9648: # Remember both $symb and $title for dynamic metadata
 9649:             $accesshash{$symb.'___crstitle'}=$title;
 9650:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9651: # Cache this title and then return it
 9652: 	    return &do_cache_new('title',$key,$title,600);
 9653: 	}
 9654: 	$urlsymb=$url;
 9655:     }
 9656:     my $title=&metadata($urlsymb,'title');
 9657:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9658:     return $title;
 9659: }
 9660: 
 9661: sub get_slot {
 9662:     my ($which,$cnum,$cdom)=@_;
 9663:     if (!$cnum || !$cdom) {
 9664: 	(undef,my $courseid)=&whichuser();
 9665: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9666: 	$cnum=$env{'course.'.$courseid.'.num'};
 9667:     }
 9668:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9669:     my %slotinfo;
 9670:     if (exists($remembered{$key})) {
 9671: 	$slotinfo{$which} = $remembered{$key};
 9672:     } else {
 9673: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9674: 	&Apache::lonhomework::showhash(%slotinfo);
 9675: 	my ($tmp)=keys(%slotinfo);
 9676: 	if ($tmp=~/^error:/) { return (); }
 9677: 	$remembered{$key} = $slotinfo{$which};
 9678:     }
 9679:     if (ref($slotinfo{$which}) eq 'HASH') {
 9680: 	return %{$slotinfo{$which}};
 9681:     }
 9682:     return $slotinfo{$which};
 9683: }
 9684: 
 9685: sub get_reservable_slots {
 9686:     my ($cnum,$cdom,$uname,$udom) = @_;
 9687:     my $now = time;
 9688:     my $reservable_info;
 9689:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9690:     if (exists($remembered{$key})) {
 9691:         $reservable_info = $remembered{$key};
 9692:     } else {
 9693:         my %resv;
 9694:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9695:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9696:         $reservable_info = \%resv;
 9697:         $remembered{$key} = $reservable_info;
 9698:     }
 9699:     return $reservable_info;
 9700: }
 9701: 
 9702: sub get_course_slots {
 9703:     my ($cnum,$cdom) = @_;
 9704:     my $hashid=$cnum.':'.$cdom;
 9705:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9706:     if (defined($cached)) {
 9707:         if (ref($result) eq 'HASH') {
 9708:             return %{$result};
 9709:         }
 9710:     } else {
 9711:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9712:         my ($tmp) = keys(%slots);
 9713:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9714:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9715:             return %slots;
 9716:         }
 9717:     }
 9718:     return;
 9719: }
 9720: 
 9721: sub devalidate_slots_cache {
 9722:     my ($cnum,$cdom)=@_;
 9723:     my $hashid=$cnum.':'.$cdom;
 9724:     &devalidate_cache_new('allslots',$hashid);
 9725: }
 9726: 
 9727: # ------------------------------------------------- Update symbolic store links
 9728: 
 9729: sub symblist {
 9730:     my ($mapname,%newhash)=@_;
 9731:     $mapname=&deversion(&declutter($mapname));
 9732:     my %hash;
 9733:     if (($env{'request.course.fn'}) && (%newhash)) {
 9734:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9735:                       &GDBM_WRCREAT(),0640)) {
 9736: 	    foreach my $url (keys(%newhash)) {
 9737: 		next if ($url eq 'last_known'
 9738: 			 && $env{'form.no_update_last_known'});
 9739: 		$hash{declutter($url)}=&encode_symb($mapname,
 9740: 						    $newhash{$url}->[1],
 9741: 						    $newhash{$url}->[0]);
 9742:             }
 9743:             if (untie(%hash)) {
 9744: 		return 'ok';
 9745:             }
 9746:         }
 9747:     }
 9748:     return 'error';
 9749: }
 9750: 
 9751: # --------------------------------------------------------------- Verify a symb
 9752: 
 9753: sub symbverify {
 9754:     my ($symb,$thisurl)=@_;
 9755:     my $thisfn=$thisurl;
 9756:     $thisfn=&declutter($thisfn);
 9757: # direct jump to resource in page or to a sequence - will construct own symbs
 9758:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9759: # check URL part
 9760:     my ($map,$resid,$url)=&decode_symb($symb);
 9761: 
 9762:     unless ($url eq $thisfn) { return 0; }
 9763: 
 9764:     $symb=&symbclean($symb);
 9765:     $thisurl=&deversion($thisurl);
 9766:     $thisfn=&deversion($thisfn);
 9767: 
 9768:     my %bighash;
 9769:     my $okay=0;
 9770: 
 9771:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9772:                             &GDBM_READER(),0640)) {
 9773:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9774:             $thisurl =~ s/\?.+$//;
 9775:         }
 9776:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9777:         unless ($ids) {
 9778:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9779:             $ids=$bighash{$idkey};
 9780:         }
 9781:         if ($ids) {
 9782: # ------------------------------------------------------------------- Has ID(s)
 9783: 	    foreach my $id (split(/\,/,$ids)) {
 9784: 	       my ($mapid,$resid)=split(/\./,$id);
 9785:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9786:                    $symb =~ s/\?.+$//;
 9787:                }
 9788:                if (
 9789:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9790:    eq $symb) { 
 9791: 		   if (($env{'request.role.adv'}) ||
 9792: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9793:                        ($thisurl eq '/adm/navmaps')) {
 9794: 		       $okay=1; 
 9795: 		   }
 9796: 	       }
 9797: 	   }
 9798:         }
 9799: 	untie(%bighash);
 9800:     }
 9801:     return $okay;
 9802: }
 9803: 
 9804: # --------------------------------------------------------------- Clean-up symb
 9805: 
 9806: sub symbclean {
 9807:     my $symb=shift;
 9808:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9809: # remove version from map
 9810:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9811: 
 9812: # remove version from URL
 9813:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9814: 
 9815: # remove wrapper
 9816: 
 9817:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9818:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9819:     return $symb;
 9820: }
 9821: 
 9822: # ---------------------------------------------- Split symb to find map and url
 9823: 
 9824: sub encode_symb {
 9825:     my ($map,$resid,$url)=@_;
 9826:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9827: }
 9828: 
 9829: sub decode_symb {
 9830:     my $symb=shift;
 9831:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9832:     my ($map,$resid,$url)=split(/___/,$symb);
 9833:     return (&fixversion($map),$resid,&fixversion($url));
 9834: }
 9835: 
 9836: sub fixversion {
 9837:     my $fn=shift;
 9838:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9839:     my %bighash;
 9840:     my $uri=&clutter($fn);
 9841:     my $key=$env{'request.course.id'}.'_'.$uri;
 9842: # is this cached?
 9843:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9844:     if (defined($cached)) { return $result; }
 9845: # unfortunately not cached, or expired
 9846:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9847: 	    &GDBM_READER(),0640)) {
 9848:  	if ($bighash{'version_'.$uri}) {
 9849:  	    my $version=$bighash{'version_'.$uri};
 9850:  	    unless (($version eq 'mostrecent') || 
 9851: 		    ($version==&getversion($uri))) {
 9852:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9853:  	    }
 9854:  	}
 9855:  	untie %bighash;
 9856:     }
 9857:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9858: }
 9859: 
 9860: sub deversion {
 9861:     my $url=shift;
 9862:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9863:     return $url;
 9864: }
 9865: 
 9866: # ------------------------------------------------------ Return symb list entry
 9867: 
 9868: sub symbread {
 9869:     my ($thisfn,$donotrecurse)=@_;
 9870:     my $cache_str='request.symbread.cached.'.$thisfn;
 9871:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9872: # no filename provided? try from environment
 9873:     unless ($thisfn) {
 9874:         if ($env{'request.symb'}) {
 9875: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9876: 	}
 9877: 	$thisfn=$env{'request.filename'};
 9878:     }
 9879:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9880: # is that filename actually a symb? Verify, clean, and return
 9881:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9882: 	if (&symbverify($thisfn,$1)) {
 9883: 	    return $env{$cache_str}=&symbclean($thisfn);
 9884: 	}
 9885:     }
 9886:     $thisfn=declutter($thisfn);
 9887:     my %hash;
 9888:     my %bighash;
 9889:     my $syval='';
 9890:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9891:         my $targetfn = $thisfn;
 9892:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9893:             $targetfn = 'adm/wrapper/'.$thisfn;
 9894:         }
 9895: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9896: 	    $targetfn=$1;
 9897: 	}
 9898:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9899:                       &GDBM_READER(),0640)) {
 9900: 	    $syval=$hash{$targetfn};
 9901:             untie(%hash);
 9902:         }
 9903: # ---------------------------------------------------------- There was an entry
 9904:         if ($syval) {
 9905: 	    #unless ($syval=~/\_\d+$/) {
 9906: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9907: 		    #&appenv({'request.ambiguous' => $thisfn});
 9908: 		    #return $env{$cache_str}='';
 9909: 		#}    
 9910: 		#$syval.=$1;
 9911: 	    #}
 9912:         } else {
 9913: # ------------------------------------------------------- Was not in symb table
 9914:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9915:                             &GDBM_READER(),0640)) {
 9916: # ---------------------------------------------- Get ID(s) for current resource
 9917:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 9918:               unless ($ids) { 
 9919:                  $ids=$bighash{'ids_/'.$thisfn};
 9920:               }
 9921:               unless ($ids) {
 9922: # alias?
 9923: 		  $ids=$bighash{'mapalias_'.$thisfn};
 9924:               }
 9925:               if ($ids) {
 9926: # ------------------------------------------------------------------- Has ID(s)
 9927:                  my @possibilities=split(/\,/,$ids);
 9928:                  if ($#possibilities==0) {
 9929: # ----------------------------------------------- There is only one possibility
 9930: 		     my ($mapid,$resid)=split(/\./,$ids);
 9931: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9932: 						    $resid,$thisfn);
 9933:                  } elsif (!$donotrecurse) {
 9934: # ------------------------------------------ There is more than one possibility
 9935:                      my $realpossible=0;
 9936:                      foreach my $id (@possibilities) {
 9937: 			 my $file=$bighash{'src_'.$id};
 9938:                          if (&allowed('bre',$file)) {
 9939:          		    my ($mapid,$resid)=split(/\./,$id);
 9940:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 9941: 				$realpossible++;
 9942:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9943: 						    $resid,$thisfn);
 9944:                             }
 9945: 			 }
 9946:                      }
 9947: 		     if ($realpossible!=1) { $syval=''; }
 9948:                  } else {
 9949:                      $syval='';
 9950:                  }
 9951: 	      }
 9952:               untie(%bighash)
 9953:            }
 9954:         }
 9955:         if ($syval) {
 9956: 	    return $env{$cache_str}=$syval;
 9957:         }
 9958:     }
 9959:     &appenv({'request.ambiguous' => $thisfn});
 9960:     return $env{$cache_str}='';
 9961: }
 9962: 
 9963: # ---------------------------------------------------------- Return random seed
 9964: 
 9965: sub numval {
 9966:     my $txt=shift;
 9967:     $txt=~tr/A-J/0-9/;
 9968:     $txt=~tr/a-j/0-9/;
 9969:     $txt=~tr/K-T/0-9/;
 9970:     $txt=~tr/k-t/0-9/;
 9971:     $txt=~tr/U-Z/0-5/;
 9972:     $txt=~tr/u-z/0-5/;
 9973:     $txt=~s/\D//g;
 9974:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 9975:     return int($txt);
 9976: }
 9977: 
 9978: sub numval2 {
 9979:     my $txt=shift;
 9980:     $txt=~tr/A-J/0-9/;
 9981:     $txt=~tr/a-j/0-9/;
 9982:     $txt=~tr/K-T/0-9/;
 9983:     $txt=~tr/k-t/0-9/;
 9984:     $txt=~tr/U-Z/0-5/;
 9985:     $txt=~tr/u-z/0-5/;
 9986:     $txt=~s/\D//g;
 9987:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9988:     my $total;
 9989:     foreach my $val (@txts) { $total+=$val; }
 9990:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 9991:     return int($total);
 9992: }
 9993: 
 9994: sub numval3 {
 9995:     use integer;
 9996:     my $txt=shift;
 9997:     $txt=~tr/A-J/0-9/;
 9998:     $txt=~tr/a-j/0-9/;
 9999:     $txt=~tr/K-T/0-9/;
10000:     $txt=~tr/k-t/0-9/;
10001:     $txt=~tr/U-Z/0-5/;
10002:     $txt=~tr/u-z/0-5/;
10003:     $txt=~s/\D//g;
10004:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10005:     my $total;
10006:     foreach my $val (@txts) { $total+=$val; }
10007:     if ($_64bit) { $total=(($total<<32)>>32); }
10008:     return $total;
10009: }
10010: 
10011: sub digest {
10012:     my ($data)=@_;
10013:     my $digest=&Digest::MD5::md5($data);
10014:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10015:     my ($e,$f);
10016:     {
10017:         use integer;
10018:         $e=($a+$b);
10019:         $f=($c+$d);
10020:         if ($_64bit) {
10021:             $e=(($e<<32)>>32);
10022:             $f=(($f<<32)>>32);
10023:         }
10024:     }
10025:     if (wantarray) {
10026: 	return ($e,$f);
10027:     } else {
10028: 	my $g;
10029: 	{
10030: 	    use integer;
10031: 	    $g=($e+$f);
10032: 	    if ($_64bit) {
10033: 		$g=(($g<<32)>>32);
10034: 	    }
10035: 	}
10036: 	return $g;
10037:     }
10038: }
10039: 
10040: sub latest_rnd_algorithm_id {
10041:     return '64bit5';
10042: }
10043: 
10044: sub get_rand_alg {
10045:     my ($courseid)=@_;
10046:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10047:     if ($courseid) {
10048: 	return $env{"course.$courseid.rndseed"};
10049:     }
10050:     return &latest_rnd_algorithm_id();
10051: }
10052: 
10053: sub validCODE {
10054:     my ($CODE)=@_;
10055:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10056:     return 0;
10057: }
10058: 
10059: sub getCODE {
10060:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10061:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10062: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10063: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10064: 	return $Apache::lonhomework::history{'resource.CODE'};
10065:     }
10066:     return undef;
10067: }
10068: #
10069: #  Determines the random seed for a specific context:
10070: #
10071: # parameters:
10072: #   symb      - in course context the symb for the seed.
10073: #   course_id - The course id of the form domain_coursenum.
10074: #   domain    - Domain for the user.
10075: #   course    - Course for the user.
10076: #   cenv      - environment of the course.
10077: #
10078: # NOTE:
10079: #   All parameters are picked out of the environment if missing
10080: #   or not defined.
10081: #   If a symb cannot be determined the current time is used instead.
10082: #
10083: #  For a given well defined symb, courside, domain, username,
10084: #  and course environment, the seed is reproducible.
10085: #
10086: sub rndseed {
10087:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10088:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10089:     if (!defined($symb)) {
10090: 	unless ($symb=$wsymb) { return time; }
10091:     }
10092:     if (!defined $courseid) { 
10093: 	$courseid=$wcourseid; 
10094:     }
10095:     if (!defined $domain) { $domain=$wdomain; }
10096:     if (!defined $username) { $username=$wusername }
10097: 
10098:     my $which;
10099:     if (defined($cenv->{'rndseed'})) {
10100: 	$which = $cenv->{'rndseed'};
10101:     } else {
10102: 	$which =&get_rand_alg($courseid);
10103:     }
10104:     if (defined(&getCODE())) {
10105: 
10106: 	if ($which eq '64bit5') {
10107: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10108: 	} elsif ($which eq '64bit4') {
10109: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10110: 	} else {
10111: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10112: 	}
10113:     } elsif ($which eq '64bit5') {
10114: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10115:     } elsif ($which eq '64bit4') {
10116: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10117:     } elsif ($which eq '64bit3') {
10118: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10119:     } elsif ($which eq '64bit2') {
10120: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10121:     } elsif ($which eq '64bit') {
10122: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10123:     }
10124:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10125: }
10126: 
10127: sub rndseed_32bit {
10128:     my ($symb,$courseid,$domain,$username)=@_;
10129:     {
10130: 	use integer;
10131: 	my $symbchck=unpack("%32C*",$symb) << 27;
10132: 	my $symbseed=numval($symb) << 22;
10133: 	my $namechck=unpack("%32C*",$username) << 17;
10134: 	my $nameseed=numval($username) << 12;
10135: 	my $domainseed=unpack("%32C*",$domain) << 7;
10136: 	my $courseseed=unpack("%32C*",$courseid);
10137: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10138: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10139: 	#&logthis("rndseed :$num:$symb");
10140: 	if ($_64bit) { $num=(($num<<32)>>32); }
10141: 	return $num;
10142:     }
10143: }
10144: 
10145: sub rndseed_64bit {
10146:     my ($symb,$courseid,$domain,$username)=@_;
10147:     {
10148: 	use integer;
10149: 	my $symbchck=unpack("%32S*",$symb) << 21;
10150: 	my $symbseed=numval($symb) << 10;
10151: 	my $namechck=unpack("%32S*",$username);
10152: 	
10153: 	my $nameseed=numval($username) << 21;
10154: 	my $domainseed=unpack("%32S*",$domain) << 10;
10155: 	my $courseseed=unpack("%32S*",$courseid);
10156: 	
10157: 	my $num1=$symbchck+$symbseed+$namechck;
10158: 	my $num2=$nameseed+$domainseed+$courseseed;
10159: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10160: 	#&logthis("rndseed :$num:$symb");
10161: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10162: 	return "$num1,$num2";
10163:     }
10164: }
10165: 
10166: sub rndseed_64bit2 {
10167:     my ($symb,$courseid,$domain,$username)=@_;
10168:     {
10169: 	use integer;
10170: 	# strings need to be an even # of cahracters long, it it is odd the
10171:         # last characters gets thrown away
10172: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10173: 	my $symbseed=numval($symb) << 10;
10174: 	my $namechck=unpack("%32S*",$username.' ');
10175: 	
10176: 	my $nameseed=numval($username) << 21;
10177: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10178: 	my $courseseed=unpack("%32S*",$courseid.' ');
10179: 	
10180: 	my $num1=$symbchck+$symbseed+$namechck;
10181: 	my $num2=$nameseed+$domainseed+$courseseed;
10182: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10183: 	#&logthis("rndseed :$num:$symb");
10184: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10185: 	return "$num1,$num2";
10186:     }
10187: }
10188: 
10189: sub rndseed_64bit3 {
10190:     my ($symb,$courseid,$domain,$username)=@_;
10191:     {
10192: 	use integer;
10193: 	# strings need to be an even # of cahracters long, it it is odd the
10194:         # last characters gets thrown away
10195: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10196: 	my $symbseed=numval2($symb) << 10;
10197: 	my $namechck=unpack("%32S*",$username.' ');
10198: 	
10199: 	my $nameseed=numval2($username) << 21;
10200: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10201: 	my $courseseed=unpack("%32S*",$courseid.' ');
10202: 	
10203: 	my $num1=$symbchck+$symbseed+$namechck;
10204: 	my $num2=$nameseed+$domainseed+$courseseed;
10205: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10206: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10207: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10208: 	
10209: 	return "$num1:$num2";
10210:     }
10211: }
10212: 
10213: sub rndseed_64bit4 {
10214:     my ($symb,$courseid,$domain,$username)=@_;
10215:     {
10216: 	use integer;
10217: 	# strings need to be an even # of cahracters long, it it is odd the
10218:         # last characters gets thrown away
10219: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10220: 	my $symbseed=numval3($symb) << 10;
10221: 	my $namechck=unpack("%32S*",$username.' ');
10222: 	
10223: 	my $nameseed=numval3($username) << 21;
10224: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10225: 	my $courseseed=unpack("%32S*",$courseid.' ');
10226: 	
10227: 	my $num1=$symbchck+$symbseed+$namechck;
10228: 	my $num2=$nameseed+$domainseed+$courseseed;
10229: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10230: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10231: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10232: 	
10233: 	return "$num1:$num2";
10234:     }
10235: }
10236: 
10237: sub rndseed_64bit5 {
10238:     my ($symb,$courseid,$domain,$username)=@_;
10239:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10240:     return "$num1:$num2";
10241: }
10242: 
10243: sub rndseed_CODE_64bit {
10244:     my ($symb,$courseid,$domain,$username)=@_;
10245:     {
10246: 	use integer;
10247: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10248: 	my $symbseed=numval2($symb);
10249: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10250: 	my $CODEseed=numval(&getCODE());
10251: 	my $courseseed=unpack("%32S*",$courseid.' ');
10252: 	my $num1=$symbseed+$CODEchck;
10253: 	my $num2=$CODEseed+$courseseed+$symbchck;
10254: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10255: 	#&logthis("rndseed :$num1:$num2:$symb");
10256: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10257: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10258: 	return "$num1:$num2";
10259:     }
10260: }
10261: 
10262: sub rndseed_CODE_64bit4 {
10263:     my ($symb,$courseid,$domain,$username)=@_;
10264:     {
10265: 	use integer;
10266: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10267: 	my $symbseed=numval3($symb);
10268: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10269: 	my $CODEseed=numval3(&getCODE());
10270: 	my $courseseed=unpack("%32S*",$courseid.' ');
10271: 	my $num1=$symbseed+$CODEchck;
10272: 	my $num2=$CODEseed+$courseseed+$symbchck;
10273: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10274: 	#&logthis("rndseed :$num1:$num2:$symb");
10275: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10276: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10277: 	return "$num1:$num2";
10278:     }
10279: }
10280: 
10281: sub rndseed_CODE_64bit5 {
10282:     my ($symb,$courseid,$domain,$username)=@_;
10283:     my $code = &getCODE();
10284:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10285:     return "$num1:$num2";
10286: }
10287: 
10288: sub setup_random_from_rndseed {
10289:     my ($rndseed)=@_;
10290:     if ($rndseed =~/([,:])/) {
10291: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10292: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10293:     } else {
10294: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10295:     }
10296: }
10297: 
10298: sub latest_receipt_algorithm_id {
10299:     return 'receipt3';
10300: }
10301: 
10302: sub recunique {
10303:     my $fucourseid=shift;
10304:     my $unique;
10305:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10306: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10307: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10308:     } else {
10309: 	$unique=$perlvar{'lonReceipt'};
10310:     }
10311:     return unpack("%32C*",$unique);
10312: }
10313: 
10314: sub recprefix {
10315:     my $fucourseid=shift;
10316:     my $prefix;
10317:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10318: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10319: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10320:     } else {
10321: 	$prefix=$perlvar{'lonHostID'};
10322:     }
10323:     return unpack("%32C*",$prefix);
10324: }
10325: 
10326: sub ireceipt {
10327:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10328: 
10329:     my $return =&recprefix($fucourseid).'-';
10330: 
10331:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10332: 	$env{'request.state'} eq 'construct') {
10333: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10334: 	return $return;
10335:     }
10336: 
10337:     my $cuname=unpack("%32C*",$funame);
10338:     my $cudom=unpack("%32C*",$fudom);
10339:     my $cucourseid=unpack("%32C*",$fucourseid);
10340:     my $cusymb=unpack("%32C*",$fusymb);
10341:     my $cunique=&recunique($fucourseid);
10342:     my $cpart=unpack("%32S*",$part);
10343:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10344: 
10345: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10346: 			       
10347: 	$return.= ($cunique%$cuname+
10348: 		   $cunique%$cudom+
10349: 		   $cusymb%$cuname+
10350: 		   $cusymb%$cudom+
10351: 		   $cucourseid%$cuname+
10352: 		   $cucourseid%$cudom+
10353: 		   $cpart%$cuname+
10354: 		   $cpart%$cudom);
10355:     } else {
10356: 	$return.= ($cunique%$cuname+
10357: 		   $cunique%$cudom+
10358: 		   $cusymb%$cuname+
10359: 		   $cusymb%$cudom+
10360: 		   $cucourseid%$cuname+
10361: 		   $cucourseid%$cudom);
10362:     }
10363:     return $return;
10364: }
10365: 
10366: sub receipt {
10367:     my ($part)=@_;
10368:     my ($symb,$courseid,$domain,$name) = &whichuser();
10369:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10370: }
10371: 
10372: sub whichuser {
10373:     my ($passedsymb)=@_;
10374:     my ($symb,$courseid,$domain,$name,$publicuser);
10375:     if (defined($env{'form.grade_symb'})) {
10376: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10377: 	my $allowed=&allowed('vgr',$tmp_courseid);
10378: 	if (!$allowed &&
10379: 	    exists($env{'request.course.sec'}) &&
10380: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10381: 	    $allowed=&allowed('vgr',$tmp_courseid.
10382: 			      '/'.$env{'request.course.sec'});
10383: 	}
10384: 	if ($allowed) {
10385: 	    ($symb)=&get_env_multiple('form.grade_symb');
10386: 	    $courseid=$tmp_courseid;
10387: 	    ($domain)=&get_env_multiple('form.grade_domain');
10388: 	    ($name)=&get_env_multiple('form.grade_username');
10389: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10390: 	}
10391:     }
10392:     if (!$passedsymb) {
10393: 	$symb=&symbread();
10394:     } else {
10395: 	$symb=$passedsymb;
10396:     }
10397:     $courseid=$env{'request.course.id'};
10398:     $domain=$env{'user.domain'};
10399:     $name=$env{'user.name'};
10400:     if ($name eq 'public' && $domain eq 'public') {
10401: 	if (!defined($env{'form.username'})) {
10402: 	    $env{'form.username'}.=time.rand(10000000);
10403: 	}
10404: 	$name.=$env{'form.username'};
10405:     }
10406:     return ($symb,$courseid,$domain,$name,$publicuser);
10407: 
10408: }
10409: 
10410: # ------------------------------------------------------------ Serves up a file
10411: # returns either the contents of the file or 
10412: # -1 if the file doesn't exist
10413: #
10414: # if the target is a file that was uploaded via DOCS, 
10415: # a check will be made to see if a current copy exists on the local server,
10416: # if it does this will be served, otherwise a copy will be retrieved from
10417: # the home server for the course and stored in /home/httpd/html/userfiles on
10418: # the local server.   
10419: 
10420: sub getfile {
10421:     my ($file) = @_;
10422:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10423:     &repcopy($file);
10424:     return &readfile($file);
10425: }
10426: 
10427: sub repcopy_userfile {
10428:     my ($file)=@_;
10429:     my $londocroot = $perlvar{'lonDocRoot'};
10430:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10431:     if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
10432:     my ($cdom,$cnum,$filename) = 
10433: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10434:     my $uri="/uploaded/$cdom/$cnum/$filename";
10435:     if (-e "$file") {
10436: # we already have a local copy, check it out
10437: 	my @fileinfo = stat($file);
10438: 	my $rtncode;
10439: 	my $info;
10440: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10441: 	if ($lwpresp ne 'ok') {
10442: # there is no such file anymore, even though we had a local copy
10443: 	    if ($rtncode eq '404') {
10444: 		unlink($file);
10445: 	    }
10446: 	    return -1;
10447: 	}
10448: 	if ($info < $fileinfo[9]) {
10449: # nice, the file we have is up-to-date, just say okay
10450: 	    return 'ok';
10451: 	} else {
10452: # the file is outdated, get rid of it
10453: 	    unlink($file);
10454: 	}
10455:     }
10456: # one way or the other, at this point, we don't have the file
10457: # construct the correct path for the file
10458:     my @parts = ($cdom,$cnum); 
10459:     if ($filename =~ m|^(.+)/[^/]+$|) {
10460: 	push @parts, split(/\//,$1);
10461:     }
10462:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10463:     foreach my $part (@parts) {
10464: 	$path .= '/'.$part;
10465: 	if (!-e $path) {
10466: 	    mkdir($path,0770);
10467: 	}
10468:     }
10469: # now the path exists for sure
10470: # get a user agent
10471:     my $ua=new LWP::UserAgent;
10472:     my $transferfile=$file.'.in.transfer';
10473: # FIXME: this should flock
10474:     if (-e $transferfile) { return 'ok'; }
10475:     my $request;
10476:     $uri=~s/^\///;
10477:     my $homeserver = &homeserver($cnum,$cdom);
10478:     my $protocol = $protocol{$homeserver};
10479:     $protocol = 'http' if ($protocol ne 'https');
10480:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10481:     my $response=$ua->request($request,$transferfile);
10482: # did it work?
10483:     if ($response->is_error()) {
10484: 	unlink($transferfile);
10485: 	&logthis("Userfile repcopy failed for $uri");
10486: 	return -1;
10487:     }
10488: # worked, rename the transfer file
10489:     rename($transferfile,$file);
10490:     return 'ok';
10491: }
10492: 
10493: sub tokenwrapper {
10494:     my $uri=shift;
10495:     $uri=~s|^https?\://([^/]+)||;
10496:     $uri=~s|^/||;
10497:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10498:     my $token=$1;
10499:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10500:     if ($udom && $uname && $file) {
10501: 	$file=~s|(\?\.*)*$||;
10502:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10503:         my $homeserver = &homeserver($uname,$udom);
10504:         my $protocol = $protocol{$homeserver};
10505:         $protocol = 'http' if ($protocol ne 'https');
10506:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10507:                (($uri=~/\?/)?'&':'?').'token='.$token.
10508:                                '&tokenissued='.$perlvar{'lonHostID'};
10509:     } else {
10510:         return '/adm/notfound.html';
10511:     }
10512: }
10513: 
10514: # call with reqtype HEAD: get last modification time
10515: # call with reqtype GET: get the file contents
10516: # Do not call this with reqtype GET for large files! It loads everything into memory
10517: #
10518: sub getuploaded {
10519:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10520:     $uri=~s/^\///;
10521:     my $homeserver = &homeserver($cnum,$cdom);
10522:     my $protocol = $protocol{$homeserver};
10523:     $protocol = 'http' if ($protocol ne 'https');
10524:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10525:     my $ua=new LWP::UserAgent;
10526:     my $request=new HTTP::Request($reqtype,$uri);
10527:     my $response=$ua->request($request);
10528:     $$rtncode = $response->code;
10529:     if (! $response->is_success()) {
10530: 	return 'failed';
10531:     }      
10532:     if ($reqtype eq 'HEAD') {
10533: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10534:     } elsif ($reqtype eq 'GET') {
10535: 	$$info = $response->content;
10536:     }
10537:     return 'ok';
10538: }
10539: 
10540: sub readfile {
10541:     my $file = shift;
10542:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10543:     my $fh;
10544:     open($fh,"<$file");
10545:     my $a='';
10546:     while (my $line = <$fh>) { $a .= $line; }
10547:     return $a;
10548: }
10549: 
10550: sub filelocation {
10551:     my ($dir,$file) = @_;
10552:     my $location;
10553:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10554: 
10555:     if ($file =~ m-^/adm/-) {
10556: 	$file=~s-^/adm/wrapper/-/-;
10557: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10558:     }
10559: 
10560:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10561:         $location = $file;
10562:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10563:         my ($udom,$uname,$filename)=
10564:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10565:         my $home=&homeserver($uname,$udom);
10566:         my $is_me=0;
10567:         my @ids=&current_machine_ids();
10568:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10569:         if ($is_me) {
10570:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10571:         } else {
10572:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10573:   	      $udom.'/'.$uname.'/'.$filename;
10574:         }
10575:     } elsif ($file =~ m-^/adm/-) {
10576: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10577:     } else {
10578:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10579:         $file=~s:^/(res|priv)/:/:;
10580:         my $space=$1;
10581:         if ( !( $file =~ m:^/:) ) {
10582:             $location = $dir. '/'.$file;
10583:         } else {
10584:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10585:         }
10586:     }
10587:     $location=~s://+:/:g; # remove duplicate /
10588:     while ($location=~m{/\.\./}) {
10589: 	if ($location =~ m{/[^/]+/\.\./}) {
10590: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10591: 	} else {
10592: 	    $location=~ s{/\.\./}{/}g;
10593: 	}
10594:     } #remove dir/..
10595:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10596:     return $location;
10597: }
10598: 
10599: sub hreflocation {
10600:     my ($dir,$file)=@_;
10601:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10602: 	$file=filelocation($dir,$file);
10603:     } elsif ($file=~m-^/adm/-) {
10604: 	$file=~s-^/adm/wrapper/-/-;
10605: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10606:     }
10607:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10608: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10609:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10610: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10611: 	        {/uploaded/$1/$2/}x;
10612:     }
10613:     if ($file=~ m{^/userfiles/}) {
10614: 	$file =~ s{^/userfiles/}{/uploaded/};
10615:     }
10616:     return $file;
10617: }
10618: 
10619: 
10620: 
10621: 
10622: 
10623: sub current_machine_domains {
10624:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10625: }
10626: 
10627: sub machine_domains {
10628:     my ($hostname) = @_;
10629:     my @domains;
10630:     my %hostname = &all_hostnames();
10631:     while( my($id, $name) = each(%hostname)) {
10632: #	&logthis("-$id-$name-$hostname-");
10633: 	if ($hostname eq $name) {
10634: 	    push(@domains,&host_domain($id));
10635: 	}
10636:     }
10637:     return @domains;
10638: }
10639: 
10640: sub current_machine_ids {
10641:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10642: }
10643: 
10644: sub machine_ids {
10645:     my ($hostname) = @_;
10646:     $hostname ||= &hostname($perlvar{'lonHostID'});
10647:     my @ids;
10648:     my %name_to_host = &all_names();
10649:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10650: 	return @{ $name_to_host{$hostname} };
10651:     }
10652:     return;
10653: }
10654: 
10655: sub additional_machine_domains {
10656:     my @domains;
10657:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10658:     while( my $line = <$fh>) {
10659:         $line =~ s/\s//g;
10660:         push(@domains,$line);
10661:     }
10662:     return @domains;
10663: }
10664: 
10665: sub default_login_domain {
10666:     my $domain = $perlvar{'lonDefDomain'};
10667:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10668:     foreach my $posdom (&current_machine_domains(),
10669:                         &additional_machine_domains()) {
10670:         if (lc($posdom) eq lc($testdomain)) {
10671:             $domain=$posdom;
10672:             last;
10673:         }
10674:     }
10675:     return $domain;
10676: }
10677: 
10678: # ------------------------------------------------------------- Declutters URLs
10679: 
10680: sub declutter {
10681:     my $thisfn=shift;
10682:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10683:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10684:     $thisfn=~s/^\///;
10685:     $thisfn=~s|^adm/wrapper/||;
10686:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10687:     $thisfn=~s/^res\///;
10688:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10689:         $thisfn=~s/\?.+$//;
10690:     }
10691:     return $thisfn;
10692: }
10693: 
10694: # ------------------------------------------------------------- Clutter up URLs
10695: 
10696: sub clutter {
10697:     my $thisfn='/'.&declutter(shift);
10698:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10699: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10700:        $thisfn='/res'.$thisfn; 
10701:     }
10702:     if ($thisfn !~m|^/adm|) {
10703: 	if ($thisfn =~ m|^/ext/|) {
10704: 	    $thisfn='/adm/wrapper'.$thisfn;
10705: 	} else {
10706: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10707: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10708: 	    if ($embstyle eq 'ssi'
10709: 		|| ($embstyle eq 'hdn')
10710: 		|| ($embstyle eq 'rat')
10711: 		|| ($embstyle eq 'prv')
10712: 		|| ($embstyle eq 'ign')) {
10713: 		#do nothing with these
10714: 	    } elsif (($embstyle eq 'img') 
10715: 		|| ($embstyle eq 'emb')
10716: 		|| ($embstyle eq 'wrp')) {
10717: 		$thisfn='/adm/wrapper'.$thisfn;
10718: 	    } elsif ($embstyle eq 'unk'
10719: 		     && $thisfn!~/\.(sequence|page)$/) {
10720: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10721: 	    } else {
10722: #		&logthis("Got a blank emb style");
10723: 	    }
10724: 	}
10725:     }
10726:     return $thisfn;
10727: }
10728: 
10729: sub clutter_with_no_wrapper {
10730:     my $uri = &clutter(shift);
10731:     if ($uri =~ m-^/adm/-) {
10732: 	$uri =~ s-^/adm/wrapper/-/-;
10733: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10734:     }
10735:     return $uri;
10736: }
10737: 
10738: sub freeze_escape {
10739:     my ($value)=@_;
10740:     if (ref($value)) {
10741: 	$value=&nfreeze($value);
10742: 	return '__FROZEN__'.&escape($value);
10743:     }
10744:     return &escape($value);
10745: }
10746: 
10747: 
10748: sub thaw_unescape {
10749:     my ($value)=@_;
10750:     if ($value =~ /^__FROZEN__/) {
10751: 	substr($value,0,10,undef);
10752: 	$value=&unescape($value);
10753: 	return &thaw($value);
10754:     }
10755:     return &unescape($value);
10756: }
10757: 
10758: sub correct_line_ends {
10759:     my ($result)=@_;
10760:     $$result =~s/\r\n/\n/mg;
10761:     $$result =~s/\r/\n/mg;
10762: }
10763: # ================================================================ Main Program
10764: 
10765: sub goodbye {
10766:    &logthis("Starting Shut down");
10767: #not converted to using infrastruture and probably shouldn't be
10768:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10769: #converted
10770: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10771:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10772: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10773: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10774: #1.1 only
10775: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10776: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10777: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10778: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10779:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10780:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10781:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10782:    &flushcourselogs();
10783:    &logthis("Shutting down");
10784: }
10785: 
10786: sub get_dns {
10787:     my ($url,$func,$ignore_cache) = @_;
10788:     if (!$ignore_cache) {
10789: 	my ($content,$cached)=
10790: 	    &Apache::lonnet::is_cached_new('dns',$url);
10791: 	if ($cached) {
10792: 	    &$func($content);
10793: 	    return;
10794: 	}
10795:     }
10796: 
10797:     my %alldns;
10798:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10799:     foreach my $dns (<$config>) {
10800: 	next if ($dns !~ /^\^(\S*)/x);
10801:         my $line = $1;
10802:         my ($host,$protocol) = split(/:/,$line);
10803:         if ($protocol ne 'https') {
10804:             $protocol = 'http';
10805:         }
10806: 	$alldns{$host} = $protocol;
10807:     }
10808:     while (%alldns) {
10809: 	my ($dns) = keys(%alldns);
10810: 	my $ua=new LWP::UserAgent;
10811:         $ua->timeout(30);
10812: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10813: 	my $response=$ua->request($request);
10814:         delete($alldns{$dns});
10815: 	next if ($response->is_error());
10816: 	my @content = split("\n",$response->content);
10817: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10818: 	&$func(\@content);
10819: 	return;
10820:     }
10821:     close($config);
10822:     my $which = (split('/',$url))[3];
10823:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10824:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10825:     my @content = <$config>;
10826:     &$func(\@content);
10827:     return;
10828: }
10829: # ------------------------------------------------------------ Read domain file
10830: {
10831:     my $loaded;
10832:     my %domain;
10833: 
10834:     sub parse_domain_tab {
10835: 	my ($lines) = @_;
10836: 	foreach my $line (@$lines) {
10837: 	    next if ($line =~ /^(\#|\s*$ )/x);
10838: 
10839: 	    chomp($line);
10840: 	    my ($name,@elements) = split(/:/,$line,9);
10841: 	    my %this_domain;
10842: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10843: 			       'lang_def', 'city', 'longi', 'lati',
10844: 			       'primary') {
10845: 		$this_domain{$field} = shift(@elements);
10846: 	    }
10847: 	    $domain{$name} = \%this_domain;
10848: 	}
10849:     }
10850: 
10851:     sub reset_domain_info {
10852: 	undef($loaded);
10853: 	undef(%domain);
10854:     }
10855: 
10856:     sub load_domain_tab {
10857: 	my ($ignore_cache) = @_;
10858: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10859: 	my $fh;
10860: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10861: 	    my @lines = <$fh>;
10862: 	    &parse_domain_tab(\@lines);
10863: 	}
10864: 	close($fh);
10865: 	$loaded = 1;
10866:     }
10867: 
10868:     sub domain {
10869: 	&load_domain_tab() if (!$loaded);
10870: 
10871: 	my ($name,$what) = @_;
10872: 	return if ( !exists($domain{$name}) );
10873: 
10874: 	if (!$what) {
10875: 	    return $domain{$name}{'description'};
10876: 	}
10877: 	return $domain{$name}{$what};
10878:     }
10879: 
10880:     sub domain_info {
10881:         &load_domain_tab() if (!$loaded);
10882:         return %domain;
10883:     }
10884: 
10885: }
10886: 
10887: 
10888: # ------------------------------------------------------------- Read hosts file
10889: {
10890:     my %hostname;
10891:     my %hostdom;
10892:     my %libserv;
10893:     my $loaded;
10894:     my %name_to_host;
10895:     my %internetdom;
10896:     my %LC_dns_serv;
10897: 
10898:     sub parse_hosts_tab {
10899: 	my ($file) = @_;
10900: 	foreach my $configline (@$file) {
10901: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10902:             chomp($configline);
10903: 	    if ($configline =~ /^\^/) {
10904:                 if ($configline =~ /^\^([\w.\-]+)/) {
10905:                     $LC_dns_serv{$1} = 1;
10906:                 }
10907:                 next;
10908:             }
10909: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10910: 	    $name=~s/\s//g;
10911: 	    if ($id && $domain && $role && $name) {
10912: 		$hostname{$id}=$name;
10913: 		push(@{$name_to_host{$name}}, $id);
10914: 		$hostdom{$id}=$domain;
10915: 		if ($role eq 'library') { $libserv{$id}=$name; }
10916:                 if (defined($protocol)) {
10917:                     if ($protocol eq 'https') {
10918:                         $protocol{$id} = $protocol;
10919:                     } else {
10920:                         $protocol{$id} = 'http'; 
10921:                     }
10922:                 } else {
10923:                     $protocol{$id} = 'http';
10924:                 }
10925:                 if (defined($intdom)) {
10926:                     $internetdom{$id} = $intdom;
10927:                 }
10928: 	    }
10929: 	}
10930:     }
10931:     
10932:     sub reset_hosts_info {
10933: 	&purge_remembered();
10934: 	&reset_domain_info();
10935: 	&reset_hosts_ip_info();
10936: 	undef(%name_to_host);
10937: 	undef(%hostname);
10938: 	undef(%hostdom);
10939: 	undef(%libserv);
10940: 	undef($loaded);
10941:     }
10942: 
10943:     sub load_hosts_tab {
10944: 	my ($ignore_cache) = @_;
10945: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10946: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10947: 	my @config = <$config>;
10948: 	&parse_hosts_tab(\@config);
10949: 	close($config);
10950: 	$loaded=1;
10951:     }
10952: 
10953:     sub hostname {
10954: 	&load_hosts_tab() if (!$loaded);
10955: 
10956: 	my ($lonid) = @_;
10957: 	return $hostname{$lonid};
10958:     }
10959: 
10960:     sub all_hostnames {
10961: 	&load_hosts_tab() if (!$loaded);
10962: 
10963: 	return %hostname;
10964:     }
10965: 
10966:     sub all_names {
10967: 	&load_hosts_tab() if (!$loaded);
10968: 
10969: 	return %name_to_host;
10970:     }
10971: 
10972:     sub all_host_domain {
10973:         &load_hosts_tab() if (!$loaded);
10974:         return %hostdom;
10975:     }
10976: 
10977:     sub is_library {
10978: 	&load_hosts_tab() if (!$loaded);
10979: 
10980: 	return exists($libserv{$_[0]});
10981:     }
10982: 
10983:     sub all_library {
10984: 	&load_hosts_tab() if (!$loaded);
10985: 
10986: 	return %libserv;
10987:     }
10988: 
10989:     sub unique_library {
10990: 	#2x reverse removes all hostnames that appear more than once
10991:         my %unique = reverse &all_library();
10992:         return reverse %unique;
10993:     }
10994: 
10995:     sub get_servers {
10996: 	&load_hosts_tab() if (!$loaded);
10997: 
10998: 	my ($domain,$type) = @_;
10999: 	my %possible_hosts = ($type eq 'library') ? %libserv
11000: 	                                          : %hostname;
11001: 	my %result;
11002: 	if (ref($domain) eq 'ARRAY') {
11003: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11004: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11005: 		    $result{$host} = $hostname;
11006: 		}
11007: 	    }
11008: 	} else {
11009: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11010: 		if ($hostdom{$host} eq $domain) {
11011: 		    $result{$host} = $hostname;
11012: 		}
11013: 	    }
11014: 	}
11015: 	return %result;
11016:     }
11017: 
11018:     sub get_unique_servers {
11019:         my %unique = reverse &get_servers(@_);
11020: 	return reverse %unique;
11021:     }
11022: 
11023:     sub host_domain {
11024: 	&load_hosts_tab() if (!$loaded);
11025: 
11026: 	my ($lonid) = @_;
11027: 	return $hostdom{$lonid};
11028:     }
11029: 
11030:     sub all_domains {
11031: 	&load_hosts_tab() if (!$loaded);
11032: 
11033: 	my %seen;
11034: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11035: 	return @uniq;
11036:     }
11037: 
11038:     sub internet_dom {
11039:         &load_hosts_tab() if (!$loaded);
11040: 
11041:         my ($lonid) = @_;
11042:         return $internetdom{$lonid};
11043:     }
11044: 
11045:     sub is_LC_dns {
11046:         &load_hosts_tab() if (!$loaded);
11047: 
11048:         my ($hostname) = @_;
11049:         return exists($LC_dns_serv{$hostname});
11050:     }
11051: 
11052: }
11053: 
11054: { 
11055:     my %iphost;
11056:     my %name_to_ip;
11057:     my %lonid_to_ip;
11058: 
11059:     sub get_hosts_from_ip {
11060: 	my ($ip) = @_;
11061: 	my %iphosts = &get_iphost();
11062: 	if (ref($iphosts{$ip})) {
11063: 	    return @{$iphosts{$ip}};
11064: 	}
11065: 	return;
11066:     }
11067:     
11068:     sub reset_hosts_ip_info {
11069: 	undef(%iphost);
11070: 	undef(%name_to_ip);
11071: 	undef(%lonid_to_ip);
11072:     }
11073: 
11074:     sub get_host_ip {
11075: 	my ($lonid) = @_;
11076: 	if (exists($lonid_to_ip{$lonid})) {
11077: 	    return $lonid_to_ip{$lonid};
11078: 	}
11079: 	my $name=&hostname($lonid);
11080:    	my $ip = gethostbyname($name);
11081: 	return if (!$ip || length($ip) ne 4);
11082: 	$ip=inet_ntoa($ip);
11083: 	$name_to_ip{$name}   = $ip;
11084: 	$lonid_to_ip{$lonid} = $ip;
11085: 	return $ip;
11086:     }
11087:     
11088:     sub get_iphost {
11089: 	my ($ignore_cache) = @_;
11090: 
11091: 	if (!$ignore_cache) {
11092: 	    if (%iphost) {
11093: 		return %iphost;
11094: 	    }
11095: 	    my ($ip_info,$cached)=
11096: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11097: 	    if ($cached) {
11098: 		%iphost      = %{$ip_info->[0]};
11099: 		%name_to_ip  = %{$ip_info->[1]};
11100: 		%lonid_to_ip = %{$ip_info->[2]};
11101: 		return %iphost;
11102: 	    }
11103: 	}
11104: 
11105: 	# get yesterday's info for fallback
11106: 	my %old_name_to_ip;
11107: 	my ($ip_info,$cached)=
11108: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11109: 	if ($cached) {
11110: 	    %old_name_to_ip = %{$ip_info->[1]};
11111: 	}
11112: 
11113: 	my %name_to_host = &all_names();
11114: 	foreach my $name (keys(%name_to_host)) {
11115: 	    my $ip;
11116: 	    if (!exists($name_to_ip{$name})) {
11117: 		$ip = gethostbyname($name);
11118: 		if (!$ip || length($ip) ne 4) {
11119: 		    if (defined($old_name_to_ip{$name})) {
11120: 			$ip = $old_name_to_ip{$name};
11121: 			&logthis("Can't find $name defaulting to old $ip");
11122: 		    } else {
11123: 			&logthis("Name $name no IP found");
11124: 			next;
11125: 		    }
11126: 		} else {
11127: 		    $ip=inet_ntoa($ip);
11128: 		}
11129: 		$name_to_ip{$name} = $ip;
11130: 	    } else {
11131: 		$ip = $name_to_ip{$name};
11132: 	    }
11133: 	    foreach my $id (@{ $name_to_host{$name} }) {
11134: 		$lonid_to_ip{$id} = $ip;
11135: 	    }
11136: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11137: 	}
11138: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11139: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11140: 				      48*60*60);
11141: 
11142: 	return %iphost;
11143:     }
11144: 
11145:     #
11146:     #  Given a DNS returns the loncapa host name for that DNS 
11147:     # 
11148:     sub host_from_dns {
11149:         my ($dns) = @_;
11150:         my @hosts;
11151:         my $ip;
11152: 
11153:         if (exists($name_to_ip{$dns})) {
11154:             $ip = $name_to_ip{$dns};
11155:         }
11156:         if (!$ip) {
11157:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11158:             if (length($ip) == 4) { 
11159: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11160:             }
11161:         }
11162:         if ($ip) {
11163: 	    @hosts = get_hosts_from_ip($ip);
11164: 	    return $hosts[0];
11165:         }
11166:         return undef;
11167:     }
11168: 
11169:     sub get_internet_names {
11170:         my ($lonid) = @_;
11171:         return if ($lonid eq '');
11172:         my ($idnref,$cached)=
11173:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11174:         if ($cached) {
11175:             return $idnref;
11176:         }
11177:         my $ip = &get_host_ip($lonid);
11178:         my @hosts = &get_hosts_from_ip($ip);
11179:         my %iphost = &get_iphost();
11180:         my (@idns,%seen);
11181:         foreach my $id (@hosts) {
11182:             my $dom = &host_domain($id);
11183:             my $prim_id = &domain($dom,'primary');
11184:             my $prim_ip = &get_host_ip($prim_id);
11185:             next if ($seen{$prim_ip});
11186:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11187:                 foreach my $id (@{$iphost{$prim_ip}}) {
11188:                     my $intdom = &internet_dom($id);
11189:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11190:                         push(@idns,$intdom);
11191:                     }
11192:                 }
11193:             }
11194:             $seen{$prim_ip} = 1;
11195:         }
11196:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11197:     }
11198: 
11199: }
11200: 
11201: sub all_loncaparevs {
11202:     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);
11203: }
11204: 
11205: BEGIN {
11206: 
11207: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11208:     unless ($readit) {
11209: {
11210:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11211:     %perlvar = (%perlvar,%{$configvars});
11212: }
11213: 
11214: 
11215: # ------------------------------------------------------ Read spare server file
11216: {
11217:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11218: 
11219:     while (my $configline=<$config>) {
11220:        chomp($configline);
11221:        if ($configline) {
11222: 	   my ($host,$type) = split(':',$configline,2);
11223: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11224: 	   push(@{ $spareid{$type} }, $host);
11225:        }
11226:     }
11227:     close($config);
11228: }
11229: # ------------------------------------------------------------ Read permissions
11230: {
11231:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11232: 
11233:     while (my $configline=<$config>) {
11234: 	chomp($configline);
11235: 	if ($configline) {
11236: 	    my ($role,$perm)=split(/ /,$configline);
11237: 	    if ($perm ne '') { $pr{$role}=$perm; }
11238: 	}
11239:     }
11240:     close($config);
11241: }
11242: 
11243: # -------------------------------------------- Read plain texts for permissions
11244: {
11245:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11246: 
11247:     while (my $configline=<$config>) {
11248: 	chomp($configline);
11249: 	if ($configline) {
11250: 	    my ($short,@plain)=split(/:/,$configline);
11251:             %{$prp{$short}} = ();
11252: 	    if (@plain > 0) {
11253:                 $prp{$short}{'std'} = $plain[0];
11254:                 for (my $i=1; $i<@plain; $i++) {
11255:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11256:                 }
11257:             }
11258: 	}
11259:     }
11260:     close($config);
11261: }
11262: 
11263: # ---------------------------------------------------------- Read package table
11264: {
11265:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11266: 
11267:     while (my $configline=<$config>) {
11268: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11269: 	chomp($configline);
11270: 	my ($short,$plain)=split(/:/,$configline);
11271: 	my ($pack,$name)=split(/\&/,$short);
11272: 	if ($plain ne '') {
11273: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11274: 	    $packagetab{$short}=$plain; 
11275: 	}
11276:     }
11277:     close($config);
11278: }
11279: 
11280: # ---------------------------------------------------------- Read loncaparev table
11281: {
11282:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11283:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11284:             while (my $configline=<$config>) {
11285:                 chomp($configline);
11286:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11287:                 $loncaparevs{$hostid}=$loncaparev;
11288:             }
11289:             close($config);
11290:         }
11291:     }
11292: }
11293: 
11294: # ---------------------------------------------------------- Read serverhostID table
11295: {
11296:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11297:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11298:             while (my $configline=<$config>) {
11299:                 chomp($configline);
11300:                 my ($name,$id)=split(/:/,$configline);
11301:                 $serverhomeIDs{$name}=$id;
11302:             }
11303:             close($config);
11304:         }
11305:     }
11306: }
11307: 
11308: {
11309:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11310:     if (-e $file) {
11311:         my $parser = HTML::LCParser->new($file);
11312:         while (my $token = $parser->get_token()) {
11313:             if ($token->[0] eq 'S') {
11314:                 my $item = $token->[1];
11315:                 my $name = $token->[2]{'name'};
11316:                 my $value = $token->[2]{'value'};
11317:                 if ($item ne '' && $name ne '' && $value ne '') {
11318:                     my $release = $parser->get_text();
11319:                     $release =~ s/(^\s*|\s*$ )//gx;
11320:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11321:                 }
11322:             }
11323:         }
11324:     }
11325: }
11326: 
11327: # ---------------------------------------------------------- Read managers table
11328: {
11329:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11330:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11331:             while (my $configline=<$config>) {
11332:                 chomp($configline);
11333:                 next if ($configline =~ /^\#/);
11334:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11335:                     $managerstab{$configline} = 1;
11336:                 }
11337:             }
11338:             close($config);
11339:         }
11340:     }
11341: }
11342: 
11343: # ------------- set up temporary directory
11344: {
11345:     $tmpdir = LONCAPA::tempdir();
11346: 
11347: }
11348: 
11349: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11350: 				'compress_threshold'=> 20_000,
11351:  			        });
11352: 
11353: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11354: $dumpcount=0;
11355: $locknum=0;
11356: 
11357: &logtouch();
11358: &logthis('<font color="yellow">INFO: Read configuration</font>');
11359: $readit=1;
11360:     {
11361: 	use integer;
11362: 	my $test=(2**32)+1;
11363: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11364: 	&logthis(" Detected 64bit platform ($_64bit)");
11365:     }
11366: }
11367: }
11368: 
11369: 1;
11370: __END__
11371: 
11372: =pod
11373: 
11374: =head1 NAME
11375: 
11376: Apache::lonnet - Subroutines to ask questions about things in the network.
11377: 
11378: =head1 SYNOPSIS
11379: 
11380: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11381: 
11382:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11383: 
11384: Common parameters:
11385: 
11386: =over 4
11387: 
11388: =item *
11389: 
11390: $uname : an internal username (if $cname expecting a course Id specifically)
11391: 
11392: =item *
11393: 
11394: $udom : a domain (if $cdom expecting a course's domain specifically)
11395: 
11396: =item *
11397: 
11398: $symb : a resource instance identifier
11399: 
11400: =item *
11401: 
11402: $namespace : the name of a .db file that contains the data needed or
11403: being set.
11404: 
11405: =back
11406: 
11407: =head1 OVERVIEW
11408: 
11409: lonnet provides subroutines which interact with the
11410: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11411: about classes, users, and resources.
11412: 
11413: For many of these objects you can also use this to store data about
11414: them or modify them in various ways.
11415: 
11416: =head2 Symbs
11417: 
11418: To identify a specific instance of a resource, LON-CAPA uses symbols
11419: or "symbs"X<symb>. These identifiers are built from the URL of the
11420: map, the resource number of the resource in the map, and the URL of
11421: the resource itself. The latter is somewhat redundant, but might help
11422: if maps change.
11423: 
11424: An example is
11425: 
11426:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11427: 
11428: The respective map entry is
11429: 
11430:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11431:   title="Problem 2">
11432:  </resource>
11433: 
11434: Symbs are used by the random number generator, as well as to store and
11435: restore data specific to a certain instance of for example a problem.
11436: 
11437: =head2 Storing And Retrieving Data
11438: 
11439: X<store()>X<cstore()>X<restore()>Three of the most important functions
11440: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11441: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11442: is is the non-critical message twin of cstore. These functions are for
11443: handlers to store a perl hash to a user's permanent data space in an
11444: easy manner, and to retrieve it again on another call. It is expected
11445: that a handler would use this once at the beginning to retrieve data,
11446: and then again once at the end to send only the new data back.
11447: 
11448: The data is stored in the user's data directory on the user's
11449: homeserver under the ID of the course.
11450: 
11451: The hash that is returned by restore will have all of the previous
11452: value for all of the elements of the hash.
11453: 
11454: Example:
11455: 
11456:  #creating a hash
11457:  my %hash;
11458:  $hash{'foo'}='bar';
11459: 
11460:  #storing it
11461:  &Apache::lonnet::cstore(\%hash);
11462: 
11463:  #changing a value
11464:  $hash{'foo'}='notbar';
11465: 
11466:  #adding a new value
11467:  $hash{'bar'}='foo';
11468:  &Apache::lonnet::cstore(\%hash);
11469: 
11470:  #retrieving the hash
11471:  my %history=&Apache::lonnet::restore();
11472: 
11473:  #print the hash
11474:  foreach my $key (sort(keys(%history))) {
11475:    print("\%history{$key} = $history{$key}");
11476:  }
11477: 
11478: Will print out:
11479: 
11480:  %history{1:foo} = bar
11481:  %history{1:keys} = foo:timestamp
11482:  %history{1:timestamp} = 990455579
11483:  %history{2:bar} = foo
11484:  %history{2:foo} = notbar
11485:  %history{2:keys} = foo:bar:timestamp
11486:  %history{2:timestamp} = 990455580
11487:  %history{bar} = foo
11488:  %history{foo} = notbar
11489:  %history{timestamp} = 990455580
11490:  %history{version} = 2
11491: 
11492: Note that the special hash entries C<keys>, C<version> and
11493: C<timestamp> were added to the hash. C<version> will be equal to the
11494: total number of versions of the data that have been stored. The
11495: C<timestamp> attribute will be the UNIX time the hash was
11496: stored. C<keys> is available in every historical section to list which
11497: keys were added or changed at a specific historical revision of a
11498: hash.
11499: 
11500: B<Warning>: do not store the hash that restore returns directly. This
11501: will cause a mess since it will restore the historical keys as if the
11502: were new keys. I.E. 1:foo will become 1:1:foo etc.
11503: 
11504: Calling convention:
11505: 
11506:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11507:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11508: 
11509: For more detailed information, see lonnet specific documentation.
11510: 
11511: =head1 RETURN MESSAGES
11512: 
11513: =over 4
11514: 
11515: =item * B<con_lost>: unable to contact remote host
11516: 
11517: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11518: when the connection is brought back up
11519: 
11520: =item * B<con_failed>: unable to contact remote host and unable to save message
11521: for later delivery
11522: 
11523: =item * B<error:>: an error a occurred, a description of the error follows the :
11524: 
11525: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11526: that was requested
11527: 
11528: =back
11529: 
11530: =head1 PUBLIC SUBROUTINES
11531: 
11532: =head2 Session Environment Functions
11533: 
11534: =over 4
11535: 
11536: =item * 
11537: X<appenv()>
11538: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11539: the user envirnoment file, and will be restored for each access this
11540: user makes during this session, also modifies the %env for the current
11541: process. Optional rolesarrayref - if defined contains a reference to an array
11542: of roles which are exempt from the restriction on modifying user.role entries 
11543: in the user's environment.db and in %env.    
11544: 
11545: =item *
11546: X<delenv()>
11547: B<delenv($delthis,$regexp)>: removes all items from the session
11548: environment file that begin with $delthis. If the 
11549: optional second arg - $regexp - is true, $delthis is treated as a 
11550: regular expression, otherwise \Q$delthis\E is used. 
11551: The values are also deleted from the current processes %env.
11552: 
11553: =item * get_env_multiple($name) 
11554: 
11555: gets $name from the %env hash, it seemlessly handles the cases where multiple
11556: values may be defined and end up as an array ref.
11557: 
11558: returns an array of values
11559: 
11560: =back
11561: 
11562: =head2 User Information
11563: 
11564: =over 4
11565: 
11566: =item *
11567: X<queryauthenticate()>
11568: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11569: authentication scheme
11570: 
11571: =item *
11572: X<authenticate()>
11573: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11574: authenticate user from domain's lib servers (first use the current
11575: one). C<$upass> should be the users password.
11576: $checkdefauth is optional (value is 1 if a check should be made to
11577:    authenticate user using default authentication method, and allow
11578:    account creation if username does not have account in the domain).
11579: $clientcancheckhost is optional (value is 1 if checking whether the
11580:    server can host will occur on the client side in lonauth.pm).   
11581: 
11582: =item *
11583: X<homeserver()>
11584: B<homeserver($uname,$udom)>: find the server which has
11585: the user's directory and files (there must be only one), this caches
11586: the answer, and also caches if there is a borken connection.
11587: 
11588: =item *
11589: X<idget()>
11590: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11591: (IDs are a unique resource in a domain, there must be only 1 ID per
11592: username, and only 1 username per ID in a specific domain) (returns
11593: hash: id=>name,id=>name)
11594: 
11595: =item *
11596: X<idrget()>
11597: B<idrget($udom,@unames)>: find the IDs behind a list of
11598: usernames (returns hash: name=>id,name=>id)
11599: 
11600: =item *
11601: X<idput()>
11602: B<idput($udom,%ids)>: store away a list of names and associated IDs
11603: 
11604: =item *
11605: X<rolesinit()>
11606: B<rolesinit($udom,$username,$authhost)>: get user privileges
11607: 
11608: =item *
11609: X<getsection()>
11610: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11611: course $cname, return section name/number or '' for "not in course"
11612: and '-1' for "no section"
11613: 
11614: =item *
11615: X<userenvironment()>
11616: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11617: passed in @what from the requested user's environment, returns a hash
11618: 
11619: =item * 
11620: X<userlog_query()>
11621: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11622: activity.log file. %filters defines filters applied when parsing the
11623: log file. These can be start or end timestamps, or the type of action
11624: - log to look for Login or Logout events, check for Checkin or
11625: Checkout, role for role selection. The response is in the form
11626: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11627: escaped strings of the action recorded in the activity.log file.
11628: 
11629: =back
11630: 
11631: =head2 User Roles
11632: 
11633: =over 4
11634: 
11635: =item *
11636: 
11637: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11638:  F: full access
11639:  U,I,K: authentication modes (cxx only)
11640:  '': forbidden
11641:  1: user needs to choose course
11642:  2: browse allowed
11643:  A: passphrase authentication needed
11644: 
11645: =item *
11646: 
11647: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11648: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11649: and course level
11650: 
11651: =item *
11652: 
11653: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11654: (rolesplain.tab); plain text explanation of a user role term.
11655: $type is Course (default) or Community.
11656: If $forcedefault evaluates to true, text returned will be default 
11657: text for $type. Otherwise, if this is a course, the text returned 
11658: will be a custom name for the role (if defined in the course's 
11659: environment).  If no custom name is defined the default is returned.
11660:    
11661: =item *
11662: 
11663: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11664: All arguments are optional. Returns a hash of a roles, either for
11665: co-author/assistant author roles for a user's Construction Space
11666: (default), or if $context is 'userroles', roles for the user himself,
11667: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11668: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11669: For each key, value is set to colon-separated start and end times for
11670: the role.  If no username and domain are specified, will default to
11671: current user/domain. Types, roles, and roledoms are references to arrays
11672: of role statuses (active, future or previous), roles 
11673: (e.g., cc,in, st etc.) and domains of the roles which can be used
11674: to restrict the list of roles reported. If no array ref is 
11675: provided for types, will default to return only active roles.
11676: 
11677: =back
11678: 
11679: =head2 User Modification
11680: 
11681: =over 4
11682: 
11683: =item *
11684: 
11685: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11686: user for the level given by URL.  Optional start and end dates (leave empty
11687: string or zero for "no date")
11688: 
11689: =item *
11690: 
11691: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11692: change a users, password, possible return values are: ok,
11693: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11694: refused
11695: 
11696: =item *
11697: 
11698: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11699: 
11700: =item *
11701: 
11702: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11703:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11704: 
11705: will update user information (firstname,middlename,lastname,generation,
11706: permanentemail), and if forceid is true, student/employee ID also.
11707: A user's institutional affiliation(s) can also be updated.
11708: User information fields will not be overwritten with empty entries 
11709: unless the field is included in the $candelete array reference.
11710: This array is included when a single user is modified via "Manage Users",
11711: or when Autoupdate.pl is run by cron in a domain.
11712: 
11713: =item *
11714: 
11715: modifystudent
11716: 
11717: modify a student's enrollment and identification information.
11718: The course id is resolved based on the current users environment.  
11719: This means the envoking user must be a course coordinator or otherwise
11720: associated with a course.
11721: 
11722: This call is essentially a wrapper for lonnet::modifyuser and
11723: lonnet::modify_student_enrollment
11724: 
11725: Inputs: 
11726: 
11727: =over 4
11728: 
11729: =item B<$udom> Student's loncapa domain
11730: 
11731: =item B<$uname> Student's loncapa login name
11732: 
11733: =item B<$uid> Student/Employee ID
11734: 
11735: =item B<$umode> Student's authentication mode
11736: 
11737: =item B<$upass> Student's password
11738: 
11739: =item B<$first> Student's first name
11740: 
11741: =item B<$middle> Student's middle name
11742: 
11743: =item B<$last> Student's last name
11744: 
11745: =item B<$gene> Student's generation
11746: 
11747: =item B<$usec> Student's section in course
11748: 
11749: =item B<$end> Unix time of the roles expiration
11750: 
11751: =item B<$start> Unix time of the roles start date
11752: 
11753: =item B<$forceid> If defined, allow $uid to be changed
11754: 
11755: =item B<$desiredhome> server to use as home server for student
11756: 
11757: =item B<$email> Student's permanent e-mail address
11758: 
11759: =item B<$type> Type of enrollment (auto or manual)
11760: 
11761: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11762: 
11763: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11764: 
11765: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11766: 
11767: =item B<$context> role change context (shown in User Management Logs display in a course)
11768: 
11769: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11770: 
11771: =back
11772: 
11773: =item *
11774: 
11775: modify_student_enrollment
11776: 
11777: Change a students enrollment status in a class.  The environment variable
11778: 'role.request.course' must be defined for this function to proceed.
11779: 
11780: Inputs:
11781: 
11782: =over 4
11783: 
11784: =item $udom, students domain
11785: 
11786: =item $uname, students name
11787: 
11788: =item $uid, students user id
11789: 
11790: =item $first, students first name
11791: 
11792: =item $middle
11793: 
11794: =item $last
11795: 
11796: =item $gene
11797: 
11798: =item $usec
11799: 
11800: =item $end
11801: 
11802: =item $start
11803: 
11804: =item $type
11805: 
11806: =item $locktype
11807: 
11808: =item $cid
11809: 
11810: =item $selfenroll
11811: 
11812: =item $context
11813: 
11814: =back
11815: 
11816: 
11817: =item *
11818: 
11819: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11820: custom role; give a custom role to a user for the level given by URL.  Specify
11821: name and domain of role author, and role name
11822: 
11823: =item *
11824: 
11825: revokerole($udom,$uname,$url,$role) : revoke a role for url
11826: 
11827: =item *
11828: 
11829: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11830: 
11831: =back
11832: 
11833: =head2 Course Infomation
11834: 
11835: =over 4
11836: 
11837: =item *
11838: 
11839: coursedescription($courseid,$options) : returns a hash of information about the
11840: specified course id, including all environment settings for the
11841: course, the description of the course will be in the hash under the
11842: key 'description'
11843: 
11844: $options is an optional parameter that if supplied is a hash reference that controls
11845: what how this function works.  It has the following key/values:
11846: 
11847: =over 4
11848: 
11849: =item freshen_cache
11850: 
11851: If defined, and the environment cache for the course is valid, it is 
11852: returned in the returned hash.
11853: 
11854: =item one_time
11855: 
11856: If defined, the last cache time is set to _now_
11857: 
11858: =item user
11859: 
11860: If defined, the supplied username is used instead of the current user.
11861: 
11862: 
11863: =back
11864: 
11865: =item *
11866: 
11867: resdata($name,$domain,$type,@which) : request for current parameter
11868: setting for a specific $type, where $type is either 'course' or 'user',
11869: @what should be a list of parameters to ask about. This routine caches
11870: answers for 5 minutes.
11871: 
11872: =item *
11873: 
11874: get_courseresdata($courseid, $domain) : dump the entire course resource
11875: data base, returning a hash that is keyed by the resource name and has
11876: values that are the resource value.  I believe that the timestamps and
11877: versions are also returned.
11878: 
11879: 
11880: =back
11881: 
11882: =head2 Course Modification
11883: 
11884: =over 4
11885: 
11886: =item *
11887: 
11888: writecoursepref($courseid,%prefs) : write preferences (environment
11889: database) for a course
11890: 
11891: =item *
11892: 
11893: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11894: 
11895: =item *
11896: 
11897: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11898: 
11899: =back
11900: 
11901: =head2 Resource Subroutines
11902: 
11903: =over 4
11904: 
11905: =item *
11906: 
11907: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11908: 
11909: =item *
11910: 
11911: repcopy($filename) : subscribes to the requested file, and attempts to
11912: replicate from the owning library server, Might return
11913: 'unavailable', 'not_found', 'forbidden', 'ok', or
11914: 'bad_request', also attempts to grab the metadata for the
11915: resource. Expects the local filesystem pathname
11916: (/home/httpd/html/res/....)
11917: 
11918: =back
11919: 
11920: =head2 Resource Information
11921: 
11922: =over 4
11923: 
11924: =item *
11925: 
11926: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11927: a vairety of different possible values, $varname should be a request
11928: string, and the other parameters can be used to specify who and what
11929: one is asking about.
11930: 
11931: Possible values for $varname are environment.lastname (or other item
11932: from the envirnment hash), user.name (or someother aspect about the
11933: user), resource.0.maxtries (or some other part and parameter of a
11934: resource)
11935: 
11936: =item *
11937: 
11938: directcondval($number) : get current value of a condition; reads from a state
11939: string
11940: 
11941: =item *
11942: 
11943: condval($condidx) : value of condition index based on state
11944: 
11945: =item *
11946: 
11947: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11948: resource's metadata, $what should be either a specific key, or either
11949: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11950: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11951: 
11952: this function automatically caches all requests
11953: 
11954: =item *
11955: 
11956: metadata_query($query,$custom,$customshow) : make a metadata query against the
11957: network of library servers; returns file handle of where SQL and regex results
11958: will be stored for query
11959: 
11960: =item *
11961: 
11962: symbread($filename) : return symbolic list entry (filename argument optional);
11963: returns the data handle
11964: 
11965: =item *
11966: 
11967: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11968: a possible symb for the URL in $thisfn, and if is an encryypted
11969: resource that the user accessed using /enc/ returns a 1 on success, 0
11970: on failure, user must be in a course, as it assumes the existance of
11971: the course initial hash, and uses $env('request.course.id'}
11972: 
11973: 
11974: =item *
11975: 
11976: symbclean($symb) : removes versions numbers from a symb, returns the
11977: cleaned symb
11978: 
11979: =item *
11980: 
11981: is_on_map($uri) : checks if the $uri is somewhere on the current
11982: course map, user must be in a course for it to work.
11983: 
11984: =item *
11985: 
11986: numval($salt) : return random seed value (addend for rndseed)
11987: 
11988: =item *
11989: 
11990: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11991: a random seed, all arguments are optional, if they aren't sent it uses the
11992: environment to derive them. Note: if symb isn't sent and it can't get one
11993: from &symbread it will use the current time as its return value
11994: 
11995: =item *
11996: 
11997: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11998: unfakeable, receipt
11999: 
12000: =item *
12001: 
12002: receipt() : API to ireceipt working off of env values; given out to users
12003: 
12004: =item *
12005: 
12006: countacc($url) : count the number of accesses to a given URL
12007: 
12008: =item *
12009: 
12010: 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
12011: 
12012: =item *
12013: 
12014: 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)
12015: 
12016: =item *
12017: 
12018: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12019: 
12020: =item *
12021: 
12022: devalidate($symb) : devalidate temporary spreadsheet calculations,
12023: forcing spreadsheet to reevaluate the resource scores next time.
12024: 
12025: =back
12026: 
12027: =head2 Storing/Retreiving Data
12028: 
12029: =over 4
12030: 
12031: =item *
12032: 
12033: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12034: for this url; hashref needs to be given and should be a \%hashname; the
12035: remaining args aren't required and if they aren't passed or are '' they will
12036: be derived from the env
12037: 
12038: =item *
12039: 
12040: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12041: uses critical subroutine
12042: 
12043: =item *
12044: 
12045: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12046: all args are optional
12047: 
12048: =item *
12049: 
12050: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12051: dumps the complete (or key matching regexp) namespace into a hash
12052: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12053: normally &store()ed into
12054: 
12055: $range should be either an integer '100' (give me the first 100
12056:                                            matching records)
12057:               or be  two integers sperated by a - with no spaces
12058:                  '30-50' (give me the 30th through the 50th matching
12059:                           records)
12060: 
12061: 
12062: =item *
12063: 
12064: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12065: replaces a &store() version of data with a replacement set of data
12066: for a particular resource in a namespace passed in the $storehash hash 
12067: reference
12068: 
12069: =item *
12070: 
12071: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12072: works very similar to store/cstore, but all data is stored in a
12073: temporary location and can be reset using tmpreset, $storehash should
12074: be a hash reference, returns nothing on success
12075: 
12076: =item *
12077: 
12078: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12079: similar to restore, but all data is stored in a temporary location and
12080: can be reset using tmpreset. Returns a hash of values on success,
12081: error string otherwise.
12082: 
12083: =item *
12084: 
12085: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12086: deltes all keys for $symb form the temporary storage hash.
12087: 
12088: =item *
12089: 
12090: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12091: reference filled in from namesp ($udom and $uname are optional)
12092: 
12093: =item *
12094: 
12095: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12096: namesp ($udom and $uname are optional)
12097: 
12098: =item *
12099: 
12100: dump($namespace,$udom,$uname,$regexp,$range) : 
12101: dumps the complete (or key matching regexp) namespace into a hash
12102: ($udom, $uname, $regexp, $range are optional)
12103: 
12104: $range should be either an integer '100' (give me the first 100
12105:                                            matching records)
12106:               or be  two integers sperated by a - with no spaces
12107:                  '30-50' (give me the 30th through the 50th matching
12108:                           records)
12109: =item *
12110: 
12111: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12112: $store can be a scalar, an array reference, or if the amount to be 
12113: incremented is > 1, a hash reference.
12114: 
12115: ($udom and $uname are optional)
12116: 
12117: =item *
12118: 
12119: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12120: ($udom and $uname are optional)
12121: 
12122: =item *
12123: 
12124: cput($namespace,$storehash,$udom,$uname) : critical put
12125: ($udom and $uname are optional)
12126: 
12127: =item *
12128: 
12129: newput($namespace,$storehash,$udom,$uname) :
12130: 
12131: Attempts to store the items in the $storehash, but only if they don't
12132: currently exist, if this succeeds you can be certain that you have 
12133: successfully created a new key value pair in the $namespace db.
12134: 
12135: 
12136: Args:
12137:  $namespace: name of database to store values to
12138:  $storehash: hashref to store to the db
12139:  $udom: (optional) domain of user containing the db
12140:  $uname: (optional) name of user caontaining the db
12141: 
12142: Returns:
12143:  'ok' -> succeeded in storing all keys of $storehash
12144:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12145:                         least <key> already existed in the db (other
12146:                         requested keys may also already exist)
12147:  'error: <msg>' -> unable to tie the DB or other error occurred
12148:  'con_lost' -> unable to contact request server
12149:  'refused' -> action was not allowed by remote machine
12150: 
12151: 
12152: =item *
12153: 
12154: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12155: reference filled in from namesp (encrypts the return communication)
12156: ($udom and $uname are optional)
12157: 
12158: =item *
12159: 
12160: log($udom,$name,$home,$message) : write to permanent log for user; use
12161: critical subroutine
12162: 
12163: =item *
12164: 
12165: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12166: array reference filled in from namespace found in domain level on either
12167: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12168: 
12169: =item *
12170: 
12171: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12172: domain level either on specified domain server ($uhome) or primary domain 
12173: server ($udom and $uhome are optional)
12174: 
12175: =item * 
12176: 
12177: get_domain_defaults($target_domain) : returns hash with defaults for
12178: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12179: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12180: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12181: Values are retrieved from cache (if current), or from domain's configuration.db
12182: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12183: or lonTabs/domain.tab. 
12184: 
12185: %domdefaults = &get_auth_defaults($target_domain);
12186: 
12187: =back
12188: 
12189: =head2 Network Status Functions
12190: 
12191: =over 4
12192: 
12193: =item *
12194: 
12195: dirlist() : return directory list based on URI (first arg).
12196: 
12197: Inputs: 1 required, 5 optional.
12198: 
12199: =over
12200: 
12201: =item 
12202: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12203: 
12204: =item
12205: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12206: 
12207: =item
12208: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12209: 
12210: =item
12211: $getpropath - boolean: 1 if prepend path using &propath(). 
12212: 
12213: =item
12214: $getuserdir - boolean: 1 if prepend path for "userfiles".
12215: 
12216: =item 
12217: $alternateRoot - path to prepend in place of path from $uri.
12218: 
12219: =back
12220: 
12221: Returns: Array of up to two items.
12222: 
12223: =over
12224: 
12225: a reference to an array of files/subdirectories
12226: 
12227: =over
12228: 
12229: Each element in the array of files/subdirectories is a & separated list of
12230: item name and the result of running stat on the item.  If dirlist was requested
12231: for a file instead of a directory, the item name will be ''. For a directory 
12232: listing, if the item is a metadata file, the element will end &N&M 
12233: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12234: default copyright set (1).  
12235: 
12236: =back
12237: 
12238: a scalar containing error condition (if encountered).
12239: 
12240: =over
12241: 
12242: =item 
12243: no_host (no homeserver identified for $username:$domain).
12244: 
12245: =item 
12246: no_such_host (server contacted for listing not identified as valid host).
12247: 
12248: =item 
12249: con_lost (connection to remote server failed).
12250: 
12251: =item 
12252: refused (invalid $username:$domain received on lond side).
12253: 
12254: =item 
12255: no_such_dir (directory at specified path on lond side does not exist). 
12256: 
12257: =item 
12258: empty (directory at specified path on lond side is empty).
12259: 
12260: =over
12261: 
12262: This is currently not encountered because the &ls3, &ls2, 
12263: &ls (_handler) routines on the lond side do not filter out
12264: . and .. from a directory listing. 
12265: 
12266: =back
12267: 
12268: =back
12269: 
12270: =back
12271: 
12272: =item *
12273: 
12274: spareserver() : find server with least workload from spare.tab
12275: 
12276: 
12277: =item *
12278: 
12279: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12280: if there is no corresponding loncapa host.
12281: 
12282: =back
12283: 
12284: 
12285: =head2 Apache Request
12286: 
12287: =over 4
12288: 
12289: =item *
12290: 
12291: ssi($url,%hash) : server side include, does a complete request cycle on url to
12292: localhost, posts hash
12293: 
12294: =back
12295: 
12296: =head2 Data to String to Data
12297: 
12298: =over 4
12299: 
12300: =item *
12301: 
12302: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12303: and '&' separators, supports elements that are arrayrefs and hashrefs
12304: 
12305: =item *
12306: 
12307: hashref2str($hashref) : convert a hashref into a string complete with
12308: escaping and '=' and '&' separators, supports elements that are
12309: arrayrefs and hashrefs
12310: 
12311: =item *
12312: 
12313: arrayref2str($arrayref) : convert an arrayref into a string complete
12314: with escaping and '&' separators, supports elements that are arrayrefs
12315: and hashrefs
12316: 
12317: =item *
12318: 
12319: str2hash($string) : convert string to hash using unescaping and
12320: splitting on '=' and '&', supports elements that are arrayrefs and
12321: hashrefs
12322: 
12323: =item *
12324: 
12325: str2array($string) : convert string to hash using unescaping and
12326: splitting on '&', supports elements that are arrayrefs and hashrefs
12327: 
12328: =back
12329: 
12330: =head2 Logging Routines
12331: 
12332: 
12333: These routines allow one to make log messages in the lonnet.log and
12334: lonnet.perm logfiles.
12335: 
12336: =over 4
12337: 
12338: =item *
12339: 
12340: logtouch() : make sure the logfile, lonnet.log, exists
12341: 
12342: =item *
12343: 
12344: logthis() : append message to the normal lonnet.log file, it gets
12345: preiodically rolled over and deleted.
12346: 
12347: =item *
12348: 
12349: logperm() : append a permanent message to lonnet.perm.log, this log
12350: file never gets deleted by any automated portion of the system, only
12351: messages of critical importance should go in here.
12352: 
12353: 
12354: =back
12355: 
12356: =head2 General File Helper Routines
12357: 
12358: =over 4
12359: 
12360: =item *
12361: 
12362: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12363: (a) files in /uploaded
12364:   (i) If a local copy of the file exists - 
12365:       compares modification date of local copy with last-modified date for 
12366:       definitive version stored on home server for course. If local copy is 
12367:       stale, requests a new version from the home server and stores it. 
12368:       If the original has been removed from the home server, then local copy 
12369:       is unlinked.
12370:   (ii) If local copy does not exist -
12371:       requests the file from the home server and stores it. 
12372:   
12373:   If $caller is 'uploadrep':  
12374:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12375:     for request for files originally uploaded via DOCS. 
12376:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12377:   
12378:   Otherwise:
12379:      This indicates a call from the content generation phase of the request.
12380:      -  returns the entire contents of the file or -1.
12381:      
12382: (b) files in /res
12383:    - returns the entire contents of a file or -1; 
12384:    it properly subscribes to and replicates the file if neccessary.
12385: 
12386: 
12387: =item *
12388: 
12389: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12390:                   reference
12391: 
12392: returns either a stat() list of data about the file or an empty list
12393: if the file doesn't exist or couldn't find out about it (connection
12394: problems or user unknown)
12395: 
12396: =item *
12397: 
12398: filelocation($dir,$file) : returns file system location of a file
12399: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12400: directory that relative $file lookups are to looked in ($dir of /a/dir
12401: and a file of ../bob will become /a/bob)
12402: 
12403: =item *
12404: 
12405: hreflocation($dir,$file) : returns file system location or a URL; same as
12406: filelocation except for hrefs
12407: 
12408: =item *
12409: 
12410: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12411: 
12412: =back
12413: 
12414: =head2 Usererfile file routines (/uploaded*)
12415: 
12416: =over 4
12417: 
12418: =item *
12419: 
12420: userfileupload(): main rotine for putting a file in a user or course's
12421:                   filespace, arguments are,
12422: 
12423:  formname - required - this is the name of the element in $env where the
12424:            filename, and the contents of the file to create/modifed exist
12425:            the filename is in $env{'form.'.$formname.'.filename'} and the
12426:            contents of the file is located in $env{'form.'.$formname}
12427:  context - if coursedoc, store the file in the course of the active role
12428:              of the current user; 
12429:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12430:            if 'canceloverwrite': delete file in tmp/overwrites directory
12431:  subdir - required - subdirectory to put the file in under ../userfiles/
12432:          if undefined, it will be placed in "unknown"
12433: 
12434:  (This routine calls clean_filename() to remove any dangerous
12435:  characters from the filename, and then calls finuserfileupload() to
12436:  complete the transaction)
12437: 
12438:  returns either the url of the uploaded file (/uploaded/....) if successful
12439:  and /adm/notfound.html if unsuccessful
12440: 
12441: =item *
12442: 
12443: clean_filename(): routine for cleaing a filename up for storage in
12444:                  userfile space, argument is:
12445: 
12446:  filename - proposed filename
12447: 
12448: returns: the new clean filename
12449: 
12450: =item *
12451: 
12452: finishuserfileupload(): routine that creates and sends the file to
12453: userspace, probably shouldn't be called directly
12454: 
12455:   docuname: username or courseid of destination for the file
12456:   docudom: domain of user/course of destination for the file
12457:   formname: same as for userfileupload()
12458:   fname: filename (including subdirectories) for the file
12459:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12460:   allfiles: reference to hash used to store objects found by parser
12461:   codebase: reference to hash used for codebases of java objects found by parser
12462:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12463:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12464:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12465:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12466:   context: if 'overwrite', will move the uploaded file from its temporary location to
12467:             userfiles to facilitate overwriting a previously uploaded file with same name.
12468:   mimetype: reference to scalar to accommodate mime type determined
12469:             from File::MMagic if $parser = parse.
12470: 
12471:  returns either the url of the uploaded file (/uploaded/....) if successful
12472:  and /adm/notfound.html if unsuccessful (or an error message if context 
12473:  was 'overwrite').
12474:  
12475: 
12476: =item *
12477: 
12478: renameuserfile(): renames an existing userfile to a new name
12479: 
12480:   Args:
12481:    docuname: username or courseid of destination for the file
12482:    docudom: domain of user/course of destination for the file
12483:    old: current file name (including any subdirs under userfiles)
12484:    new: desired file name (including any subdirs under userfiles)
12485: 
12486: =item *
12487: 
12488: mkdiruserfile(): creates a directory is a userfiles dir
12489: 
12490:   Args:
12491:    docuname: username or courseid of destination for the file
12492:    docudom: domain of user/course of destination for the file
12493:    dir: dir to create (including any subdirs under userfiles)
12494: 
12495: =item *
12496: 
12497: removeuserfile(): removes a file that exists in userfiles
12498: 
12499:   Args:
12500:    docuname: username or courseid of destination for the file
12501:    docudom: domain of user/course of destination for the file
12502:    fname: filname to delete (including any subdirs under userfiles)
12503: 
12504: =item *
12505: 
12506: removeuploadedurl(): convience function for removeuserfile()
12507: 
12508:   Args:
12509:    url:  a full /uploaded/... url to delete
12510: 
12511: =item * 
12512: 
12513: get_portfile_permissions():
12514:   Args:
12515:     domain: domain of user or course contain the portfolio files
12516:     user: name of user or num of course contain the portfolio files
12517:   Returns:
12518:     hashref of a dump of the proper file_permissions.db
12519:    
12520: 
12521: =item * 
12522: 
12523: get_access_controls():
12524: 
12525: Args:
12526:   current_permissions: the hash ref returned from get_portfile_permissions()
12527:   group: (optional) the group you want the files associated with
12528:   file: (optional) the file you want access info on
12529: 
12530: Returns:
12531:     a hash (keys are file names) of hashes containing
12532:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12533:         values are XML containing access control settings (see below) 
12534: 
12535: Internal notes:
12536: 
12537:  access controls are stored in file_permissions.db as key=value pairs.
12538:     key -> path to file/file_name\0uniqueID:scope_end_start
12539:         where scope -> public,guest,course,group,domains or users.
12540:               end -> UNIX time for end of access (0 -> no end date)
12541:               start -> UNIX time for start of access
12542: 
12543:     value -> XML description of access control
12544:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12545:             <start></start>
12546:             <end></end>
12547: 
12548:             <password></password>  for scope type = guest
12549: 
12550:             <domain></domain>     for scope type = course or group
12551:             <number></number>
12552:             <roles id="">
12553:              <role></role>
12554:              <access></access>
12555:              <section></section>
12556:              <group></group>
12557:             </roles>
12558: 
12559:             <dom></dom>         for scope type = domains
12560: 
12561:             <users>             for scope type = users
12562:              <user>
12563:               <uname></uname>
12564:               <udom></udom>
12565:              </user>
12566:             </users>
12567:            </scope> 
12568:               
12569:  Access data is also aggregated for each file in an additional key=value pair:
12570:  key -> path to file/file_name\0accesscontrol 
12571:  value -> reference to hash
12572:           hash contains key = value pairs
12573:           where key = uniqueID:scope_end_start
12574:                 value = UNIX time record was last updated
12575: 
12576:           Used to improve speed of look-ups of access controls for each file.  
12577:  
12578:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12579: 
12580: modify_access_controls():
12581: 
12582: Modifies access controls for a portfolio file
12583: Args
12584: 1. file name
12585: 2. reference to hash of required changes,
12586: 3. domain
12587: 4. username
12588:   where domain,username are the domain of the portfolio owner 
12589:   (either a user or a course) 
12590: 
12591: Returns:
12592: 1. result of additions or updates ('ok' or 'error', with error message). 
12593: 2. result of deletions ('ok' or 'error', with error message).
12594: 3. reference to hash of any new or updated access controls.
12595: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12596:    key = integer (inbound ID)
12597:    value = uniqueID  
12598: 
12599: =back
12600: 
12601: =head2 HTTP Helper Routines
12602: 
12603: =over 4
12604: 
12605: =item *
12606: 
12607: escape() : unpack non-word characters into CGI-compatible hex codes
12608: 
12609: =item *
12610: 
12611: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12612: 
12613: =back
12614: 
12615: =head1 PRIVATE SUBROUTINES
12616: 
12617: =head2 Underlying communication routines (Shouldn't call)
12618: 
12619: =over 4
12620: 
12621: =item *
12622: 
12623: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12624: 
12625: =item *
12626: 
12627: reply() : uses subreply to send a message to remote machine, logs all failures
12628: 
12629: =item *
12630: 
12631: critical() : passes a critical message to another server; if cannot
12632: get through then place message in connection buffer directory and
12633: returns con_delayed, if incapable of saving message, returns
12634: con_failed
12635: 
12636: =item *
12637: 
12638: reconlonc() : tries to reconnect lonc client processes.
12639: 
12640: =back
12641: 
12642: =head2 Resource Access Logging
12643: 
12644: =over 4
12645: 
12646: =item *
12647: 
12648: flushcourselogs() : flush (save) buffer logs and access logs
12649: 
12650: =item *
12651: 
12652: courselog($what) : save message for course in hash
12653: 
12654: =item *
12655: 
12656: courseacclog($what) : save message for course using &courselog().  Perform
12657: special processing for specific resource types (problems, exams, quizzes, etc).
12658: 
12659: =item *
12660: 
12661: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12662: as a PerlChildExitHandler
12663: 
12664: =back
12665: 
12666: =head2 Other
12667: 
12668: =over 4
12669: 
12670: =item *
12671: 
12672: symblist($mapname,%newhash) : update symbolic storage links
12673: 
12674: =back
12675: 
12676: =cut
12677: 

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