File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1164: download - view: text, annotated - select for diffs
Sat Apr 14 00:52:16 2012 UTC (12 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- &extract_embedded_items() can now detect dependencies in a Camtasia
  index.html.
- early out for &repcopy_userfile() and &repcopy() when file is within
  /home/httpd/lonUsers, i.e., file is a file uploaded to a course,
  and current server is course's homesever, so replication is not needed.
  - replaces regexp for non-existent /home/httpd/html/lonUsers (first
    appeared in rev 1.538).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1164 2012/04/14 00:52:16 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/home/httpd/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 (%lastids,%related,%shockwave,%flashvars);
 3037:     my %javafiles = (
 3038:                       codebase => '',
 3039:                       code => '',
 3040:                       archive => ''
 3041:                     );
 3042:     my %mediafiles = (
 3043:                       src => '',
 3044:                       movie => '',
 3045:                      );
 3046:     my $p;
 3047:     if ($content) {
 3048:         $p = HTML::LCParser->new($content);
 3049:     } else {
 3050:         $p = HTML::LCParser->new($fullpath);
 3051:     }
 3052:     while (my $t=$p->get_token()) {
 3053: 	if ($t->[0] eq 'S') {
 3054: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3055: 	    push(@state, $tagname);
 3056:             if (lc($tagname) eq 'allow') {
 3057:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3058:             }
 3059: 	    if (lc($tagname) eq 'img') {
 3060: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3061: 	    }
 3062: 	    if (lc($tagname) eq 'a') {
 3063: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3064: 	    }
 3065:             if (lc($tagname) eq 'script') {
 3066:                 my $src;
 3067:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3068:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3069:                 } else {
 3070:                     if ($attr->{'src'} ne '') {
 3071:                         $src = $attr->{'src'};
 3072:                         &add_filetype($allfiles,$src,'src');
 3073:                     }
 3074:                 }
 3075:                 my $text = $p->get_trimmed_text();
 3076:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3077:                     my @swfargs = split(/,/,$1);
 3078:                     foreach my $item (@swfargs) {
 3079:                         $item =~ s/["']//g;
 3080:                         $item =~ s/^\s+//;
 3081:                         $item =~ s/\s+$//;
 3082:                     }
 3083:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3084:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3085:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3086:                         } else {
 3087:                             $related{$swfargs[0]} = [$swfargs[2]];
 3088:                         }
 3089:                     }
 3090:                 }
 3091:             }
 3092:             if (lc($tagname) eq 'link') {
 3093:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3094:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3095:                 }
 3096:             }
 3097: 	    if (lc($tagname) eq 'object' ||
 3098: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3099: 		foreach my $item (keys(%javafiles)) {
 3100: 		    $javafiles{$item} = '';
 3101: 		}
 3102:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3103:                     $lastids{lc($tagname)} = $attr->{'id'};
 3104:                 }
 3105: 	    }
 3106: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3107: 		my $name = lc($attr->{'name'});
 3108: 		foreach my $item (keys(%javafiles)) {
 3109: 		    if ($name eq $item) {
 3110: 			$javafiles{$item} = $attr->{'value'};
 3111: 			last;
 3112: 		    }
 3113: 		}
 3114:                 my $pathfrom;
 3115: 		foreach my $item (keys(%mediafiles)) {
 3116: 		    if ($name eq $item) {
 3117:                         $pathfrom = $attr->{'value'};
 3118:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3119: 			&add_filetype($allfiles,$pathfrom,$name);
 3120: 			last;
 3121: 		    }
 3122: 		}
 3123:                 if ($name eq 'flashvars') {
 3124:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3125:                 }
 3126:                 if ($pathfrom ne '') {
 3127:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3128:                                          $pathfrom);
 3129:                 }
 3130: 	    }
 3131: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3132: 		foreach my $item (keys(%javafiles)) {
 3133: 		    if ($attr->{$item}) {
 3134: 			$javafiles{$item} = $attr->{$item};
 3135: 			last;
 3136: 		    }
 3137: 		}
 3138: 		foreach my $item (keys(%mediafiles)) {
 3139: 		    if ($attr->{$item}) {
 3140: 			&add_filetype($allfiles,$attr->{$item},$item);
 3141: 			last;
 3142: 		    }
 3143: 		}
 3144:                 if (lc($tagname) eq 'embed') {
 3145:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3146:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3147:                                              $attr->{'src'});
 3148:                     }
 3149:                 }
 3150: 	    }
 3151:             if ($t->[4] =~ m{/>$}) {
 3152:                 pop(@state);  
 3153:             }
 3154: 	} elsif ($t->[0] eq 'E') {
 3155: 	    my ($tagname) = ($t->[1]);
 3156: 	    if ($javafiles{'codebase'} ne '') {
 3157: 		$javafiles{'codebase'} .= '/';
 3158: 	    }  
 3159: 	    if (lc($tagname) eq 'applet' ||
 3160: 		lc($tagname) eq 'object' ||
 3161: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3162: 		) {
 3163: 		foreach my $item (keys(%javafiles)) {
 3164: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3165: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3166: 			&add_filetype($allfiles,$file,$item);
 3167: 		    }
 3168: 		}
 3169: 	    } 
 3170: 	    pop @state;
 3171: 	}
 3172:     }
 3173:     foreach my $id (sort(keys(%flashvars))) {
 3174:         if ($shockwave{$id} ne '') {
 3175:             my @pairs = split(/\&/,$flashvars{$id});
 3176:             foreach my $pair (@pairs) {
 3177:                 my ($key,$value) = split(/\=/,$pair);
 3178:                 if ($key eq 'thumb') {
 3179:                     &add_filetype($allfiles,$value,$key);
 3180:                 } elsif ($key eq 'content') {
 3181:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3182:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3183:                     if ($ext ne '') {
 3184:                         &add_filetype($allfiles,$path.$value,$ext);
 3185:                     }
 3186:                 }
 3187:             }
 3188:         }
 3189:     }
 3190:     return 'ok';
 3191: }
 3192: 
 3193: sub add_filetype {
 3194:     my ($allfiles,$file,$type)=@_;
 3195:     if (exists($allfiles->{$file})) {
 3196: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3197: 	    push(@{$allfiles->{$file}}, &escape($type));
 3198: 	}
 3199:     } else {
 3200: 	@{$allfiles->{$file}} = (&escape($type));
 3201:     }
 3202: }
 3203: 
 3204: sub embedded_dependency {
 3205:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3206:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3207:         if (($identifier ne '') &&
 3208:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3209:             ($pathfrom ne '')) {
 3210:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3211:             foreach my $dep (@{$related->{$identifier}}) {
 3212:                 &add_filetype($allfiles,$path.$dep,'object');
 3213:             }
 3214:         }
 3215:     }
 3216:     return;
 3217: }
 3218: 
 3219: sub removeuploadedurl {
 3220:     my ($url)=@_;	
 3221:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3222:     return &removeuserfile($uname,$udom,$fname);
 3223: }
 3224: 
 3225: sub removeuserfile {
 3226:     my ($docuname,$docudom,$fname)=@_;
 3227:     my $home=&homeserver($docuname,$docudom);    
 3228:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3229:     if ($result eq 'ok') {	
 3230:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3231:             my $metafile = $fname.'.meta';
 3232:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3233: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3234:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3235:             my $sqlresult = 
 3236:                 &update_portfolio_table($docuname,$docudom,$file,
 3237:                                         'portfolio_metadata',$group,
 3238:                                         'delete');
 3239:         }
 3240:     }
 3241:     return $result;
 3242: }
 3243: 
 3244: sub mkdiruserfile {
 3245:     my ($docuname,$docudom,$dir)=@_;
 3246:     my $home=&homeserver($docuname,$docudom);
 3247:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3248: }
 3249: 
 3250: sub renameuserfile {
 3251:     my ($docuname,$docudom,$old,$new)=@_;
 3252:     my $home=&homeserver($docuname,$docudom);
 3253:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3254:                         &escape("$old").':'.&escape("$new"),$home);
 3255:     if ($result eq 'ok') {
 3256:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3257:             my $oldmeta = $old.'.meta';
 3258:             my $newmeta = $new.'.meta';
 3259:             my $metaresult = 
 3260:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3261: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3262:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3263:             my $sqlresult = 
 3264:                 &update_portfolio_table($docuname,$docudom,$file,
 3265:                                         'portfolio_metadata',$group,
 3266:                                         'delete');
 3267:         }
 3268:     }
 3269:     return $result;
 3270: }
 3271: 
 3272: # ------------------------------------------------------------------------- Log
 3273: 
 3274: sub log {
 3275:     my ($dom,$nam,$hom,$what)=@_;
 3276:     return critical("log:$dom:$nam:$what",$hom);
 3277: }
 3278: 
 3279: # ------------------------------------------------------------------ Course Log
 3280: #
 3281: # This routine flushes several buffers of non-mission-critical nature
 3282: #
 3283: 
 3284: sub flushcourselogs {
 3285:     &logthis('Flushing log buffers');
 3286: #
 3287: # course logs
 3288: # This is a log of all transactions in a course, which can be used
 3289: # for data mining purposes
 3290: #
 3291: # It also collects the courseid database, which lists last transaction
 3292: # times and course titles for all courseids
 3293: #
 3294:     my %courseidbuffer=();
 3295:     foreach my $crsid (keys(%courselogs)) {
 3296:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3297: 		          &escape($courselogs{$crsid}),
 3298: 		          $coursehombuf{$crsid}) eq 'ok') {
 3299: 	    delete $courselogs{$crsid};
 3300:         } else {
 3301:             &logthis('Failed to flush log buffer for '.$crsid);
 3302:             if (length($courselogs{$crsid})>40000) {
 3303:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3304:                         " exceeded maximum size, deleting.</font>");
 3305:                delete $courselogs{$crsid};
 3306:             }
 3307:         }
 3308:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3309:             'description' => $coursedescrbuf{$crsid},
 3310:             'inst_code'    => $courseinstcodebuf{$crsid},
 3311:             'type'        => $coursetypebuf{$crsid},
 3312:             'owner'       => $courseownerbuf{$crsid},
 3313:         };
 3314:     }
 3315: #
 3316: # Write course id database (reverse lookup) to homeserver of courses 
 3317: # Is used in pickcourse
 3318: #
 3319:     foreach my $crs_home (keys(%courseidbuffer)) {
 3320:         my $response = &courseidput(&host_domain($crs_home),
 3321:                                     $courseidbuffer{$crs_home},
 3322:                                     $crs_home,'timeonly');
 3323:     }
 3324: #
 3325: # File accesses
 3326: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3327: #
 3328:     foreach my $entry (keys(%accesshash)) {
 3329:         if ($entry =~ /___count$/) {
 3330:             my ($dom,$name);
 3331:             ($dom,$name,undef)=
 3332: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3333:             if (! defined($dom) || $dom eq '' || 
 3334:                 ! defined($name) || $name eq '') {
 3335:                 my $cid = $env{'request.course.id'};
 3336:                 $dom  = $env{'request.'.$cid.'.domain'};
 3337:                 $name = $env{'request.'.$cid.'.num'};
 3338:             }
 3339:             my $value = $accesshash{$entry};
 3340:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3341:             my %temphash=($url => $value);
 3342:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3343:             if ($result eq 'ok') {
 3344:                 delete $accesshash{$entry};
 3345:             }
 3346:         } else {
 3347:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3348:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3349:             my %temphash=($entry => $accesshash{$entry});
 3350:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3351:                 delete $accesshash{$entry};
 3352:             }
 3353:         }
 3354:     }
 3355: #
 3356: # Roles
 3357: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3358: #
 3359:     foreach my $entry (keys(%userrolehash)) {
 3360:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3361: 	    split(/\:/,$entry);
 3362:         if (&Apache::lonnet::put('nohist_userroles',
 3363:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3364:                 $rudom,$runame) eq 'ok') {
 3365: 	    delete $userrolehash{$entry};
 3366:         }
 3367:     }
 3368: #
 3369: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3370: #
 3371:     my %domrolebuffer = ();
 3372:     foreach my $entry (keys(%domainrolehash)) {
 3373:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3374:         if ($domrolebuffer{$rudom}) {
 3375:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3376:                       '='.&escape($domainrolehash{$entry});
 3377:         } else {
 3378:             $domrolebuffer{$rudom}.=&escape($entry).
 3379:                       '='.&escape($domainrolehash{$entry});
 3380:         }
 3381:         delete $domainrolehash{$entry};
 3382:     }
 3383:     foreach my $dom (keys(%domrolebuffer)) {
 3384: 	my %servers = &get_servers($dom,'library');
 3385: 	foreach my $tryserver (keys(%servers)) {
 3386: 	    unless (&reply('domroleput:'.$dom.':'.
 3387: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3388: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3389: 	    }
 3390:         }
 3391:     }
 3392:     $dumpcount++;
 3393: }
 3394: 
 3395: sub courselog {
 3396:     my $what=shift;
 3397:     $what=time.':'.$what;
 3398:     unless ($env{'request.course.id'}) { return ''; }
 3399:     $coursedombuf{$env{'request.course.id'}}=
 3400:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3401:     $coursenumbuf{$env{'request.course.id'}}=
 3402:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3403:     $coursehombuf{$env{'request.course.id'}}=
 3404:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3405:     $coursedescrbuf{$env{'request.course.id'}}=
 3406:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3407:     $courseinstcodebuf{$env{'request.course.id'}}=
 3408:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3409:     $courseownerbuf{$env{'request.course.id'}}=
 3410:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3411:     $coursetypebuf{$env{'request.course.id'}}=
 3412:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3413:     if (defined $courselogs{$env{'request.course.id'}}) {
 3414: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3415:     } else {
 3416: 	$courselogs{$env{'request.course.id'}}.=$what;
 3417:     }
 3418:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3419: 	&flushcourselogs();
 3420:     }
 3421: }
 3422: 
 3423: sub courseacclog {
 3424:     my $fnsymb=shift;
 3425:     unless ($env{'request.course.id'}) { return ''; }
 3426:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3427:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3428:         $what.=':POST';
 3429:         # FIXME: Probably ought to escape things....
 3430: 	foreach my $key (keys(%env)) {
 3431:             if ($key=~/^form\.(.*)/) {
 3432:                 my $formitem = $1;
 3433:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3434:                     $what.=':'.$formitem.'='.$env{$key};
 3435:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3436:                     $what.=':'.$formitem.'='.$env{$key};
 3437:                 }
 3438:             }
 3439:         }
 3440:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3441:         # FIXME: We should not be depending on a form parameter that someone
 3442:         # editing lonsearchcat.pm might change in the future.
 3443:         if ($env{'form.phase'} eq 'course_search') {
 3444:             $what.= ':POST';
 3445:             # FIXME: Probably ought to escape things....
 3446:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3447:                                  'crsdiscuss') {
 3448:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3449:             }
 3450:         }
 3451:     }
 3452:     &courselog($what);
 3453: }
 3454: 
 3455: sub countacc {
 3456:     my $url=&declutter(shift);
 3457:     return if (! defined($url) || $url eq '');
 3458:     unless ($env{'request.course.id'}) { return ''; }
 3459: #
 3460: # Mark that this url was used in this course
 3461: #
 3462:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3463: #
 3464: # Increase the access count for this resource in this child process
 3465: #
 3466:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3467:     $accesshash{$key}++;
 3468: }
 3469: 
 3470: sub linklog {
 3471:     my ($from,$to)=@_;
 3472:     $from=&declutter($from);
 3473:     $to=&declutter($to);
 3474:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3475:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3476: }
 3477: 
 3478: sub statslog {
 3479:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3480:     if ($users<2) { return; }
 3481:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3482:             'course'       => $env{'request.course.id'},
 3483:             'sections'     => '"all"',
 3484:             'num_students' => $users,
 3485:             'part'         => $part,
 3486:             'symb'         => $symb,
 3487:             'mean_tries'   => $av_attempts,
 3488:             'deg_of_diff'  => $degdiff});
 3489:     foreach my $key (keys(%dynstore)) {
 3490:         $accesshash{$key}=$dynstore{$key};
 3491:     }
 3492: }
 3493:   
 3494: sub userrolelog {
 3495:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3496:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 3497:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 3498:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 3499:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 3500:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3501:        $userrolehash
 3502:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3503:                     =$tend.':'.$tstart;
 3504:     }
 3505:     if (($env{'request.role'} =~ /dc\./) &&
 3506: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 3507: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 3508: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 3509:          ($trole=~/^co/))) {
 3510:        $userrolehash
 3511:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3512:                     =$tend.':'.$tstart;
 3513:     }
 3514:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 3515:         ($trole=~/^li/) || ($trole=~/^li/) ||
 3516:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 3517:         ($trole=~/^sc/)) {
 3518:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3519:        $domainrolehash
 3520:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3521:                     = $tend.':'.$tstart;
 3522:     }
 3523: }
 3524: 
 3525: sub courserolelog {
 3526:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3527:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3528:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3529:         ($trole eq 'ta') || ($trole eq 'st') ||
 3530:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3531:         ($trole eq 'co')) {
 3532:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3533:             my $cdom = $1;
 3534:             my $cnum = $2;
 3535:             my $sec = $3;
 3536:             my $namespace = 'rolelog';
 3537:             my %storehash = (
 3538:                                role    => $trole,
 3539:                                start   => $tstart,
 3540:                                end     => $tend,
 3541:                                selfenroll => $selfenroll,
 3542:                                context    => $context,
 3543:                             );
 3544:             if ($trole eq 'gr') {
 3545:                 $namespace = 'groupslog';
 3546:                 $storehash{'group'} = $sec;
 3547:             } else {
 3548:                 $storehash{'section'} = $sec;
 3549:             }
 3550:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3551:             if (($trole ne 'st') || ($sec ne '')) {
 3552:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3553:             }
 3554:         }
 3555:     }
 3556:     return;
 3557: }
 3558: 
 3559: sub get_course_adv_roles {
 3560:     my ($cid,$codes) = @_;
 3561:     $cid=$env{'request.course.id'} unless (defined($cid));
 3562:     my %coursehash=&coursedescription($cid);
 3563:     my $crstype = &Apache::loncommon::course_type($cid);
 3564:     my %nothide=();
 3565:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3566:         if ($user !~ /:/) {
 3567: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3568:         } else {
 3569:             $nothide{$user}=1;
 3570:         }
 3571:     }
 3572:     my %returnhash=();
 3573:     my %dumphash=
 3574:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3575:     my $now=time;
 3576:     my %privileged;
 3577:     foreach my $entry (keys(%dumphash)) {
 3578: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3579:         if (($tstart) && ($tstart<0)) { next; }
 3580:         if (($tend) && ($tend<$now)) { next; }
 3581:         if (($tstart) && ($now<$tstart)) { next; }
 3582:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3583: 	if ($username eq '' || $domain eq '') { next; }
 3584:         unless (ref($privileged{$domain}) eq 'HASH') {
 3585:             my %dompersonnel =
 3586:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3587:             $privileged{$domain} = {};
 3588:             foreach my $server (keys(%dompersonnel)) {
 3589:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3590:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3591:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3592:                         $privileged{$udom}{$uname} = 1;
 3593:                     }
 3594:                 }
 3595:             }
 3596:         }
 3597:         if ((exists($privileged{$domain}{$username})) && 
 3598:             (!$nothide{$username.':'.$domain})) { next; }
 3599: 	if ($role eq 'cr') { next; }
 3600:         if ($codes) {
 3601:             if ($section) { $role .= ':'.$section; }
 3602:             if ($returnhash{$role}) {
 3603:                 $returnhash{$role}.=','.$username.':'.$domain;
 3604:             } else {
 3605:                 $returnhash{$role}=$username.':'.$domain;
 3606:             }
 3607:         } else {
 3608:             my $key=&plaintext($role,$crstype);
 3609:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3610:             if ($returnhash{$key}) {
 3611: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3612:             } else {
 3613:                 $returnhash{$key}=$username.':'.$domain;
 3614:             }
 3615:         }
 3616:     }
 3617:     return %returnhash;
 3618: }
 3619: 
 3620: sub get_my_roles {
 3621:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3622:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3623:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3624:     my (%dumphash,%nothide);
 3625:     if ($context eq 'userroles') {
 3626:         my $extra = &freeze_escape({'skipcheck' => 1});
 3627:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
 3628:     } else {
 3629:         %dumphash=
 3630:             &dump('nohist_userroles',$udom,$uname);
 3631:         if ($hidepriv) {
 3632:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3633:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3634:                 if ($user !~ /:/) {
 3635:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3636:                 } else {
 3637:                     $nothide{$user} = 1;
 3638:                 }
 3639:             }
 3640:         }
 3641:     }
 3642:     my %returnhash=();
 3643:     my $now=time;
 3644:     my %privileged;
 3645:     foreach my $entry (keys(%dumphash)) {
 3646:         my ($role,$tend,$tstart);
 3647:         if ($context eq 'userroles') {
 3648:             next if ($entry =~ /^rolesdef/);
 3649: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3650:         } else {
 3651:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3652:         }
 3653:         if (($tstart) && ($tstart<0)) { next; }
 3654:         my $status = 'active';
 3655:         if (($tend) && ($tend<=$now)) {
 3656:             $status = 'previous';
 3657:         } 
 3658:         if (($tstart) && ($now<$tstart)) {
 3659:             $status = 'future';
 3660:         }
 3661:         if (ref($types) eq 'ARRAY') {
 3662:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3663:                 next;
 3664:             } 
 3665:         } else {
 3666:             if ($status ne 'active') {
 3667:                 next;
 3668:             }
 3669:         }
 3670:         my ($rolecode,$username,$domain,$section,$area);
 3671:         if ($context eq 'userroles') {
 3672:             ($area,$rolecode) = split(/_/,$entry);
 3673:             (undef,$domain,$username,$section) = split(/\//,$area);
 3674:         } else {
 3675:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3676:         }
 3677:         if (ref($roledoms) eq 'ARRAY') {
 3678:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3679:                 next;
 3680:             }
 3681:         }
 3682:         if (ref($roles) eq 'ARRAY') {
 3683:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3684:                 if ($role =~ /^cr\//) {
 3685:                     if (!grep(/^cr$/,@{$roles})) {
 3686:                         next;
 3687:                     }
 3688:                 } elsif ($role =~ /^gr\//) {
 3689:                     if (!grep(/^gr$/,@{$roles})) {
 3690:                         next;
 3691:                     }
 3692:                 } else {
 3693:                     next;
 3694:                 }
 3695:             }
 3696:         }
 3697:         if ($hidepriv) {
 3698:             if ($context eq 'userroles') {
 3699:                 if ((&privileged($username,$domain)) &&
 3700:                     (!$nothide{$username.':'.$domain})) {
 3701:                     next;
 3702:                 }
 3703:             } else {
 3704:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3705:                     my %dompersonnel =
 3706:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3707:                     $privileged{$domain} = {};
 3708:                     if (keys(%dompersonnel)) {
 3709:                         foreach my $server (keys(%dompersonnel)) {
 3710:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3711:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3712:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3713:                                     $privileged{$udom}{$uname} = $trole;
 3714:                                 }
 3715:                             }
 3716:                         }
 3717:                     }
 3718:                 }
 3719:                 if (exists($privileged{$domain}{$username})) {
 3720:                     if (!$nothide{$username.':'.$domain}) {
 3721:                         next;
 3722:                     }
 3723:                 }
 3724:             }
 3725:         }
 3726:         if ($withsec) {
 3727:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3728:                 $tstart.':'.$tend;
 3729:         } else {
 3730:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3731:         }
 3732:     }
 3733:     return %returnhash;
 3734: }
 3735: 
 3736: # ----------------------------------------------------- Frontpage Announcements
 3737: #
 3738: #
 3739: 
 3740: sub postannounce {
 3741:     my ($server,$text)=@_;
 3742:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3743:     unless ($text=~/\w/) { $text=''; }
 3744:     return &reply('setannounce:'.&escape($text),$server);
 3745: }
 3746: 
 3747: sub getannounce {
 3748: 
 3749:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3750: 	my $announcement='';
 3751: 	while (my $line = <$fh>) { $announcement .= $line; }
 3752: 	close($fh);
 3753: 	if ($announcement=~/\w/) { 
 3754: 	    return 
 3755:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3756:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3757: 	} else {
 3758: 	    return '';
 3759: 	}
 3760:     } else {
 3761: 	return '';
 3762:     }
 3763: }
 3764: 
 3765: # ---------------------------------------------------------- Course ID routines
 3766: # Deal with domain's nohist_courseid.db files
 3767: #
 3768: 
 3769: sub courseidput {
 3770:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3771:     return unless (ref($storehash) eq 'HASH');
 3772:     my $outcome;
 3773:     if ($caller eq 'timeonly') {
 3774:         my $cids = '';
 3775:         foreach my $item (keys(%$storehash)) {
 3776:             $cids.=&escape($item).'&';
 3777:         }
 3778:         $cids=~s/\&$//;
 3779:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3780:                           $coursehome);       
 3781:     } else {
 3782:         my $items = '';
 3783:         foreach my $item (keys(%$storehash)) {
 3784:             $items.= &escape($item).'='.
 3785:                      &freeze_escape($$storehash{$item}).'&';
 3786:         }
 3787:         $items=~s/\&$//;
 3788:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3789:                           $coursehome);
 3790:     }
 3791:     if ($outcome eq 'unknown_cmd') {
 3792:         my $what;
 3793:         foreach my $cid (keys(%$storehash)) {
 3794:             $what .= &escape($cid).'=';
 3795:             foreach my $item ('description','inst_code','owner','type') {
 3796:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3797:             }
 3798:             $what =~ s/\:$/&/;
 3799:         }
 3800:         $what =~ s/\&$//;  
 3801:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3802:     } else {
 3803:         return $outcome;
 3804:     }
 3805: }
 3806: 
 3807: sub courseiddump {
 3808:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3809:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3810:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3811:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3812:     my $as_hash = 1;
 3813:     my %returnhash;
 3814:     if (!$domfilter) { $domfilter=''; }
 3815:     my %libserv = &all_library();
 3816:     foreach my $tryserver (keys(%libserv)) {
 3817:         if ( (  $hostidflag == 1 
 3818: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3819: 	     || (!defined($hostidflag)) ) {
 3820: 
 3821: 	    if (($domfilter eq '') ||
 3822: 		(&host_domain($tryserver) eq $domfilter)) {
 3823:                 my $rep = 
 3824:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3825:                          $sincefilter.':'.&escape($descfilter).':'.
 3826:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3827:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3828:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3829:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3830:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3831:                          &escape($cc_clone).':'.$cloneonly.':'.
 3832:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3833:                          &escape($creationcontext).':'.$domcloner,
 3834:                          $tryserver);
 3835:                 my @pairs=split(/\&/,$rep);
 3836:                 foreach my $item (@pairs) {
 3837:                     my ($key,$value)=split(/\=/,$item,2);
 3838:                     $key = &unescape($key);
 3839:                     next if ($key =~ /^error: 2 /);
 3840:                     my $result = &thaw_unescape($value);
 3841:                     if (ref($result) eq 'HASH') {
 3842:                         $returnhash{$key}=$result;
 3843:                     } else {
 3844:                         my @responses = split(/:/,$value);
 3845:                         my @items = ('description','inst_code','owner','type');
 3846:                         for (my $i=0; $i<@responses; $i++) {
 3847:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3848:                         }
 3849:                     }
 3850:                 }
 3851:             }
 3852:         }
 3853:     }
 3854:     return %returnhash;
 3855: }
 3856: 
 3857: sub courselastaccess {
 3858:     my ($cdom,$cnum,$hostidref) = @_;
 3859:     my %returnhash;
 3860:     if ($cdom && $cnum) {
 3861:         my $chome = &homeserver($cnum,$cdom);
 3862:         if ($chome ne 'no_host') {
 3863:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3864:             &extract_lastaccess(\%returnhash,$rep);
 3865:         }
 3866:     } else {
 3867:         if (!$cdom) { $cdom=''; }
 3868:         my %libserv = &all_library();
 3869:         foreach my $tryserver (keys(%libserv)) {
 3870:             if (ref($hostidref) eq 'ARRAY') {
 3871:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3872:             } 
 3873:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3874:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3875:                 &extract_lastaccess(\%returnhash,$rep);
 3876:             }
 3877:         }
 3878:     }
 3879:     return %returnhash;
 3880: }
 3881: 
 3882: sub extract_lastaccess {
 3883:     my ($returnhash,$rep) = @_;
 3884:     if (ref($returnhash) eq 'HASH') {
 3885:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3886:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3887:                  $rep eq '') {
 3888:             my @pairs=split(/\&/,$rep);
 3889:             foreach my $item (@pairs) {
 3890:                 my ($key,$value)=split(/\=/,$item,2);
 3891:                 $key = &unescape($key);
 3892:                 next if ($key =~ /^error: 2 /);
 3893:                 $returnhash->{$key} = &thaw_unescape($value);
 3894:             }
 3895:         }
 3896:     }
 3897:     return;
 3898: }
 3899: 
 3900: # ---------------------------------------------------------- DC e-mail
 3901: 
 3902: sub dcmailput {
 3903:     my ($domain,$msgid,$message,$server)=@_;
 3904:     my $status = &Apache::lonnet::critical(
 3905:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3906:        &escape($message),$server);
 3907:     return $status;
 3908: }
 3909: 
 3910: sub dcmaildump {
 3911:     my ($dom,$startdate,$enddate,$senders) = @_;
 3912:     my %returnhash=();
 3913: 
 3914:     if (defined(&domain($dom,'primary'))) {
 3915:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3916:                                                          &escape($enddate).':';
 3917: 	my @esc_senders=map { &escape($_)} @$senders;
 3918: 	$cmd.=&escape(join('&',@esc_senders));
 3919: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3920:             my ($key,$value) = split(/\=/,$line,2);
 3921:             if (($key) && ($value)) {
 3922:                 $returnhash{&unescape($key)} = &unescape($value);
 3923:             }
 3924:         }
 3925:     }
 3926:     return %returnhash;
 3927: }
 3928: # ---------------------------------------------------------- Domain roles
 3929: 
 3930: sub get_domain_roles {
 3931:     my ($dom,$roles,$startdate,$enddate)=@_;
 3932:     if ((!defined($startdate)) || ($startdate eq '')) {
 3933:         $startdate = '.';
 3934:     }
 3935:     if ((!defined($enddate)) || ($enddate eq '')) {
 3936:         $enddate = '.';
 3937:     }
 3938:     my $rolelist;
 3939:     if (ref($roles) eq 'ARRAY') {
 3940:         $rolelist = join(':',@{$roles});
 3941:     }
 3942:     my %personnel = ();
 3943: 
 3944:     my %servers = &get_servers($dom,'library');
 3945:     foreach my $tryserver (keys(%servers)) {
 3946: 	%{$personnel{$tryserver}}=();
 3947: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3948: 					    &escape($startdate).':'.
 3949: 					    &escape($enddate).':'.
 3950: 					    &escape($rolelist), $tryserver))) {
 3951: 	    my ($key,$value) = split(/\=/,$line,2);
 3952: 	    if (($key) && ($value)) {
 3953: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3954: 	    }
 3955: 	}
 3956:     }
 3957:     return %personnel;
 3958: }
 3959: 
 3960: # ----------------------------------------------------------- Interval timing 
 3961: 
 3962: {
 3963: # Caches needed for speedup of navmaps
 3964: # We don't want to cache this for very long at all (5 seconds at most)
 3965: # 
 3966: # The user for whom we cache
 3967: my $cachedkey='';
 3968: # The cached times for this user
 3969: my %cachedtimes=();
 3970: # When this was last done
 3971: my $cachedtime=();
 3972: 
 3973: sub load_all_first_access {
 3974:     my ($uname,$udom)=@_;
 3975:     if (($cachedkey eq $uname.':'.$udom) &&
 3976:         (abs($cachedtime-time)<5)) {
 3977:         return;
 3978:     }
 3979:     $cachedtime=time;
 3980:     $cachedkey=$uname.':'.$udom;
 3981:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 3982: }
 3983: 
 3984: sub get_first_access {
 3985:     my ($type,$argsymb,$argmap)=@_;
 3986:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3987:     if ($argsymb) { $symb=$argsymb; }
 3988:     my ($map,$id,$res)=&decode_symb($symb);
 3989:     if ($argmap) { $map = $argmap; }
 3990:     if ($type eq 'course') {
 3991: 	$res='course';
 3992:     } elsif ($type eq 'map') {
 3993: 	$res=&symbread($map);
 3994:     } else {
 3995: 	$res=$symb;
 3996:     }
 3997:     &load_all_first_access($uname,$udom);
 3998:     return $cachedtimes{"$courseid\0$res"};
 3999: }
 4000: 
 4001: sub set_first_access {
 4002:     my ($type,$interval)=@_;
 4003:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4004:     my ($map,$id,$res)=&decode_symb($symb);
 4005:     if ($type eq 'course') {
 4006: 	$res='course';
 4007:     } elsif ($type eq 'map') {
 4008: 	$res=&symbread($map);
 4009:     } else {
 4010: 	$res=$symb;
 4011:     }
 4012:     $cachedkey='';
 4013:     my $firstaccess=&get_first_access($type,$symb,$map);
 4014:     if (!$firstaccess) {
 4015:         my $start = time;
 4016: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4017:                           $udom,$uname);
 4018:         if ($putres eq 'ok') {
 4019:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4020:                  $udom,$uname); 
 4021:             &appenv(
 4022:                      {
 4023:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4024:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4025:                      }
 4026:                   );
 4027:         }
 4028:         return $putres;
 4029:     }
 4030:     return 'already_set';
 4031: }
 4032: }
 4033: # --------------------------------------------- Set Expire Date for Spreadsheet
 4034: 
 4035: sub expirespread {
 4036:     my ($uname,$udom,$stype,$usymb)=@_;
 4037:     my $cid=$env{'request.course.id'}; 
 4038:     if ($cid) {
 4039:        my $now=time;
 4040:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4041:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4042:                             $env{'course.'.$cid.'.num'}.
 4043: 	        	    ':nohist_expirationdates:'.
 4044:                             &escape($key).'='.$now,
 4045:                             $env{'course.'.$cid.'.home'})
 4046:     }
 4047:     return 'ok';
 4048: }
 4049: 
 4050: # ----------------------------------------------------- Devalidate Spreadsheets
 4051: 
 4052: sub devalidate {
 4053:     my ($symb,$uname,$udom)=@_;
 4054:     my $cid=$env{'request.course.id'}; 
 4055:     if ($cid) {
 4056:         # delete the stored spreadsheets for
 4057:         # - the student level sheet of this user in course's homespace
 4058:         # - the assessment level sheet for this resource 
 4059:         #   for this user in user's homespace
 4060: 	# - current conditional state info
 4061: 	my $key=$uname.':'.$udom.':';
 4062:         my $status=
 4063: 	    &del('nohist_calculatedsheets',
 4064: 		 [$key.'studentcalc:'],
 4065: 		 $env{'course.'.$cid.'.domain'},
 4066: 		 $env{'course.'.$cid.'.num'})
 4067: 		.' '.
 4068: 	    &del('nohist_calculatedsheets_'.$cid,
 4069: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4070:         unless ($status eq 'ok ok') {
 4071:            &logthis('Could not devalidate spreadsheet '.
 4072:                     $uname.' at '.$udom.' for '.
 4073: 		    $symb.': '.$status);
 4074:         }
 4075: 	&delenv('user.state.'.$cid);
 4076:     }
 4077: }
 4078: 
 4079: sub get_scalar {
 4080:     my ($string,$end) = @_;
 4081:     my $value;
 4082:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4083: 	$value = $1;
 4084:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4085: 	$value = $1;
 4086:     }
 4087:     return &unescape($value);
 4088: }
 4089: 
 4090: sub array2str {
 4091:   my (@array) = @_;
 4092:   my $result=&arrayref2str(\@array);
 4093:   $result=~s/^__ARRAY_REF__//;
 4094:   $result=~s/__END_ARRAY_REF__$//;
 4095:   return $result;
 4096: }
 4097: 
 4098: sub arrayref2str {
 4099:   my ($arrayref) = @_;
 4100:   my $result='__ARRAY_REF__';
 4101:   foreach my $elem (@$arrayref) {
 4102:     if(ref($elem) eq 'ARRAY') {
 4103:       $result.=&arrayref2str($elem).'&';
 4104:     } elsif(ref($elem) eq 'HASH') {
 4105:       $result.=&hashref2str($elem).'&';
 4106:     } elsif(ref($elem)) {
 4107:       #print("Got a ref of ".(ref($elem))." skipping.");
 4108:     } else {
 4109:       $result.=&escape($elem).'&';
 4110:     }
 4111:   }
 4112:   $result=~s/\&$//;
 4113:   $result .= '__END_ARRAY_REF__';
 4114:   return $result;
 4115: }
 4116: 
 4117: sub hash2str {
 4118:   my (%hash) = @_;
 4119:   my $result=&hashref2str(\%hash);
 4120:   $result=~s/^__HASH_REF__//;
 4121:   $result=~s/__END_HASH_REF__$//;
 4122:   return $result;
 4123: }
 4124: 
 4125: sub hashref2str {
 4126:   my ($hashref)=@_;
 4127:   my $result='__HASH_REF__';
 4128:   foreach my $key (sort(keys(%$hashref))) {
 4129:     if (ref($key) eq 'ARRAY') {
 4130:       $result.=&arrayref2str($key).'=';
 4131:     } elsif (ref($key) eq 'HASH') {
 4132:       $result.=&hashref2str($key).'=';
 4133:     } elsif (ref($key)) {
 4134:       $result.='=';
 4135:       #print("Got a ref of ".(ref($key))." skipping.");
 4136:     } else {
 4137: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4138:     }
 4139: 
 4140:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4141:       $result.=&arrayref2str($hashref->{$key}).'&';
 4142:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4143:       $result.=&hashref2str($hashref->{$key}).'&';
 4144:     } elsif(ref($hashref->{$key})) {
 4145:        $result.='&';
 4146:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4147:     } else {
 4148:       $result.=&escape($hashref->{$key}).'&';
 4149:     }
 4150:   }
 4151:   $result=~s/\&$//;
 4152:   $result .= '__END_HASH_REF__';
 4153:   return $result;
 4154: }
 4155: 
 4156: sub str2hash {
 4157:     my ($string)=@_;
 4158:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4159:     return %$hash;
 4160: }
 4161: 
 4162: sub str2hashref {
 4163:   my ($string) = @_;
 4164: 
 4165:   my %hash;
 4166: 
 4167:   if($string !~ /^__HASH_REF__/) {
 4168:       if (! ($string eq '' || !defined($string))) {
 4169: 	  $hash{'error'}='Not hash reference';
 4170:       }
 4171:       return (\%hash, $string);
 4172:   }
 4173: 
 4174:   $string =~ s/^__HASH_REF__//;
 4175: 
 4176:   while($string !~ /^__END_HASH_REF__/) {
 4177:       #key
 4178:       my $key='';
 4179:       if($string =~ /^__HASH_REF__/) {
 4180:           ($key, $string)=&str2hashref($string);
 4181:           if(defined($key->{'error'})) {
 4182:               $hash{'error'}='Bad data';
 4183:               return (\%hash, $string);
 4184:           }
 4185:       } elsif($string =~ /^__ARRAY_REF__/) {
 4186:           ($key, $string)=&str2arrayref($string);
 4187:           if($key->[0] eq 'Array reference error') {
 4188:               $hash{'error'}='Bad data';
 4189:               return (\%hash, $string);
 4190:           }
 4191:       } else {
 4192:           $string =~ s/^(.*?)=//;
 4193: 	  $key=&unescape($1);
 4194:       }
 4195:       $string =~ s/^=//;
 4196: 
 4197:       #value
 4198:       my $value='';
 4199:       if($string =~ /^__HASH_REF__/) {
 4200:           ($value, $string)=&str2hashref($string);
 4201:           if(defined($value->{'error'})) {
 4202:               $hash{'error'}='Bad data';
 4203:               return (\%hash, $string);
 4204:           }
 4205:       } elsif($string =~ /^__ARRAY_REF__/) {
 4206:           ($value, $string)=&str2arrayref($string);
 4207:           if($value->[0] eq 'Array reference error') {
 4208:               $hash{'error'}='Bad data';
 4209:               return (\%hash, $string);
 4210:           }
 4211:       } else {
 4212: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4213:       }
 4214:       $string =~ s/^&//;
 4215: 
 4216:       $hash{$key}=$value;
 4217:   }
 4218: 
 4219:   $string =~ s/^__END_HASH_REF__//;
 4220: 
 4221:   return (\%hash, $string);
 4222: }
 4223: 
 4224: sub str2array {
 4225:     my ($string)=@_;
 4226:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4227:     return @$array;
 4228: }
 4229: 
 4230: sub str2arrayref {
 4231:   my ($string) = @_;
 4232:   my @array;
 4233: 
 4234:   if($string !~ /^__ARRAY_REF__/) {
 4235:       if (! ($string eq '' || !defined($string))) {
 4236: 	  $array[0]='Array reference error';
 4237:       }
 4238:       return (\@array, $string);
 4239:   }
 4240: 
 4241:   $string =~ s/^__ARRAY_REF__//;
 4242: 
 4243:   while($string !~ /^__END_ARRAY_REF__/) {
 4244:       my $value='';
 4245:       if($string =~ /^__HASH_REF__/) {
 4246:           ($value, $string)=&str2hashref($string);
 4247:           if(defined($value->{'error'})) {
 4248:               $array[0] ='Array reference error';
 4249:               return (\@array, $string);
 4250:           }
 4251:       } elsif($string =~ /^__ARRAY_REF__/) {
 4252:           ($value, $string)=&str2arrayref($string);
 4253:           if($value->[0] eq 'Array reference error') {
 4254:               $array[0] ='Array reference error';
 4255:               return (\@array, $string);
 4256:           }
 4257:       } else {
 4258: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4259:       }
 4260:       $string =~ s/^&//;
 4261: 
 4262:       push(@array, $value);
 4263:   }
 4264: 
 4265:   $string =~ s/^__END_ARRAY_REF__//;
 4266: 
 4267:   return (\@array, $string);
 4268: }
 4269: 
 4270: # -------------------------------------------------------------------Temp Store
 4271: 
 4272: sub tmpreset {
 4273:   my ($symb,$namespace,$domain,$stuname) = @_;
 4274:   if (!$symb) {
 4275:     $symb=&symbread();
 4276:     if (!$symb) { $symb= $env{'request.url'}; }
 4277:   }
 4278:   $symb=escape($symb);
 4279: 
 4280:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4281:   $namespace=~s/\//\_/g;
 4282:   $namespace=~s/\W//g;
 4283: 
 4284:   if (!$domain) { $domain=$env{'user.domain'}; }
 4285:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4286:   if ($domain eq 'public' && $stuname eq 'public') {
 4287:       $stuname=$ENV{'REMOTE_ADDR'};
 4288:   }
 4289:   my $path=LONCAPA::tempdir();
 4290:   my %hash;
 4291:   if (tie(%hash,'GDBM_File',
 4292: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4293: 	  &GDBM_WRCREAT(),0640)) {
 4294:     foreach my $key (keys(%hash)) {
 4295:       if ($key=~ /:$symb/) {
 4296: 	delete($hash{$key});
 4297:       }
 4298:     }
 4299:   }
 4300: }
 4301: 
 4302: sub tmpstore {
 4303:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4304: 
 4305:   if (!$symb) {
 4306:     $symb=&symbread();
 4307:     if (!$symb) { $symb= $env{'request.url'}; }
 4308:   }
 4309:   $symb=escape($symb);
 4310: 
 4311:   if (!$namespace) {
 4312:     # I don't think we would ever want to store this for a course.
 4313:     # it seems this will only be used if we don't have a course.
 4314:     #$namespace=$env{'request.course.id'};
 4315:     #if (!$namespace) {
 4316:       $namespace=$env{'request.state'};
 4317:     #}
 4318:   }
 4319:   $namespace=~s/\//\_/g;
 4320:   $namespace=~s/\W//g;
 4321:   if (!$domain) { $domain=$env{'user.domain'}; }
 4322:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4323:   if ($domain eq 'public' && $stuname eq 'public') {
 4324:       $stuname=$ENV{'REMOTE_ADDR'};
 4325:   }
 4326:   my $now=time;
 4327:   my %hash;
 4328:   my $path=LONCAPA::tempdir();
 4329:   if (tie(%hash,'GDBM_File',
 4330: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4331: 	  &GDBM_WRCREAT(),0640)) {
 4332:     $hash{"version:$symb"}++;
 4333:     my $version=$hash{"version:$symb"};
 4334:     my $allkeys=''; 
 4335:     foreach my $key (keys(%$storehash)) {
 4336:       $allkeys.=$key.':';
 4337:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4338:     }
 4339:     $hash{"$version:$symb:timestamp"}=$now;
 4340:     $allkeys.='timestamp';
 4341:     $hash{"$version:keys:$symb"}=$allkeys;
 4342:     if (untie(%hash)) {
 4343:       return 'ok';
 4344:     } else {
 4345:       return "error:$!";
 4346:     }
 4347:   } else {
 4348:     return "error:$!";
 4349:   }
 4350: }
 4351: 
 4352: # -----------------------------------------------------------------Temp Restore
 4353: 
 4354: sub tmprestore {
 4355:   my ($symb,$namespace,$domain,$stuname) = @_;
 4356: 
 4357:   if (!$symb) {
 4358:     $symb=&symbread();
 4359:     if (!$symb) { $symb= $env{'request.url'}; }
 4360:   }
 4361:   $symb=escape($symb);
 4362: 
 4363:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4364: 
 4365:   if (!$domain) { $domain=$env{'user.domain'}; }
 4366:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4367:   if ($domain eq 'public' && $stuname eq 'public') {
 4368:       $stuname=$ENV{'REMOTE_ADDR'};
 4369:   }
 4370:   my %returnhash;
 4371:   $namespace=~s/\//\_/g;
 4372:   $namespace=~s/\W//g;
 4373:   my %hash;
 4374:   my $path=LONCAPA::tempdir();
 4375:   if (tie(%hash,'GDBM_File',
 4376: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4377: 	  &GDBM_READER(),0640)) {
 4378:     my $version=$hash{"version:$symb"};
 4379:     $returnhash{'version'}=$version;
 4380:     my $scope;
 4381:     for ($scope=1;$scope<=$version;$scope++) {
 4382:       my $vkeys=$hash{"$scope:keys:$symb"};
 4383:       my @keys=split(/:/,$vkeys);
 4384:       my $key;
 4385:       $returnhash{"$scope:keys"}=$vkeys;
 4386:       foreach $key (@keys) {
 4387: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4388: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4389:       }
 4390:     }
 4391:     if (!(untie(%hash))) {
 4392:       return "error:$!";
 4393:     }
 4394:   } else {
 4395:     return "error:$!";
 4396:   }
 4397:   return %returnhash;
 4398: }
 4399: 
 4400: # ----------------------------------------------------------------------- Store
 4401: 
 4402: sub store {
 4403:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4404:     my $home='';
 4405: 
 4406:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4407: 
 4408:     $symb=&symbclean($symb);
 4409:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4410: 
 4411:     if (!$domain) { $domain=$env{'user.domain'}; }
 4412:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4413: 
 4414:     &devalidate($symb,$stuname,$domain);
 4415: 
 4416:     $symb=escape($symb);
 4417:     if (!$namespace) { 
 4418:        unless ($namespace=$env{'request.course.id'}) { 
 4419:           return ''; 
 4420:        } 
 4421:     }
 4422:     if (!$home) { $home=$env{'user.home'}; }
 4423: 
 4424:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4425:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4426: 
 4427:     my $namevalue='';
 4428:     foreach my $key (keys(%$storehash)) {
 4429:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4430:     }
 4431:     $namevalue=~s/\&$//;
 4432:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4433:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4434: }
 4435: 
 4436: # -------------------------------------------------------------- Critical Store
 4437: 
 4438: sub cstore {
 4439:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4440:     my $home='';
 4441: 
 4442:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4443: 
 4444:     $symb=&symbclean($symb);
 4445:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4446: 
 4447:     if (!$domain) { $domain=$env{'user.domain'}; }
 4448:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4449: 
 4450:     &devalidate($symb,$stuname,$domain);
 4451: 
 4452:     $symb=escape($symb);
 4453:     if (!$namespace) { 
 4454:        unless ($namespace=$env{'request.course.id'}) { 
 4455:           return ''; 
 4456:        } 
 4457:     }
 4458:     if (!$home) { $home=$env{'user.home'}; }
 4459: 
 4460:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4461:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4462: 
 4463:     my $namevalue='';
 4464:     foreach my $key (keys(%$storehash)) {
 4465:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4466:     }
 4467:     $namevalue=~s/\&$//;
 4468:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4469:     return critical
 4470:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4471: }
 4472: 
 4473: # --------------------------------------------------------------------- Restore
 4474: 
 4475: sub restore {
 4476:     my ($symb,$namespace,$domain,$stuname) = @_;
 4477:     my $home='';
 4478: 
 4479:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4480: 
 4481:     if (!$symb) {
 4482:       unless ($symb=escape(&symbread())) { return ''; }
 4483:     } else {
 4484:       $symb=&escape(&symbclean($symb));
 4485:     }
 4486:     if (!$namespace) { 
 4487:        unless ($namespace=$env{'request.course.id'}) { 
 4488:           return ''; 
 4489:        } 
 4490:     }
 4491:     if (!$domain) { $domain=$env{'user.domain'}; }
 4492:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4493:     if (!$home) { $home=$env{'user.home'}; }
 4494:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4495: 
 4496:     my %returnhash=();
 4497:     foreach my $line (split(/\&/,$answer)) {
 4498: 	my ($name,$value)=split(/\=/,$line);
 4499:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4500:     }
 4501:     my $version;
 4502:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4503:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4504:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4505:        }
 4506:     }
 4507:     return %returnhash;
 4508: }
 4509: 
 4510: # ---------------------------------------------------------- Course Description
 4511: #
 4512: #  
 4513: 
 4514: sub coursedescription {
 4515:     my ($courseid,$args)=@_;
 4516:     $courseid=~s/^\///;
 4517:     $courseid=~s/\_/\//g;
 4518:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4519:     my $chome=&homeserver($cnum,$cdomain);
 4520:     my $normalid=$cdomain.'_'.$cnum;
 4521:     # need to always cache even if we get errors otherwise we keep 
 4522:     # trying and trying and trying to get the course description.
 4523:     my %envhash=();
 4524:     my %returnhash=();
 4525:     
 4526:     my $expiretime=600;
 4527:     if ($env{'request.course.id'} eq $normalid) {
 4528: 	$expiretime=120;
 4529:     }
 4530: 
 4531:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4532:     if (!$args->{'freshen_cache'}
 4533: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4534: 	foreach my $key (keys(%env)) {
 4535: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4536: 	    my ($setting) = $1;
 4537: 	    $returnhash{$setting} = $env{$key};
 4538: 	}
 4539: 	return %returnhash;
 4540:     }
 4541: 
 4542:     # get the data again
 4543: 
 4544:     if (!$args->{'one_time'}) {
 4545: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4546:     }
 4547: 
 4548:     if ($chome ne 'no_host') {
 4549:        %returnhash=&dump('environment',$cdomain,$cnum);
 4550:        if (!exists($returnhash{'con_lost'})) {
 4551: 	   my $username = $env{'user.name'}; # Defult username
 4552: 	   if(defined $args->{'user'}) {
 4553: 	       $username = $args->{'user'};
 4554: 	   }
 4555:            $returnhash{'home'}= $chome;
 4556: 	   $returnhash{'domain'} = $cdomain;
 4557: 	   $returnhash{'num'} = $cnum;
 4558:            if (!defined($returnhash{'type'})) {
 4559:                $returnhash{'type'} = 'Course';
 4560:            }
 4561:            while (my ($name,$value) = each %returnhash) {
 4562:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4563:            }
 4564:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4565:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4566: 	       $username.'_'.$cdomain.'_'.$cnum;
 4567:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4568:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4569:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4570:        }
 4571:     }
 4572:     if (!$args->{'one_time'}) {
 4573: 	&appenv(\%envhash);
 4574:     }
 4575:     return %returnhash;
 4576: }
 4577: 
 4578: sub update_released_required {
 4579:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4580:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4581:         $cid = $env{'request.course.id'};
 4582:         $cdom = $env{'course.'.$cid.'.domain'};
 4583:         $cnum = $env{'course.'.$cid.'.num'};
 4584:         $chome = $env{'course.'.$cid.'.home'};
 4585:     }
 4586:     if ($needsrelease) {
 4587:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4588:         my $needsupdate;
 4589:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4590:             $needsupdate = 1;
 4591:         } else {
 4592:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4593:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4594:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4595:                 $needsupdate = 1;
 4596:             }
 4597:         }
 4598:         if ($needsupdate) {
 4599:             my %needshash = (
 4600:                              'internal.releaserequired' => $needsrelease,
 4601:                             );
 4602:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4603:             if ($putresult eq 'ok') {
 4604:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4605:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4606:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4607:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4608:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4609:                 }
 4610:             }
 4611:         }
 4612:     }
 4613:     return;
 4614: }
 4615: 
 4616: # -------------------------------------------------See if a user is privileged
 4617: 
 4618: sub privileged {
 4619:     my ($username,$domain)=@_;
 4620:     my $rolesdump=&reply("dump:$domain:$username:roles",
 4621: 			&homeserver($username,$domain));
 4622:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4623:         ($rolesdump =~ /^error:/)) {
 4624:         return 0;
 4625:     }
 4626:     my $now=time;
 4627:     if ($rolesdump ne '') {
 4628:         foreach my $entry (split(/&/,$rolesdump)) {
 4629: 	    if ($entry!~/^rolesdef_/) {
 4630: 		my ($area,$role)=split(/=/,$entry);
 4631: 		$area=~s/\_\w\w$//;
 4632: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 4633: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 4634: 		    my $active=1;
 4635: 		    if ($tend) {
 4636: 			if ($tend<$now) { $active=0; }
 4637: 		    }
 4638: 		    if ($tstart) {
 4639: 			if ($tstart>$now) { $active=0; }
 4640: 		    }
 4641: 		    if ($active) { return 1; }
 4642: 		}
 4643: 	    }
 4644: 	}
 4645:     }
 4646:     return 0;
 4647: }
 4648: 
 4649: # -------------------------------------------------------- Get user privileges
 4650: 
 4651: sub rolesinit {
 4652:     my ($domain,$username,$authhost)=@_;
 4653:     my $now=time;
 4654:     my %userroles = ('user.login.time' => $now);
 4655:     my $extra = &freeze_escape({'skipcheck' => 1});
 4656:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
 4657:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4658:         ($rolesdump =~ /^error:/)) {
 4659:         return \%userroles;
 4660:     }
 4661:     my %firstaccess = &dump('firstaccesstimes',$domain,$username);
 4662:     my %timerinterval = &dump('timerinterval',$domain,$username);
 4663:     my (%coursetimerstarts,%firstaccchk,%firstaccenv,
 4664:         %coursetimerintervals,%timerintchk,%timerintenv);
 4665:     foreach my $key (keys(%firstaccess)) {
 4666:         my ($cid,$rest) = split(/\0/,$key);
 4667:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4668:     }
 4669:     foreach my $key (keys(%timerinterval)) {
 4670:         my ($cid,$rest) = split(/\0/,$key);
 4671:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4672:     }
 4673:     my %allroles=();
 4674:     my %allgroups=();
 4675: 
 4676:     if ($rolesdump ne '') {
 4677:         foreach my $entry (split(/&/,$rolesdump)) {
 4678: 	  if ($entry!~/^rolesdef_/) {
 4679:             my ($area,$role)=split(/=/,$entry);
 4680: 	    $area=~s/\_\w\w$//;
 4681:             my ($trole,$tend,$tstart,$group_privs);
 4682: 	    if ($role=~/^cr/) { 
 4683: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4684: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 4685: 		    ($tend,$tstart)=split('_',$trest);
 4686: 		} else {
 4687: 		    $trole=$role;
 4688: 		}
 4689:             } elsif ($role =~ m|^gr/|) {
 4690:                 ($trole,$tend,$tstart) = split(/_/,$role);
 4691:                 next if ($tstart eq '-1');
 4692:                 ($trole,$group_privs) = split(/\//,$trole);
 4693:                 $group_privs = &unescape($group_privs);
 4694: 	    } else {
 4695: 		($trole,$tend,$tstart)=split(/_/,$role);
 4696: 	    }
 4697: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4698: 					 $username);
 4699: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4700:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 4701:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 4702:             if (($area ne '') && ($trole ne '')) {
 4703: 		my $spec=$trole.'.'.$area;
 4704: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 4705: 		if ($trole =~ /^cr\//) {
 4706:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4707:                 } elsif ($trole eq 'gr') {
 4708:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4709: 		} else {
 4710:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4711: 		}
 4712:                 if ($trole ne 'gr') {
 4713:                     my $cid = $tdomain.'_'.$trest;
 4714:                     unless ($firstaccchk{$cid}) {
 4715:                         if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4716:                             foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4717:                                 $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4718:                                     $coursetimerstarts{$cid}{$item}; 
 4719:                             }
 4720:                         }
 4721:                         $firstaccchk{$cid} = 1;
 4722:                     }
 4723:                     unless ($timerintchk{$cid}) {
 4724:                         if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4725:                             foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4726:                                 $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4727:                                    $coursetimerintervals{$cid}{$item};
 4728:                             }
 4729:                         }
 4730:                         $timerintchk{$cid} = 1;
 4731:                     }
 4732:                 }
 4733:             }
 4734:           }
 4735:         }
 4736:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4737:         $userroles{'user.adv'}    = $adv;
 4738: 	$userroles{'user.author'} = $author;
 4739:         $env{'user.adv'}=$adv;
 4740:     }
 4741:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4742: }
 4743: 
 4744: sub set_arearole {
 4745:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4746: # log the associated role with the area
 4747:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4748:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4749: }
 4750: 
 4751: sub custom_roleprivs {
 4752:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4753:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4754:     my $homsvr=homeserver($rauthor,$rdomain);
 4755:     if (&hostname($homsvr) ne '') {
 4756:         my ($rdummy,$roledef)=
 4757:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4758:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4759:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4760:             if (defined($syspriv)) {
 4761:                 if ($trest =~ /^$match_community$/) {
 4762:                     $syspriv =~ s/bre\&S//; 
 4763:                 }
 4764:                 $$allroles{'cm./'}.=':'.$syspriv;
 4765:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4766:             }
 4767:             if ($tdomain ne '') {
 4768:                 if (defined($dompriv)) {
 4769:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4770:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4771:                 }
 4772:                 if (($trest ne '') && (defined($coursepriv))) {
 4773:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4774:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4775:                 }
 4776:             }
 4777:         }
 4778:     }
 4779: }
 4780: 
 4781: sub group_roleprivs {
 4782:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4783:     my $access = 1;
 4784:     my $now = time;
 4785:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4786:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4787:     if ($access) {
 4788:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4789:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4790:     }
 4791: }
 4792: 
 4793: sub standard_roleprivs {
 4794:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4795:     if (defined($pr{$trole.':s'})) {
 4796:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4797:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4798:     }
 4799:     if ($tdomain ne '') {
 4800:         if (defined($pr{$trole.':d'})) {
 4801:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4802:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4803:         }
 4804:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4805:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4806:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4807:         }
 4808:     }
 4809: }
 4810: 
 4811: sub set_userprivs {
 4812:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4813:     my $author=0;
 4814:     my $adv=0;
 4815:     my %grouproles = ();
 4816:     if (keys(%{$allgroups}) > 0) {
 4817:         my @groupkeys; 
 4818:         foreach my $role (keys(%{$allroles})) {
 4819:             push(@groupkeys,$role);
 4820:         }
 4821:         if (ref($groups_roles) eq 'HASH') {
 4822:             foreach my $key (keys(%{$groups_roles})) {
 4823:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4824:                     push(@groupkeys,$key);
 4825:                 }
 4826:             }
 4827:         }
 4828:         if (@groupkeys > 0) {
 4829:             foreach my $role (@groupkeys) {
 4830:                 my ($trole,$area,$sec,$extendedarea);
 4831:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4832:                     $trole = $1;
 4833:                     $area = $2;
 4834:                     $sec = $3;
 4835:                     $extendedarea = $area.$sec;
 4836:                     if (exists($$allgroups{$area})) {
 4837:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4838:                             my $spec = $trole.'.'.$extendedarea;
 4839:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4840:                                                 $$allgroups{$area}{$group};
 4841:                         }
 4842:                     }
 4843:                 }
 4844:             }
 4845:         }
 4846:     }
 4847:     foreach my $group (keys(%grouproles)) {
 4848:         $$allroles{$group} = $grouproles{$group};
 4849:     }
 4850:     foreach my $role (keys(%{$allroles})) {
 4851:         my %thesepriv;
 4852:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4853:         foreach my $item (split(/:/,$$allroles{$role})) {
 4854:             if ($item ne '') {
 4855:                 my ($privilege,$restrictions)=split(/&/,$item);
 4856:                 if ($restrictions eq '') {
 4857:                     $thesepriv{$privilege}='F';
 4858:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4859:                     $thesepriv{$privilege}.=$restrictions;
 4860:                 }
 4861:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4862:             }
 4863:         }
 4864:         my $thesestr='';
 4865:         foreach my $priv (sort(keys(%thesepriv))) {
 4866: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4867: 	}
 4868:         $userroles->{'user.priv.'.$role} = $thesestr;
 4869:     }
 4870:     return ($author,$adv);
 4871: }
 4872: 
 4873: sub role_status {
 4874:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4875:     my @pwhere = ();
 4876:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4877:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4878:         unless (!defined($$role) || $$role eq '') {
 4879:             $$where=join('.',@pwhere);
 4880:             $$trolecode=$$role.'.'.$$where;
 4881:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4882:             $$tstatus='is';
 4883:             if ($$tstart && $$tstart>$update) {
 4884:                 $$tstatus='future';
 4885:                 if ($$tstart<$now) {
 4886:                     if ($$tstart && $$tstart>$refresh) {
 4887:                         if (($$where ne '') && ($$role ne '')) {
 4888:                             my (%allroles,%allgroups,$group_privs,
 4889:                                 %groups_roles,@rolecodes);
 4890:                             my %userroles = (
 4891:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4892:                             );
 4893:                             @rolecodes = ('cm'); 
 4894:                             my $spec=$$role.'.'.$$where;
 4895:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4896:                             if ($$role =~ /^cr\//) {
 4897:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4898:                                 push(@rolecodes,'cr');
 4899:                             } elsif ($$role eq 'gr') {
 4900:                                 push(@rolecodes,$$role);
 4901:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4902:                                                     $env{'user.name'});
 4903:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4904:                                 (undef,my $group_privs) = split(/\//,$trole);
 4905:                                 $group_privs = &unescape($group_privs);
 4906:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4907:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4908:                                 &get_groups_roles($tdomain,$trest,
 4909:                                                   \%course_roles,\@rolecodes,
 4910:                                                   \%groups_roles);
 4911:                             } else {
 4912:                                 push(@rolecodes,$$role);
 4913:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4914:                             }
 4915:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4916:                             &appenv(\%userroles,\@rolecodes);
 4917:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4918:                         }
 4919:                     }
 4920:                     $$tstatus = 'is';
 4921:                 }
 4922:             }
 4923:             if ($$tend) {
 4924:                 if ($$tend<$update) {
 4925:                     $$tstatus='expired';
 4926:                 } elsif ($$tend<$now) {
 4927:                     $$tstatus='will_not';
 4928:                 }
 4929:             }
 4930:         }
 4931:     }
 4932: }
 4933: 
 4934: sub get_groups_roles {
 4935:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4936:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4937:                   (ref($rolecodes) eq 'ARRAY') && 
 4938:                   (ref($groups_roles) eq 'HASH')); 
 4939:     if (keys(%{$cdom_courseroles}) > 0) {
 4940:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4941:         if ($cdom ne '' && $cnum ne '') {
 4942:             foreach my $key (keys(%{$cdom_courseroles})) {
 4943:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4944:                     my $crsrole = $1;
 4945:                     my $crssec = $2;
 4946:                     if ($crsrole =~ /^cr/) {
 4947:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4948:                             push(@{$rolecodes},'cr');
 4949:                         }
 4950:                     } else {
 4951:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4952:                             push(@{$rolecodes},$crsrole);
 4953:                         }
 4954:                     }
 4955:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4956:                     if ($crssec ne '') {
 4957:                         $rolekey .= "/$crssec";
 4958:                     }
 4959:                     $rolekey .= './';
 4960:                     $groups_roles->{$rolekey} = $rolecodes;
 4961:                 }
 4962:             }
 4963:         }
 4964:     }
 4965:     return;
 4966: }
 4967: 
 4968: sub delete_env_groupprivs {
 4969:     my ($where,$courseroles,$possroles) = @_;
 4970:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4971:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4972:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4973:         %{$courseroles->{$udom}} =
 4974:             &get_my_roles('','','userroles',['active'],
 4975:                           $possroles,[$udom],1);
 4976:     }
 4977:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4978:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4979:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4980:             my $area = '/'.$cdom.'/'.$cnum;
 4981:             my $privkey = "user.priv.$crsrole.$area";
 4982:             if ($crssec ne '') {
 4983:                 $privkey .= '/'.$crssec;
 4984:             }
 4985:             $privkey .= ".$area/$group";
 4986:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4987:         }
 4988:     }
 4989:     return;
 4990: }
 4991: 
 4992: sub check_adhoc_privs {
 4993:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4994:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4995:     if ($env{$cckey}) {
 4996:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4997:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4998:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4999:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5000:         }
 5001:     } else {
 5002:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5003:     }
 5004: }
 5005: 
 5006: sub set_adhoc_privileges {
 5007: # role can be cc or ca
 5008:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5009:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5010:     my $spec = $role.'.'.$area;
 5011:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5012:                                   $env{'user.name'});
 5013:     my %ccrole = ();
 5014:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5015:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5016:     &appenv(\%userroles,[$role,'cm']);
 5017:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5018:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5019:         &appenv( {'request.role'        => $spec,
 5020:                   'request.role.domain' => $dcdom,
 5021:                   'request.course.sec'  => ''
 5022:                  }
 5023:                );
 5024:         my $tadv=0;
 5025:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5026:         &appenv({'request.role.adv'    => $tadv});
 5027:     }
 5028: }
 5029: 
 5030: # --------------------------------------------------------------- get interface
 5031: 
 5032: sub get {
 5033:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5034:    my $items='';
 5035:    foreach my $item (@$storearr) {
 5036:        $items.=&escape($item).'&';
 5037:    }
 5038:    $items=~s/\&$//;
 5039:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5040:    if (!$uname) { $uname=$env{'user.name'}; }
 5041:    my $uhome=&homeserver($uname,$udomain);
 5042: 
 5043:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5044:    my @pairs=split(/\&/,$rep);
 5045:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5046:      return @pairs;
 5047:    }
 5048:    my %returnhash=();
 5049:    my $i=0;
 5050:    foreach my $item (@$storearr) {
 5051:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5052:       $i++;
 5053:    }
 5054:    return %returnhash;
 5055: }
 5056: 
 5057: # --------------------------------------------------------------- del interface
 5058: 
 5059: sub del {
 5060:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5061:    my $items='';
 5062:    foreach my $item (@$storearr) {
 5063:        $items.=&escape($item).'&';
 5064:    }
 5065: 
 5066:    $items=~s/\&$//;
 5067:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5068:    if (!$uname) { $uname=$env{'user.name'}; }
 5069:    my $uhome=&homeserver($uname,$udomain);
 5070:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5071: }
 5072: 
 5073: # -------------------------------------------------------------- dump interface
 5074: 
 5075: sub dump {
 5076:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
 5077:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5078:     if (!$uname) { $uname=$env{'user.name'}; }
 5079:     my $uhome=&homeserver($uname,$udomain);
 5080:     if ($regexp) {
 5081: 	$regexp=&escape($regexp);
 5082:     } else {
 5083: 	$regexp='.';
 5084:     }
 5085:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
 5086:     my @pairs=split(/\&/,$rep);
 5087:     my %returnhash=();
 5088:     if (!($rep =~ /^error/ )) {
 5089: 	foreach my $item (@pairs) {
 5090: 	    my ($key,$value)=split(/=/,$item,2);
 5091: 	    $key = &unescape($key);
 5092: 	    next if ($key =~ /^error: 2 /);
 5093: 	    $returnhash{$key}=&thaw_unescape($value);
 5094: 	}
 5095:     }
 5096:     return %returnhash;
 5097: }
 5098: 
 5099: 
 5100: # --------------------------------------------------------- dumpstore interface
 5101: 
 5102: sub dumpstore {
 5103:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5104:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5105:    if (!$uname) { $uname=$env{'user.name'}; }
 5106:    my $uhome=&homeserver($uname,$udomain);
 5107:    if ($regexp) {
 5108:        $regexp=&escape($regexp);
 5109:    } else {
 5110:        $regexp='.';
 5111:    }
 5112:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5113:    my @pairs=split(/\&/,$rep);
 5114:    my %returnhash=();
 5115:    foreach my $item (@pairs) {
 5116:        my ($key,$value)=split(/=/,$item,2);
 5117:        next if ($key =~ /^error: 2 /);
 5118:        $returnhash{$key}=&thaw_unescape($value);
 5119:    }
 5120:    return %returnhash;
 5121: }
 5122: 
 5123: # -------------------------------------------------------------- keys interface
 5124: 
 5125: sub getkeys {
 5126:    my ($namespace,$udomain,$uname)=@_;
 5127:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5128:    if (!$uname) { $uname=$env{'user.name'}; }
 5129:    my $uhome=&homeserver($uname,$udomain);
 5130:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5131:    my @keyarray=();
 5132:    foreach my $key (split(/\&/,$rep)) {
 5133:       next if ($key =~ /^error: 2 /);
 5134:       push(@keyarray,&unescape($key));
 5135:    }
 5136:    return @keyarray;
 5137: }
 5138: 
 5139: # --------------------------------------------------------------- currentdump
 5140: sub currentdump {
 5141:    my ($courseid,$sdom,$sname)=@_;
 5142:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5143:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5144:    $sname    = $env{'user.name'}         if (! defined($sname));
 5145:    my $uhome = &homeserver($sname,$sdom);
 5146:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5147:    return if ($rep =~ /^(error:|no_such_host)/);
 5148:    #
 5149:    my %returnhash=();
 5150:    #
 5151:    if ($rep eq "unknown_cmd") { 
 5152:        # an old lond will not know currentdump
 5153:        # Do a dump and make it look like a currentdump
 5154:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5155:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5156:        my %hash = @tmp;
 5157:        @tmp=();
 5158:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5159:    } else {
 5160:        my @pairs=split(/\&/,$rep);
 5161:        foreach my $pair (@pairs) {
 5162:            my ($key,$value)=split(/=/,$pair,2);
 5163:            my ($symb,$param) = split(/:/,$key);
 5164:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5165:                                                         &thaw_unescape($value);
 5166:        }
 5167:    }
 5168:    return %returnhash;
 5169: }
 5170: 
 5171: sub convert_dump_to_currentdump{
 5172:     my %hash = %{shift()};
 5173:     my %returnhash;
 5174:     # Code ripped from lond, essentially.  The only difference
 5175:     # here is the unescaping done by lonnet::dump().  Conceivably
 5176:     # we might run in to problems with parameter names =~ /^v\./
 5177:     while (my ($key,$value) = each(%hash)) {
 5178:         my ($v,$symb,$param) = split(/:/,$key);
 5179: 	$symb  = &unescape($symb);
 5180: 	$param = &unescape($param);
 5181:         next if ($v eq 'version' || $symb eq 'keys');
 5182:         next if (exists($returnhash{$symb}) &&
 5183:                  exists($returnhash{$symb}->{$param}) &&
 5184:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5185:         $returnhash{$symb}->{$param}=$value;
 5186:         $returnhash{$symb}->{'v.'.$param}=$v;
 5187:     }
 5188:     #
 5189:     # Remove all of the keys in the hashes which keep track of
 5190:     # the version of the parameter.
 5191:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5192:         # use a foreach because we are going to delete from the hash.
 5193:         foreach my $key (keys(%$param_hash)) {
 5194:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5195:         }
 5196:     }
 5197:     return \%returnhash;
 5198: }
 5199: 
 5200: # ------------------------------------------------------ critical inc interface
 5201: 
 5202: sub cinc {
 5203:     return &inc(@_,'critical');
 5204: }
 5205: 
 5206: # --------------------------------------------------------------- inc interface
 5207: 
 5208: sub inc {
 5209:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5210:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5211:     if (!$uname) { $uname=$env{'user.name'}; }
 5212:     my $uhome=&homeserver($uname,$udomain);
 5213:     my $items='';
 5214:     if (! ref($store)) {
 5215:         # got a single value, so use that instead
 5216:         $items = &escape($store).'=&';
 5217:     } elsif (ref($store) eq 'SCALAR') {
 5218:         $items = &escape($$store).'=&';        
 5219:     } elsif (ref($store) eq 'ARRAY') {
 5220:         $items = join('=&',map {&escape($_);} @{$store});
 5221:     } elsif (ref($store) eq 'HASH') {
 5222:         while (my($key,$value) = each(%{$store})) {
 5223:             $items.= &escape($key).'='.&escape($value).'&';
 5224:         }
 5225:     }
 5226:     $items=~s/\&$//;
 5227:     if ($critical) {
 5228: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5229:     } else {
 5230: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5231:     }
 5232: }
 5233: 
 5234: # --------------------------------------------------------------- put interface
 5235: 
 5236: sub put {
 5237:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5238:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5239:    if (!$uname) { $uname=$env{'user.name'}; }
 5240:    my $uhome=&homeserver($uname,$udomain);
 5241:    my $items='';
 5242:    foreach my $item (keys(%$storehash)) {
 5243:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5244:    }
 5245:    $items=~s/\&$//;
 5246:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5247: }
 5248: 
 5249: # ------------------------------------------------------------ newput interface
 5250: 
 5251: sub newput {
 5252:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5253:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5254:    if (!$uname) { $uname=$env{'user.name'}; }
 5255:    my $uhome=&homeserver($uname,$udomain);
 5256:    my $items='';
 5257:    foreach my $key (keys(%$storehash)) {
 5258:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5259:    }
 5260:    $items=~s/\&$//;
 5261:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5262: }
 5263: 
 5264: # ---------------------------------------------------------  putstore interface
 5265: 
 5266: sub putstore {
 5267:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5268:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5269:    if (!$uname) { $uname=$env{'user.name'}; }
 5270:    my $uhome=&homeserver($uname,$udomain);
 5271:    my $items='';
 5272:    foreach my $key (keys(%$storehash)) {
 5273:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5274:    }
 5275:    $items=~s/\&$//;
 5276:    my $esc_symb=&escape($symb);
 5277:    my $esc_v=&escape($version);
 5278:    my $reply =
 5279:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5280: 	      $uhome);
 5281:    if ($reply eq 'unknown_cmd') {
 5282:        # gfall back to way things use to be done
 5283:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5284: 			    $uname);
 5285:    }
 5286:    return $reply;
 5287: }
 5288: 
 5289: sub old_putstore {
 5290:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5291:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5292:     if (!$uname) { $uname=$env{'user.name'}; }
 5293:     my $uhome=&homeserver($uname,$udomain);
 5294:     my %newstorehash;
 5295:     foreach my $item (keys(%$storehash)) {
 5296: 	my $key = $version.':'.&escape($symb).':'.$item;
 5297: 	$newstorehash{$key} = $storehash->{$item};
 5298:     }
 5299:     my $items='';
 5300:     my %allitems = ();
 5301:     foreach my $item (keys(%newstorehash)) {
 5302: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5303: 	    my $key = $1.':keys:'.$2;
 5304: 	    $allitems{$key} .= $3.':';
 5305: 	}
 5306: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5307:     }
 5308:     foreach my $item (keys(%allitems)) {
 5309: 	$allitems{$item} =~ s/\:$//;
 5310: 	$items.= $item.'='.$allitems{$item}.'&';
 5311:     }
 5312:     $items=~s/\&$//;
 5313:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5314: }
 5315: 
 5316: # ------------------------------------------------------ critical put interface
 5317: 
 5318: sub cput {
 5319:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5320:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5321:    if (!$uname) { $uname=$env{'user.name'}; }
 5322:    my $uhome=&homeserver($uname,$udomain);
 5323:    my $items='';
 5324:    foreach my $item (keys(%$storehash)) {
 5325:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5326:    }
 5327:    $items=~s/\&$//;
 5328:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5329: }
 5330: 
 5331: # -------------------------------------------------------------- eget interface
 5332: 
 5333: sub eget {
 5334:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5335:    my $items='';
 5336:    foreach my $item (@$storearr) {
 5337:        $items.=&escape($item).'&';
 5338:    }
 5339:    $items=~s/\&$//;
 5340:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5341:    if (!$uname) { $uname=$env{'user.name'}; }
 5342:    my $uhome=&homeserver($uname,$udomain);
 5343:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5344:    my @pairs=split(/\&/,$rep);
 5345:    my %returnhash=();
 5346:    my $i=0;
 5347:    foreach my $item (@$storearr) {
 5348:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5349:       $i++;
 5350:    }
 5351:    return %returnhash;
 5352: }
 5353: 
 5354: # ------------------------------------------------------------ tmpput interface
 5355: sub tmpput {
 5356:     my ($storehash,$server,$context)=@_;
 5357:     my $items='';
 5358:     foreach my $item (keys(%$storehash)) {
 5359: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5360:     }
 5361:     $items=~s/\&$//;
 5362:     if (defined($context)) {
 5363:         $items .= ':'.&escape($context);
 5364:     }
 5365:     return &reply("tmpput:$items",$server);
 5366: }
 5367: 
 5368: # ------------------------------------------------------------ tmpget interface
 5369: sub tmpget {
 5370:     my ($token,$server)=@_;
 5371:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5372:     my $rep=&reply("tmpget:$token",$server);
 5373:     my %returnhash;
 5374:     foreach my $item (split(/\&/,$rep)) {
 5375: 	my ($key,$value)=split(/=/,$item);
 5376:         next if ($key =~ /^error: 2 /);
 5377: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5378:     }
 5379:     return %returnhash;
 5380: }
 5381: 
 5382: # ------------------------------------------------------------ tmpdel interface
 5383: sub tmpdel {
 5384:     my ($token,$server)=@_;
 5385:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5386:     return &reply("tmpdel:$token",$server);
 5387: }
 5388: 
 5389: # -------------------------------------------------- portfolio access checking
 5390: 
 5391: sub portfolio_access {
 5392:     my ($requrl) = @_;
 5393:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5394:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5395:     if ($result) {
 5396:         my %setters;
 5397:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5398:             my ($startblock,$endblock) =
 5399:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5400:             if ($startblock && $endblock) {
 5401:                 return 'B';
 5402:             }
 5403:         } else {
 5404:             my ($startblock,$endblock) =
 5405:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5406:             if ($startblock && $endblock) {
 5407:                 return 'B';
 5408:             }
 5409:         }
 5410:     }
 5411:     if ($result eq 'ok') {
 5412:        return 'F';
 5413:     } elsif ($result =~ /^[^:]+:guest_/) {
 5414:        return 'A';
 5415:     }
 5416:     return '';
 5417: }
 5418: 
 5419: sub get_portfolio_access {
 5420:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5421: 
 5422:     if (!ref($access_hash)) {
 5423: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5424: 	my %access_controls = &get_access_controls($current_perms,$group,
 5425: 						   $file_name);
 5426: 	$access_hash = $access_controls{$file_name};
 5427:     }
 5428: 
 5429:     my ($public,$guest,@domains,@users,@courses,@groups);
 5430:     my $now = time;
 5431:     if (ref($access_hash) eq 'HASH') {
 5432:         foreach my $key (keys(%{$access_hash})) {
 5433:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5434:             if ($start > $now) {
 5435:                 next;
 5436:             }
 5437:             if ($end && $end<$now) {
 5438:                 next;
 5439:             }
 5440:             if ($scope eq 'public') {
 5441:                 $public = $key;
 5442:                 last;
 5443:             } elsif ($scope eq 'guest') {
 5444:                 $guest = $key;
 5445:             } elsif ($scope eq 'domains') {
 5446:                 push(@domains,$key);
 5447:             } elsif ($scope eq 'users') {
 5448:                 push(@users,$key);
 5449:             } elsif ($scope eq 'course') {
 5450:                 push(@courses,$key);
 5451:             } elsif ($scope eq 'group') {
 5452:                 push(@groups,$key);
 5453:             }
 5454:         }
 5455:         if ($public) {
 5456:             return 'ok';
 5457:         }
 5458:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5459:             if ($guest) {
 5460:                 return $guest;
 5461:             }
 5462:         } else {
 5463:             if (@domains > 0) {
 5464:                 foreach my $domkey (@domains) {
 5465:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5466:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5467:                             return 'ok';
 5468:                         }
 5469:                     }
 5470:                 }
 5471:             }
 5472:             if (@users > 0) {
 5473:                 foreach my $userkey (@users) {
 5474:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5475:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5476:                             if (ref($item) eq 'HASH') {
 5477:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5478:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5479:                                     return 'ok';
 5480:                                 }
 5481:                             }
 5482:                         }
 5483:                     } 
 5484:                 }
 5485:             }
 5486:             my %roleshash;
 5487:             my @courses_and_groups = @courses;
 5488:             push(@courses_and_groups,@groups); 
 5489:             if (@courses_and_groups > 0) {
 5490:                 my (%allgroups,%allroles); 
 5491:                 my ($start,$end,$role,$sec,$group);
 5492:                 foreach my $envkey (%env) {
 5493:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5494:                         my $cid = $2.'_'.$3; 
 5495:                         if ($1 eq 'gr') {
 5496:                             $group = $4;
 5497:                             $allgroups{$cid}{$group} = $env{$envkey};
 5498:                         } else {
 5499:                             if ($4 eq '') {
 5500:                                 $sec = 'none';
 5501:                             } else {
 5502:                                 $sec = $4;
 5503:                             }
 5504:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5505:                         }
 5506:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5507:                         my $cid = $2.'_'.$3;
 5508:                         if ($4 eq '') {
 5509:                             $sec = 'none';
 5510:                         } else {
 5511:                             $sec = $4;
 5512:                         }
 5513:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5514:                     }
 5515:                 }
 5516:                 if (keys(%allroles) == 0) {
 5517:                     return;
 5518:                 }
 5519:                 foreach my $key (@courses_and_groups) {
 5520:                     my %content = %{$$access_hash{$key}};
 5521:                     my $cnum = $content{'number'};
 5522:                     my $cdom = $content{'domain'};
 5523:                     my $cid = $cdom.'_'.$cnum;
 5524:                     if (!exists($allroles{$cid})) {
 5525:                         next;
 5526:                     }    
 5527:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5528:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5529:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5530:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5531:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5532:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5533:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5534:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5535:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5536:                                         if (grep/^all$/,@sections) {
 5537:                                             return 'ok';
 5538:                                         } else {
 5539:                                             if (grep/^$sec$/,@sections) {
 5540:                                                 return 'ok';
 5541:                                             }
 5542:                                         }
 5543:                                     }
 5544:                                 }
 5545:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5546:                                     if (grep/^none$/,@groups) {
 5547:                                         return 'ok';
 5548:                                     }
 5549:                                 } else {
 5550:                                     if (grep/^all$/,@groups) {
 5551:                                         return 'ok';
 5552:                                     } 
 5553:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5554:                                         if (grep/^$group$/,@groups) {
 5555:                                             return 'ok';
 5556:                                         }
 5557:                                     }
 5558:                                 } 
 5559:                             }
 5560:                         }
 5561:                     }
 5562:                 }
 5563:             }
 5564:             if ($guest) {
 5565:                 return $guest;
 5566:             }
 5567:         }
 5568:     }
 5569:     return;
 5570: }
 5571: 
 5572: sub course_group_datechecker {
 5573:     my ($dates,$now,$status) = @_;
 5574:     my ($start,$end) = split(/\./,$dates);
 5575:     if (!$start && !$end) {
 5576:         return 'ok';
 5577:     }
 5578:     if (grep/^active$/,@{$status}) {
 5579:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5580:             return 'ok';
 5581:         }
 5582:     }
 5583:     if (grep/^previous$/,@{$status}) {
 5584:         if ($end > $now ) {
 5585:             return 'ok';
 5586:         }
 5587:     }
 5588:     if (grep/^future$/,@{$status}) {
 5589:         if ($start > $now) {
 5590:             return 'ok';
 5591:         }
 5592:     }
 5593:     return; 
 5594: }
 5595: 
 5596: sub parse_portfolio_url {
 5597:     my ($url) = @_;
 5598: 
 5599:     my ($type,$udom,$unum,$group,$file_name);
 5600:     
 5601:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5602: 	$type = 1;
 5603:         $udom = $1;
 5604:         $unum = $2;
 5605:         $file_name = $3;
 5606:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5607: 	$type = 2;
 5608:         $udom = $1;
 5609:         $unum = $2;
 5610:         $group = $3;
 5611:         $file_name = $3.'/'.$4;
 5612:     }
 5613:     if (wantarray) {
 5614: 	return ($type,$udom,$unum,$file_name,$group);
 5615:     }
 5616:     return $type;
 5617: }
 5618: 
 5619: sub is_portfolio_url {
 5620:     my ($url) = @_;
 5621:     return scalar(&parse_portfolio_url($url));
 5622: }
 5623: 
 5624: sub is_portfolio_file {
 5625:     my ($file) = @_;
 5626:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5627:         return 1;
 5628:     }
 5629:     return;
 5630: }
 5631: 
 5632: sub usertools_access {
 5633:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5634:     my ($access,%tools);
 5635:     if ($context eq '') {
 5636:         $context = 'tools';
 5637:     }
 5638:     if ($context eq 'requestcourses') {
 5639:         %tools = (
 5640:                       official   => 1,
 5641:                       unofficial => 1,
 5642:                       community  => 1,
 5643:                  );
 5644:     } else {
 5645:         %tools = (
 5646:                       aboutme   => 1,
 5647:                       blog      => 1,
 5648:                       portfolio => 1,
 5649:                  );
 5650:     }
 5651:     return if (!defined($tools{$tool}));
 5652: 
 5653:     if ((!defined($udom)) || (!defined($uname))) {
 5654:         $udom = $env{'user.domain'};
 5655:         $uname = $env{'user.name'};
 5656:     }
 5657: 
 5658:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5659:         if ($action ne 'reload') {
 5660:             if ($context eq 'requestcourses') {
 5661:                 return $env{'environment.canrequest.'.$tool};
 5662:             } else {
 5663:                 return $env{'environment.availabletools.'.$tool};
 5664:             }
 5665:         }
 5666:     }
 5667: 
 5668:     my ($toolstatus,$inststatus);
 5669: 
 5670:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5671:          ($action ne 'reload')) {
 5672:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5673:         $inststatus = $env{'environment.inststatus'};
 5674:     } else {
 5675:         if (ref($userenvref) eq 'HASH') {
 5676:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5677:             $inststatus = $userenvref->{'inststatus'};
 5678:         } else {
 5679:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5680:             $toolstatus = $userenv{$context.'.'.$tool};
 5681:             $inststatus = $userenv{'inststatus'};
 5682:         }
 5683:     }
 5684: 
 5685:     if ($toolstatus ne '') {
 5686:         if ($toolstatus) {
 5687:             $access = 1;
 5688:         } else {
 5689:             $access = 0;
 5690:         }
 5691:         return $access;
 5692:     }
 5693: 
 5694:     my ($is_adv,%domdef);
 5695:     if (ref($is_advref) eq 'HASH') {
 5696:         $is_adv = $is_advref->{'is_adv'};
 5697:     } else {
 5698:         $is_adv = &is_advanced_user($udom,$uname);
 5699:     }
 5700:     if (ref($domdefref) eq 'HASH') {
 5701:         %domdef = %{$domdefref};
 5702:     } else {
 5703:         %domdef = &get_domain_defaults($udom);
 5704:     }
 5705:     if (ref($domdef{$tool}) eq 'HASH') {
 5706:         if ($is_adv) {
 5707:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5708:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5709:                     $access = 1;
 5710:                 } else {
 5711:                     $access = 0;
 5712:                 }
 5713:                 return $access;
 5714:             }
 5715:         }
 5716:         if ($inststatus ne '') {
 5717:             my ($hasaccess,$hasnoaccess);
 5718:             foreach my $affiliation (split(/:/,$inststatus)) {
 5719:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5720:                     if ($domdef{$tool}{$affiliation}) {
 5721:                         $hasaccess = 1;
 5722:                     } else {
 5723:                         $hasnoaccess = 1;
 5724:                     }
 5725:                 }
 5726:             }
 5727:             if ($hasaccess || $hasnoaccess) {
 5728:                 if ($hasaccess) {
 5729:                     $access = 1;
 5730:                 } elsif ($hasnoaccess) {
 5731:                     $access = 0; 
 5732:                 }
 5733:                 return $access;
 5734:             }
 5735:         } else {
 5736:             if ($domdef{$tool}{'default'} ne '') {
 5737:                 if ($domdef{$tool}{'default'}) {
 5738:                     $access = 1;
 5739:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5740:                     $access = 0;
 5741:                 }
 5742:                 return $access;
 5743:             }
 5744:         }
 5745:     } else {
 5746:         if ($context eq 'tools') {
 5747:             $access = 1;
 5748:         } else {
 5749:             $access = 0;
 5750:         }
 5751:         return $access;
 5752:     }
 5753: }
 5754: 
 5755: sub is_course_owner {
 5756:     my ($cdom,$cnum,$udom,$uname) = @_;
 5757:     if (($udom eq '') || ($uname eq '')) {
 5758:         $udom = $env{'user.domain'};
 5759:         $uname = $env{'user.name'};
 5760:     }
 5761:     unless (($udom eq '') || ($uname eq '')) {
 5762:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5763:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5764:                 return 1;
 5765:             } else {
 5766:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5767:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5768:                     return 1;
 5769:                 }
 5770:             }
 5771:         }
 5772:     }
 5773:     return;
 5774: }
 5775: 
 5776: sub is_advanced_user {
 5777:     my ($udom,$uname) = @_;
 5778:     if ($udom ne '' && $uname ne '') {
 5779:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5780:             if (wantarray) {
 5781:                 return ($env{'user.adv'},$env{'user.author'});
 5782:             } else {
 5783:                 return $env{'user.adv'};
 5784:             }
 5785:         }
 5786:     }
 5787:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5788:     my %allroles;
 5789:     my ($is_adv,$is_author);
 5790:     foreach my $role (keys(%roleshash)) {
 5791:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5792:         my $area = '/'.$tdomain.'/'.$trest;
 5793:         if ($sec ne '') {
 5794:             $area .= '/'.$sec;
 5795:         }
 5796:         if (($area ne '') && ($trole ne '')) {
 5797:             my $spec=$trole.'.'.$area;
 5798:             if ($trole =~ /^cr\//) {
 5799:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5800:             } elsif ($trole ne 'gr') {
 5801:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5802:             }
 5803:             if ($trole eq 'au') {
 5804:                 $is_author = 1;
 5805:             }
 5806:         }
 5807:     }
 5808:     foreach my $role (keys(%allroles)) {
 5809:         last if ($is_adv);
 5810:         foreach my $item (split(/:/,$allroles{$role})) {
 5811:             if ($item ne '') {
 5812:                 my ($privilege,$restrictions)=split(/&/,$item);
 5813:                 if ($privilege eq 'adv') {
 5814:                     $is_adv = 1;
 5815:                     last;
 5816:                 }
 5817:             }
 5818:         }
 5819:     }
 5820:     if (wantarray) {
 5821:         return ($is_adv,$is_author);
 5822:     }
 5823:     return $is_adv;
 5824: }
 5825: 
 5826: sub check_can_request {
 5827:     my ($dom,$can_request,$request_domains) = @_;
 5828:     my $canreq = 0;
 5829:     my ($types,$typename) = &Apache::loncommon::course_types();
 5830:     my @options = ('approval','validate','autolimit');
 5831:     my $optregex = join('|',@options);
 5832:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5833:         foreach my $type (@{$types}) {
 5834:             if (&usertools_access($env{'user.name'},
 5835:                                   $env{'user.domain'},
 5836:                                   $type,undef,'requestcourses')) {
 5837:                 $canreq ++;
 5838:                 if (ref($request_domains) eq 'HASH') {
 5839:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5840:                 }
 5841:                 if ($dom eq $env{'user.domain'}) {
 5842:                     $can_request->{$type} = 1;
 5843:                 }
 5844:             }
 5845:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5846:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5847:                 if (@curr > 0) {
 5848:                     foreach my $item (@curr) {
 5849:                         if (ref($request_domains) eq 'HASH') {
 5850:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5851:                             if ($otherdom ne '') {
 5852:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5853:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5854:                                         push(@{$request_domains->{$type}},$otherdom);
 5855:                                     }
 5856:                                 } else {
 5857:                                     push(@{$request_domains->{$type}},$otherdom);
 5858:                                 }
 5859:                             }
 5860:                         }
 5861:                     }
 5862:                     unless($dom eq $env{'user.domain'}) {
 5863:                         $canreq ++;
 5864:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5865:                             $can_request->{$type} = 1;
 5866:                         }
 5867:                     }
 5868:                 }
 5869:             }
 5870:         }
 5871:     }
 5872:     return $canreq;
 5873: }
 5874: 
 5875: # ---------------------------------------------- Custom access rule evaluation
 5876: 
 5877: sub customaccess {
 5878:     my ($priv,$uri)=@_;
 5879:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5880:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5881:     $udom = &LONCAPA::clean_domain($udom);
 5882:     $ucrs = &LONCAPA::clean_username($ucrs);
 5883:     my $access=0;
 5884:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5885: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5886: 	if ($type eq 'user') {
 5887: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5888: 		my ($tdom,$tuname)=split(m{/},$scope);
 5889: 		if ($tdom) {
 5890: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5891: 		}
 5892: 		if ($tuname) {
 5893: 		    if ($tuname ne $env{'user.name'}) { next; }
 5894: 		}
 5895: 		$access=($effect eq 'allow');
 5896: 		last;
 5897: 	    }
 5898: 	} else {
 5899: 	    if ($role) {
 5900: 		if ($role ne $urole) { next; }
 5901: 	    }
 5902: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5903: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5904: 		if ($tdom) {
 5905: 		    if ($tdom ne $udom) { next; }
 5906: 		}
 5907: 		if ($tcrs) {
 5908: 		    if ($tcrs ne $ucrs) { next; }
 5909: 		}
 5910: 		if ($tsec) {
 5911: 		    if ($tsec ne $usec) { next; }
 5912: 		}
 5913: 		$access=($effect eq 'allow');
 5914: 		last;
 5915: 	    }
 5916: 	    if ($realm eq '' && $role eq '') {
 5917: 		$access=($effect eq 'allow');
 5918: 	    }
 5919: 	}
 5920:     }
 5921:     return $access;
 5922: }
 5923: 
 5924: # ------------------------------------------------- Check for a user privilege
 5925: 
 5926: sub allowed {
 5927:     my ($priv,$uri,$symb,$role)=@_;
 5928:     my $ver_orguri=$uri;
 5929:     $uri=&deversion($uri);
 5930:     my $orguri=$uri;
 5931:     $uri=&declutter($uri);
 5932: 
 5933:     if ($priv eq 'evb') {
 5934: # Evade communication block restrictions for specified role in a course
 5935:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5936:             return $1;
 5937:         } else {
 5938:             return;
 5939:         }
 5940:     }
 5941: 
 5942:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5943: # Free bre access to adm and meta resources
 5944:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5945: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5946: 	&& ($priv eq 'bre')) {
 5947: 	return 'F';
 5948:     }
 5949: 
 5950: # Free bre access to user's own portfolio contents
 5951:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5952:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5953: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5954:         my %setters;
 5955:         my ($startblock,$endblock) = 
 5956:             &Apache::loncommon::blockcheck(\%setters,'port');
 5957:         if ($startblock && $endblock) {
 5958:             return 'B';
 5959:         } else {
 5960:             return 'F';
 5961:         }
 5962:     }
 5963: 
 5964: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5965:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5966:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5967:         if (exists($env{'request.course.id'})) {
 5968:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5969:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5970:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5971:                 my $courseprivid=$env{'request.course.id'};
 5972:                 $courseprivid=~s/\_/\//;
 5973:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5974:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5975:                     return $1; 
 5976:                 } else {
 5977:                     if ($env{'request.course.sec'}) {
 5978:                         $courseprivid.='/'.$env{'request.course.sec'};
 5979:                     }
 5980:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5981:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5982:                         return $2;
 5983:                     }
 5984:                 }
 5985:             }
 5986:         }
 5987:     }
 5988: 
 5989: # Free bre to public access
 5990: 
 5991:     if ($priv eq 'bre') {
 5992:         my $copyright=&metadata($uri,'copyright');
 5993: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5994:            return 'F'; 
 5995:         }
 5996:         if ($copyright eq 'priv') {
 5997:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5998: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5999: 		return '';
 6000:             }
 6001:         }
 6002:         if ($copyright eq 'domain') {
 6003:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6004: 	    unless (($env{'user.domain'} eq $1) ||
 6005:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6006: 		return '';
 6007:             }
 6008:         }
 6009:         if ($env{'request.role'}=~ /li\.\//) {
 6010:             # Library role, so allow browsing of resources in this domain.
 6011:             return 'F';
 6012:         }
 6013:         if ($copyright eq 'custom') {
 6014: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6015:         }
 6016:     }
 6017:     # Domain coordinator is trying to create a course
 6018:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6019:         # uri is the requested domain in this case.
 6020:         # comparison to 'request.role.domain' shows if the user has selected
 6021:         # a role of dc for the domain in question.
 6022:         return 'F' if ($uri eq $env{'request.role.domain'});
 6023:     }
 6024: 
 6025:     my $thisallowed='';
 6026:     my $statecond=0;
 6027:     my $courseprivid='';
 6028: 
 6029:     my $ownaccess;
 6030:     # Community Coordinator or Assistant Co-author browsing resource space.
 6031:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6032:         if ($uri eq '') {
 6033:             $ownaccess = 1;
 6034:         } else {
 6035:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6036:                 my $udom = $env{'user.domain'};
 6037:                 my $uname = $env{'user.name'};
 6038:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6039:                     $ownaccess = 1;
 6040:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6041:                     unless ($uri =~ m{\.\./}) {
 6042:                         $ownaccess = 1;
 6043:                     }
 6044:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6045:                     my $now = time;
 6046:                     if ($uri =~ m{^([^/]+)/?$}) {
 6047:                         my $adom = $1;
 6048:                         foreach my $key (keys(%env)) {
 6049:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6050:                                 my ($start,$end) = split('.',$env{$key});
 6051:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6052:                                     $ownaccess = 1;
 6053:                                     last;
 6054:                                 }
 6055:                             }
 6056:                         }
 6057:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6058:                         my $adom = $1;
 6059:                         my $aname = $2;
 6060:                         foreach my $role ('ca','aa') { 
 6061:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6062:                                 my ($start,$end) =
 6063:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6064:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6065:                                     $ownaccess = 1;
 6066:                                     last;
 6067:                                 }
 6068:                             }
 6069:                         }
 6070:                     }
 6071:                 }
 6072:             }
 6073:         }
 6074:     }
 6075: 
 6076: # Course
 6077: 
 6078:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6079:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6080:             $thisallowed.=$1;
 6081:         }
 6082:     }
 6083: 
 6084: # Domain
 6085: 
 6086:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6087:        =~/\Q$priv\E\&([^\:]*)/) {
 6088:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6089:             $thisallowed.=$1;
 6090:         }
 6091:     }
 6092: 
 6093: # User who is not author or co-author might still be able to edit
 6094: # resource of an author in the domain (e.g., if Domain Coordinator).
 6095:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6096:         (&allowed('mdc',$env{'request.course.id'}))) {
 6097:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6098:             $thisallowed.=$1;
 6099:         }
 6100:     }
 6101: 
 6102: # Course: uri itself is a course
 6103:     my $courseuri=$uri;
 6104:     $courseuri=~s/\_(\d)/\/$1/;
 6105:     $courseuri=~s/^([^\/])/\/$1/;
 6106: 
 6107:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6108:        =~/\Q$priv\E\&([^\:]*)/) {
 6109:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6110:             $thisallowed.=$1;
 6111:         }
 6112:     }
 6113: 
 6114: # URI is an uploaded document for this course, default permissions don't matter
 6115: # not allowing 'edit' access (editupload) to uploaded course docs
 6116:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6117: 	$thisallowed='';
 6118:         my ($match)=&is_on_map($uri);
 6119:         if ($match) {
 6120:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6121:                   =~/\Q$priv\E\&([^\:]*)/) {
 6122:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6123:                 if (@blockers > 0) {
 6124:                     $thisallowed = 'B';
 6125:                 } else {
 6126:                     $thisallowed.=$1;
 6127:                 }
 6128:             }
 6129:         } else {
 6130:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6131:             if ($refuri) {
 6132:                 if ($refuri =~ m|^/adm/|) {
 6133:                     $thisallowed='F';
 6134:                 } else {
 6135:                     $refuri=&declutter($refuri);
 6136:                     my ($match) = &is_on_map($refuri);
 6137:                     if ($match) {
 6138:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6139:                         if (@blockers > 0) {
 6140:                             $thisallowed = 'B';
 6141:                         } else {
 6142:                             $thisallowed='F';
 6143:                         }
 6144:                     }
 6145:                 }
 6146:             }
 6147:         }
 6148:     }
 6149: 
 6150:     if ($priv eq 'bre'
 6151: 	&& $thisallowed ne 'F' 
 6152: 	&& $thisallowed ne '2'
 6153: 	&& &is_portfolio_url($uri)) {
 6154: 	$thisallowed = &portfolio_access($uri);
 6155:     }
 6156:     
 6157: # Full access at system, domain or course-wide level? Exit.
 6158:     if ($thisallowed=~/F/) {
 6159: 	return 'F';
 6160:     }
 6161: 
 6162: # If this is generating or modifying users, exit with special codes
 6163: 
 6164:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6165: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6166: 	    my ($audom,$auname)=split('/',$uri);
 6167: # no author name given, so this just checks on the general right to make a co-author in this domain
 6168: 	    unless ($auname) { return $thisallowed; }
 6169: # an author name is given, so we are about to actually make a co-author for a certain account
 6170: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6171: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6172: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6173: 	}
 6174: 	return $thisallowed;
 6175:     }
 6176: #
 6177: # Gathered so far: system, domain and course wide privileges
 6178: #
 6179: # Course: See if uri or referer is an individual resource that is part of 
 6180: # the course
 6181: 
 6182:     if ($env{'request.course.id'}) {
 6183: 
 6184:        $courseprivid=$env{'request.course.id'};
 6185:        if ($env{'request.course.sec'}) {
 6186:           $courseprivid.='/'.$env{'request.course.sec'};
 6187:        }
 6188:        $courseprivid=~s/\_/\//;
 6189:        my $checkreferer=1;
 6190:        my ($match,$cond)=&is_on_map($uri);
 6191:        if ($match) {
 6192:            $statecond=$cond;
 6193:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6194:                =~/\Q$priv\E\&([^\:]*)/) {
 6195:                my $value = $1;
 6196:                if ($priv eq 'bre') {
 6197:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6198:                    if (@blockers > 0) {
 6199:                        $thisallowed = 'B';
 6200:                    } else {
 6201:                        $thisallowed.=$value;
 6202:                    }
 6203:                } else {
 6204:                    $thisallowed.=$value;
 6205:                }
 6206:                $checkreferer=0;
 6207:            }
 6208:        }
 6209:        
 6210:        if ($checkreferer) {
 6211: 	  my $refuri=$env{'httpref.'.$orguri};
 6212:             unless ($refuri) {
 6213:                 foreach my $key (keys(%env)) {
 6214: 		    if ($key=~/^httpref\..*\*/) {
 6215: 			my $pattern=$key;
 6216:                         $pattern=~s/^httpref\.\/res\///;
 6217:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6218:                         $pattern=~s/\//\\\//g;
 6219:                         if ($orguri=~/$pattern/) {
 6220: 			    $refuri=$env{$key};
 6221:                         }
 6222:                     }
 6223:                 }
 6224:             }
 6225: 
 6226:          if ($refuri) { 
 6227: 	  $refuri=&declutter($refuri);
 6228:           my ($match,$cond)=&is_on_map($refuri);
 6229:             if ($match) {
 6230:               my $refstatecond=$cond;
 6231:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6232:                   =~/\Q$priv\E\&([^\:]*)/) {
 6233:                   my $value = $1;
 6234:                   if ($priv eq 'bre') {
 6235:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6236:                       if (@blockers > 0) {
 6237:                           $thisallowed = 'B';
 6238:                       } else {
 6239:                           $thisallowed.=$value;
 6240:                       }
 6241:                   } else {
 6242:                       $thisallowed.=$value;
 6243:                   }
 6244:                   $uri=$refuri;
 6245:                   $statecond=$refstatecond;
 6246:               }
 6247:           }
 6248:         }
 6249:        }
 6250:    }
 6251: 
 6252: #
 6253: # Gathered now: all privileges that could apply, and condition number
 6254: # 
 6255: #
 6256: # Full or no access?
 6257: #
 6258: 
 6259:     if ($thisallowed=~/F/) {
 6260: 	return 'F';
 6261:     }
 6262: 
 6263:     unless ($thisallowed) {
 6264:         return '';
 6265:     }
 6266: 
 6267: # Restrictions exist, deal with them
 6268: #
 6269: #   C:according to course preferences
 6270: #   R:according to resource settings
 6271: #   L:unless locked
 6272: #   X:according to user session state
 6273: #
 6274: 
 6275: # Possibly locked functionality, check all courses
 6276: # Locks might take effect only after 10 minutes cache expiration for other
 6277: # courses, and 2 minutes for current course
 6278: 
 6279:     my $envkey;
 6280:     if ($thisallowed=~/L/) {
 6281:         foreach $envkey (keys(%env)) {
 6282:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6283:                my $courseid=$2;
 6284:                my $roleid=$1.'.'.$2;
 6285:                $courseid=~s/^\///;
 6286:                my $expiretime=600;
 6287:                if ($env{'request.role'} eq $roleid) {
 6288: 		  $expiretime=120;
 6289:                }
 6290: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6291:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6292:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6293: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6294:                }
 6295:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6296:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6297: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6298:                        &log($env{'user.domain'},$env{'user.name'},
 6299:                             $env{'user.home'},
 6300:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6301:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6302:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6303: 		       return '';
 6304:                    }
 6305:                }
 6306:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6307:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6308: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6309:                        &log($env{'user.domain'},$env{'user.name'},
 6310:                             $env{'user.home'},
 6311:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6312:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6313:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6314: 		       return '';
 6315:                    }
 6316:                }
 6317: 	   }
 6318:        }
 6319:     }
 6320:    
 6321: #
 6322: # Rest of the restrictions depend on selected course
 6323: #
 6324: 
 6325:     unless ($env{'request.course.id'}) {
 6326: 	if ($thisallowed eq 'A') {
 6327: 	    return 'A';
 6328:         } elsif ($thisallowed eq 'B') {
 6329:             return 'B';
 6330: 	} else {
 6331: 	    return '1';
 6332: 	}
 6333:     }
 6334: 
 6335: #
 6336: # Now user is definitely in a course
 6337: #
 6338: 
 6339: 
 6340: # Course preferences
 6341: 
 6342:    if ($thisallowed=~/C/) {
 6343:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6344:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6345:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6346: 	   =~/\Q$rolecode\E/) {
 6347: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6348: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6349: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6350: 			$env{'request.course.id'});
 6351: 	   }
 6352:            return '';
 6353:        }
 6354: 
 6355:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6356: 	   =~/\Q$unamedom\E/) {
 6357: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6358: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6359: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6360: 			$env{'request.course.id'});
 6361: 	   }
 6362:            return '';
 6363:        }
 6364:    }
 6365: 
 6366: # Resource preferences
 6367: 
 6368:    if ($thisallowed=~/R/) {
 6369:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6370:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6371: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6372: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6373: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6374: 	   }
 6375: 	   return '';
 6376:        }
 6377:    }
 6378: 
 6379: # Restricted by state or randomout?
 6380: 
 6381:    if ($thisallowed=~/X/) {
 6382:       if ($env{'acc.randomout'}) {
 6383: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6384:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6385:             return ''; 
 6386:          }
 6387:       }
 6388:       if (&condval($statecond)) {
 6389: 	 return '2';
 6390:       } else {
 6391:          return '';
 6392:       }
 6393:    }
 6394: 
 6395:     if ($thisallowed eq 'A') {
 6396: 	return 'A';
 6397:     } elsif ($thisallowed eq 'B') {
 6398:         return 'B';
 6399:     }
 6400:    return 'F';
 6401: }
 6402: 
 6403: sub get_comm_blocks {
 6404:     my ($cdom,$cnum) = @_;
 6405:     if ($cdom eq '' || $cnum eq '') {
 6406:         return unless ($env{'request.course.id'});
 6407:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6408:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6409:     }
 6410:     my %commblocks;
 6411:     my $hashid=$cdom.'_'.$cnum;
 6412:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6413:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6414:         %commblocks = %{$blocksref};
 6415:     } else {
 6416:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6417:         my $cachetime = 600;
 6418:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6419:     }
 6420:     return %commblocks;
 6421: }
 6422: 
 6423: sub has_comm_blocking {
 6424:     my ($priv,$symb,$uri,$blocks) = @_;
 6425:     return unless ($env{'request.course.id'});
 6426:     return unless ($priv eq 'bre');
 6427:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6428:     my %commblocks;
 6429:     if (ref($blocks) eq 'HASH') {
 6430:         %commblocks = %{$blocks};
 6431:     } else {
 6432:         %commblocks = &get_comm_blocks();
 6433:     }
 6434:     return unless (keys(%commblocks) > 0);
 6435:     if (!$symb) { $symb=&symbread($uri,1); }
 6436:     my ($map,$resid,undef)=&decode_symb($symb);
 6437:     my %tocheck = (
 6438:                     maps      => $map,
 6439:                     resources => $symb,
 6440:                   );
 6441:     my @blockers;
 6442:     my $now = time;
 6443:     my $navmap = Apache::lonnavmaps::navmap->new();
 6444:     foreach my $block (keys(%commblocks)) {
 6445:         if ($block =~ /^(\d+)____(\d+)$/) {
 6446:             my ($start,$end) = ($1,$2);
 6447:             if ($start <= $now && $end >= $now) {
 6448:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6449:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6450:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6451:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6452:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6453:                                     push(@blockers,$block);
 6454:                                 }
 6455:                             }
 6456:                         }
 6457:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6458:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6459:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6460:                                     push(@blockers,$block);
 6461:                                 }
 6462:                             }
 6463:                         }
 6464:                     }
 6465:                 }
 6466:             }
 6467:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6468:             my $item = $1;
 6469:             my @to_test;
 6470:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6471:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6472:                     my $check_interval;
 6473:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6474:                         my @interval;
 6475:                         my $type = 'map';
 6476:                         if ($item eq 'course') {
 6477:                             $type = 'course';
 6478:                             @interval=&EXT("resource.0.interval");
 6479:                         } else {
 6480:                             if ($item =~ /___\d+___/) {
 6481:                                 $type = 'resource';
 6482:                                 @interval=&EXT("resource.0.interval",$item);
 6483:                                 if (ref($navmap)) {                        
 6484:                                     my $res = $navmap->getBySymb($item); 
 6485:                                     push(@to_test,$res);
 6486:                                 }
 6487:                             } else {
 6488:                                 my $mapsymb = &symbread($item,1);
 6489:                                 if ($mapsymb) {
 6490:                                     if (ref($navmap)) {
 6491:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6492:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6493:                                         foreach my $res (@to_test) {
 6494:                                             my $symb = $res->symb();
 6495:                                             next if ($symb eq $mapsymb);
 6496:                                             if ($symb ne '') {
 6497:                                                 @interval=&EXT("resource.0.interval",$symb);
 6498:                                                 last;
 6499:                                             }
 6500:                                         }
 6501:                                     }
 6502:                                 }
 6503:                             }
 6504:                         }
 6505:                         if ($interval[0] =~ /\d+/) {
 6506:                             my $first_access;
 6507:                             if ($type eq 'resource') {
 6508:                                 $first_access=&get_first_access($interval[1],$item);
 6509:                             } elsif ($type eq 'map') {
 6510:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6511:                             } else {
 6512:                                 $first_access=&get_first_access($interval[1]);
 6513:                             }
 6514:                             if ($first_access) {
 6515:                                 my $timesup = $first_access+$interval[0];
 6516:                                 if ($timesup > $now) {
 6517:                                     foreach my $res (@to_test) {
 6518:                                         if ($res->is_problem()) {
 6519:                                             if ($res->completable()) {
 6520:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6521:                                                     push(@blockers,$block);
 6522:                                                 }
 6523:                                                 last;
 6524:                                             }
 6525:                                         }
 6526:                                     }
 6527:                                 }
 6528:                             }
 6529:                         }
 6530:                     }
 6531:                 }
 6532:             }
 6533:         }
 6534:     }
 6535:     return @blockers;
 6536: }
 6537: 
 6538: sub check_docs_block {
 6539:     my ($docsblock,$tocheck) =@_;
 6540:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6541:         return;
 6542:     }
 6543:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6544:         if ($tocheck->{'maps'}) {
 6545:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6546:                 return 1;
 6547:             }
 6548:         }
 6549:     }
 6550:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6551:         if ($tocheck->{'resources'}) {
 6552:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6553:                 return 1;
 6554:             }
 6555:         }
 6556:     }
 6557:     return;
 6558: }
 6559: 
 6560: #
 6561: #   Removes the versino from a URI and
 6562: #   splits it in to its filename and path to the filename.
 6563: #   Seems like File::Basename could have done this more clearly.
 6564: #   Parameters:
 6565: #      $uri   - input URI
 6566: #   Returns:
 6567: #     Two element list consisting of 
 6568: #     $pathname  - the URI up to and excluding the trailing /
 6569: #     $filename  - The part of the URI following the last /
 6570: #  NOTE:
 6571: #    Another realization of this is simply:
 6572: #    use File::Basename;
 6573: #    ...
 6574: #    $uri = shift;
 6575: #    $filename = basename($uri);
 6576: #    $path     = dirname($uri);
 6577: #    return ($filename, $path);
 6578: #
 6579: #     The implementation below is probably faster however.
 6580: #
 6581: sub split_uri_for_cond {
 6582:     my $uri=&deversion(&declutter(shift));
 6583:     my @uriparts=split(/\//,$uri);
 6584:     my $filename=pop(@uriparts);
 6585:     my $pathname=join('/',@uriparts);
 6586:     return ($pathname,$filename);
 6587: }
 6588: # --------------------------------------------------- Is a resource on the map?
 6589: 
 6590: sub is_on_map {
 6591:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6592:     #Trying to find the conditional for the file
 6593:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6594: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6595:     if ($match) {
 6596: 	return (1,$1);
 6597:     } else {
 6598: 	return (0,0);
 6599:     }
 6600: }
 6601: 
 6602: # --------------------------------------------------------- Get symb from alias
 6603: 
 6604: sub get_symb_from_alias {
 6605:     my $symb=shift;
 6606:     my ($map,$resid,$url)=&decode_symb($symb);
 6607: # Already is a symb
 6608:     if ($url) { return $symb; }
 6609: # Must be an alias
 6610:     my $aliassymb='';
 6611:     my %bighash;
 6612:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6613:                             &GDBM_READER(),0640)) {
 6614:         my $rid=$bighash{'mapalias_'.$symb};
 6615: 	if ($rid) {
 6616: 	    my ($mapid,$resid)=split(/\./,$rid);
 6617: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6618: 				    $resid,$bighash{'src_'.$rid});
 6619: 	}
 6620:         untie %bighash;
 6621:     }
 6622:     return $aliassymb;
 6623: }
 6624: 
 6625: # ----------------------------------------------------------------- Define Role
 6626: 
 6627: sub definerole {
 6628:   if (allowed('mcr','/')) {
 6629:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6630:     foreach my $role (split(':',$sysrole)) {
 6631: 	my ($crole,$cqual)=split(/\&/,$role);
 6632:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6633:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6634: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6635:                return "refused:s:$crole&$cqual"; 
 6636:             }
 6637:         }
 6638:     }
 6639:     foreach my $role (split(':',$domrole)) {
 6640: 	my ($crole,$cqual)=split(/\&/,$role);
 6641:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6642:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6643: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6644:                return "refused:d:$crole&$cqual"; 
 6645:             }
 6646:         }
 6647:     }
 6648:     foreach my $role (split(':',$courole)) {
 6649: 	my ($crole,$cqual)=split(/\&/,$role);
 6650:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6651:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6652: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6653:                return "refused:c:$crole&$cqual"; 
 6654:             }
 6655:         }
 6656:     }
 6657:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6658:                 "$env{'user.domain'}:$env{'user.name'}:".
 6659: 	        "rolesdef_$rolename=".
 6660:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6661:     return reply($command,$env{'user.home'});
 6662:   } else {
 6663:     return 'refused';
 6664:   }
 6665: }
 6666: 
 6667: # ---------------- Make a metadata query against the network of library servers
 6668: 
 6669: sub metadata_query {
 6670:     my ($query,$custom,$customshow,$server_array)=@_;
 6671:     my %rhash;
 6672:     my %libserv = &all_library();
 6673:     my @server_list = (defined($server_array) ? @$server_array
 6674:                                               : keys(%libserv) );
 6675:     for my $server (@server_list) {
 6676: 	unless ($custom or $customshow) {
 6677: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6678: 	    $rhash{$server}=$reply;
 6679: 	}
 6680: 	else {
 6681: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6682: 			     &escape($custom).':'.&escape($customshow),
 6683: 			     $server);
 6684: 	    $rhash{$server}=$reply;
 6685: 	}
 6686:     }
 6687:     return \%rhash;
 6688: }
 6689: 
 6690: # ----------------------------------------- Send log queries and wait for reply
 6691: 
 6692: sub log_query {
 6693:     my ($uname,$udom,$query,%filters)=@_;
 6694:     my $uhome=&homeserver($uname,$udom);
 6695:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6696:     my $uhost=&hostname($uhome);
 6697:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6698:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6699:                        $uhome);
 6700:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6701:     return get_query_reply($queryid);
 6702: }
 6703: 
 6704: # -------------------------- Update MySQL table for portfolio file
 6705: 
 6706: sub update_portfolio_table {
 6707:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6708:     if ($group ne '') {
 6709:         $file_name =~s /^\Q$group\E//;
 6710:     }
 6711:     my $homeserver = &homeserver($uname,$udom);
 6712:     my $queryid=
 6713:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6714:                ':'.&escape($file_name).':'.$action,$homeserver);
 6715:     my $reply = &get_query_reply($queryid);
 6716:     return $reply;
 6717: }
 6718: 
 6719: # -------------------------- Update MySQL allusers table
 6720: 
 6721: sub update_allusers_table {
 6722:     my ($uname,$udom,$names) = @_;
 6723:     my $homeserver = &homeserver($uname,$udom);
 6724:     my $queryid=
 6725:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6726:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6727:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6728:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6729:                'generation='.&escape($names->{'generation'}).'%%'.
 6730:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6731:                'id='.&escape($names->{'id'}),$homeserver);
 6732:     return;
 6733: }
 6734: 
 6735: # ------- Request retrieval of institutional classlists for course(s)
 6736: 
 6737: sub fetch_enrollment_query {
 6738:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6739:     my $homeserver;
 6740:     my $maxtries = 1;
 6741:     if ($context eq 'automated') {
 6742:         $homeserver = $perlvar{'lonHostID'};
 6743:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6744:     } else {
 6745:         $homeserver = &homeserver($cnum,$dom);
 6746:     }
 6747:     my $host=&hostname($homeserver);
 6748:     my $cmd = '';
 6749:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6750:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6751:     }
 6752:     $cmd =~ s/%%$//;
 6753:     $cmd = &escape($cmd);
 6754:     my $query = 'fetchenrollment';
 6755:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6756:     unless ($queryid=~/^\Q$host\E\_/) { 
 6757:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6758:         return 'error: '.$queryid;
 6759:     }
 6760:     my $reply = &get_query_reply($queryid);
 6761:     my $tries = 1;
 6762:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6763:         $reply = &get_query_reply($queryid);
 6764:         $tries ++;
 6765:     }
 6766:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6767:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6768:     } else {
 6769:         my @responses = split(/:/,$reply);
 6770:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6771:             foreach my $line (@responses) {
 6772:                 my ($key,$value) = split(/=/,$line,2);
 6773:                 $$replyref{$key} = $value;
 6774:             }
 6775:         } else {
 6776:             my $pathname = LONCAPA::tempdir();
 6777:             foreach my $line (@responses) {
 6778:                 my ($key,$value) = split(/=/,$line);
 6779:                 $$replyref{$key} = $value;
 6780:                 if ($value > 0) {
 6781:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6782:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6783:                         my $destname = $pathname.'/'.$filename;
 6784:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6785:                         if ($xml_classlist =~ /^error/) {
 6786:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6787:                         } else {
 6788:                             if ( open(FILE,">$destname") ) {
 6789:                                 print FILE &unescape($xml_classlist);
 6790:                                 close(FILE);
 6791:                             } else {
 6792:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6793:                             }
 6794:                         }
 6795:                     }
 6796:                 }
 6797:             }
 6798:         }
 6799:         return 'ok';
 6800:     }
 6801:     return 'error';
 6802: }
 6803: 
 6804: sub get_query_reply {
 6805:     my $queryid=shift;
 6806:     my $replyfile=LONCAPA::tempdir().$queryid;
 6807:     my $reply='';
 6808:     for (1..100) {
 6809: 	sleep 2;
 6810:         if (-e $replyfile.'.end') {
 6811: 	    if (open(my $fh,$replyfile)) {
 6812: 		$reply = join('',<$fh>);
 6813: 		close($fh);
 6814: 	   } else { return 'error: reply_file_error'; }
 6815:            return &unescape($reply);
 6816: 	}
 6817:     }
 6818:     return 'timeout:'.$queryid;
 6819: }
 6820: 
 6821: sub courselog_query {
 6822: #
 6823: # possible filters:
 6824: # url: url or symb
 6825: # username
 6826: # domain
 6827: # action: view, submit, grade
 6828: # start: timestamp
 6829: # end: timestamp
 6830: #
 6831:     my (%filters)=@_;
 6832:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6833:     if ($filters{'url'}) {
 6834: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6835:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6836:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6837:     }
 6838:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6839:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6840:     return &log_query($cname,$cdom,'courselog',%filters);
 6841: }
 6842: 
 6843: sub userlog_query {
 6844: #
 6845: # possible filters:
 6846: # action: log check role
 6847: # start: timestamp
 6848: # end: timestamp
 6849: #
 6850:     my ($uname,$udom,%filters)=@_;
 6851:     return &log_query($uname,$udom,'userlog',%filters);
 6852: }
 6853: 
 6854: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6855: 
 6856: sub auto_run {
 6857:     my ($cnum,$cdom) = @_;
 6858:     my $response = 0;
 6859:     my $settings;
 6860:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6861:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6862:         $settings = $domconfig{'autoenroll'};
 6863:         if ($settings->{'run'} eq '1') {
 6864:             $response = 1;
 6865:         }
 6866:     } else {
 6867:         my $homeserver;
 6868:         if (&is_course($cdom,$cnum)) {
 6869:             $homeserver = &homeserver($cnum,$cdom);
 6870:         } else {
 6871:             $homeserver = &domain($cdom,'primary');
 6872:         }
 6873:         if ($homeserver ne 'no_host') {
 6874:             $response = &reply('autorun:'.$cdom,$homeserver);
 6875:         }
 6876:     }
 6877:     return $response;
 6878: }
 6879: 
 6880: sub auto_get_sections {
 6881:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6882:     my $homeserver;
 6883:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6884:         $homeserver = &homeserver($cnum,$cdom);
 6885:     }
 6886:     if (!defined($homeserver)) { 
 6887:         if ($cdom =~ /^$match_domain$/) {
 6888:             $homeserver = &domain($cdom,'primary');
 6889:         }
 6890:     }
 6891:     my @secs;
 6892:     if (defined($homeserver)) {
 6893:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6894:         unless ($response eq 'refused') {
 6895:             @secs = split(/:/,$response);
 6896:         }
 6897:     }
 6898:     return @secs;
 6899: }
 6900: 
 6901: sub auto_new_course {
 6902:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6903:     my $homeserver = &homeserver($cnum,$cdom);
 6904:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6905:     return $response;
 6906: }
 6907: 
 6908: sub auto_validate_courseID {
 6909:     my ($cnum,$cdom,$inst_course_id) = @_;
 6910:     my $homeserver = &homeserver($cnum,$cdom);
 6911:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6912:     return $response;
 6913: }
 6914: 
 6915: sub auto_validate_instcode {
 6916:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6917:     my ($homeserver,$response);
 6918:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6919:         $homeserver = &homeserver($cnum,$cdom);
 6920:     }
 6921:     if (!defined($homeserver)) {
 6922:         if ($cdom =~ /^$match_domain$/) {
 6923:             $homeserver = &domain($cdom,'primary');
 6924:         }
 6925:     }
 6926:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6927:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6928:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6929:     return ($outcome,$description);
 6930: }
 6931: 
 6932: sub auto_create_password {
 6933:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6934:     my ($homeserver,$response);
 6935:     my $create_passwd = 0;
 6936:     my $authchk = '';
 6937:     if ($udom =~ /^$match_domain$/) {
 6938:         $homeserver = &domain($udom,'primary');
 6939:     }
 6940:     if ($homeserver eq '') {
 6941:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6942:             $homeserver = &homeserver($cnum,$cdom);
 6943:         }
 6944:     }
 6945:     if ($homeserver eq '') {
 6946:         $authchk = 'nodomain';
 6947:     } else {
 6948:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6949:         if ($response eq 'refused') {
 6950:             $authchk = 'refused';
 6951:         } else {
 6952:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6953:         }
 6954:     }
 6955:     return ($authparam,$create_passwd,$authchk);
 6956: }
 6957: 
 6958: sub auto_photo_permission {
 6959:     my ($cnum,$cdom,$students) = @_;
 6960:     my $homeserver = &homeserver($cnum,$cdom);
 6961:     my ($outcome,$perm_reqd,$conditions) = 
 6962: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6963:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6964: 	return (undef,undef);
 6965:     }
 6966:     return ($outcome,$perm_reqd,$conditions);
 6967: }
 6968: 
 6969: sub auto_checkphotos {
 6970:     my ($uname,$udom,$pid) = @_;
 6971:     my $homeserver = &homeserver($uname,$udom);
 6972:     my ($result,$resulttype);
 6973:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6974: 				   &escape($uname).':'.&escape($pid),
 6975: 				   $homeserver));
 6976:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6977: 	return (undef,undef);
 6978:     }
 6979:     if ($outcome) {
 6980:         ($result,$resulttype) = split(/:/,$outcome);
 6981:     } 
 6982:     return ($result,$resulttype);
 6983: }
 6984: 
 6985: sub auto_photochoice {
 6986:     my ($cnum,$cdom) = @_;
 6987:     my $homeserver = &homeserver($cnum,$cdom);
 6988:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6989: 						       &escape($cdom),
 6990: 						       $homeserver)));
 6991:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6992: 	return (undef,undef);
 6993:     }
 6994:     return ($update,$comment);
 6995: }
 6996: 
 6997: sub auto_photoupdate {
 6998:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6999:     my $homeserver = &homeserver($cnum,$dom);
 7000:     my $host=&hostname($homeserver);
 7001:     my $cmd = '';
 7002:     my $maxtries = 1;
 7003:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7004:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7005:     }
 7006:     $cmd =~ s/%%$//;
 7007:     $cmd = &escape($cmd);
 7008:     my $query = 'institutionalphotos';
 7009:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7010:     unless ($queryid=~/^\Q$host\E\_/) {
 7011:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7012:         return 'error: '.$queryid;
 7013:     }
 7014:     my $reply = &get_query_reply($queryid);
 7015:     my $tries = 1;
 7016:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7017:         $reply = &get_query_reply($queryid);
 7018:         $tries ++;
 7019:     }
 7020:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7021:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7022:     } else {
 7023:         my @responses = split(/:/,$reply);
 7024:         my $outcome = shift(@responses); 
 7025:         foreach my $item (@responses) {
 7026:             my ($key,$value) = split(/=/,$item);
 7027:             $$photo{$key} = $value;
 7028:         }
 7029:         return $outcome;
 7030:     }
 7031:     return 'error';
 7032: }
 7033: 
 7034: sub auto_instcode_format {
 7035:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7036: 	$cat_order) = @_;
 7037:     my $courses = '';
 7038:     my @homeservers;
 7039:     if ($caller eq 'global') {
 7040: 	my %servers = &get_servers($codedom,'library');
 7041: 	foreach my $tryserver (keys(%servers)) {
 7042: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7043: 		push(@homeservers,$tryserver);
 7044: 	    }
 7045:         }
 7046:     } elsif ($caller eq 'requests') {
 7047:         if ($codedom =~ /^$match_domain$/) {
 7048:             my $chome = &domain($codedom,'primary');
 7049:             unless ($chome eq 'no_host') {
 7050:                 push(@homeservers,$chome);
 7051:             }
 7052:         }
 7053:     } else {
 7054:         push(@homeservers,&homeserver($caller,$codedom));
 7055:     }
 7056:     foreach my $code (keys(%{$instcodes})) {
 7057:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7058:     }
 7059:     chop($courses);
 7060:     my $ok_response = 0;
 7061:     my $response;
 7062:     while (@homeservers > 0 && $ok_response == 0) {
 7063:         my $server = shift(@homeservers); 
 7064:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7065:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7066:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7067: 		split(/:/,$response);
 7068:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7069:             push(@{$codetitles},&str2array($codetitles_str));
 7070:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7071:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7072:             $ok_response = 1;
 7073:         }
 7074:     }
 7075:     if ($ok_response) {
 7076:         return 'ok';
 7077:     } else {
 7078:         return $response;
 7079:     }
 7080: }
 7081: 
 7082: sub auto_instcode_defaults {
 7083:     my ($domain,$returnhash,$code_order) = @_;
 7084:     my @homeservers;
 7085: 
 7086:     my %servers = &get_servers($domain,'library');
 7087:     foreach my $tryserver (keys(%servers)) {
 7088: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7089: 	    push(@homeservers,$tryserver);
 7090: 	}
 7091:     }
 7092: 
 7093:     my $response;
 7094:     foreach my $server (@homeservers) {
 7095:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7096:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7097: 	
 7098: 	foreach my $pair (split(/\&/,$response)) {
 7099: 	    my ($name,$value)=split(/\=/,$pair);
 7100: 	    if ($name eq 'code_order') {
 7101: 		@{$code_order} = split(/\&/,&unescape($value));
 7102: 	    } else {
 7103: 		$returnhash->{&unescape($name)}=&unescape($value);
 7104: 	    }
 7105: 	}
 7106: 	return 'ok';
 7107:     }
 7108: 
 7109:     return $response;
 7110: }
 7111: 
 7112: sub auto_possible_instcodes {
 7113:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7114:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7115:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7116:         return;
 7117:     }
 7118:     my (@homeservers,$uhome);
 7119:     if (defined(&domain($domain,'primary'))) {
 7120:         $uhome=&domain($domain,'primary');
 7121:         push(@homeservers,&domain($domain,'primary'));
 7122:     } else {
 7123:         my %servers = &get_servers($domain,'library');
 7124:         foreach my $tryserver (keys(%servers)) {
 7125:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7126:                 push(@homeservers,$tryserver);
 7127:             }
 7128:         }
 7129:     }
 7130:     my $response;
 7131:     foreach my $server (@homeservers) {
 7132:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7133:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7134:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7135:             split(':',$response);
 7136:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7137:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7138:         foreach my $item (split('&',$cat_title)) {   
 7139:             my ($name,$value)=split('=',$item);
 7140:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7141:         }
 7142:         foreach my $item (split('&',$cat_order)) {
 7143:             my ($name,$value)=split('=',$item);
 7144:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7145:         }
 7146:         return 'ok';
 7147:     }
 7148:     return $response;
 7149: }
 7150: 
 7151: sub auto_courserequest_checks {
 7152:     my ($dom) = @_;
 7153:     my ($homeserver,%validations);
 7154:     if ($dom =~ /^$match_domain$/) {
 7155:         $homeserver = &domain($dom,'primary');
 7156:     }
 7157:     unless ($homeserver eq 'no_host') {
 7158:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7159:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7160:             my @items = split(/&/,$response);
 7161:             foreach my $item (@items) {
 7162:                 my ($key,$value) = split('=',$item);
 7163:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7164:             }
 7165:         }
 7166:     }
 7167:     return %validations; 
 7168: }
 7169: 
 7170: sub auto_courserequest_validation {
 7171:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7172:     my ($homeserver,$response);
 7173:     if ($dom =~ /^$match_domain$/) {
 7174:         $homeserver = &domain($dom,'primary');
 7175:     }
 7176:     unless ($homeserver eq 'no_host') {  
 7177:           
 7178:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7179:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7180:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7181:                                     $homeserver));
 7182:     }
 7183:     return $response;
 7184: }
 7185: 
 7186: sub auto_validate_class_sec {
 7187:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7188:     my $homeserver = &homeserver($cnum,$cdom);
 7189:     my $ownerlist;
 7190:     if (ref($owners) eq 'ARRAY') {
 7191:         $ownerlist = join(',',@{$owners});
 7192:     } else {
 7193:         $ownerlist = $owners;
 7194:     }
 7195:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7196:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7197:     return $response;
 7198: }
 7199: 
 7200: # ------------------------------------------------------- Course Group routines
 7201: 
 7202: sub get_coursegroups {
 7203:     my ($cdom,$cnum,$group,$namespace) = @_;
 7204:     return(&dump($namespace,$cdom,$cnum,$group));
 7205: }
 7206: 
 7207: sub modify_coursegroup {
 7208:     my ($cdom,$cnum,$groupsettings) = @_;
 7209:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7210: }
 7211: 
 7212: sub toggle_coursegroup_status {
 7213:     my ($cdom,$cnum,$group,$action) = @_;
 7214:     my ($from_namespace,$to_namespace);
 7215:     if ($action eq 'delete') {
 7216:         $from_namespace = 'coursegroups';
 7217:         $to_namespace = 'deleted_groups';
 7218:     } else {
 7219:         $from_namespace = 'deleted_groups';
 7220:         $to_namespace = 'coursegroups';
 7221:     }
 7222:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7223:     if (my $tmp = &error(%curr_group)) {
 7224:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7225:         return ('read error',$tmp);
 7226:     } else {
 7227:         my %savedsettings = %curr_group; 
 7228:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7229:         my $deloutcome;
 7230:         if ($result eq 'ok') {
 7231:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7232:         } else {
 7233:             return ('write error',$result);
 7234:         }
 7235:         if ($deloutcome eq 'ok') {
 7236:             return 'ok';
 7237:         } else {
 7238:             return ('delete error',$deloutcome);
 7239:         }
 7240:     }
 7241: }
 7242: 
 7243: sub modify_group_roles {
 7244:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7245:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7246:     my $role = 'gr/'.&escape($userprivs);
 7247:     my ($uname,$udom) = split(/:/,$user);
 7248:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7249:     if ($result eq 'ok') {
 7250:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7251:     }
 7252:     return $result;
 7253: }
 7254: 
 7255: sub modify_coursegroup_membership {
 7256:     my ($cdom,$cnum,$membership) = @_;
 7257:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7258:     return $result;
 7259: }
 7260: 
 7261: sub get_active_groups {
 7262:     my ($udom,$uname,$cdom,$cnum) = @_;
 7263:     my $now = time;
 7264:     my %groups = ();
 7265:     foreach my $key (keys(%env)) {
 7266:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7267:             my ($start,$end) = split(/\./,$env{$key});
 7268:             if (($end!=0) && ($end<$now)) { next; }
 7269:             if (($start!=0) && ($start>$now)) { next; }
 7270:             if ($1 eq $cdom && $2 eq $cnum) {
 7271:                 $groups{$3} = $env{$key} ;
 7272:             }
 7273:         }
 7274:     }
 7275:     return %groups;
 7276: }
 7277: 
 7278: sub get_group_membership {
 7279:     my ($cdom,$cnum,$group) = @_;
 7280:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7281: }
 7282: 
 7283: sub get_users_groups {
 7284:     my ($udom,$uname,$courseid) = @_;
 7285:     my @usersgroups;
 7286:     my $cachetime=1800;
 7287: 
 7288:     my $hashid="$udom:$uname:$courseid";
 7289:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7290:     if (defined($cached)) {
 7291:         @usersgroups = split(/:/,$grouplist);
 7292:     } else {  
 7293:         $grouplist = '';
 7294:         my $courseurl = &courseid_to_courseurl($courseid);
 7295:         my $extra = &freeze_escape({'skipcheck' => 1});
 7296:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
 7297:         my $access_end = $env{'course.'.$courseid.
 7298:                               '.default_enrollment_end_date'};
 7299:         my $now = time;
 7300:         foreach my $key (keys(%roleshash)) {
 7301:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7302:                 my $group = $1;
 7303:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7304:                     my $start = $2;
 7305:                     my $end = $1;
 7306:                     if ($start == -1) { next; } # deleted from group
 7307:                     if (($start!=0) && ($start>$now)) { next; }
 7308:                     if (($end!=0) && ($end<$now)) {
 7309:                         if ($access_end && $access_end < $now) {
 7310:                             if ($access_end - $end < 86400) {
 7311:                                 push(@usersgroups,$group);
 7312:                             }
 7313:                         }
 7314:                         next;
 7315:                     }
 7316:                     push(@usersgroups,$group);
 7317:                 }
 7318:             }
 7319:         }
 7320:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7321:         $grouplist = join(':',@usersgroups);
 7322:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7323:     }
 7324:     return @usersgroups;
 7325: }
 7326: 
 7327: sub devalidate_getgroups_cache {
 7328:     my ($udom,$uname,$cdom,$cnum)=@_;
 7329:     my $courseid = $cdom.'_'.$cnum;
 7330: 
 7331:     my $hashid="$udom:$uname:$courseid";
 7332:     &devalidate_cache_new('getgroups',$hashid);
 7333: }
 7334: 
 7335: # ------------------------------------------------------------------ Plain Text
 7336: 
 7337: sub plaintext {
 7338:     my ($short,$type,$cid,$forcedefault) = @_;
 7339:     if ($short =~ m{^cr/}) {
 7340: 	return (split('/',$short))[-1];
 7341:     }
 7342:     if (!defined($cid)) {
 7343:         $cid = $env{'request.course.id'};
 7344:     }
 7345:     my %rolenames = (
 7346:                       Course    => 'std',
 7347:                       Community => 'alt1',
 7348:                     );
 7349:     if ($cid ne '') {
 7350:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7351:             unless ($forcedefault) {
 7352:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7353:                 &Apache::lonlocal::mt_escape(\$roletext);
 7354:                 return &Apache::lonlocal::mt($roletext);
 7355:             }
 7356:         }
 7357:     }
 7358:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7359:         (defined($rolenames{$type})) && 
 7360:         (defined($prp{$short}{$rolenames{$type}}))) {
 7361:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7362:     } elsif ($cid ne '') {
 7363:         my $crstype = $env{'course.'.$cid.'.type'};
 7364:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7365:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7366:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7367:         }
 7368:     }
 7369:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7370: }
 7371: 
 7372: # ----------------------------------------------------------------- Assign Role
 7373: 
 7374: sub assignrole {
 7375:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7376:         $context)=@_;
 7377:     my $mrole;
 7378:     if ($role =~ /^cr\//) {
 7379:         my $cwosec=$url;
 7380:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7381: 	unless (&allowed('ccr',$cwosec)) {
 7382:            my $refused = 1;
 7383:            if ($context eq 'requestcourses') {
 7384:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7385:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7386:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7387:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7388:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7389:                            if ($crsenv{'internal.courseowner'} eq
 7390:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7391:                                $refused = '';
 7392:                            }
 7393:                        }
 7394:                    }
 7395:                }
 7396:            }
 7397:            if ($refused) {
 7398:                &logthis('Refused custom assignrole: '.
 7399:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7400:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7401:                return 'refused';
 7402:            }
 7403:         }
 7404:         $mrole='cr';
 7405:     } elsif ($role =~ /^gr\//) {
 7406:         my $cwogrp=$url;
 7407:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7408:         unless (&allowed('mdg',$cwogrp)) {
 7409:             &logthis('Refused group assignrole: '.
 7410:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7411:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7412:             return 'refused';
 7413:         }
 7414:         $mrole='gr';
 7415:     } else {
 7416:         my $cwosec=$url;
 7417:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7418:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7419:             my $refused;
 7420:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7421:                 if (!(&allowed('c'.$role,$url))) {
 7422:                     $refused = 1;
 7423:                 }
 7424:             } else {
 7425:                 $refused = 1;
 7426:             }
 7427:             if ($refused) {
 7428:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7429:                 if (!$selfenroll && $context eq 'course') {
 7430:                     my %crsenv;
 7431:                     if ($role eq 'cc' || $role eq 'co') {
 7432:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7433:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7434:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7435:                                 if ($crsenv{'internal.courseowner'} eq 
 7436:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7437:                                     $refused = '';
 7438:                                 }
 7439:                             }
 7440:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7441:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7442:                                 if ($crsenv{'internal.courseowner'} eq 
 7443:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7444:                                     $refused = '';
 7445:                                 }
 7446:                             }
 7447:                         }
 7448:                     }
 7449:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7450:                     $refused = '';
 7451:                 } elsif ($context eq 'requestcourses') {
 7452:                     my @possroles = ('st','ta','ep','in','cc','co');
 7453:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7454:                         my $wrongcc;
 7455:                         if ($cnum =~ /^$match_community$/) {
 7456:                             $wrongcc = 1 if ($role eq 'cc');
 7457:                         } else {
 7458:                             $wrongcc = 1 if ($role eq 'co');
 7459:                         }
 7460:                         unless ($wrongcc) {
 7461:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7462:                             if ($crsenv{'internal.courseowner'} eq 
 7463:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7464:                                 $refused = '';
 7465:                             }
 7466:                         }
 7467:                     }
 7468:                 }
 7469:                 if ($refused) {
 7470:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7471:                              ' '.$role.' '.$end.' '.$start.' by '.
 7472: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7473:                     return 'refused';
 7474:                 }
 7475:             }
 7476:         } elsif ($role eq 'au') {
 7477:             if ($url ne '/'.$udom.'/') {
 7478:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7479:                          ' to assign author role for '.$uname.':'.$udom.
 7480:                          ' in domain: '.$url.' refused (wrong domain).');
 7481:                 return 'refused';
 7482:             }
 7483:         }
 7484:         $mrole=$role;
 7485:     }
 7486:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7487:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7488:     if ($end) { $command.='_'.$end; }
 7489:     if ($start) {
 7490: 	if ($end) { 
 7491:            $command.='_'.$start; 
 7492:         } else {
 7493:            $command.='_0_'.$start;
 7494:         }
 7495:     }
 7496:     my $origstart = $start;
 7497:     my $origend = $end;
 7498:     my $delflag;
 7499: # actually delete
 7500:     if ($deleteflag) {
 7501: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7502: # modify command to delete the role
 7503:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7504:                 "$udom:$uname:$url".'_'."$mrole";
 7505: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7506: # set start and finish to negative values for userrolelog
 7507:            $start=-1;
 7508:            $end=-1;
 7509:            $delflag = 1;
 7510:         }
 7511:     }
 7512: # send command
 7513:     my $answer=&reply($command,&homeserver($uname,$udom));
 7514: # log new user role if status is ok
 7515:     if ($answer eq 'ok') {
 7516: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7517: # for course roles, perform group memberships changes triggered by role change.
 7518:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7519:         unless ($role =~ /^gr/) {
 7520:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7521:                                              $origstart,$selfenroll,$context);
 7522:         }
 7523:         if ($role eq 'cc') {
 7524:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7525:         }
 7526:     }
 7527:     return $answer;
 7528: }
 7529: 
 7530: sub autoupdate_coowners {
 7531:     my ($url,$end,$start,$uname,$udom) = @_;
 7532:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7533:     if (($cdom ne '') && ($cnum ne '')) {
 7534:         my $now = time;
 7535:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7536:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7537:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7538:             my $instcode = $coursehash{'internal.coursecode'};
 7539:             if ($instcode ne '') {
 7540:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7541:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7542:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7543:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7544:                         if ($result eq 'valid') {
 7545:                             if ($coursehash{'internal.co-owners'}) {
 7546:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7547:                                     push(@newcoowners,$coowner);
 7548:                                 }
 7549:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7550:                                     push(@newcoowners,$uname.':'.$udom);
 7551:                                 }
 7552:                                 @newcoowners = sort(@newcoowners);
 7553:                             } else {
 7554:                                 push(@newcoowners,$uname.':'.$udom);
 7555:                             }
 7556:                         } else {
 7557:                             if ($coursehash{'internal.co-owners'}) {
 7558:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7559:                                     unless ($coowner eq $uname.':'.$udom) {
 7560:                                         push(@newcoowners,$coowner);
 7561:                                     }
 7562:                                 }
 7563:                                 unless (@newcoowners > 0) {
 7564:                                     $delcoowners = 1;
 7565:                                     $coowners = '';
 7566:                                 }
 7567:                             }
 7568:                         }
 7569:                         if (@newcoowners || $delcoowners) {
 7570:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7571:                                             $delcoowners,@newcoowners);
 7572:                         }
 7573:                     }
 7574:                 }
 7575:             }
 7576:         }
 7577:     }
 7578: }
 7579: 
 7580: sub store_coowners {
 7581:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7582:     my $cid = $cdom.'_'.$cnum;
 7583:     my ($coowners,$delresult,$putresult);
 7584:     if (@newcoowners) {
 7585:         $coowners = join(',',@newcoowners);
 7586:         my %coownershash = (
 7587:                             'internal.co-owners' => $coowners,
 7588:                            );
 7589:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7590:         if ($putresult eq 'ok') {
 7591:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7592:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7593:             }
 7594:         }
 7595:     }
 7596:     if ($delcoowners) {
 7597:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7598:         if ($delresult eq 'ok') {
 7599:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7600:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7601:             }
 7602:         }
 7603:     }
 7604:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7605:         my %crsinfo =
 7606:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7607:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7608:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7609:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7610:         }
 7611:     }
 7612: }
 7613: 
 7614: # -------------------------------------------------- Modify user authentication
 7615: # Overrides without validation
 7616: 
 7617: sub modifyuserauth {
 7618:     my ($udom,$uname,$umode,$upass)=@_;
 7619:     my $uhome=&homeserver($uname,$udom);
 7620:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7621:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7622:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7623:              ' in domain '.$env{'request.role.domain'});  
 7624:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7625: 		     &escape($upass),$uhome);
 7626:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7627:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7628:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7629:     &log($udom,,$uname,$uhome,
 7630:         'Authentication changed by '.$env{'user.domain'}.', '.
 7631:                                      $env{'user.name'}.', '.$umode.
 7632:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7633:     unless ($reply eq 'ok') {
 7634:         &logthis('Authentication mode error: '.$reply);
 7635: 	return 'error: '.$reply;
 7636:     }   
 7637:     return 'ok';
 7638: }
 7639: 
 7640: # --------------------------------------------------------------- Modify a user
 7641: 
 7642: sub modifyuser {
 7643:     my ($udom,    $uname, $uid,
 7644:         $umode,   $upass, $first,
 7645:         $middle,  $last,  $gene,
 7646:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7647:     $udom= &LONCAPA::clean_domain($udom);
 7648:     $uname=&LONCAPA::clean_username($uname);
 7649:     my $showcandelete = 'none';
 7650:     if (ref($candelete) eq 'ARRAY') {
 7651:         if (@{$candelete} > 0) {
 7652:             $showcandelete = join(', ',@{$candelete});
 7653:         }
 7654:     }
 7655:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7656:              $umode.', '.$first.', '.$middle.', '.
 7657: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7658:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7659:                                      ' desiredhome not specified'). 
 7660:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7661:              ' in domain '.$env{'request.role.domain'});
 7662:     my $uhome=&homeserver($uname,$udom,'true');
 7663:     my $newuser;
 7664:     if ($uhome eq 'no_host') {
 7665:         $newuser = 1;
 7666:     }
 7667: # ----------------------------------------------------------------- Create User
 7668:     if (($uhome eq 'no_host') && 
 7669: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7670:         my $unhome='';
 7671:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7672:             $unhome = $desiredhome;
 7673: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7674: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7675:         } else { # load balancing routine for determining $unhome
 7676:             my $loadm=10000000;
 7677: 	    my %servers = &get_servers($udom,'library');
 7678: 	    foreach my $tryserver (keys(%servers)) {
 7679: 		my $answer=reply('load',$tryserver);
 7680: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7681: 		    $loadm=$answer;
 7682: 		    $unhome=$tryserver;
 7683: 		}
 7684: 	    }
 7685:         }
 7686:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7687: 	    return 'error: unable to find a home server for '.$uname.
 7688:                    ' in domain '.$udom;
 7689:         }
 7690:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7691:                          &escape($upass),$unhome);
 7692: 	unless ($reply eq 'ok') {
 7693:             return 'error: '.$reply;
 7694:         }   
 7695:         $uhome=&homeserver($uname,$udom,'true');
 7696:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7697: 	    return 'error: unable verify users home machine.';
 7698:         }
 7699:     }   # End of creation of new user
 7700: # ---------------------------------------------------------------------- Add ID
 7701:     if ($uid) {
 7702:        $uid=~tr/A-Z/a-z/;
 7703:        my %uidhash=&idrget($udom,$uname);
 7704:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7705:          && (!$forceid)) {
 7706: 	  unless ($uid eq $uidhash{$uname}) {
 7707: 	      return 'error: user id "'.$uid.'" does not match '.
 7708:                   'current user id "'.$uidhash{$uname}.'".';
 7709:           }
 7710:        } else {
 7711: 	  &idput($udom,($uname => $uid));
 7712:        }
 7713:     }
 7714: # -------------------------------------------------------------- Add names, etc
 7715:     my @tmp=&get('environment',
 7716: 		   ['firstname','middlename','lastname','generation','id',
 7717:                     'permanentemail','inststatus'],
 7718: 		   $udom,$uname);
 7719:     my (%names,%oldnames);
 7720:     if ($tmp[0] =~ m/^error:.*/) { 
 7721:         %names=(); 
 7722:     } else {
 7723:         %names = @tmp;
 7724:         %oldnames = %names;
 7725:     }
 7726: #
 7727: # If name, email and/or uid are blank (e.g., because an uploaded file
 7728: # of users did not contain them), do not overwrite existing values
 7729: # unless field is in $candelete array ref.  
 7730: #
 7731: 
 7732:     my @fields = ('firstname','middlename','lastname','generation',
 7733:                   'permanentemail','id');
 7734:     my %newvalues;
 7735:     if (ref($candelete) eq 'ARRAY') {
 7736:         foreach my $field (@fields) {
 7737:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7738:                 if ($field eq 'firstname') {
 7739:                     $names{$field} = $first;
 7740:                 } elsif ($field eq 'middlename') {
 7741:                     $names{$field} = $middle;
 7742:                 } elsif ($field eq 'lastname') {
 7743:                     $names{$field} = $last;
 7744:                 } elsif ($field eq 'generation') { 
 7745:                     $names{$field} = $gene;
 7746:                 } elsif ($field eq 'permanentemail') {
 7747:                     $names{$field} = $email;
 7748:                 } elsif ($field eq 'id') {
 7749:                     $names{$field}  = $uid;
 7750:                 }
 7751:             }
 7752:         }
 7753:     }
 7754:     if ($first)  { $names{'firstname'}  = $first; }
 7755:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7756:     if ($last)   { $names{'lastname'}   = $last; }
 7757:     if (defined($gene))   { $names{'generation'} = $gene; }
 7758:     if ($email) {
 7759:        $email=~s/[^\w\@\.\-\,]//gs;
 7760:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7761:     }
 7762:     if ($uid) { $names{'id'}  = $uid; }
 7763:     if (defined($inststatus)) {
 7764:         $names{'inststatus'} = '';
 7765:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7766:         if (ref($usertypes) eq 'HASH') {
 7767:             my @okstatuses; 
 7768:             foreach my $item (split(/:/,$inststatus)) {
 7769:                 if (defined($usertypes->{$item})) {
 7770:                     push(@okstatuses,$item);  
 7771:                 }
 7772:             }
 7773:             if (@okstatuses) {
 7774:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7775:             }
 7776:         }
 7777:     }
 7778:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7779:                  $umode.', '.$first.', '.$middle.', '.
 7780:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7781:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7782:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7783:     } else {
 7784:         $logmsg .= ' during self creation';
 7785:     }
 7786:     my $changed;
 7787:     if ($newuser) {
 7788:         $changed = 1;
 7789:     } else {
 7790:         foreach my $field (@fields) {
 7791:             if ($names{$field} ne $oldnames{$field}) {
 7792:                 $changed = 1;
 7793:                 last;
 7794:             }
 7795:         }
 7796:     }
 7797:     unless ($changed) {
 7798:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7799:         &logthis($logmsg);
 7800:         return 'ok';
 7801:     }
 7802:     my $reply = &put('environment', \%names, $udom,$uname);
 7803:     if ($reply ne 'ok') { 
 7804:         return 'error: '.$reply;
 7805:     }
 7806:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7807:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7808:     }
 7809:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7810:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7811:     $logmsg = 'Success modifying user '.$logmsg;
 7812:     &logthis($logmsg);
 7813:     return 'ok';
 7814: }
 7815: 
 7816: # -------------------------------------------------------------- Modify student
 7817: 
 7818: sub modifystudent {
 7819:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7820:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7821:         $selfenroll,$context,$inststatus)=@_;
 7822:     if (!$cid) {
 7823: 	unless ($cid=$env{'request.course.id'}) {
 7824: 	    return 'not_in_class';
 7825: 	}
 7826:     }
 7827: # --------------------------------------------------------------- Make the user
 7828:     my $reply=&modifyuser
 7829: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7830:          $desiredhome,$email,$inststatus);
 7831:     unless ($reply eq 'ok') { return $reply; }
 7832:     # This will cause &modify_student_enrollment to get the uid from the
 7833:     # students environment
 7834:     $uid = undef if (!$forceid);
 7835:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7836: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7837:     return $reply;
 7838: }
 7839: 
 7840: sub modify_student_enrollment {
 7841:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7842:     my ($cdom,$cnum,$chome);
 7843:     if (!$cid) {
 7844: 	unless ($cid=$env{'request.course.id'}) {
 7845: 	    return 'not_in_class';
 7846: 	}
 7847: 	$cdom=$env{'course.'.$cid.'.domain'};
 7848: 	$cnum=$env{'course.'.$cid.'.num'};
 7849:     } else {
 7850: 	($cdom,$cnum)=split(/_/,$cid);
 7851:     }
 7852:     $chome=$env{'course.'.$cid.'.home'};
 7853:     if (!$chome) {
 7854: 	$chome=&homeserver($cnum,$cdom);
 7855:     }
 7856:     if (!$chome) { return 'unknown_course'; }
 7857:     # Make sure the user exists
 7858:     my $uhome=&homeserver($uname,$udom);
 7859:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7860: 	return 'error: no such user';
 7861:     }
 7862:     # Get student data if we were not given enough information
 7863:     if (!defined($first)  || $first  eq '' || 
 7864:         !defined($last)   || $last   eq '' || 
 7865:         !defined($uid)    || $uid    eq '' || 
 7866:         !defined($middle) || $middle eq '' || 
 7867:         !defined($gene)   || $gene   eq '') {
 7868:         # They did not supply us with enough data to enroll the student, so
 7869:         # we need to pick up more information.
 7870:         my %tmp = &get('environment',
 7871:                        ['firstname','middlename','lastname', 'generation','id']
 7872:                        ,$udom,$uname);
 7873: 
 7874:         #foreach my $key (keys(%tmp)) {
 7875:         #    &logthis("key $key = ".$tmp{$key});
 7876:         #}
 7877:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7878:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7879:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7880:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7881:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7882:     }
 7883:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7884:     my $user = "$uname:$udom";
 7885:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7886:     my $reply=cput('classlist',
 7887: 		   {$user => 
 7888: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7889: 		   $cdom,$cnum);
 7890:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7891:         &devalidate_getsection_cache($udom,$uname,$cid);
 7892:     } else { 
 7893: 	return 'error: '.$reply;
 7894:     }
 7895:     # Add student role to user
 7896:     my $uurl='/'.$cid;
 7897:     $uurl=~s/\_/\//g;
 7898:     if ($usec) {
 7899: 	$uurl.='/'.$usec;
 7900:     }
 7901:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7902:                              $selfenroll,$context);
 7903:     if ($result ne 'ok') {
 7904:         if ($old_entry{$user} ne '') {
 7905:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7906:         } else {
 7907:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7908:         }
 7909:     }
 7910:     return $result; 
 7911: }
 7912: 
 7913: sub format_name {
 7914:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7915:     my $name;
 7916:     if ($first ne 'lastname') {
 7917: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7918:     } else {
 7919: 	if ($lastname=~/\S/) {
 7920: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7921: 	    $name=~s/\s+,/,/;
 7922: 	} else {
 7923: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7924: 	}
 7925:     }
 7926:     $name=~s/^\s+//;
 7927:     $name=~s/\s+$//;
 7928:     $name=~s/\s+/ /g;
 7929:     return $name;
 7930: }
 7931: 
 7932: # ------------------------------------------------- Write to course preferences
 7933: 
 7934: sub writecoursepref {
 7935:     my ($courseid,%prefs)=@_;
 7936:     $courseid=~s/^\///;
 7937:     $courseid=~s/\_/\//g;
 7938:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7939:     my $chome=homeserver($cnum,$cdomain);
 7940:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7941: 	return 'error: no such course';
 7942:     }
 7943:     my $cstring='';
 7944:     foreach my $pref (keys(%prefs)) {
 7945: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7946:     }
 7947:     $cstring=~s/\&$//;
 7948:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7949: }
 7950: 
 7951: # ---------------------------------------------------------- Make/modify course
 7952: 
 7953: sub createcourse {
 7954:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7955:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7956:     $url=&declutter($url);
 7957:     my $cid='';
 7958:     if ($context eq 'requestcourses') {
 7959:         my $can_create = 0;
 7960:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7961:         if ($udom eq $ownerdom) {
 7962:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7963:                                   $context)) {
 7964:                 $can_create = 1;
 7965:             }
 7966:         } else {
 7967:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7968:                                            $category);
 7969:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7970:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7971:                 if (@curr > 0) {
 7972:                     my @options = qw(approval validate autolimit);
 7973:                     my $optregex = join('|',@options);
 7974:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7975:                         $can_create = 1;
 7976:                     }
 7977:                 }
 7978:             }
 7979:         }
 7980:         if ($can_create) {
 7981:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7982:                 unless (&allowed('ccc',$udom)) {
 7983:                     return 'refused'; 
 7984:                 }
 7985:             }
 7986:         } else {
 7987:             return 'refused';
 7988:         }
 7989:     } elsif (!&allowed('ccc',$udom)) {
 7990:         return 'refused';
 7991:     }
 7992: # --------------------------------------------------------------- Get Unique ID
 7993:     my $uname;
 7994:     if ($cnum =~ /^$match_courseid$/) {
 7995:         my $chome=&homeserver($cnum,$udom,'true');
 7996:         if (($chome eq '') || ($chome eq 'no_host')) {
 7997:             $uname = $cnum;
 7998:         } else {
 7999:             $uname = &generate_coursenum($udom,$crstype);
 8000:         }
 8001:     } else {
 8002:         $uname = &generate_coursenum($udom,$crstype);
 8003:     }
 8004:     return $uname if ($uname =~ /^error/);
 8005: # -------------------------------------------------- Check supplied server name
 8006:     if (!defined($course_server)) {
 8007:         if (defined(&domain($udom,'primary'))) {
 8008:             $course_server = &domain($udom,'primary');
 8009:         } else {
 8010:             $course_server = $env{'user.home'}; 
 8011:         }
 8012:     }
 8013:     my %host_servers =
 8014:         &Apache::lonnet::get_servers($udom,'library');
 8015:     unless ($host_servers{$course_server}) {
 8016:         return 'error: invalid home server for course: '.$course_server;
 8017:     }
 8018: # ------------------------------------------------------------- Make the course
 8019:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8020:                       $course_server);
 8021:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8022:     my $uhome=&homeserver($uname,$udom,'true');
 8023:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8024: 	return 'error: no such course';
 8025:     }
 8026: # ----------------------------------------------------------------- Course made
 8027: # log existence
 8028:     my $now = time;
 8029:     my $newcourse = {
 8030:                     $udom.'_'.$uname => {
 8031:                                      description => $description,
 8032:                                      inst_code   => $inst_code,
 8033:                                      owner       => $course_owner,
 8034:                                      type        => $crstype,
 8035:                                      creator     => $env{'user.name'}.':'.
 8036:                                                     $env{'user.domain'},
 8037:                                      created     => $now,
 8038:                                      context     => $context,
 8039:                                                 },
 8040:                     };
 8041:     &courseidput($udom,$newcourse,$uhome,'notime');
 8042: # set toplevel url
 8043:     my $topurl=$url;
 8044:     unless ($nonstandard) {
 8045: # ------------------------------------------ For standard courses, make top url
 8046:         my $mapurl=&clutter($url);
 8047:         if ($mapurl eq '/res/') { $mapurl=''; }
 8048:         $env{'form.initmap'}=(<<ENDINITMAP);
 8049: <map>
 8050: <resource id="1" type="start"></resource>
 8051: <resource id="2" src="$mapurl"></resource>
 8052: <resource id="3" type="finish"></resource>
 8053: <link index="1" from="1" to="2"></link>
 8054: <link index="2" from="2" to="3"></link>
 8055: </map>
 8056: ENDINITMAP
 8057:         $topurl=&declutter(
 8058:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8059:                           );
 8060:     }
 8061: # ----------------------------------------------------------- Write preferences
 8062:     &writecoursepref($udom.'_'.$uname,
 8063:                      ('description'              => $description,
 8064:                       'url'                      => $topurl,
 8065:                       'internal.creator'         => $env{'user.name'}.':'.
 8066:                                                     $env{'user.domain'},
 8067:                       'internal.created'         => $now,
 8068:                       'internal.creationcontext' => $context)
 8069:                     );
 8070:     return '/'.$udom.'/'.$uname;
 8071: }
 8072: 
 8073: # ------------------------------------------------------------------- Create ID
 8074: sub generate_coursenum {
 8075:     my ($udom,$crstype) = @_;
 8076:     my $domdesc = &domain($udom);
 8077:     return 'error: invalid domain' if ($domdesc eq '');
 8078:     my $first;
 8079:     if ($crstype eq 'Community') {
 8080:         $first = '0';
 8081:     } else {
 8082:         $first = int(1+rand(9)); 
 8083:     } 
 8084:     my $uname=$first.
 8085:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8086:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8087:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8088: # ----------------------------------------------- Make sure that does not exist
 8089:     my $uhome=&homeserver($uname,$udom,'true');
 8090:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8091:         if ($crstype eq 'Community') {
 8092:             $first = '0';
 8093:         } else {
 8094:             $first = int(1+rand(9));
 8095:         }
 8096:         $uname=$first.
 8097:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8098:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8099:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8100:         $uhome=&homeserver($uname,$udom,'true');
 8101:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8102:             return 'error: unable to generate unique course-ID';
 8103:         }
 8104:     }
 8105:     return $uname;
 8106: }
 8107: 
 8108: sub is_course {
 8109:     my ($cdom,$cnum) = @_;
 8110:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 8111: 				undef,'.');
 8112:     if (exists($courses{$cdom.'_'.$cnum})) {
 8113:         return 1;
 8114:     }
 8115:     return 0;
 8116: }
 8117: 
 8118: sub store_userdata {
 8119:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8120:     my $result;
 8121:     if ($datakey ne '') {
 8122:         if (ref($storehash) eq 'HASH') {
 8123:             if ($udom eq '' || $uname eq '') {
 8124:                 $udom = $env{'user.domain'};
 8125:                 $uname = $env{'user.name'};
 8126:             }
 8127:             my $uhome=&homeserver($uname,$udom);
 8128:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8129:                 $result = 'error: no_host';
 8130:             } else {
 8131:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8132:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8133: 
 8134:                 my $namevalue='';
 8135:                 foreach my $key (keys(%{$storehash})) {
 8136:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8137:                 }
 8138:                 $namevalue=~s/\&$//;
 8139:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8140:                                   $namevalue,$uhome);
 8141:             }
 8142:         } else {
 8143:             $result = 'error: data to store was not a hash reference'; 
 8144:         }
 8145:     } else {
 8146:         $result= 'error: invalid requestkey'; 
 8147:     }
 8148:     return $result;
 8149: }
 8150: 
 8151: # ---------------------------------------------------------- Assign Custom Role
 8152: 
 8153: sub assigncustomrole {
 8154:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8155:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8156:                        $end,$start,$deleteflag,$selfenroll,$context);
 8157: }
 8158: 
 8159: # ----------------------------------------------------------------- Revoke Role
 8160: 
 8161: sub revokerole {
 8162:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8163:     my $now=time;
 8164:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8165: }
 8166: 
 8167: # ---------------------------------------------------------- Revoke Custom Role
 8168: 
 8169: sub revokecustomrole {
 8170:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8171:     my $now=time;
 8172:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8173:            $deleteflag,$selfenroll,$context);
 8174: }
 8175: 
 8176: # ------------------------------------------------------------ Disk usage
 8177: sub diskusage {
 8178:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8179:     $directorypath =~ s/\/$//;
 8180:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8181:                        .&escape($getpropath).':'.&escape($uname).':'
 8182:                        .&escape($udom),homeserver($uname,$udom));
 8183:     if ($listing eq 'unknown_cmd') {
 8184:         if ($getpropath) {
 8185:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8186:         }
 8187:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8188:     }
 8189:     return $listing;
 8190: }
 8191: 
 8192: sub is_locked {
 8193:     my ($file_name, $domain, $user, $which) = @_;
 8194:     my @check;
 8195:     my $is_locked;
 8196:     push (@check,$file_name);
 8197:     my %locked = &get('file_permissions',\@check,
 8198: 		      $env{'user.domain'},$env{'user.name'});
 8199:     my ($tmp)=keys(%locked);
 8200:     if ($tmp=~/^error:/) { undef(%locked); }
 8201:     
 8202:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8203:         $is_locked = 'false';
 8204:         foreach my $entry (@{$locked{$file_name}}) {
 8205:            if (ref($entry) eq 'ARRAY') {
 8206:                $is_locked = 'true';
 8207:                if (ref($which) eq 'ARRAY') {
 8208:                    push(@{$which},$entry);
 8209:                } else {
 8210:                    last;
 8211:                }
 8212:            }
 8213:        }
 8214:     } else {
 8215:         $is_locked = 'false';
 8216:     }
 8217:     return $is_locked;
 8218: }
 8219: 
 8220: sub declutter_portfile {
 8221:     my ($file) = @_;
 8222:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8223:     return $file;
 8224: }
 8225: 
 8226: # ------------------------------------------------------------- Mark as Read Only
 8227: 
 8228: sub mark_as_readonly {
 8229:     my ($domain,$user,$files,$what) = @_;
 8230:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8231:     my ($tmp)=keys(%current_permissions);
 8232:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8233:     foreach my $file (@{$files}) {
 8234: 	$file = &declutter_portfile($file);
 8235:         push(@{$current_permissions{$file}},$what);
 8236:     }
 8237:     &put('file_permissions',\%current_permissions,$domain,$user);
 8238:     return;
 8239: }
 8240: 
 8241: # ------------------------------------------------------------Save Selected Files
 8242: 
 8243: sub save_selected_files {
 8244:     my ($user, $path, @files) = @_;
 8245:     my $filename = $user."savedfiles";
 8246:     my @other_files = &files_not_in_path($user, $path);
 8247:     open (OUT, '>'.$tmpdir.$filename);
 8248:     foreach my $file (@files) {
 8249:         print (OUT $env{'form.currentpath'}.$file."\n");
 8250:     }
 8251:     foreach my $file (@other_files) {
 8252:         print (OUT $file."\n");
 8253:     }
 8254:     close (OUT);
 8255:     return 'ok';
 8256: }
 8257: 
 8258: sub clear_selected_files {
 8259:     my ($user) = @_;
 8260:     my $filename = $user."savedfiles";
 8261:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8262:     print (OUT undef);
 8263:     close (OUT);
 8264:     return ("ok");    
 8265: }
 8266: 
 8267: sub files_in_path {
 8268:     my ($user, $path) = @_;
 8269:     my $filename = $user."savedfiles";
 8270:     my %return_files;
 8271:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8272:     while (my $line_in = <IN>) {
 8273:         chomp ($line_in);
 8274:         my @paths_and_file = split (m!/!, $line_in);
 8275:         my $file_part = pop (@paths_and_file);
 8276:         my $path_part = join ('/', @paths_and_file);
 8277:         $path_part.='/';
 8278:         my $path_and_file = $path_part.$file_part;
 8279:         if ($path_part eq $path) {
 8280:             $return_files{$file_part}= 'selected';
 8281:         }
 8282:     }
 8283:     close (IN);
 8284:     return (\%return_files);
 8285: }
 8286: 
 8287: # called in portfolio select mode, to show files selected NOT in current directory
 8288: sub files_not_in_path {
 8289:     my ($user, $path) = @_;
 8290:     my $filename = $user."savedfiles";
 8291:     my @return_files;
 8292:     my $path_part;
 8293:     open(IN, '<'.LONCAPA::.$filename);
 8294:     while (my $line = <IN>) {
 8295:         #ok, I know it's clunky, but I want it to work
 8296:         my @paths_and_file = split(m|/|, $line);
 8297:         my $file_part = pop(@paths_and_file);
 8298:         chomp($file_part);
 8299:         my $path_part = join('/', @paths_and_file);
 8300:         $path_part .= '/';
 8301:         my $path_and_file = $path_part.$file_part;
 8302:         if ($path_part ne $path) {
 8303:             push(@return_files, ($path_and_file));
 8304:         }
 8305:     }
 8306:     close(OUT);
 8307:     return (@return_files);
 8308: }
 8309: 
 8310: #----------------------------------------------Get portfolio file permissions
 8311: 
 8312: sub get_portfile_permissions {
 8313:     my ($domain,$user) = @_;
 8314:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8315:     my ($tmp)=keys(%current_permissions);
 8316:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8317:     return \%current_permissions;
 8318: }
 8319: 
 8320: #---------------------------------------------Get portfolio file access controls
 8321: 
 8322: sub get_access_controls {
 8323:     my ($current_permissions,$group,$file) = @_;
 8324:     my %access;
 8325:     my $real_file = $file;
 8326:     $file =~ s/\.meta$//;
 8327:     if (defined($file)) {
 8328:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8329:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8330:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8331:             }
 8332:         }
 8333:     } else {
 8334:         foreach my $key (keys(%{$current_permissions})) {
 8335:             if ($key =~ /\0accesscontrol$/) {
 8336:                 if (defined($group)) {
 8337:                     if ($key !~ m-^\Q$group\E/-) {
 8338:                         next;
 8339:                     }
 8340:                 }
 8341:                 my ($fullpath) = split(/\0/,$key);
 8342:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8343:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8344:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8345:                     }
 8346:                 }
 8347:             }
 8348:         }
 8349:     }
 8350:     return %access;
 8351: }
 8352: 
 8353: sub modify_access_controls {
 8354:     my ($file_name,$changes,$domain,$user)=@_;
 8355:     my ($outcome,$deloutcome);
 8356:     my %store_permissions;
 8357:     my %new_values;
 8358:     my %new_control;
 8359:     my %translation;
 8360:     my @deletions = ();
 8361:     my $now = time;
 8362:     if (exists($$changes{'activate'})) {
 8363:         if (ref($$changes{'activate'}) eq 'HASH') {
 8364:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8365:             my $numnew = scalar(@newitems);
 8366:             for (my $i=0; $i<$numnew; $i++) {
 8367:                 my $newkey = $newitems[$i];
 8368:                 my $newid = &Apache::loncommon::get_cgi_id();
 8369:                 if ($newkey =~ /^\d+:/) { 
 8370:                     $newkey =~ s/^(\d+)/$newid/;
 8371:                     $translation{$1} = $newid;
 8372:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8373:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8374:                     $translation{$1} = $newid;
 8375:                 }
 8376:                 $new_values{$file_name."\0".$newkey} = 
 8377:                                           $$changes{'activate'}{$newitems[$i]};
 8378:                 $new_control{$newkey} = $now;
 8379:             }
 8380:         }
 8381:     }
 8382:     my %todelete;
 8383:     my %changed_items;
 8384:     foreach my $action ('delete','update') {
 8385:         if (exists($$changes{$action})) {
 8386:             if (ref($$changes{$action}) eq 'HASH') {
 8387:                 foreach my $key (keys(%{$$changes{$action}})) {
 8388:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8389:                     if ($action eq 'delete') { 
 8390:                         $todelete{$itemnum} = 1;
 8391:                     } else {
 8392:                         $changed_items{$itemnum} = $key;
 8393:                     }
 8394:                 }
 8395:             }
 8396:         }
 8397:     }
 8398:     # get lock on access controls for file.
 8399:     my $lockhash = {
 8400:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8401:                                                        ':'.$env{'user.domain'},
 8402:                    }; 
 8403:     my $tries = 0;
 8404:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8405:    
 8406:     while (($gotlock ne 'ok') && $tries <3) {
 8407:         $tries ++;
 8408:         sleep 1;
 8409:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8410:     }
 8411:     if ($gotlock eq 'ok') {
 8412:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8413:         my ($tmp)=keys(%curr_permissions);
 8414:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8415:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8416:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8417:             if (ref($curr_controls) eq 'HASH') {
 8418:                 foreach my $control_item (keys(%{$curr_controls})) {
 8419:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8420:                     if (defined($todelete{$itemnum})) {
 8421:                         push(@deletions,$file_name."\0".$control_item);
 8422:                     } else {
 8423:                         if (defined($changed_items{$itemnum})) {
 8424:                             $new_control{$changed_items{$itemnum}} = $now;
 8425:                             push(@deletions,$file_name."\0".$control_item);
 8426:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8427:                         } else {
 8428:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8429:                         }
 8430:                     }
 8431:                 }
 8432:             }
 8433:         }
 8434:         my ($group);
 8435:         if (&is_course($domain,$user)) {
 8436:             ($group,my $file) = split(/\//,$file_name,2);
 8437:         }
 8438:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8439:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8440:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8441:         #  remove lock
 8442:         my @del_lock = ($file_name."\0".'locked_access_records');
 8443:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8444:         my $sqlresult =
 8445:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8446:                                     $group);
 8447:     } else {
 8448:         $outcome = "error: could not obtain lockfile\n";  
 8449:     }
 8450:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8451: }
 8452: 
 8453: sub make_public_indefinitely {
 8454:     my ($requrl) = @_;
 8455:     my $now = time;
 8456:     my $action = 'activate';
 8457:     my $aclnum = 0;
 8458:     if (&is_portfolio_url($requrl)) {
 8459:         my (undef,$udom,$unum,$file_name,$group) =
 8460:             &parse_portfolio_url($requrl);
 8461:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8462:         my %access_controls = &get_access_controls($current_perms,
 8463:                                                    $group,$file_name);
 8464:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8465:             my ($num,$scope,$end,$start) = 
 8466:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8467:             if ($scope eq 'public') {
 8468:                 if ($start <= $now && $end == 0) {
 8469:                     $action = 'none';
 8470:                 } else {
 8471:                     $action = 'update';
 8472:                     $aclnum = $num;
 8473:                 }
 8474:                 last;
 8475:             }
 8476:         }
 8477:         if ($action eq 'none') {
 8478:              return 'ok';
 8479:         } else {
 8480:             my %changes;
 8481:             my $newend = 0;
 8482:             my $newstart = $now;
 8483:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8484:             $changes{$action}{$newkey} = {
 8485:                 type => 'public',
 8486:                 time => {
 8487:                     start => $newstart,
 8488:                     end   => $newend,
 8489:                 },
 8490:             };
 8491:             my ($outcome,$deloutcome,$new_values,$translation) =
 8492:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8493:             return $outcome;
 8494:         }
 8495:     } else {
 8496:         return 'invalid';
 8497:     }
 8498: }
 8499: 
 8500: #------------------------------------------------------Get Marked as Read Only
 8501: 
 8502: sub get_marked_as_readonly {
 8503:     my ($domain,$user,$what,$group) = @_;
 8504:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8505:     my @readonly_files;
 8506:     my $cmp1=$what;
 8507:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8508:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8509:         if (defined($group)) {
 8510:             if ($file_name !~ m-^\Q$group\E/-) {
 8511:                 next;
 8512:             }
 8513:         }
 8514:         if (ref($value) eq "ARRAY"){
 8515:             foreach my $stored_what (@{$value}) {
 8516:                 my $cmp2=$stored_what;
 8517:                 if (ref($stored_what) eq 'ARRAY') {
 8518:                     $cmp2=join('',@{$stored_what});
 8519:                 }
 8520:                 if ($cmp1 eq $cmp2) {
 8521:                     push(@readonly_files, $file_name);
 8522:                     last;
 8523:                 } elsif (!defined($what)) {
 8524:                     push(@readonly_files, $file_name);
 8525:                     last;
 8526:                 }
 8527:             }
 8528:         }
 8529:     }
 8530:     return @readonly_files;
 8531: }
 8532: #-----------------------------------------------------------Get Marked as Read Only Hash
 8533: 
 8534: sub get_marked_as_readonly_hash {
 8535:     my ($current_permissions,$group,$what) = @_;
 8536:     my %readonly_files;
 8537:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8538:         if (defined($group)) {
 8539:             if ($file_name !~ m-^\Q$group\E/-) {
 8540:                 next;
 8541:             }
 8542:         }
 8543:         if (ref($value) eq "ARRAY"){
 8544:             foreach my $stored_what (@{$value}) {
 8545:                 if (ref($stored_what) eq 'ARRAY') {
 8546:                     foreach my $lock_descriptor(@{$stored_what}) {
 8547:                         if ($lock_descriptor eq 'graded') {
 8548:                             $readonly_files{$file_name} = 'graded';
 8549:                         } elsif ($lock_descriptor eq 'handback') {
 8550:                             $readonly_files{$file_name} = 'handback';
 8551:                         } else {
 8552:                             if (!exists($readonly_files{$file_name})) {
 8553:                                 $readonly_files{$file_name} = 'locked';
 8554:                             }
 8555:                         }
 8556:                     }
 8557:                 } 
 8558:             }
 8559:         } 
 8560:     }
 8561:     return %readonly_files;
 8562: }
 8563: # ------------------------------------------------------------ Unmark as Read Only
 8564: 
 8565: sub unmark_as_readonly {
 8566:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8567:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8568:     my ($domain,$user,$what,$file_name,$group) = @_;
 8569:     $file_name = &declutter_portfile($file_name);
 8570:     my $symb_crs = $what;
 8571:     if (ref($what)) { $symb_crs=join('',@$what); }
 8572:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8573:     my ($tmp)=keys(%current_permissions);
 8574:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8575:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8576:     foreach my $file (@readonly_files) {
 8577: 	my $clean_file = &declutter_portfile($file);
 8578: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8579: 	my $current_locks = $current_permissions{$file};
 8580:         my @new_locks;
 8581:         my @del_keys;
 8582:         if (ref($current_locks) eq "ARRAY"){
 8583:             foreach my $locker (@{$current_locks}) {
 8584:                 my $compare=$locker;
 8585:                 if (ref($locker) eq 'ARRAY') {
 8586:                     $compare=join('',@{$locker});
 8587:                     if ($compare ne $symb_crs) {
 8588:                         push(@new_locks, $locker);
 8589:                     }
 8590:                 }
 8591:             }
 8592:             if (scalar(@new_locks) > 0) {
 8593:                 $current_permissions{$file} = \@new_locks;
 8594:             } else {
 8595:                 push(@del_keys, $file);
 8596:                 &del('file_permissions',\@del_keys, $domain, $user);
 8597:                 delete($current_permissions{$file});
 8598:             }
 8599:         }
 8600:     }
 8601:     &put('file_permissions',\%current_permissions,$domain,$user);
 8602:     return;
 8603: }
 8604: 
 8605: # ------------------------------------------------------------ Directory lister
 8606: 
 8607: sub dirlist {
 8608:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8609:     $uri=~s/^\///;
 8610:     $uri=~s/\/$//;
 8611:     my ($udom, $uname);
 8612:     if ($getuserdir) {
 8613:         $udom = $userdomain;
 8614:         $uname = $username;
 8615:     } else {
 8616:         (undef,$udom,$uname)=split(/\//,$uri);
 8617:         if(defined($userdomain)) {
 8618:             $udom = $userdomain;
 8619:         }
 8620:         if(defined($username)) {
 8621:             $uname = $username;
 8622:         }
 8623:     }
 8624:     my ($dirRoot,$listing,@listing_results);
 8625: 
 8626:     $dirRoot = $perlvar{'lonDocRoot'};
 8627:     if (defined($getpropath)) {
 8628:         $dirRoot = &propath($udom,$uname);
 8629:         $dirRoot =~ s/\/$//;
 8630:     } elsif (defined($getuserdir)) {
 8631:         my $subdir=$uname.'__';
 8632:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8633:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8634:                    ."/$udom/$subdir/$uname";
 8635:     } elsif (defined($alternateRoot)) {
 8636:         $dirRoot = $alternateRoot;
 8637:     }
 8638: 
 8639:     if($udom) {
 8640:         if($uname) {
 8641:             my $uhome = &homeserver($uname,$udom);
 8642:             if ($uhome eq 'no_host') {
 8643:                 return ([],'no_host');
 8644:             }
 8645:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8646:                               .$getuserdir.':'.&escape($dirRoot)
 8647:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8648:             if ($listing eq 'unknown_cmd') {
 8649:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8650:             } else {
 8651:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8652:             }
 8653:             if ($listing eq 'unknown_cmd') {
 8654:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8655:                 @listing_results = split(/:/,$listing);
 8656:             } else {
 8657:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8658:             }
 8659:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8660:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8661:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8662:                 return ([],$listing);
 8663:             } else {
 8664:                 return (\@listing_results);
 8665:             }
 8666:         } elsif(!$alternateRoot) {
 8667:             my (%allusers,%listerror);
 8668: 	    my %servers = &get_servers($udom,'library');
 8669:  	    foreach my $tryserver (keys(%servers)) {
 8670:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8671:                                   &escape($udom),$tryserver);
 8672:                 if ($listing eq 'unknown_cmd') {
 8673: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8674: 				      $udom, $tryserver);
 8675:                 } else {
 8676:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8677:                 }
 8678: 		if ($listing eq 'unknown_cmd') {
 8679: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8680: 				      $udom, $tryserver);
 8681: 		    @listing_results = split(/:/,$listing);
 8682: 		} else {
 8683: 		    @listing_results =
 8684: 			map { &unescape($_); } split(/:/,$listing);
 8685: 		}
 8686:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8687:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8688:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8689:                     $listerror{$tryserver} = $listing;
 8690:                 } else {
 8691: 		    foreach my $line (@listing_results) {
 8692: 			my ($entry) = split(/&/,$line,2);
 8693: 			$allusers{$entry} = 1;
 8694: 		    }
 8695: 		}
 8696:             }
 8697:             my @alluserslist=();
 8698:             foreach my $user (sort(keys(%allusers))) {
 8699:                 push(@alluserslist,$user.'&user');
 8700:             }
 8701:             return (\@alluserslist);
 8702:         } else {
 8703:             return ([],'missing username');
 8704:         }
 8705:     } elsif(!defined($getpropath)) {
 8706:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8707:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8708:         return (\@all_domains);
 8709:     } else {
 8710:         return ([],'missing domain');
 8711:     }
 8712: }
 8713: 
 8714: # --------------------------------------------- GetFileTimestamp
 8715: # This function utilizes dirlist and returns the date stamp for
 8716: # when it was last modified.  It will also return an error of -1
 8717: # if an error occurs
 8718: 
 8719: sub GetFileTimestamp {
 8720:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8721:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8722:     $studentName   = &LONCAPA::clean_username($studentName);
 8723:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8724:                                     undef,$getuserdir);
 8725:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8726:         return -1;
 8727:     }
 8728:     if (ref($fileref) eq 'ARRAY') {
 8729:         my @stats = split('&',$fileref->[0]);
 8730:         # @stats contains first the filename, then the stat output
 8731:         return $stats[10]; # so this is 10 instead of 9.
 8732:     } else {
 8733:         return -1;
 8734:     }
 8735: }
 8736: 
 8737: sub stat_file {
 8738:     my ($uri) = @_;
 8739:     $uri = &clutter_with_no_wrapper($uri);
 8740: 
 8741:     my ($udom,$uname,$file);
 8742:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8743: 	($udom,$uname,$file) =
 8744: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8745: 	$file = 'userfiles/'.$file;
 8746:     }
 8747:     if ($uri =~ m-^/res/-) {
 8748: 	($udom,$uname) = 
 8749: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8750: 	$file = $uri;
 8751:     }
 8752: 
 8753:     if (!$udom || !$uname || !$file) {
 8754: 	# unable to handle the uri
 8755: 	return ();
 8756:     }
 8757:     my $getpropath;
 8758:     if ($file =~ /^userfiles\//) {
 8759:         $getpropath = 1;
 8760:     }
 8761:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8762:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8763:         return ();
 8764:     } else {
 8765:         if (ref($listref) eq 'ARRAY') {
 8766:             my @stats = split('&',$listref->[0]);
 8767: 	    shift(@stats); #filename is first
 8768: 	    return @stats;
 8769:         }
 8770:     }
 8771:     return ();
 8772: }
 8773: 
 8774: # -------------------------------------------------------- Value of a Condition
 8775: 
 8776: # gets the value of a specific preevaluated condition
 8777: #    stored in the string  $env{user.state.<cid>}
 8778: # or looks up a condition reference in the bighash and if if hasn't
 8779: # already been evaluated recurses into docondval to get the value of
 8780: # the condition, then memoizing it to 
 8781: #   $env{user.state.<cid>.<condition>}
 8782: sub directcondval {
 8783:     my $number=shift;
 8784:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8785: 	&Apache::lonuserstate::evalstate();
 8786:     }
 8787:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8788: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8789:     } elsif ($number =~ /^_/) {
 8790: 	my $sub_condition;
 8791: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8792: 		&GDBM_READER(),0640)) {
 8793: 	    $sub_condition=$bighash{'conditions'.$number};
 8794: 	    untie(%bighash);
 8795: 	}
 8796: 	my $value = &docondval($sub_condition);
 8797: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8798: 	return $value;
 8799:     }
 8800:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8801:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8802:     } else {
 8803:        return 2;
 8804:     }
 8805: }
 8806: 
 8807: # get the collection of conditions for this resource
 8808: sub condval {
 8809:     my $condidx=shift;
 8810:     my $allpathcond='';
 8811:     foreach my $cond (split(/\|/,$condidx)) {
 8812: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8813: 	    $allpathcond.=
 8814: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8815: 	}
 8816:     }
 8817:     $allpathcond=~s/\|$//;
 8818:     return &docondval($allpathcond);
 8819: }
 8820: 
 8821: #evaluates an expression of conditions
 8822: sub docondval {
 8823:     my ($allpathcond) = @_;
 8824:     my $result=0;
 8825:     if ($env{'request.course.id'}
 8826: 	&& defined($allpathcond)) {
 8827: 	my $operand='|';
 8828: 	my @stack;
 8829: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8830: 	    if ($chunk eq '(') {
 8831: 		push @stack,($operand,$result);
 8832: 	    } elsif ($chunk eq ')') {
 8833: 		my $before=pop @stack;
 8834: 		if (pop @stack eq '&') {
 8835: 		    $result=$result>$before?$before:$result;
 8836: 		} else {
 8837: 		    $result=$result>$before?$result:$before;
 8838: 		}
 8839: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8840: 		$operand=$chunk;
 8841: 	    } else {
 8842: 		my $new=directcondval($chunk);
 8843: 		if ($operand eq '&') {
 8844: 		    $result=$result>$new?$new:$result;
 8845: 		} else {
 8846: 		    $result=$result>$new?$result:$new;
 8847: 		}
 8848: 	    }
 8849: 	}
 8850:     }
 8851:     return $result;
 8852: }
 8853: 
 8854: # ---------------------------------------------------- Devalidate courseresdata
 8855: 
 8856: sub devalidatecourseresdata {
 8857:     my ($coursenum,$coursedomain)=@_;
 8858:     my $hashid=$coursenum.':'.$coursedomain;
 8859:     &devalidate_cache_new('courseres',$hashid);
 8860: }
 8861: 
 8862: 
 8863: # --------------------------------------------------- Course Resourcedata Query
 8864: #
 8865: #  Parameters:
 8866: #      $coursenum    - Number of the course.
 8867: #      $coursedomain - Domain at which the course was created.
 8868: #  Returns:
 8869: #     A hash of the course parameters along (I think) with timestamps
 8870: #     and version info.
 8871: 
 8872: sub get_courseresdata {
 8873:     my ($coursenum,$coursedomain)=@_;
 8874:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8875:     my $hashid=$coursenum.':'.$coursedomain;
 8876:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8877:     my %dumpreply;
 8878:     unless (defined($cached)) {
 8879: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8880: 	$result=\%dumpreply;
 8881: 	my ($tmp) = keys(%dumpreply);
 8882: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8883: 	    &do_cache_new('courseres',$hashid,$result,600);
 8884: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8885: 	    return $tmp;
 8886: 	} elsif ($tmp =~ /^(error)/) {
 8887: 	    $result=undef;
 8888: 	    &do_cache_new('courseres',$hashid,$result,600);
 8889: 	}
 8890:     }
 8891:     return $result;
 8892: }
 8893: 
 8894: sub devalidateuserresdata {
 8895:     my ($uname,$udom)=@_;
 8896:     my $hashid="$udom:$uname";
 8897:     &devalidate_cache_new('userres',$hashid);
 8898: }
 8899: 
 8900: sub get_userresdata {
 8901:     my ($uname,$udom)=@_;
 8902:     #most student don\'t have any data set, check if there is some data
 8903:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8904: 
 8905:     my $hashid="$udom:$uname";
 8906:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8907:     if (!defined($cached)) {
 8908: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8909: 	$result=\%resourcedata;
 8910: 	&do_cache_new('userres',$hashid,$result,600);
 8911:     }
 8912:     my ($tmp)=keys(%$result);
 8913:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8914: 	return $result;
 8915:     }
 8916:     #error 2 occurs when the .db doesn't exist
 8917:     if ($tmp!~/error: 2 /) {
 8918: 	&logthis("<font color=\"blue\">WARNING:".
 8919: 		 " Trying to get resource data for ".
 8920: 		 $uname." at ".$udom.": ".
 8921: 		 $tmp."</font>");
 8922:     } elsif ($tmp=~/error: 2 /) {
 8923: 	#&EXT_cache_set($udom,$uname);
 8924: 	&do_cache_new('userres',$hashid,undef,600);
 8925: 	undef($tmp); # not really an error so don't send it back
 8926:     }
 8927:     return $tmp;
 8928: }
 8929: #----------------------------------------------- resdata - return resource data
 8930: #  Purpose:
 8931: #    Return resource data for either users or for a course.
 8932: #  Parameters:
 8933: #     $name      - Course/user name.
 8934: #     $domain    - Name of the domain the user/course is registered on.
 8935: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8936: #     @which     - Array of names of resources desired.
 8937: #  Returns:
 8938: #     The value of the first reasource in @which that is found in the
 8939: #     resource hash.
 8940: #  Exceptional Conditions:
 8941: #     If the $type passed in is not valid (not the string 'course' or 
 8942: #     'user', an undefined  reference is returned.
 8943: #     If none of the resources are found, an undef is returned
 8944: sub resdata {
 8945:     my ($name,$domain,$type,@which)=@_;
 8946:     my $result;
 8947:     if ($type eq 'course') {
 8948: 	$result=&get_courseresdata($name,$domain);
 8949:     } elsif ($type eq 'user') {
 8950: 	$result=&get_userresdata($name,$domain);
 8951:     }
 8952:     if (!ref($result)) { return $result; }    
 8953:     foreach my $item (@which) {
 8954: 	if (defined($result->{$item->[0]})) {
 8955: 	    return [$result->{$item->[0]},$item->[1]];
 8956: 	}
 8957:     }
 8958:     return undef;
 8959: }
 8960: 
 8961: #
 8962: # EXT resource caching routines
 8963: #
 8964: 
 8965: sub clear_EXT_cache_status {
 8966:     &delenv('cache.EXT.');
 8967: }
 8968: 
 8969: sub EXT_cache_status {
 8970:     my ($target_domain,$target_user) = @_;
 8971:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8972:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8973:         # We know already the user has no data
 8974:         return 1;
 8975:     } else {
 8976:         return 0;
 8977:     }
 8978: }
 8979: 
 8980: sub EXT_cache_set {
 8981:     my ($target_domain,$target_user) = @_;
 8982:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8983:     #&appenv({$cachename => time});
 8984: }
 8985: 
 8986: # --------------------------------------------------------- Value of a Variable
 8987: sub EXT {
 8988: 
 8989:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8990:     unless ($varname) { return ''; }
 8991:     #get real user name/domain, courseid and symb
 8992:     my $courseid;
 8993:     my $publicuser;
 8994:     if ($symbparm) {
 8995: 	$symbparm=&get_symb_from_alias($symbparm);
 8996:     }
 8997:     if (!($uname && $udom)) {
 8998:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8999:       if (!$symbparm) {	$symbparm=$cursymb; }
 9000:     } else {
 9001: 	$courseid=$env{'request.course.id'};
 9002:     }
 9003:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9004:     my $rest;
 9005:     if (defined($therest[0])) {
 9006:        $rest=join('.',@therest);
 9007:     } else {
 9008:        $rest='';
 9009:     }
 9010: 
 9011:     my $qualifierrest=$qualifier;
 9012:     if ($rest) { $qualifierrest.='.'.$rest; }
 9013:     my $spacequalifierrest=$space;
 9014:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9015:     if ($realm eq 'user') {
 9016: # --------------------------------------------------------------- user.resource
 9017: 	if ($space eq 'resource') {
 9018: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9019: 		  || defined($Apache::lonhomework::parsing_a_task))
 9020: 		 &&
 9021: 		 ($symbparm eq &symbread()) ) {	
 9022: 		# if we are in the middle of processing the resource the
 9023: 		# get the value we are planning on committing
 9024:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9025:                     return $Apache::lonhomework::results{$qualifierrest};
 9026:                 } else {
 9027:                     return $Apache::lonhomework::history{$qualifierrest};
 9028:                 }
 9029: 	    } else {
 9030: 		my %restored;
 9031: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9032: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9033: 		} else {
 9034: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9035: 		}
 9036: 		return $restored{$qualifierrest};
 9037: 	    }
 9038: # ----------------------------------------------------------------- user.access
 9039:         } elsif ($space eq 'access') {
 9040: 	    # FIXME - not supporting calls for a specific user
 9041:             return &allowed($qualifier,$rest);
 9042: # ------------------------------------------ user.preferences, user.environment
 9043:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9044: 	    if (($uname eq $env{'user.name'}) &&
 9045: 		($udom eq $env{'user.domain'})) {
 9046: 		return $env{join('.',('environment',$qualifierrest))};
 9047: 	    } else {
 9048: 		my %returnhash;
 9049: 		if (!$publicuser) {
 9050: 		    %returnhash=&userenvironment($udom,$uname,
 9051: 						 $qualifierrest);
 9052: 		}
 9053: 		return $returnhash{$qualifierrest};
 9054: 	    }
 9055: # ----------------------------------------------------------------- user.course
 9056:         } elsif ($space eq 'course') {
 9057: 	    # FIXME - not supporting calls for a specific user
 9058:             return $env{join('.',('request.course',$qualifier))};
 9059: # ------------------------------------------------------------------- user.role
 9060:         } elsif ($space eq 'role') {
 9061: 	    # FIXME - not supporting calls for a specific user
 9062:             my ($role,$where)=split(/\./,$env{'request.role'});
 9063:             if ($qualifier eq 'value') {
 9064: 		return $role;
 9065:             } elsif ($qualifier eq 'extent') {
 9066:                 return $where;
 9067:             }
 9068: # ----------------------------------------------------------------- user.domain
 9069:         } elsif ($space eq 'domain') {
 9070:             return $udom;
 9071: # ------------------------------------------------------------------- user.name
 9072:         } elsif ($space eq 'name') {
 9073:             return $uname;
 9074: # ---------------------------------------------------- Any other user namespace
 9075:         } else {
 9076: 	    my %reply;
 9077: 	    if (!$publicuser) {
 9078: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9079: 	    }
 9080: 	    return $reply{$qualifierrest};
 9081:         }
 9082:     } elsif ($realm eq 'query') {
 9083: # ---------------------------------------------- pull stuff out of query string
 9084:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9085: 						[$spacequalifierrest]);
 9086: 	return $env{'form.'.$spacequalifierrest}; 
 9087:    } elsif ($realm eq 'request') {
 9088: # ------------------------------------------------------------- request.browser
 9089:         if ($space eq 'browser') {
 9090:             return $env{'browser.'.$qualifier};
 9091: # ------------------------------------------------------------ request.filename
 9092:         } else {
 9093:             return $env{'request.'.$spacequalifierrest};
 9094:         }
 9095:     } elsif ($realm eq 'course') {
 9096: # ---------------------------------------------------------- course.description
 9097:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9098:     } elsif ($realm eq 'resource') {
 9099: 
 9100: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9101: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9102: 	}
 9103: 
 9104: 	if ($space eq 'title') {
 9105: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9106: 	    return &gettitle($symbparm);
 9107: 	}
 9108: 	
 9109: 	if ($space eq 'map') {
 9110: 	    my ($map) = &decode_symb($symbparm);
 9111: 	    return &symbread($map);
 9112: 	}
 9113: 	if ($space eq 'filename') {
 9114: 	    if ($symbparm) {
 9115: 		return &clutter((&decode_symb($symbparm))[2]);
 9116: 	    }
 9117: 	    return &hreflocation('',$env{'request.filename'});
 9118: 	}
 9119: 
 9120: 	my ($section, $group, @groups);
 9121: 	my ($courselevelm,$courselevel);
 9122: 	if ($symbparm && defined($courseid) && 
 9123: 	    $courseid eq $env{'request.course.id'}) {
 9124: 
 9125: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9126: 
 9127: # ----------------------------------------------------- Cascading lookup scheme
 9128: 	    my $symbp=$symbparm;
 9129: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9130: 
 9131: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9132: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9133: 
 9134: 	    if (($env{'user.name'} eq $uname) &&
 9135: 		($env{'user.domain'} eq $udom)) {
 9136: 		$section=$env{'request.course.sec'};
 9137:                 @groups = split(/:/,$env{'request.course.groups'});  
 9138:                 @groups=&sort_course_groups($courseid,@groups); 
 9139: 	    } else {
 9140: 		if (! defined($usection)) {
 9141: 		    $section=&getsection($udom,$uname,$courseid);
 9142: 		} else {
 9143: 		    $section = $usection;
 9144: 		}
 9145:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9146: 	    }
 9147: 
 9148: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9149: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9150: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9151: 
 9152: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9153: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9154: 	    $courselevelm=$courseid.'.'.$mapparm;
 9155: 
 9156: # ----------------------------------------------------------- first, check user
 9157: 
 9158: 	    my $userreply=&resdata($uname,$udom,'user',
 9159: 				       ([$courselevelr,'resource'],
 9160: 					[$courselevelm,'map'     ],
 9161: 					[$courselevel, 'course'  ]));
 9162: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9163: 
 9164: # ------------------------------------------------ second, check some of course
 9165:             my $coursereply;
 9166:             if (@groups > 0) {
 9167:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9168:                                        $mapparm,$spacequalifierrest);
 9169:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9170:             }
 9171: 
 9172: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9173: 				  $env{'course.'.$courseid.'.domain'},
 9174: 				  'course',
 9175: 				  ([$seclevelr,   'resource'],
 9176: 				   [$seclevelm,   'map'     ],
 9177: 				   [$seclevel,    'course'  ],
 9178: 				   [$courselevelr,'resource']));
 9179: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9180: 
 9181: # ------------------------------------------------------ third, check map parms
 9182: 	    my %parmhash=();
 9183: 	    my $thisparm='';
 9184: 	    if (tie(%parmhash,'GDBM_File',
 9185: 		    $env{'request.course.fn'}.'_parms.db',
 9186: 		    &GDBM_READER(),0640)) {
 9187: 		$thisparm=$parmhash{$symbparm};
 9188: 		untie(%parmhash);
 9189: 	    }
 9190: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9191: 	}
 9192: # ------------------------------------------ fourth, look in resource metadata
 9193: 
 9194: 	$spacequalifierrest=~s/\./\_/;
 9195: 	my $filename;
 9196: 	if (!$symbparm) { $symbparm=&symbread(); }
 9197: 	if ($symbparm) {
 9198: 	    $filename=(&decode_symb($symbparm))[2];
 9199: 	} else {
 9200: 	    $filename=$env{'request.filename'};
 9201: 	}
 9202: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9203: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9204: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9205: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9206: 
 9207: # ---------------------------------------------- fourth, look in rest of course
 9208: 	if ($symbparm && defined($courseid) && 
 9209: 	    $courseid eq $env{'request.course.id'}) {
 9210: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9211: 				     $env{'course.'.$courseid.'.domain'},
 9212: 				     'course',
 9213: 				     ([$courselevelm,'map'   ],
 9214: 				      [$courselevel, 'course']));
 9215: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9216: 	}
 9217: # ------------------------------------------------------------------ Cascade up
 9218: 	unless ($space eq '0') {
 9219: 	    my @parts=split(/_/,$space);
 9220: 	    my $id=pop(@parts);
 9221: 	    my $part=join('_',@parts);
 9222: 	    if ($part eq '') { $part='0'; }
 9223: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9224: 				 $symbparm,$udom,$uname,$section,1);
 9225: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9226: 	}
 9227: 	if ($recurse) { return undef; }
 9228: 	my $pack_def=&packages_tab_default($filename,$varname);
 9229: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9230: # ---------------------------------------------------- Any other user namespace
 9231:     } elsif ($realm eq 'environment') {
 9232: # ----------------------------------------------------------------- environment
 9233: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9234: 	    return $env{'environment.'.$spacequalifierrest};
 9235: 	} else {
 9236: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9237: 		return '';
 9238: 	    }
 9239: 	    my %returnhash=&userenvironment($udom,$uname,
 9240: 					    $spacequalifierrest);
 9241: 	    return $returnhash{$spacequalifierrest};
 9242: 	}
 9243:     } elsif ($realm eq 'system') {
 9244: # ----------------------------------------------------------------- system.time
 9245: 	if ($space eq 'time') {
 9246: 	    return time;
 9247:         }
 9248:     } elsif ($realm eq 'server') {
 9249: # ----------------------------------------------------------------- system.time
 9250: 	if ($space eq 'name') {
 9251: 	    return $ENV{'SERVER_NAME'};
 9252:         }
 9253:     }
 9254:     return '';
 9255: }
 9256: 
 9257: sub get_reply {
 9258:     my ($reply_value) = @_;
 9259:     if (ref($reply_value) eq 'ARRAY') {
 9260:         if (wantarray) {
 9261: 	    return @$reply_value;
 9262:         }
 9263:         return $reply_value->[0];
 9264:     } else {
 9265:         return $reply_value;
 9266:     }
 9267: }
 9268: 
 9269: sub check_group_parms {
 9270:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9271:     my @groupitems = ();
 9272:     my $resultitem;
 9273:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9274:     foreach my $group (@{$groups}) {
 9275:         foreach my $level (@levels) {
 9276:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9277:              push(@groupitems,[$item,$level->[1]]);
 9278:         }
 9279:     }
 9280:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9281:                             $env{'course.'.$courseid.'.domain'},
 9282:                                      'course',@groupitems);
 9283:     return $coursereply;
 9284: }
 9285: 
 9286: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9287:     my ($courseid,@groups) = @_;
 9288:     @groups = sort(@groups);
 9289:     return @groups;
 9290: }
 9291: 
 9292: sub packages_tab_default {
 9293:     my ($uri,$varname)=@_;
 9294:     my (undef,$part,$name)=split(/\./,$varname);
 9295: 
 9296:     my (@extension,@specifics,$do_default);
 9297:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9298: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9299: 	if ($pack_type eq 'default') {
 9300: 	    $do_default=1;
 9301: 	} elsif ($pack_type eq 'extension') {
 9302: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9303: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9304: 	    # only look at packages defaults for packages that this id is
 9305: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9306: 	}
 9307:     }
 9308:     # first look for a package that matches the requested part id
 9309:     foreach my $package (@specifics) {
 9310: 	my (undef,$pack_type,$pack_part)=@{$package};
 9311: 	next if ($pack_part ne $part);
 9312: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9313: 	    return $packagetab{"$pack_type&$name&default"};
 9314: 	}
 9315:     }
 9316:     # look for any possible matching non extension_ package
 9317:     foreach my $package (@specifics) {
 9318: 	my (undef,$pack_type,$pack_part)=@{$package};
 9319: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9320: 	    return $packagetab{"$pack_type&$name&default"};
 9321: 	}
 9322: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9323: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9324: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9325: 	}
 9326:     }
 9327:     # look for any posible extension_ match
 9328:     foreach my $package (@extension) {
 9329: 	my ($package,$pack_type)=@{$package};
 9330: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9331: 	    return $packagetab{"$pack_type&$name&default"};
 9332: 	}
 9333: 	if (defined($packagetab{$package."&$name&default"})) {
 9334: 	    return $packagetab{$package."&$name&default"};
 9335: 	}
 9336:     }
 9337:     # look for a global default setting
 9338:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9339: 	return $packagetab{"default&$name&default"};
 9340:     }
 9341:     return undef;
 9342: }
 9343: 
 9344: sub add_prefix_and_part {
 9345:     my ($prefix,$part)=@_;
 9346:     my $keyroot;
 9347:     if (defined($prefix) && $prefix !~ /^__/) {
 9348: 	# prefix that has a part already
 9349: 	$keyroot=$prefix;
 9350:     } elsif (defined($prefix)) {
 9351: 	# prefix that is missing a part
 9352: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9353:     } else {
 9354: 	# no prefix at all
 9355: 	if (defined($part)) { $keyroot='_'.$part; }
 9356:     }
 9357:     return $keyroot;
 9358: }
 9359: 
 9360: # ---------------------------------------------------------------- Get metadata
 9361: 
 9362: my %metaentry;
 9363: my %importedpartids;
 9364: sub metadata {
 9365:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9366:     $uri=&declutter($uri);
 9367:     # if it is a non metadata possible uri return quickly
 9368:     if (($uri eq '') || 
 9369: 	(($uri =~ m|^/*adm/|) && 
 9370: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9371:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9372: 	return undef;
 9373:     }
 9374:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9375: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9376: 	return undef;
 9377:     }
 9378:     my $filename=$uri;
 9379:     $uri=~s/\.meta$//;
 9380: #
 9381: # Is the metadata already cached?
 9382: # Look at timestamp of caching
 9383: # Everything is cached by the main uri, libraries are never directly cached
 9384: #
 9385:     if (!defined($liburi)) {
 9386: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9387: 	if (defined($cached)) { return $result->{':'.$what}; }
 9388:     }
 9389:     {
 9390: # Imported parts would go here
 9391:         my %importedids=();
 9392:         my @origfileimportpartids=();
 9393:         my $importedparts=0;
 9394: #
 9395: # Is this a recursive call for a library?
 9396: #
 9397: #	if (! exists($metacache{$uri})) {
 9398: #	    $metacache{$uri}={};
 9399: #	}
 9400: 	my $cachetime = 60*60;
 9401:         if ($liburi) {
 9402: 	    $liburi=&declutter($liburi);
 9403:             $filename=$liburi;
 9404:         } else {
 9405: 	    &devalidate_cache_new('meta',$uri);
 9406: 	    undef(%metaentry);
 9407: 	}
 9408:         my %metathesekeys=();
 9409:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9410: 	my $metastring;
 9411: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9412: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9413: 	    $metastring = 
 9414: 		&Apache::lonnet::ssi_body($which,
 9415: 					  ('grade_target' => 'meta'));
 9416: 	    $cachetime = 1; # only want this cached in the child not long term
 9417: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9418:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9419: 	    my $file=&filelocation('',&clutter($filename));
 9420: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9421: 	    $metastring=&getfile($file);
 9422: 	}
 9423:         my $parser=HTML::LCParser->new(\$metastring);
 9424:         my $token;
 9425:         undef %metathesekeys;
 9426:         while ($token=$parser->get_token) {
 9427: 	    if ($token->[0] eq 'S') {
 9428: 		if (defined($token->[2]->{'package'})) {
 9429: #
 9430: # This is a package - get package info
 9431: #
 9432: 		    my $package=$token->[2]->{'package'};
 9433: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9434: 		    if (defined($token->[2]->{'id'})) { 
 9435: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9436: 		    }
 9437: 		    if ($metaentry{':packages'}) {
 9438: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9439: 		    } else {
 9440: 			$metaentry{':packages'}=$package.$keyroot;
 9441: 		    }
 9442: 		    foreach my $pack_entry (keys(%packagetab)) {
 9443: 			my $part=$keyroot;
 9444: 			$part=~s/^\_//;
 9445: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9446: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9447: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9448: 			    # ignore package.tab specified default values
 9449:                             # here &package_tab_default() will fetch those
 9450: 			    if ($subp eq 'default') { next; }
 9451: 			    my $value=$packagetab{$pack_entry};
 9452: 			    my $unikey;
 9453: 			    if ($pack =~ /_0$/) {
 9454: 				$unikey='parameter_0_'.$name;
 9455: 				$part=0;
 9456: 			    } else {
 9457: 				$unikey='parameter'.$keyroot.'_'.$name;
 9458: 			    }
 9459: 			    if ($subp eq 'display') {
 9460: 				$value.=' [Part: '.$part.']';
 9461: 			    }
 9462: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9463: 			    $metathesekeys{$unikey}=1;
 9464: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9465: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9466: 			    }
 9467: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9468: 				$metaentry{':'.$unikey}=
 9469: 				    $metaentry{':'.$unikey.'.default'};
 9470: 			    }
 9471: 			}
 9472: 		    }
 9473: 		} else {
 9474: #
 9475: # This is not a package - some other kind of start tag
 9476: #
 9477: 		    my $entry=$token->[1];
 9478: 		    my $unikey='';
 9479: 
 9480: 		    if ($entry eq 'import') {
 9481: #
 9482: # Importing a library here
 9483: #
 9484:                         my $location=$parser->get_text('/import');
 9485:                         my $dir=$filename;
 9486:                         $dir=~s|[^/]*$||;
 9487:                         $location=&filelocation($dir,$location);
 9488:                        
 9489:                         my $importmode=$token->[2]->{'importmode'};
 9490:                         if ($importmode eq 'problem') {
 9491: # Import as problem/response
 9492:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9493:                         } elsif ($importmode eq 'part') {
 9494: # Import as part(s)
 9495:                            $importedparts=1;
 9496: # We need to get the original file and the imported file to get the part order correct
 9497: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9498: # Load and inspect original file
 9499:                            if ($#origfileimportpartids<0) {
 9500:                               undef(%importedpartids);
 9501:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9502:                               my $origfile=&getfile($origfilelocation);
 9503:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9504:                            }
 9505: 
 9506: # Load and inspect imported file
 9507:                            my $impfile=&getfile($location);
 9508:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9509:                            if ($#impfilepartids>=0) {
 9510: # This problem had parts
 9511:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9512:                            } else {
 9513: # Importing by turning a single problem into a problem part
 9514: # It gets the import-tags ID as part-ID
 9515:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9516:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9517:                            }
 9518:                         } else {
 9519: # Normal import
 9520:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9521:                            if (defined($token->[2]->{'id'})) {
 9522:                               $unikey.='_'.$token->[2]->{'id'};
 9523:                            }
 9524:                         }
 9525: 
 9526: 			if ($depthcount<20) {
 9527: 			    my $metadata = 
 9528: 				&metadata($uri,'keys', $location,$unikey,
 9529: 					  $depthcount+1);
 9530: 			    foreach my $meta (split(',',$metadata)) {
 9531: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9532: 				$metathesekeys{$meta}=1;
 9533: 			    }
 9534: 			
 9535:                         }
 9536: 		    } else {
 9537: #
 9538: # Not importing, some other kind of non-package, non-library start tag
 9539: # 
 9540:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9541:                         if (defined($token->[2]->{'id'})) {
 9542:                             $unikey.='_'.$token->[2]->{'id'};
 9543:                         }
 9544: 			if (defined($token->[2]->{'name'})) { 
 9545: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9546: 			}
 9547: 			$metathesekeys{$unikey}=1;
 9548: 			foreach my $param (@{$token->[3]}) {
 9549: 			    $metaentry{':'.$unikey.'.'.$param} =
 9550: 				$token->[2]->{$param};
 9551: 			}
 9552: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9553: 			my $default=$metaentry{':'.$unikey.'.default'};
 9554: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9555: 		 # only ws inside the tag, and not in default, so use default
 9556: 		 # as value
 9557: 			    $metaentry{':'.$unikey}=$default;
 9558: 			} elsif ( $internaltext =~ /\S/ ) {
 9559: 		  # something interesting inside the tag
 9560: 			    $metaentry{':'.$unikey}=$internaltext;
 9561: 			} else {
 9562: 		  # no interesting values, don't set a default
 9563: 			}
 9564: # end of not-a-package not-a-library import
 9565: 		    }
 9566: # end of not-a-package start tag
 9567: 		}
 9568: # the next is the end of "start tag"
 9569: 	    }
 9570: 	}
 9571: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9572: 	$extension = lc($extension);
 9573: 	if ($extension eq 'htm') { $extension='html'; }
 9574: 
 9575: 	foreach my $key (keys(%packagetab)) {
 9576: 	    #no specific packages #how's our extension
 9577: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9578: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9579: 					 \%metathesekeys);
 9580: 	}
 9581: 
 9582: 	if (!exists($metaentry{':packages'})
 9583: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9584: 	    foreach my $key (keys(%packagetab)) {
 9585: 		#no specific packages well let's get default then
 9586: 		if ($key!~/^default&/) { next; }
 9587: 		&metadata_create_package_def($uri,$key,'default',
 9588: 					     \%metathesekeys);
 9589: 	    }
 9590: 	}
 9591: # are there custom rights to evaluate
 9592: 	if ($metaentry{':copyright'} eq 'custom') {
 9593: 
 9594:     #
 9595:     # Importing a rights file here
 9596:     #
 9597: 	    unless ($depthcount) {
 9598: 		my $location=$metaentry{':customdistributionfile'};
 9599: 		my $dir=$filename;
 9600: 		$dir=~s|[^/]*$||;
 9601: 		$location=&filelocation($dir,$location);
 9602: 		my $rights_metadata =
 9603: 		    &metadata($uri,'keys',$location,'_rights',
 9604: 			      $depthcount+1);
 9605: 		foreach my $rights (split(',',$rights_metadata)) {
 9606: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9607: 		    $metathesekeys{$rights}=1;
 9608: 		}
 9609: 	    }
 9610: 	}
 9611: 	# uniqifiy package listing
 9612: 	my %seen;
 9613: 	my @uniq_packages =
 9614: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9615: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9616: 
 9617:         if ($importedparts) {
 9618: # We had imported parts and need to rebuild partorder
 9619:            $metaentry{':partorder'}='';
 9620:            $metathesekeys{'partorder'}=1;
 9621:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9622:                if ($origfileimportpartids[$index] eq 'part') {
 9623: # original part, part of the problem
 9624:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9625:                } else {
 9626: # we have imported parts at this position
 9627:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9628:                }
 9629:            }
 9630:            $metaentry{':partorder'}=~s/^\,//;
 9631:         }
 9632: 
 9633: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9634: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9635: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9636: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9637: # this is the end of "was not already recently cached
 9638:     }
 9639:     return $metaentry{':'.$what};
 9640: }
 9641: 
 9642: sub metadata_create_package_def {
 9643:     my ($uri,$key,$package,$metathesekeys)=@_;
 9644:     my ($pack,$name,$subp)=split(/\&/,$key);
 9645:     if ($subp eq 'default') { next; }
 9646:     
 9647:     if (defined($metaentry{':packages'})) {
 9648: 	$metaentry{':packages'}.=','.$package;
 9649:     } else {
 9650: 	$metaentry{':packages'}=$package;
 9651:     }
 9652:     my $value=$packagetab{$key};
 9653:     my $unikey;
 9654:     $unikey='parameter_0_'.$name;
 9655:     $metaentry{':'.$unikey.'.part'}=0;
 9656:     $$metathesekeys{$unikey}=1;
 9657:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9658: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9659:     }
 9660:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9661: 	$metaentry{':'.$unikey}=
 9662: 	    $metaentry{':'.$unikey.'.default'};
 9663:     }
 9664: }
 9665: 
 9666: sub metadata_generate_part0 {
 9667:     my ($metadata,$metacache,$uri) = @_;
 9668:     my %allnames;
 9669:     foreach my $metakey (keys(%$metadata)) {
 9670: 	if ($metakey=~/^parameter\_(.*)/) {
 9671: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9672: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9673: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9674: 	    $allnames{$name}=$part;
 9675: 	  }
 9676: 	}
 9677:     }
 9678:     foreach my $name (keys(%allnames)) {
 9679:       $$metadata{"parameter_0_$name"}=1;
 9680:       my $key=":parameter_0_$name";
 9681:       $$metacache{"$key.part"}='0';
 9682:       $$metacache{"$key.name"}=$name;
 9683:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9684: 					   $allnames{$name}.'_'.$name.
 9685: 					   '.type'};
 9686:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9687: 			     '.display'};
 9688:       my $expr='[Part: '.$allnames{$name}.']';
 9689:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9690:       $$metacache{"$key.display"}=$olddis;
 9691:     }
 9692: }
 9693: 
 9694: # ------------------------------------------------------ Devalidate title cache
 9695: 
 9696: sub devalidate_title_cache {
 9697:     my ($url)=@_;
 9698:     if (!$env{'request.course.id'}) { return; }
 9699:     my $symb=&symbread($url);
 9700:     if (!$symb) { return; }
 9701:     my $key=$env{'request.course.id'}."\0".$symb;
 9702:     &devalidate_cache_new('title',$key);
 9703: }
 9704: 
 9705: # ------------------------------------------------- Get the title of a course
 9706: 
 9707: sub current_course_title {
 9708:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9709: }
 9710: # ------------------------------------------------- Get the title of a resource
 9711: 
 9712: sub gettitle {
 9713:     my $urlsymb=shift;
 9714:     my $symb=&symbread($urlsymb);
 9715:     if ($symb) {
 9716: 	my $key=$env{'request.course.id'}."\0".$symb;
 9717: 	my ($result,$cached)=&is_cached_new('title',$key);
 9718: 	if (defined($cached)) { 
 9719: 	    return $result;
 9720: 	}
 9721: 	my ($map,$resid,$url)=&decode_symb($symb);
 9722: 	my $title='';
 9723: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9724: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9725: 	} else {
 9726: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9727: 		    &GDBM_READER(),0640)) {
 9728: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9729: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9730: 		untie(%bighash);
 9731: 	    }
 9732: 	}
 9733: 	$title=~s/\&colon\;/\:/gs;
 9734: 	if ($title) {
 9735: # Remember both $symb and $title for dynamic metadata
 9736:             $accesshash{$symb.'___crstitle'}=$title;
 9737:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9738: # Cache this title and then return it
 9739: 	    return &do_cache_new('title',$key,$title,600);
 9740: 	}
 9741: 	$urlsymb=$url;
 9742:     }
 9743:     my $title=&metadata($urlsymb,'title');
 9744:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9745:     return $title;
 9746: }
 9747: 
 9748: sub get_slot {
 9749:     my ($which,$cnum,$cdom)=@_;
 9750:     if (!$cnum || !$cdom) {
 9751: 	(undef,my $courseid)=&whichuser();
 9752: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9753: 	$cnum=$env{'course.'.$courseid.'.num'};
 9754:     }
 9755:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9756:     my %slotinfo;
 9757:     if (exists($remembered{$key})) {
 9758: 	$slotinfo{$which} = $remembered{$key};
 9759:     } else {
 9760: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9761: 	&Apache::lonhomework::showhash(%slotinfo);
 9762: 	my ($tmp)=keys(%slotinfo);
 9763: 	if ($tmp=~/^error:/) { return (); }
 9764: 	$remembered{$key} = $slotinfo{$which};
 9765:     }
 9766:     if (ref($slotinfo{$which}) eq 'HASH') {
 9767: 	return %{$slotinfo{$which}};
 9768:     }
 9769:     return $slotinfo{$which};
 9770: }
 9771: 
 9772: sub get_reservable_slots {
 9773:     my ($cnum,$cdom,$uname,$udom) = @_;
 9774:     my $now = time;
 9775:     my $reservable_info;
 9776:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9777:     if (exists($remembered{$key})) {
 9778:         $reservable_info = $remembered{$key};
 9779:     } else {
 9780:         my %resv;
 9781:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9782:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9783:         $reservable_info = \%resv;
 9784:         $remembered{$key} = $reservable_info;
 9785:     }
 9786:     return $reservable_info;
 9787: }
 9788: 
 9789: sub get_course_slots {
 9790:     my ($cnum,$cdom) = @_;
 9791:     my $hashid=$cnum.':'.$cdom;
 9792:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9793:     if (defined($cached)) {
 9794:         if (ref($result) eq 'HASH') {
 9795:             return %{$result};
 9796:         }
 9797:     } else {
 9798:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9799:         my ($tmp) = keys(%slots);
 9800:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9801:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9802:             return %slots;
 9803:         }
 9804:     }
 9805:     return;
 9806: }
 9807: 
 9808: sub devalidate_slots_cache {
 9809:     my ($cnum,$cdom)=@_;
 9810:     my $hashid=$cnum.':'.$cdom;
 9811:     &devalidate_cache_new('allslots',$hashid);
 9812: }
 9813: 
 9814: # ------------------------------------------------- Update symbolic store links
 9815: 
 9816: sub symblist {
 9817:     my ($mapname,%newhash)=@_;
 9818:     $mapname=&deversion(&declutter($mapname));
 9819:     my %hash;
 9820:     if (($env{'request.course.fn'}) && (%newhash)) {
 9821:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9822:                       &GDBM_WRCREAT(),0640)) {
 9823: 	    foreach my $url (keys(%newhash)) {
 9824: 		next if ($url eq 'last_known'
 9825: 			 && $env{'form.no_update_last_known'});
 9826: 		$hash{declutter($url)}=&encode_symb($mapname,
 9827: 						    $newhash{$url}->[1],
 9828: 						    $newhash{$url}->[0]);
 9829:             }
 9830:             if (untie(%hash)) {
 9831: 		return 'ok';
 9832:             }
 9833:         }
 9834:     }
 9835:     return 'error';
 9836: }
 9837: 
 9838: # --------------------------------------------------------------- Verify a symb
 9839: 
 9840: sub symbverify {
 9841:     my ($symb,$thisurl)=@_;
 9842:     my $thisfn=$thisurl;
 9843:     $thisfn=&declutter($thisfn);
 9844: # direct jump to resource in page or to a sequence - will construct own symbs
 9845:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9846: # check URL part
 9847:     my ($map,$resid,$url)=&decode_symb($symb);
 9848: 
 9849:     unless ($url eq $thisfn) { return 0; }
 9850: 
 9851:     $symb=&symbclean($symb);
 9852:     $thisurl=&deversion($thisurl);
 9853:     $thisfn=&deversion($thisfn);
 9854: 
 9855:     my %bighash;
 9856:     my $okay=0;
 9857: 
 9858:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9859:                             &GDBM_READER(),0640)) {
 9860:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9861:             $thisurl =~ s/\?.+$//;
 9862:         }
 9863:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9864:         unless ($ids) {
 9865:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9866:             $ids=$bighash{$idkey};
 9867:         }
 9868:         if ($ids) {
 9869: # ------------------------------------------------------------------- Has ID(s)
 9870: 	    foreach my $id (split(/\,/,$ids)) {
 9871: 	       my ($mapid,$resid)=split(/\./,$id);
 9872:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9873:                    $symb =~ s/\?.+$//;
 9874:                }
 9875:                if (
 9876:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9877:    eq $symb) { 
 9878: 		   if (($env{'request.role.adv'}) ||
 9879: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9880:                        ($thisurl eq '/adm/navmaps')) {
 9881: 		       $okay=1; 
 9882: 		   }
 9883: 	       }
 9884: 	   }
 9885:         }
 9886: 	untie(%bighash);
 9887:     }
 9888:     return $okay;
 9889: }
 9890: 
 9891: # --------------------------------------------------------------- Clean-up symb
 9892: 
 9893: sub symbclean {
 9894:     my $symb=shift;
 9895:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9896: # remove version from map
 9897:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9898: 
 9899: # remove version from URL
 9900:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9901: 
 9902: # remove wrapper
 9903: 
 9904:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9905:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9906:     return $symb;
 9907: }
 9908: 
 9909: # ---------------------------------------------- Split symb to find map and url
 9910: 
 9911: sub encode_symb {
 9912:     my ($map,$resid,$url)=@_;
 9913:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9914: }
 9915: 
 9916: sub decode_symb {
 9917:     my $symb=shift;
 9918:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9919:     my ($map,$resid,$url)=split(/___/,$symb);
 9920:     return (&fixversion($map),$resid,&fixversion($url));
 9921: }
 9922: 
 9923: sub fixversion {
 9924:     my $fn=shift;
 9925:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9926:     my %bighash;
 9927:     my $uri=&clutter($fn);
 9928:     my $key=$env{'request.course.id'}.'_'.$uri;
 9929: # is this cached?
 9930:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9931:     if (defined($cached)) { return $result; }
 9932: # unfortunately not cached, or expired
 9933:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9934: 	    &GDBM_READER(),0640)) {
 9935:  	if ($bighash{'version_'.$uri}) {
 9936:  	    my $version=$bighash{'version_'.$uri};
 9937:  	    unless (($version eq 'mostrecent') || 
 9938: 		    ($version==&getversion($uri))) {
 9939:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9940:  	    }
 9941:  	}
 9942:  	untie %bighash;
 9943:     }
 9944:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9945: }
 9946: 
 9947: sub deversion {
 9948:     my $url=shift;
 9949:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9950:     return $url;
 9951: }
 9952: 
 9953: # ------------------------------------------------------ Return symb list entry
 9954: 
 9955: sub symbread {
 9956:     my ($thisfn,$donotrecurse)=@_;
 9957:     my $cache_str='request.symbread.cached.'.$thisfn;
 9958:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9959: # no filename provided? try from environment
 9960:     unless ($thisfn) {
 9961:         if ($env{'request.symb'}) {
 9962: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9963: 	}
 9964: 	$thisfn=$env{'request.filename'};
 9965:     }
 9966:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9967: # is that filename actually a symb? Verify, clean, and return
 9968:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9969: 	if (&symbverify($thisfn,$1)) {
 9970: 	    return $env{$cache_str}=&symbclean($thisfn);
 9971: 	}
 9972:     }
 9973:     $thisfn=declutter($thisfn);
 9974:     my %hash;
 9975:     my %bighash;
 9976:     my $syval='';
 9977:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9978:         my $targetfn = $thisfn;
 9979:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9980:             $targetfn = 'adm/wrapper/'.$thisfn;
 9981:         }
 9982: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9983: 	    $targetfn=$1;
 9984: 	}
 9985:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9986:                       &GDBM_READER(),0640)) {
 9987: 	    $syval=$hash{$targetfn};
 9988:             untie(%hash);
 9989:         }
 9990: # ---------------------------------------------------------- There was an entry
 9991:         if ($syval) {
 9992: 	    #unless ($syval=~/\_\d+$/) {
 9993: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9994: 		    #&appenv({'request.ambiguous' => $thisfn});
 9995: 		    #return $env{$cache_str}='';
 9996: 		#}    
 9997: 		#$syval.=$1;
 9998: 	    #}
 9999:         } else {
10000: # ------------------------------------------------------- Was not in symb table
10001:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10002:                             &GDBM_READER(),0640)) {
10003: # ---------------------------------------------- Get ID(s) for current resource
10004:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10005:               unless ($ids) { 
10006:                  $ids=$bighash{'ids_/'.$thisfn};
10007:               }
10008:               unless ($ids) {
10009: # alias?
10010: 		  $ids=$bighash{'mapalias_'.$thisfn};
10011:               }
10012:               if ($ids) {
10013: # ------------------------------------------------------------------- Has ID(s)
10014:                  my @possibilities=split(/\,/,$ids);
10015:                  if ($#possibilities==0) {
10016: # ----------------------------------------------- There is only one possibility
10017: 		     my ($mapid,$resid)=split(/\./,$ids);
10018: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10019: 						    $resid,$thisfn);
10020:                  } elsif (!$donotrecurse) {
10021: # ------------------------------------------ There is more than one possibility
10022:                      my $realpossible=0;
10023:                      foreach my $id (@possibilities) {
10024: 			 my $file=$bighash{'src_'.$id};
10025:                          if (&allowed('bre',$file)) {
10026:          		    my ($mapid,$resid)=split(/\./,$id);
10027:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10028: 				$realpossible++;
10029:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10030: 						    $resid,$thisfn);
10031:                             }
10032: 			 }
10033:                      }
10034: 		     if ($realpossible!=1) { $syval=''; }
10035:                  } else {
10036:                      $syval='';
10037:                  }
10038: 	      }
10039:               untie(%bighash)
10040:            }
10041:         }
10042:         if ($syval) {
10043: 	    return $env{$cache_str}=$syval;
10044:         }
10045:     }
10046:     &appenv({'request.ambiguous' => $thisfn});
10047:     return $env{$cache_str}='';
10048: }
10049: 
10050: # ---------------------------------------------------------- Return random seed
10051: 
10052: sub numval {
10053:     my $txt=shift;
10054:     $txt=~tr/A-J/0-9/;
10055:     $txt=~tr/a-j/0-9/;
10056:     $txt=~tr/K-T/0-9/;
10057:     $txt=~tr/k-t/0-9/;
10058:     $txt=~tr/U-Z/0-5/;
10059:     $txt=~tr/u-z/0-5/;
10060:     $txt=~s/\D//g;
10061:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10062:     return int($txt);
10063: }
10064: 
10065: sub numval2 {
10066:     my $txt=shift;
10067:     $txt=~tr/A-J/0-9/;
10068:     $txt=~tr/a-j/0-9/;
10069:     $txt=~tr/K-T/0-9/;
10070:     $txt=~tr/k-t/0-9/;
10071:     $txt=~tr/U-Z/0-5/;
10072:     $txt=~tr/u-z/0-5/;
10073:     $txt=~s/\D//g;
10074:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10075:     my $total;
10076:     foreach my $val (@txts) { $total+=$val; }
10077:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10078:     return int($total);
10079: }
10080: 
10081: sub numval3 {
10082:     use integer;
10083:     my $txt=shift;
10084:     $txt=~tr/A-J/0-9/;
10085:     $txt=~tr/a-j/0-9/;
10086:     $txt=~tr/K-T/0-9/;
10087:     $txt=~tr/k-t/0-9/;
10088:     $txt=~tr/U-Z/0-5/;
10089:     $txt=~tr/u-z/0-5/;
10090:     $txt=~s/\D//g;
10091:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10092:     my $total;
10093:     foreach my $val (@txts) { $total+=$val; }
10094:     if ($_64bit) { $total=(($total<<32)>>32); }
10095:     return $total;
10096: }
10097: 
10098: sub digest {
10099:     my ($data)=@_;
10100:     my $digest=&Digest::MD5::md5($data);
10101:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10102:     my ($e,$f);
10103:     {
10104:         use integer;
10105:         $e=($a+$b);
10106:         $f=($c+$d);
10107:         if ($_64bit) {
10108:             $e=(($e<<32)>>32);
10109:             $f=(($f<<32)>>32);
10110:         }
10111:     }
10112:     if (wantarray) {
10113: 	return ($e,$f);
10114:     } else {
10115: 	my $g;
10116: 	{
10117: 	    use integer;
10118: 	    $g=($e+$f);
10119: 	    if ($_64bit) {
10120: 		$g=(($g<<32)>>32);
10121: 	    }
10122: 	}
10123: 	return $g;
10124:     }
10125: }
10126: 
10127: sub latest_rnd_algorithm_id {
10128:     return '64bit5';
10129: }
10130: 
10131: sub get_rand_alg {
10132:     my ($courseid)=@_;
10133:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10134:     if ($courseid) {
10135: 	return $env{"course.$courseid.rndseed"};
10136:     }
10137:     return &latest_rnd_algorithm_id();
10138: }
10139: 
10140: sub validCODE {
10141:     my ($CODE)=@_;
10142:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10143:     return 0;
10144: }
10145: 
10146: sub getCODE {
10147:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10148:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10149: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10150: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10151: 	return $Apache::lonhomework::history{'resource.CODE'};
10152:     }
10153:     return undef;
10154: }
10155: #
10156: #  Determines the random seed for a specific context:
10157: #
10158: # parameters:
10159: #   symb      - in course context the symb for the seed.
10160: #   course_id - The course id of the form domain_coursenum.
10161: #   domain    - Domain for the user.
10162: #   course    - Course for the user.
10163: #   cenv      - environment of the course.
10164: #
10165: # NOTE:
10166: #   All parameters are picked out of the environment if missing
10167: #   or not defined.
10168: #   If a symb cannot be determined the current time is used instead.
10169: #
10170: #  For a given well defined symb, courside, domain, username,
10171: #  and course environment, the seed is reproducible.
10172: #
10173: sub rndseed {
10174:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10175:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10176:     if (!defined($symb)) {
10177: 	unless ($symb=$wsymb) { return time; }
10178:     }
10179:     if (!defined $courseid) { 
10180: 	$courseid=$wcourseid; 
10181:     }
10182:     if (!defined $domain) { $domain=$wdomain; }
10183:     if (!defined $username) { $username=$wusername }
10184: 
10185:     my $which;
10186:     if (defined($cenv->{'rndseed'})) {
10187: 	$which = $cenv->{'rndseed'};
10188:     } else {
10189: 	$which =&get_rand_alg($courseid);
10190:     }
10191:     if (defined(&getCODE())) {
10192: 
10193: 	if ($which eq '64bit5') {
10194: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10195: 	} elsif ($which eq '64bit4') {
10196: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10197: 	} else {
10198: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10199: 	}
10200:     } elsif ($which eq '64bit5') {
10201: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10202:     } elsif ($which eq '64bit4') {
10203: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10204:     } elsif ($which eq '64bit3') {
10205: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10206:     } elsif ($which eq '64bit2') {
10207: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10208:     } elsif ($which eq '64bit') {
10209: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10210:     }
10211:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10212: }
10213: 
10214: sub rndseed_32bit {
10215:     my ($symb,$courseid,$domain,$username)=@_;
10216:     {
10217: 	use integer;
10218: 	my $symbchck=unpack("%32C*",$symb) << 27;
10219: 	my $symbseed=numval($symb) << 22;
10220: 	my $namechck=unpack("%32C*",$username) << 17;
10221: 	my $nameseed=numval($username) << 12;
10222: 	my $domainseed=unpack("%32C*",$domain) << 7;
10223: 	my $courseseed=unpack("%32C*",$courseid);
10224: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10225: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10226: 	#&logthis("rndseed :$num:$symb");
10227: 	if ($_64bit) { $num=(($num<<32)>>32); }
10228: 	return $num;
10229:     }
10230: }
10231: 
10232: sub rndseed_64bit {
10233:     my ($symb,$courseid,$domain,$username)=@_;
10234:     {
10235: 	use integer;
10236: 	my $symbchck=unpack("%32S*",$symb) << 21;
10237: 	my $symbseed=numval($symb) << 10;
10238: 	my $namechck=unpack("%32S*",$username);
10239: 	
10240: 	my $nameseed=numval($username) << 21;
10241: 	my $domainseed=unpack("%32S*",$domain) << 10;
10242: 	my $courseseed=unpack("%32S*",$courseid);
10243: 	
10244: 	my $num1=$symbchck+$symbseed+$namechck;
10245: 	my $num2=$nameseed+$domainseed+$courseseed;
10246: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10247: 	#&logthis("rndseed :$num:$symb");
10248: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10249: 	return "$num1,$num2";
10250:     }
10251: }
10252: 
10253: sub rndseed_64bit2 {
10254:     my ($symb,$courseid,$domain,$username)=@_;
10255:     {
10256: 	use integer;
10257: 	# strings need to be an even # of cahracters long, it it is odd the
10258:         # last characters gets thrown away
10259: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10260: 	my $symbseed=numval($symb) << 10;
10261: 	my $namechck=unpack("%32S*",$username.' ');
10262: 	
10263: 	my $nameseed=numval($username) << 21;
10264: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10265: 	my $courseseed=unpack("%32S*",$courseid.' ');
10266: 	
10267: 	my $num1=$symbchck+$symbseed+$namechck;
10268: 	my $num2=$nameseed+$domainseed+$courseseed;
10269: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10270: 	#&logthis("rndseed :$num:$symb");
10271: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10272: 	return "$num1,$num2";
10273:     }
10274: }
10275: 
10276: sub rndseed_64bit3 {
10277:     my ($symb,$courseid,$domain,$username)=@_;
10278:     {
10279: 	use integer;
10280: 	# strings need to be an even # of cahracters long, it it is odd the
10281:         # last characters gets thrown away
10282: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10283: 	my $symbseed=numval2($symb) << 10;
10284: 	my $namechck=unpack("%32S*",$username.' ');
10285: 	
10286: 	my $nameseed=numval2($username) << 21;
10287: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10288: 	my $courseseed=unpack("%32S*",$courseid.' ');
10289: 	
10290: 	my $num1=$symbchck+$symbseed+$namechck;
10291: 	my $num2=$nameseed+$domainseed+$courseseed;
10292: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10293: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10294: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10295: 	
10296: 	return "$num1:$num2";
10297:     }
10298: }
10299: 
10300: sub rndseed_64bit4 {
10301:     my ($symb,$courseid,$domain,$username)=@_;
10302:     {
10303: 	use integer;
10304: 	# strings need to be an even # of cahracters long, it it is odd the
10305:         # last characters gets thrown away
10306: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10307: 	my $symbseed=numval3($symb) << 10;
10308: 	my $namechck=unpack("%32S*",$username.' ');
10309: 	
10310: 	my $nameseed=numval3($username) << 21;
10311: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10312: 	my $courseseed=unpack("%32S*",$courseid.' ');
10313: 	
10314: 	my $num1=$symbchck+$symbseed+$namechck;
10315: 	my $num2=$nameseed+$domainseed+$courseseed;
10316: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10317: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10318: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10319: 	
10320: 	return "$num1:$num2";
10321:     }
10322: }
10323: 
10324: sub rndseed_64bit5 {
10325:     my ($symb,$courseid,$domain,$username)=@_;
10326:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10327:     return "$num1:$num2";
10328: }
10329: 
10330: sub rndseed_CODE_64bit {
10331:     my ($symb,$courseid,$domain,$username)=@_;
10332:     {
10333: 	use integer;
10334: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10335: 	my $symbseed=numval2($symb);
10336: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10337: 	my $CODEseed=numval(&getCODE());
10338: 	my $courseseed=unpack("%32S*",$courseid.' ');
10339: 	my $num1=$symbseed+$CODEchck;
10340: 	my $num2=$CODEseed+$courseseed+$symbchck;
10341: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10342: 	#&logthis("rndseed :$num1:$num2:$symb");
10343: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10344: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10345: 	return "$num1:$num2";
10346:     }
10347: }
10348: 
10349: sub rndseed_CODE_64bit4 {
10350:     my ($symb,$courseid,$domain,$username)=@_;
10351:     {
10352: 	use integer;
10353: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10354: 	my $symbseed=numval3($symb);
10355: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10356: 	my $CODEseed=numval3(&getCODE());
10357: 	my $courseseed=unpack("%32S*",$courseid.' ');
10358: 	my $num1=$symbseed+$CODEchck;
10359: 	my $num2=$CODEseed+$courseseed+$symbchck;
10360: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10361: 	#&logthis("rndseed :$num1:$num2:$symb");
10362: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10363: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10364: 	return "$num1:$num2";
10365:     }
10366: }
10367: 
10368: sub rndseed_CODE_64bit5 {
10369:     my ($symb,$courseid,$domain,$username)=@_;
10370:     my $code = &getCODE();
10371:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10372:     return "$num1:$num2";
10373: }
10374: 
10375: sub setup_random_from_rndseed {
10376:     my ($rndseed)=@_;
10377:     if ($rndseed =~/([,:])/) {
10378: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10379: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10380:     } else {
10381: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10382:     }
10383: }
10384: 
10385: sub latest_receipt_algorithm_id {
10386:     return 'receipt3';
10387: }
10388: 
10389: sub recunique {
10390:     my $fucourseid=shift;
10391:     my $unique;
10392:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10393: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10394: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10395:     } else {
10396: 	$unique=$perlvar{'lonReceipt'};
10397:     }
10398:     return unpack("%32C*",$unique);
10399: }
10400: 
10401: sub recprefix {
10402:     my $fucourseid=shift;
10403:     my $prefix;
10404:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10405: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10406: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10407:     } else {
10408: 	$prefix=$perlvar{'lonHostID'};
10409:     }
10410:     return unpack("%32C*",$prefix);
10411: }
10412: 
10413: sub ireceipt {
10414:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10415: 
10416:     my $return =&recprefix($fucourseid).'-';
10417: 
10418:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10419: 	$env{'request.state'} eq 'construct') {
10420: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10421: 	return $return;
10422:     }
10423: 
10424:     my $cuname=unpack("%32C*",$funame);
10425:     my $cudom=unpack("%32C*",$fudom);
10426:     my $cucourseid=unpack("%32C*",$fucourseid);
10427:     my $cusymb=unpack("%32C*",$fusymb);
10428:     my $cunique=&recunique($fucourseid);
10429:     my $cpart=unpack("%32S*",$part);
10430:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10431: 
10432: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10433: 			       
10434: 	$return.= ($cunique%$cuname+
10435: 		   $cunique%$cudom+
10436: 		   $cusymb%$cuname+
10437: 		   $cusymb%$cudom+
10438: 		   $cucourseid%$cuname+
10439: 		   $cucourseid%$cudom+
10440: 		   $cpart%$cuname+
10441: 		   $cpart%$cudom);
10442:     } else {
10443: 	$return.= ($cunique%$cuname+
10444: 		   $cunique%$cudom+
10445: 		   $cusymb%$cuname+
10446: 		   $cusymb%$cudom+
10447: 		   $cucourseid%$cuname+
10448: 		   $cucourseid%$cudom);
10449:     }
10450:     return $return;
10451: }
10452: 
10453: sub receipt {
10454:     my ($part)=@_;
10455:     my ($symb,$courseid,$domain,$name) = &whichuser();
10456:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10457: }
10458: 
10459: sub whichuser {
10460:     my ($passedsymb)=@_;
10461:     my ($symb,$courseid,$domain,$name,$publicuser);
10462:     if (defined($env{'form.grade_symb'})) {
10463: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10464: 	my $allowed=&allowed('vgr',$tmp_courseid);
10465: 	if (!$allowed &&
10466: 	    exists($env{'request.course.sec'}) &&
10467: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10468: 	    $allowed=&allowed('vgr',$tmp_courseid.
10469: 			      '/'.$env{'request.course.sec'});
10470: 	}
10471: 	if ($allowed) {
10472: 	    ($symb)=&get_env_multiple('form.grade_symb');
10473: 	    $courseid=$tmp_courseid;
10474: 	    ($domain)=&get_env_multiple('form.grade_domain');
10475: 	    ($name)=&get_env_multiple('form.grade_username');
10476: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10477: 	}
10478:     }
10479:     if (!$passedsymb) {
10480: 	$symb=&symbread();
10481:     } else {
10482: 	$symb=$passedsymb;
10483:     }
10484:     $courseid=$env{'request.course.id'};
10485:     $domain=$env{'user.domain'};
10486:     $name=$env{'user.name'};
10487:     if ($name eq 'public' && $domain eq 'public') {
10488: 	if (!defined($env{'form.username'})) {
10489: 	    $env{'form.username'}.=time.rand(10000000);
10490: 	}
10491: 	$name.=$env{'form.username'};
10492:     }
10493:     return ($symb,$courseid,$domain,$name,$publicuser);
10494: 
10495: }
10496: 
10497: # ------------------------------------------------------------ Serves up a file
10498: # returns either the contents of the file or 
10499: # -1 if the file doesn't exist
10500: #
10501: # if the target is a file that was uploaded via DOCS, 
10502: # a check will be made to see if a current copy exists on the local server,
10503: # if it does this will be served, otherwise a copy will be retrieved from
10504: # the home server for the course and stored in /home/httpd/html/userfiles on
10505: # the local server.   
10506: 
10507: sub getfile {
10508:     my ($file) = @_;
10509:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10510:     &repcopy($file);
10511:     return &readfile($file);
10512: }
10513: 
10514: sub repcopy_userfile {
10515:     my ($file)=@_;
10516:     my $londocroot = $perlvar{'lonDocRoot'};
10517:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10518:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10519:     my ($cdom,$cnum,$filename) = 
10520: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10521:     my $uri="/uploaded/$cdom/$cnum/$filename";
10522:     if (-e "$file") {
10523: # we already have a local copy, check it out
10524: 	my @fileinfo = stat($file);
10525: 	my $rtncode;
10526: 	my $info;
10527: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10528: 	if ($lwpresp ne 'ok') {
10529: # there is no such file anymore, even though we had a local copy
10530: 	    if ($rtncode eq '404') {
10531: 		unlink($file);
10532: 	    }
10533: 	    return -1;
10534: 	}
10535: 	if ($info < $fileinfo[9]) {
10536: # nice, the file we have is up-to-date, just say okay
10537: 	    return 'ok';
10538: 	} else {
10539: # the file is outdated, get rid of it
10540: 	    unlink($file);
10541: 	}
10542:     }
10543: # one way or the other, at this point, we don't have the file
10544: # construct the correct path for the file
10545:     my @parts = ($cdom,$cnum); 
10546:     if ($filename =~ m|^(.+)/[^/]+$|) {
10547: 	push @parts, split(/\//,$1);
10548:     }
10549:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10550:     foreach my $part (@parts) {
10551: 	$path .= '/'.$part;
10552: 	if (!-e $path) {
10553: 	    mkdir($path,0770);
10554: 	}
10555:     }
10556: # now the path exists for sure
10557: # get a user agent
10558:     my $ua=new LWP::UserAgent;
10559:     my $transferfile=$file.'.in.transfer';
10560: # FIXME: this should flock
10561:     if (-e $transferfile) { return 'ok'; }
10562:     my $request;
10563:     $uri=~s/^\///;
10564:     my $homeserver = &homeserver($cnum,$cdom);
10565:     my $protocol = $protocol{$homeserver};
10566:     $protocol = 'http' if ($protocol ne 'https');
10567:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10568:     my $response=$ua->request($request,$transferfile);
10569: # did it work?
10570:     if ($response->is_error()) {
10571: 	unlink($transferfile);
10572: 	&logthis("Userfile repcopy failed for $uri");
10573: 	return -1;
10574:     }
10575: # worked, rename the transfer file
10576:     rename($transferfile,$file);
10577:     return 'ok';
10578: }
10579: 
10580: sub tokenwrapper {
10581:     my $uri=shift;
10582:     $uri=~s|^https?\://([^/]+)||;
10583:     $uri=~s|^/||;
10584:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10585:     my $token=$1;
10586:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10587:     if ($udom && $uname && $file) {
10588: 	$file=~s|(\?\.*)*$||;
10589:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10590:         my $homeserver = &homeserver($uname,$udom);
10591:         my $protocol = $protocol{$homeserver};
10592:         $protocol = 'http' if ($protocol ne 'https');
10593:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10594:                (($uri=~/\?/)?'&':'?').'token='.$token.
10595:                                '&tokenissued='.$perlvar{'lonHostID'};
10596:     } else {
10597:         return '/adm/notfound.html';
10598:     }
10599: }
10600: 
10601: # call with reqtype HEAD: get last modification time
10602: # call with reqtype GET: get the file contents
10603: # Do not call this with reqtype GET for large files! It loads everything into memory
10604: #
10605: sub getuploaded {
10606:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10607:     $uri=~s/^\///;
10608:     my $homeserver = &homeserver($cnum,$cdom);
10609:     my $protocol = $protocol{$homeserver};
10610:     $protocol = 'http' if ($protocol ne 'https');
10611:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10612:     my $ua=new LWP::UserAgent;
10613:     my $request=new HTTP::Request($reqtype,$uri);
10614:     my $response=$ua->request($request);
10615:     $$rtncode = $response->code;
10616:     if (! $response->is_success()) {
10617: 	return 'failed';
10618:     }      
10619:     if ($reqtype eq 'HEAD') {
10620: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10621:     } elsif ($reqtype eq 'GET') {
10622: 	$$info = $response->content;
10623:     }
10624:     return 'ok';
10625: }
10626: 
10627: sub readfile {
10628:     my $file = shift;
10629:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10630:     my $fh;
10631:     open($fh,"<$file");
10632:     my $a='';
10633:     while (my $line = <$fh>) { $a .= $line; }
10634:     return $a;
10635: }
10636: 
10637: sub filelocation {
10638:     my ($dir,$file) = @_;
10639:     my $location;
10640:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10641: 
10642:     if ($file =~ m-^/adm/-) {
10643: 	$file=~s-^/adm/wrapper/-/-;
10644: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10645:     }
10646: 
10647:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10648:         $location = $file;
10649:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10650:         my ($udom,$uname,$filename)=
10651:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10652:         my $home=&homeserver($uname,$udom);
10653:         my $is_me=0;
10654:         my @ids=&current_machine_ids();
10655:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10656:         if ($is_me) {
10657:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10658:         } else {
10659:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10660:   	      $udom.'/'.$uname.'/'.$filename;
10661:         }
10662:     } elsif ($file =~ m-^/adm/-) {
10663: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10664:     } else {
10665:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10666:         $file=~s:^/(res|priv)/:/:;
10667:         my $space=$1;
10668:         if ( !( $file =~ m:^/:) ) {
10669:             $location = $dir. '/'.$file;
10670:         } else {
10671:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10672:         }
10673:     }
10674:     $location=~s://+:/:g; # remove duplicate /
10675:     while ($location=~m{/\.\./}) {
10676: 	if ($location =~ m{/[^/]+/\.\./}) {
10677: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10678: 	} else {
10679: 	    $location=~ s{/\.\./}{/}g;
10680: 	}
10681:     } #remove dir/..
10682:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10683:     return $location;
10684: }
10685: 
10686: sub hreflocation {
10687:     my ($dir,$file)=@_;
10688:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10689: 	$file=filelocation($dir,$file);
10690:     } elsif ($file=~m-^/adm/-) {
10691: 	$file=~s-^/adm/wrapper/-/-;
10692: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10693:     }
10694:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10695: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10696:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10697: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10698: 	        {/uploaded/$1/$2/}x;
10699:     }
10700:     if ($file=~ m{^/userfiles/}) {
10701: 	$file =~ s{^/userfiles/}{/uploaded/};
10702:     }
10703:     return $file;
10704: }
10705: 
10706: 
10707: 
10708: 
10709: 
10710: sub current_machine_domains {
10711:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10712: }
10713: 
10714: sub machine_domains {
10715:     my ($hostname) = @_;
10716:     my @domains;
10717:     my %hostname = &all_hostnames();
10718:     while( my($id, $name) = each(%hostname)) {
10719: #	&logthis("-$id-$name-$hostname-");
10720: 	if ($hostname eq $name) {
10721: 	    push(@domains,&host_domain($id));
10722: 	}
10723:     }
10724:     return @domains;
10725: }
10726: 
10727: sub current_machine_ids {
10728:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10729: }
10730: 
10731: sub machine_ids {
10732:     my ($hostname) = @_;
10733:     $hostname ||= &hostname($perlvar{'lonHostID'});
10734:     my @ids;
10735:     my %name_to_host = &all_names();
10736:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10737: 	return @{ $name_to_host{$hostname} };
10738:     }
10739:     return;
10740: }
10741: 
10742: sub additional_machine_domains {
10743:     my @domains;
10744:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10745:     while( my $line = <$fh>) {
10746:         $line =~ s/\s//g;
10747:         push(@domains,$line);
10748:     }
10749:     return @domains;
10750: }
10751: 
10752: sub default_login_domain {
10753:     my $domain = $perlvar{'lonDefDomain'};
10754:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10755:     foreach my $posdom (&current_machine_domains(),
10756:                         &additional_machine_domains()) {
10757:         if (lc($posdom) eq lc($testdomain)) {
10758:             $domain=$posdom;
10759:             last;
10760:         }
10761:     }
10762:     return $domain;
10763: }
10764: 
10765: # ------------------------------------------------------------- Declutters URLs
10766: 
10767: sub declutter {
10768:     my $thisfn=shift;
10769:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10770:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10771:     $thisfn=~s/^\///;
10772:     $thisfn=~s|^adm/wrapper/||;
10773:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10774:     $thisfn=~s/^res\///;
10775:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10776:         $thisfn=~s/\?.+$//;
10777:     }
10778:     return $thisfn;
10779: }
10780: 
10781: # ------------------------------------------------------------- Clutter up URLs
10782: 
10783: sub clutter {
10784:     my $thisfn='/'.&declutter(shift);
10785:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10786: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10787:        $thisfn='/res'.$thisfn; 
10788:     }
10789:     if ($thisfn !~m|^/adm|) {
10790: 	if ($thisfn =~ m|^/ext/|) {
10791: 	    $thisfn='/adm/wrapper'.$thisfn;
10792: 	} else {
10793: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10794: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10795: 	    if ($embstyle eq 'ssi'
10796: 		|| ($embstyle eq 'hdn')
10797: 		|| ($embstyle eq 'rat')
10798: 		|| ($embstyle eq 'prv')
10799: 		|| ($embstyle eq 'ign')) {
10800: 		#do nothing with these
10801: 	    } elsif (($embstyle eq 'img') 
10802: 		|| ($embstyle eq 'emb')
10803: 		|| ($embstyle eq 'wrp')) {
10804: 		$thisfn='/adm/wrapper'.$thisfn;
10805: 	    } elsif ($embstyle eq 'unk'
10806: 		     && $thisfn!~/\.(sequence|page)$/) {
10807: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10808: 	    } else {
10809: #		&logthis("Got a blank emb style");
10810: 	    }
10811: 	}
10812:     }
10813:     return $thisfn;
10814: }
10815: 
10816: sub clutter_with_no_wrapper {
10817:     my $uri = &clutter(shift);
10818:     if ($uri =~ m-^/adm/-) {
10819: 	$uri =~ s-^/adm/wrapper/-/-;
10820: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10821:     }
10822:     return $uri;
10823: }
10824: 
10825: sub freeze_escape {
10826:     my ($value)=@_;
10827:     if (ref($value)) {
10828: 	$value=&nfreeze($value);
10829: 	return '__FROZEN__'.&escape($value);
10830:     }
10831:     return &escape($value);
10832: }
10833: 
10834: 
10835: sub thaw_unescape {
10836:     my ($value)=@_;
10837:     if ($value =~ /^__FROZEN__/) {
10838: 	substr($value,0,10,undef);
10839: 	$value=&unescape($value);
10840: 	return &thaw($value);
10841:     }
10842:     return &unescape($value);
10843: }
10844: 
10845: sub correct_line_ends {
10846:     my ($result)=@_;
10847:     $$result =~s/\r\n/\n/mg;
10848:     $$result =~s/\r/\n/mg;
10849: }
10850: # ================================================================ Main Program
10851: 
10852: sub goodbye {
10853:    &logthis("Starting Shut down");
10854: #not converted to using infrastruture and probably shouldn't be
10855:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10856: #converted
10857: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10858:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10859: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10860: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10861: #1.1 only
10862: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10863: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10864: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10865: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10866:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10867:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10868:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10869:    &flushcourselogs();
10870:    &logthis("Shutting down");
10871: }
10872: 
10873: sub get_dns {
10874:     my ($url,$func,$ignore_cache) = @_;
10875:     if (!$ignore_cache) {
10876: 	my ($content,$cached)=
10877: 	    &Apache::lonnet::is_cached_new('dns',$url);
10878: 	if ($cached) {
10879: 	    &$func($content);
10880: 	    return;
10881: 	}
10882:     }
10883: 
10884:     my %alldns;
10885:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10886:     foreach my $dns (<$config>) {
10887: 	next if ($dns !~ /^\^(\S*)/x);
10888:         my $line = $1;
10889:         my ($host,$protocol) = split(/:/,$line);
10890:         if ($protocol ne 'https') {
10891:             $protocol = 'http';
10892:         }
10893: 	$alldns{$host} = $protocol;
10894:     }
10895:     while (%alldns) {
10896: 	my ($dns) = keys(%alldns);
10897: 	my $ua=new LWP::UserAgent;
10898:         $ua->timeout(30);
10899: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10900: 	my $response=$ua->request($request);
10901:         delete($alldns{$dns});
10902: 	next if ($response->is_error());
10903: 	my @content = split("\n",$response->content);
10904: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10905: 	&$func(\@content);
10906: 	return;
10907:     }
10908:     close($config);
10909:     my $which = (split('/',$url))[3];
10910:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10911:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10912:     my @content = <$config>;
10913:     &$func(\@content);
10914:     return;
10915: }
10916: # ------------------------------------------------------------ Read domain file
10917: {
10918:     my $loaded;
10919:     my %domain;
10920: 
10921:     sub parse_domain_tab {
10922: 	my ($lines) = @_;
10923: 	foreach my $line (@$lines) {
10924: 	    next if ($line =~ /^(\#|\s*$ )/x);
10925: 
10926: 	    chomp($line);
10927: 	    my ($name,@elements) = split(/:/,$line,9);
10928: 	    my %this_domain;
10929: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10930: 			       'lang_def', 'city', 'longi', 'lati',
10931: 			       'primary') {
10932: 		$this_domain{$field} = shift(@elements);
10933: 	    }
10934: 	    $domain{$name} = \%this_domain;
10935: 	}
10936:     }
10937: 
10938:     sub reset_domain_info {
10939: 	undef($loaded);
10940: 	undef(%domain);
10941:     }
10942: 
10943:     sub load_domain_tab {
10944: 	my ($ignore_cache) = @_;
10945: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10946: 	my $fh;
10947: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10948: 	    my @lines = <$fh>;
10949: 	    &parse_domain_tab(\@lines);
10950: 	}
10951: 	close($fh);
10952: 	$loaded = 1;
10953:     }
10954: 
10955:     sub domain {
10956: 	&load_domain_tab() if (!$loaded);
10957: 
10958: 	my ($name,$what) = @_;
10959: 	return if ( !exists($domain{$name}) );
10960: 
10961: 	if (!$what) {
10962: 	    return $domain{$name}{'description'};
10963: 	}
10964: 	return $domain{$name}{$what};
10965:     }
10966: 
10967:     sub domain_info {
10968:         &load_domain_tab() if (!$loaded);
10969:         return %domain;
10970:     }
10971: 
10972: }
10973: 
10974: 
10975: # ------------------------------------------------------------- Read hosts file
10976: {
10977:     my %hostname;
10978:     my %hostdom;
10979:     my %libserv;
10980:     my $loaded;
10981:     my %name_to_host;
10982:     my %internetdom;
10983:     my %LC_dns_serv;
10984: 
10985:     sub parse_hosts_tab {
10986: 	my ($file) = @_;
10987: 	foreach my $configline (@$file) {
10988: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10989:             chomp($configline);
10990: 	    if ($configline =~ /^\^/) {
10991:                 if ($configline =~ /^\^([\w.\-]+)/) {
10992:                     $LC_dns_serv{$1} = 1;
10993:                 }
10994:                 next;
10995:             }
10996: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10997: 	    $name=~s/\s//g;
10998: 	    if ($id && $domain && $role && $name) {
10999: 		$hostname{$id}=$name;
11000: 		push(@{$name_to_host{$name}}, $id);
11001: 		$hostdom{$id}=$domain;
11002: 		if ($role eq 'library') { $libserv{$id}=$name; }
11003:                 if (defined($protocol)) {
11004:                     if ($protocol eq 'https') {
11005:                         $protocol{$id} = $protocol;
11006:                     } else {
11007:                         $protocol{$id} = 'http'; 
11008:                     }
11009:                 } else {
11010:                     $protocol{$id} = 'http';
11011:                 }
11012:                 if (defined($intdom)) {
11013:                     $internetdom{$id} = $intdom;
11014:                 }
11015: 	    }
11016: 	}
11017:     }
11018:     
11019:     sub reset_hosts_info {
11020: 	&purge_remembered();
11021: 	&reset_domain_info();
11022: 	&reset_hosts_ip_info();
11023: 	undef(%name_to_host);
11024: 	undef(%hostname);
11025: 	undef(%hostdom);
11026: 	undef(%libserv);
11027: 	undef($loaded);
11028:     }
11029: 
11030:     sub load_hosts_tab {
11031: 	my ($ignore_cache) = @_;
11032: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11033: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11034: 	my @config = <$config>;
11035: 	&parse_hosts_tab(\@config);
11036: 	close($config);
11037: 	$loaded=1;
11038:     }
11039: 
11040:     sub hostname {
11041: 	&load_hosts_tab() if (!$loaded);
11042: 
11043: 	my ($lonid) = @_;
11044: 	return $hostname{$lonid};
11045:     }
11046: 
11047:     sub all_hostnames {
11048: 	&load_hosts_tab() if (!$loaded);
11049: 
11050: 	return %hostname;
11051:     }
11052: 
11053:     sub all_names {
11054: 	&load_hosts_tab() if (!$loaded);
11055: 
11056: 	return %name_to_host;
11057:     }
11058: 
11059:     sub all_host_domain {
11060:         &load_hosts_tab() if (!$loaded);
11061:         return %hostdom;
11062:     }
11063: 
11064:     sub is_library {
11065: 	&load_hosts_tab() if (!$loaded);
11066: 
11067: 	return exists($libserv{$_[0]});
11068:     }
11069: 
11070:     sub all_library {
11071: 	&load_hosts_tab() if (!$loaded);
11072: 
11073: 	return %libserv;
11074:     }
11075: 
11076:     sub unique_library {
11077: 	#2x reverse removes all hostnames that appear more than once
11078:         my %unique = reverse &all_library();
11079:         return reverse %unique;
11080:     }
11081: 
11082:     sub get_servers {
11083: 	&load_hosts_tab() if (!$loaded);
11084: 
11085: 	my ($domain,$type) = @_;
11086: 	my %possible_hosts = ($type eq 'library') ? %libserv
11087: 	                                          : %hostname;
11088: 	my %result;
11089: 	if (ref($domain) eq 'ARRAY') {
11090: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11091: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11092: 		    $result{$host} = $hostname;
11093: 		}
11094: 	    }
11095: 	} else {
11096: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11097: 		if ($hostdom{$host} eq $domain) {
11098: 		    $result{$host} = $hostname;
11099: 		}
11100: 	    }
11101: 	}
11102: 	return %result;
11103:     }
11104: 
11105:     sub get_unique_servers {
11106:         my %unique = reverse &get_servers(@_);
11107: 	return reverse %unique;
11108:     }
11109: 
11110:     sub host_domain {
11111: 	&load_hosts_tab() if (!$loaded);
11112: 
11113: 	my ($lonid) = @_;
11114: 	return $hostdom{$lonid};
11115:     }
11116: 
11117:     sub all_domains {
11118: 	&load_hosts_tab() if (!$loaded);
11119: 
11120: 	my %seen;
11121: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11122: 	return @uniq;
11123:     }
11124: 
11125:     sub internet_dom {
11126:         &load_hosts_tab() if (!$loaded);
11127: 
11128:         my ($lonid) = @_;
11129:         return $internetdom{$lonid};
11130:     }
11131: 
11132:     sub is_LC_dns {
11133:         &load_hosts_tab() if (!$loaded);
11134: 
11135:         my ($hostname) = @_;
11136:         return exists($LC_dns_serv{$hostname});
11137:     }
11138: 
11139: }
11140: 
11141: { 
11142:     my %iphost;
11143:     my %name_to_ip;
11144:     my %lonid_to_ip;
11145: 
11146:     sub get_hosts_from_ip {
11147: 	my ($ip) = @_;
11148: 	my %iphosts = &get_iphost();
11149: 	if (ref($iphosts{$ip})) {
11150: 	    return @{$iphosts{$ip}};
11151: 	}
11152: 	return;
11153:     }
11154:     
11155:     sub reset_hosts_ip_info {
11156: 	undef(%iphost);
11157: 	undef(%name_to_ip);
11158: 	undef(%lonid_to_ip);
11159:     }
11160: 
11161:     sub get_host_ip {
11162: 	my ($lonid) = @_;
11163: 	if (exists($lonid_to_ip{$lonid})) {
11164: 	    return $lonid_to_ip{$lonid};
11165: 	}
11166: 	my $name=&hostname($lonid);
11167:    	my $ip = gethostbyname($name);
11168: 	return if (!$ip || length($ip) ne 4);
11169: 	$ip=inet_ntoa($ip);
11170: 	$name_to_ip{$name}   = $ip;
11171: 	$lonid_to_ip{$lonid} = $ip;
11172: 	return $ip;
11173:     }
11174:     
11175:     sub get_iphost {
11176: 	my ($ignore_cache) = @_;
11177: 
11178: 	if (!$ignore_cache) {
11179: 	    if (%iphost) {
11180: 		return %iphost;
11181: 	    }
11182: 	    my ($ip_info,$cached)=
11183: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11184: 	    if ($cached) {
11185: 		%iphost      = %{$ip_info->[0]};
11186: 		%name_to_ip  = %{$ip_info->[1]};
11187: 		%lonid_to_ip = %{$ip_info->[2]};
11188: 		return %iphost;
11189: 	    }
11190: 	}
11191: 
11192: 	# get yesterday's info for fallback
11193: 	my %old_name_to_ip;
11194: 	my ($ip_info,$cached)=
11195: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11196: 	if ($cached) {
11197: 	    %old_name_to_ip = %{$ip_info->[1]};
11198: 	}
11199: 
11200: 	my %name_to_host = &all_names();
11201: 	foreach my $name (keys(%name_to_host)) {
11202: 	    my $ip;
11203: 	    if (!exists($name_to_ip{$name})) {
11204: 		$ip = gethostbyname($name);
11205: 		if (!$ip || length($ip) ne 4) {
11206: 		    if (defined($old_name_to_ip{$name})) {
11207: 			$ip = $old_name_to_ip{$name};
11208: 			&logthis("Can't find $name defaulting to old $ip");
11209: 		    } else {
11210: 			&logthis("Name $name no IP found");
11211: 			next;
11212: 		    }
11213: 		} else {
11214: 		    $ip=inet_ntoa($ip);
11215: 		}
11216: 		$name_to_ip{$name} = $ip;
11217: 	    } else {
11218: 		$ip = $name_to_ip{$name};
11219: 	    }
11220: 	    foreach my $id (@{ $name_to_host{$name} }) {
11221: 		$lonid_to_ip{$id} = $ip;
11222: 	    }
11223: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11224: 	}
11225: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11226: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11227: 				      48*60*60);
11228: 
11229: 	return %iphost;
11230:     }
11231: 
11232:     #
11233:     #  Given a DNS returns the loncapa host name for that DNS 
11234:     # 
11235:     sub host_from_dns {
11236:         my ($dns) = @_;
11237:         my @hosts;
11238:         my $ip;
11239: 
11240:         if (exists($name_to_ip{$dns})) {
11241:             $ip = $name_to_ip{$dns};
11242:         }
11243:         if (!$ip) {
11244:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11245:             if (length($ip) == 4) { 
11246: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11247:             }
11248:         }
11249:         if ($ip) {
11250: 	    @hosts = get_hosts_from_ip($ip);
11251: 	    return $hosts[0];
11252:         }
11253:         return undef;
11254:     }
11255: 
11256:     sub get_internet_names {
11257:         my ($lonid) = @_;
11258:         return if ($lonid eq '');
11259:         my ($idnref,$cached)=
11260:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11261:         if ($cached) {
11262:             return $idnref;
11263:         }
11264:         my $ip = &get_host_ip($lonid);
11265:         my @hosts = &get_hosts_from_ip($ip);
11266:         my %iphost = &get_iphost();
11267:         my (@idns,%seen);
11268:         foreach my $id (@hosts) {
11269:             my $dom = &host_domain($id);
11270:             my $prim_id = &domain($dom,'primary');
11271:             my $prim_ip = &get_host_ip($prim_id);
11272:             next if ($seen{$prim_ip});
11273:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11274:                 foreach my $id (@{$iphost{$prim_ip}}) {
11275:                     my $intdom = &internet_dom($id);
11276:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11277:                         push(@idns,$intdom);
11278:                     }
11279:                 }
11280:             }
11281:             $seen{$prim_ip} = 1;
11282:         }
11283:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11284:     }
11285: 
11286: }
11287: 
11288: sub all_loncaparevs {
11289:     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);
11290: }
11291: 
11292: BEGIN {
11293: 
11294: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11295:     unless ($readit) {
11296: {
11297:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11298:     %perlvar = (%perlvar,%{$configvars});
11299: }
11300: 
11301: 
11302: # ------------------------------------------------------ Read spare server file
11303: {
11304:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11305: 
11306:     while (my $configline=<$config>) {
11307:        chomp($configline);
11308:        if ($configline) {
11309: 	   my ($host,$type) = split(':',$configline,2);
11310: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11311: 	   push(@{ $spareid{$type} }, $host);
11312:        }
11313:     }
11314:     close($config);
11315: }
11316: # ------------------------------------------------------------ Read permissions
11317: {
11318:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11319: 
11320:     while (my $configline=<$config>) {
11321: 	chomp($configline);
11322: 	if ($configline) {
11323: 	    my ($role,$perm)=split(/ /,$configline);
11324: 	    if ($perm ne '') { $pr{$role}=$perm; }
11325: 	}
11326:     }
11327:     close($config);
11328: }
11329: 
11330: # -------------------------------------------- Read plain texts for permissions
11331: {
11332:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11333: 
11334:     while (my $configline=<$config>) {
11335: 	chomp($configline);
11336: 	if ($configline) {
11337: 	    my ($short,@plain)=split(/:/,$configline);
11338:             %{$prp{$short}} = ();
11339: 	    if (@plain > 0) {
11340:                 $prp{$short}{'std'} = $plain[0];
11341:                 for (my $i=1; $i<@plain; $i++) {
11342:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11343:                 }
11344:             }
11345: 	}
11346:     }
11347:     close($config);
11348: }
11349: 
11350: # ---------------------------------------------------------- Read package table
11351: {
11352:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11353: 
11354:     while (my $configline=<$config>) {
11355: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11356: 	chomp($configline);
11357: 	my ($short,$plain)=split(/:/,$configline);
11358: 	my ($pack,$name)=split(/\&/,$short);
11359: 	if ($plain ne '') {
11360: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11361: 	    $packagetab{$short}=$plain; 
11362: 	}
11363:     }
11364:     close($config);
11365: }
11366: 
11367: # ---------------------------------------------------------- Read loncaparev table
11368: {
11369:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11370:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11371:             while (my $configline=<$config>) {
11372:                 chomp($configline);
11373:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11374:                 $loncaparevs{$hostid}=$loncaparev;
11375:             }
11376:             close($config);
11377:         }
11378:     }
11379: }
11380: 
11381: # ---------------------------------------------------------- Read serverhostID table
11382: {
11383:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11384:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11385:             while (my $configline=<$config>) {
11386:                 chomp($configline);
11387:                 my ($name,$id)=split(/:/,$configline);
11388:                 $serverhomeIDs{$name}=$id;
11389:             }
11390:             close($config);
11391:         }
11392:     }
11393: }
11394: 
11395: {
11396:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11397:     if (-e $file) {
11398:         my $parser = HTML::LCParser->new($file);
11399:         while (my $token = $parser->get_token()) {
11400:             if ($token->[0] eq 'S') {
11401:                 my $item = $token->[1];
11402:                 my $name = $token->[2]{'name'};
11403:                 my $value = $token->[2]{'value'};
11404:                 if ($item ne '' && $name ne '' && $value ne '') {
11405:                     my $release = $parser->get_text();
11406:                     $release =~ s/(^\s*|\s*$ )//gx;
11407:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11408:                 }
11409:             }
11410:         }
11411:     }
11412: }
11413: 
11414: # ---------------------------------------------------------- Read managers table
11415: {
11416:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11417:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11418:             while (my $configline=<$config>) {
11419:                 chomp($configline);
11420:                 next if ($configline =~ /^\#/);
11421:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11422:                     $managerstab{$configline} = 1;
11423:                 }
11424:             }
11425:             close($config);
11426:         }
11427:     }
11428: }
11429: 
11430: # ------------- set up temporary directory
11431: {
11432:     $tmpdir = LONCAPA::tempdir();
11433: 
11434: }
11435: 
11436: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11437: 				'compress_threshold'=> 20_000,
11438:  			        });
11439: 
11440: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11441: $dumpcount=0;
11442: $locknum=0;
11443: 
11444: &logtouch();
11445: &logthis('<font color="yellow">INFO: Read configuration</font>');
11446: $readit=1;
11447:     {
11448: 	use integer;
11449: 	my $test=(2**32)+1;
11450: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11451: 	&logthis(" Detected 64bit platform ($_64bit)");
11452:     }
11453: }
11454: }
11455: 
11456: 1;
11457: __END__
11458: 
11459: =pod
11460: 
11461: =head1 NAME
11462: 
11463: Apache::lonnet - Subroutines to ask questions about things in the network.
11464: 
11465: =head1 SYNOPSIS
11466: 
11467: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11468: 
11469:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11470: 
11471: Common parameters:
11472: 
11473: =over 4
11474: 
11475: =item *
11476: 
11477: $uname : an internal username (if $cname expecting a course Id specifically)
11478: 
11479: =item *
11480: 
11481: $udom : a domain (if $cdom expecting a course's domain specifically)
11482: 
11483: =item *
11484: 
11485: $symb : a resource instance identifier
11486: 
11487: =item *
11488: 
11489: $namespace : the name of a .db file that contains the data needed or
11490: being set.
11491: 
11492: =back
11493: 
11494: =head1 OVERVIEW
11495: 
11496: lonnet provides subroutines which interact with the
11497: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11498: about classes, users, and resources.
11499: 
11500: For many of these objects you can also use this to store data about
11501: them or modify them in various ways.
11502: 
11503: =head2 Symbs
11504: 
11505: To identify a specific instance of a resource, LON-CAPA uses symbols
11506: or "symbs"X<symb>. These identifiers are built from the URL of the
11507: map, the resource number of the resource in the map, and the URL of
11508: the resource itself. The latter is somewhat redundant, but might help
11509: if maps change.
11510: 
11511: An example is
11512: 
11513:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11514: 
11515: The respective map entry is
11516: 
11517:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11518:   title="Problem 2">
11519:  </resource>
11520: 
11521: Symbs are used by the random number generator, as well as to store and
11522: restore data specific to a certain instance of for example a problem.
11523: 
11524: =head2 Storing And Retrieving Data
11525: 
11526: X<store()>X<cstore()>X<restore()>Three of the most important functions
11527: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11528: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11529: is is the non-critical message twin of cstore. These functions are for
11530: handlers to store a perl hash to a user's permanent data space in an
11531: easy manner, and to retrieve it again on another call. It is expected
11532: that a handler would use this once at the beginning to retrieve data,
11533: and then again once at the end to send only the new data back.
11534: 
11535: The data is stored in the user's data directory on the user's
11536: homeserver under the ID of the course.
11537: 
11538: The hash that is returned by restore will have all of the previous
11539: value for all of the elements of the hash.
11540: 
11541: Example:
11542: 
11543:  #creating a hash
11544:  my %hash;
11545:  $hash{'foo'}='bar';
11546: 
11547:  #storing it
11548:  &Apache::lonnet::cstore(\%hash);
11549: 
11550:  #changing a value
11551:  $hash{'foo'}='notbar';
11552: 
11553:  #adding a new value
11554:  $hash{'bar'}='foo';
11555:  &Apache::lonnet::cstore(\%hash);
11556: 
11557:  #retrieving the hash
11558:  my %history=&Apache::lonnet::restore();
11559: 
11560:  #print the hash
11561:  foreach my $key (sort(keys(%history))) {
11562:    print("\%history{$key} = $history{$key}");
11563:  }
11564: 
11565: Will print out:
11566: 
11567:  %history{1:foo} = bar
11568:  %history{1:keys} = foo:timestamp
11569:  %history{1:timestamp} = 990455579
11570:  %history{2:bar} = foo
11571:  %history{2:foo} = notbar
11572:  %history{2:keys} = foo:bar:timestamp
11573:  %history{2:timestamp} = 990455580
11574:  %history{bar} = foo
11575:  %history{foo} = notbar
11576:  %history{timestamp} = 990455580
11577:  %history{version} = 2
11578: 
11579: Note that the special hash entries C<keys>, C<version> and
11580: C<timestamp> were added to the hash. C<version> will be equal to the
11581: total number of versions of the data that have been stored. The
11582: C<timestamp> attribute will be the UNIX time the hash was
11583: stored. C<keys> is available in every historical section to list which
11584: keys were added or changed at a specific historical revision of a
11585: hash.
11586: 
11587: B<Warning>: do not store the hash that restore returns directly. This
11588: will cause a mess since it will restore the historical keys as if the
11589: were new keys. I.E. 1:foo will become 1:1:foo etc.
11590: 
11591: Calling convention:
11592: 
11593:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11594:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11595: 
11596: For more detailed information, see lonnet specific documentation.
11597: 
11598: =head1 RETURN MESSAGES
11599: 
11600: =over 4
11601: 
11602: =item * B<con_lost>: unable to contact remote host
11603: 
11604: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11605: when the connection is brought back up
11606: 
11607: =item * B<con_failed>: unable to contact remote host and unable to save message
11608: for later delivery
11609: 
11610: =item * B<error:>: an error a occurred, a description of the error follows the :
11611: 
11612: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11613: that was requested
11614: 
11615: =back
11616: 
11617: =head1 PUBLIC SUBROUTINES
11618: 
11619: =head2 Session Environment Functions
11620: 
11621: =over 4
11622: 
11623: =item * 
11624: X<appenv()>
11625: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11626: the user envirnoment file, and will be restored for each access this
11627: user makes during this session, also modifies the %env for the current
11628: process. Optional rolesarrayref - if defined contains a reference to an array
11629: of roles which are exempt from the restriction on modifying user.role entries 
11630: in the user's environment.db and in %env.    
11631: 
11632: =item *
11633: X<delenv()>
11634: B<delenv($delthis,$regexp)>: removes all items from the session
11635: environment file that begin with $delthis. If the 
11636: optional second arg - $regexp - is true, $delthis is treated as a 
11637: regular expression, otherwise \Q$delthis\E is used. 
11638: The values are also deleted from the current processes %env.
11639: 
11640: =item * get_env_multiple($name) 
11641: 
11642: gets $name from the %env hash, it seemlessly handles the cases where multiple
11643: values may be defined and end up as an array ref.
11644: 
11645: returns an array of values
11646: 
11647: =back
11648: 
11649: =head2 User Information
11650: 
11651: =over 4
11652: 
11653: =item *
11654: X<queryauthenticate()>
11655: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11656: authentication scheme
11657: 
11658: =item *
11659: X<authenticate()>
11660: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11661: authenticate user from domain's lib servers (first use the current
11662: one). C<$upass> should be the users password.
11663: $checkdefauth is optional (value is 1 if a check should be made to
11664:    authenticate user using default authentication method, and allow
11665:    account creation if username does not have account in the domain).
11666: $clientcancheckhost is optional (value is 1 if checking whether the
11667:    server can host will occur on the client side in lonauth.pm).   
11668: 
11669: =item *
11670: X<homeserver()>
11671: B<homeserver($uname,$udom)>: find the server which has
11672: the user's directory and files (there must be only one), this caches
11673: the answer, and also caches if there is a borken connection.
11674: 
11675: =item *
11676: X<idget()>
11677: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11678: (IDs are a unique resource in a domain, there must be only 1 ID per
11679: username, and only 1 username per ID in a specific domain) (returns
11680: hash: id=>name,id=>name)
11681: 
11682: =item *
11683: X<idrget()>
11684: B<idrget($udom,@unames)>: find the IDs behind a list of
11685: usernames (returns hash: name=>id,name=>id)
11686: 
11687: =item *
11688: X<idput()>
11689: B<idput($udom,%ids)>: store away a list of names and associated IDs
11690: 
11691: =item *
11692: X<rolesinit()>
11693: B<rolesinit($udom,$username,$authhost)>: get user privileges
11694: 
11695: =item *
11696: X<getsection()>
11697: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11698: course $cname, return section name/number or '' for "not in course"
11699: and '-1' for "no section"
11700: 
11701: =item *
11702: X<userenvironment()>
11703: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11704: passed in @what from the requested user's environment, returns a hash
11705: 
11706: =item * 
11707: X<userlog_query()>
11708: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11709: activity.log file. %filters defines filters applied when parsing the
11710: log file. These can be start or end timestamps, or the type of action
11711: - log to look for Login or Logout events, check for Checkin or
11712: Checkout, role for role selection. The response is in the form
11713: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11714: escaped strings of the action recorded in the activity.log file.
11715: 
11716: =back
11717: 
11718: =head2 User Roles
11719: 
11720: =over 4
11721: 
11722: =item *
11723: 
11724: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11725:  F: full access
11726:  U,I,K: authentication modes (cxx only)
11727:  '': forbidden
11728:  1: user needs to choose course
11729:  2: browse allowed
11730:  A: passphrase authentication needed
11731: 
11732: =item *
11733: 
11734: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11735: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11736: and course level
11737: 
11738: =item *
11739: 
11740: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11741: (rolesplain.tab); plain text explanation of a user role term.
11742: $type is Course (default) or Community.
11743: If $forcedefault evaluates to true, text returned will be default 
11744: text for $type. Otherwise, if this is a course, the text returned 
11745: will be a custom name for the role (if defined in the course's 
11746: environment).  If no custom name is defined the default is returned.
11747:    
11748: =item *
11749: 
11750: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11751: All arguments are optional. Returns a hash of a roles, either for
11752: co-author/assistant author roles for a user's Construction Space
11753: (default), or if $context is 'userroles', roles for the user himself,
11754: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11755: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11756: For each key, value is set to colon-separated start and end times for
11757: the role.  If no username and domain are specified, will default to
11758: current user/domain. Types, roles, and roledoms are references to arrays
11759: of role statuses (active, future or previous), roles 
11760: (e.g., cc,in, st etc.) and domains of the roles which can be used
11761: to restrict the list of roles reported. If no array ref is 
11762: provided for types, will default to return only active roles.
11763: 
11764: =back
11765: 
11766: =head2 User Modification
11767: 
11768: =over 4
11769: 
11770: =item *
11771: 
11772: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11773: user for the level given by URL.  Optional start and end dates (leave empty
11774: string or zero for "no date")
11775: 
11776: =item *
11777: 
11778: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11779: change a users, password, possible return values are: ok,
11780: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11781: refused
11782: 
11783: =item *
11784: 
11785: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11786: 
11787: =item *
11788: 
11789: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11790:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11791: 
11792: will update user information (firstname,middlename,lastname,generation,
11793: permanentemail), and if forceid is true, student/employee ID also.
11794: A user's institutional affiliation(s) can also be updated.
11795: User information fields will not be overwritten with empty entries 
11796: unless the field is included in the $candelete array reference.
11797: This array is included when a single user is modified via "Manage Users",
11798: or when Autoupdate.pl is run by cron in a domain.
11799: 
11800: =item *
11801: 
11802: modifystudent
11803: 
11804: modify a student's enrollment and identification information.
11805: The course id is resolved based on the current users environment.  
11806: This means the envoking user must be a course coordinator or otherwise
11807: associated with a course.
11808: 
11809: This call is essentially a wrapper for lonnet::modifyuser and
11810: lonnet::modify_student_enrollment
11811: 
11812: Inputs: 
11813: 
11814: =over 4
11815: 
11816: =item B<$udom> Student's loncapa domain
11817: 
11818: =item B<$uname> Student's loncapa login name
11819: 
11820: =item B<$uid> Student/Employee ID
11821: 
11822: =item B<$umode> Student's authentication mode
11823: 
11824: =item B<$upass> Student's password
11825: 
11826: =item B<$first> Student's first name
11827: 
11828: =item B<$middle> Student's middle name
11829: 
11830: =item B<$last> Student's last name
11831: 
11832: =item B<$gene> Student's generation
11833: 
11834: =item B<$usec> Student's section in course
11835: 
11836: =item B<$end> Unix time of the roles expiration
11837: 
11838: =item B<$start> Unix time of the roles start date
11839: 
11840: =item B<$forceid> If defined, allow $uid to be changed
11841: 
11842: =item B<$desiredhome> server to use as home server for student
11843: 
11844: =item B<$email> Student's permanent e-mail address
11845: 
11846: =item B<$type> Type of enrollment (auto or manual)
11847: 
11848: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11849: 
11850: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11851: 
11852: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11853: 
11854: =item B<$context> role change context (shown in User Management Logs display in a course)
11855: 
11856: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11857: 
11858: =back
11859: 
11860: =item *
11861: 
11862: modify_student_enrollment
11863: 
11864: Change a students enrollment status in a class.  The environment variable
11865: 'role.request.course' must be defined for this function to proceed.
11866: 
11867: Inputs:
11868: 
11869: =over 4
11870: 
11871: =item $udom, students domain
11872: 
11873: =item $uname, students name
11874: 
11875: =item $uid, students user id
11876: 
11877: =item $first, students first name
11878: 
11879: =item $middle
11880: 
11881: =item $last
11882: 
11883: =item $gene
11884: 
11885: =item $usec
11886: 
11887: =item $end
11888: 
11889: =item $start
11890: 
11891: =item $type
11892: 
11893: =item $locktype
11894: 
11895: =item $cid
11896: 
11897: =item $selfenroll
11898: 
11899: =item $context
11900: 
11901: =back
11902: 
11903: 
11904: =item *
11905: 
11906: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11907: custom role; give a custom role to a user for the level given by URL.  Specify
11908: name and domain of role author, and role name
11909: 
11910: =item *
11911: 
11912: revokerole($udom,$uname,$url,$role) : revoke a role for url
11913: 
11914: =item *
11915: 
11916: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11917: 
11918: =back
11919: 
11920: =head2 Course Infomation
11921: 
11922: =over 4
11923: 
11924: =item *
11925: 
11926: coursedescription($courseid,$options) : returns a hash of information about the
11927: specified course id, including all environment settings for the
11928: course, the description of the course will be in the hash under the
11929: key 'description'
11930: 
11931: $options is an optional parameter that if supplied is a hash reference that controls
11932: what how this function works.  It has the following key/values:
11933: 
11934: =over 4
11935: 
11936: =item freshen_cache
11937: 
11938: If defined, and the environment cache for the course is valid, it is 
11939: returned in the returned hash.
11940: 
11941: =item one_time
11942: 
11943: If defined, the last cache time is set to _now_
11944: 
11945: =item user
11946: 
11947: If defined, the supplied username is used instead of the current user.
11948: 
11949: 
11950: =back
11951: 
11952: =item *
11953: 
11954: resdata($name,$domain,$type,@which) : request for current parameter
11955: setting for a specific $type, where $type is either 'course' or 'user',
11956: @what should be a list of parameters to ask about. This routine caches
11957: answers for 5 minutes.
11958: 
11959: =item *
11960: 
11961: get_courseresdata($courseid, $domain) : dump the entire course resource
11962: data base, returning a hash that is keyed by the resource name and has
11963: values that are the resource value.  I believe that the timestamps and
11964: versions are also returned.
11965: 
11966: 
11967: =back
11968: 
11969: =head2 Course Modification
11970: 
11971: =over 4
11972: 
11973: =item *
11974: 
11975: writecoursepref($courseid,%prefs) : write preferences (environment
11976: database) for a course
11977: 
11978: =item *
11979: 
11980: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11981: 
11982: =item *
11983: 
11984: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11985: 
11986: =back
11987: 
11988: =head2 Resource Subroutines
11989: 
11990: =over 4
11991: 
11992: =item *
11993: 
11994: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11995: 
11996: =item *
11997: 
11998: repcopy($filename) : subscribes to the requested file, and attempts to
11999: replicate from the owning library server, Might return
12000: 'unavailable', 'not_found', 'forbidden', 'ok', or
12001: 'bad_request', also attempts to grab the metadata for the
12002: resource. Expects the local filesystem pathname
12003: (/home/httpd/html/res/....)
12004: 
12005: =back
12006: 
12007: =head2 Resource Information
12008: 
12009: =over 4
12010: 
12011: =item *
12012: 
12013: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12014: a vairety of different possible values, $varname should be a request
12015: string, and the other parameters can be used to specify who and what
12016: one is asking about.
12017: 
12018: Possible values for $varname are environment.lastname (or other item
12019: from the envirnment hash), user.name (or someother aspect about the
12020: user), resource.0.maxtries (or some other part and parameter of a
12021: resource)
12022: 
12023: =item *
12024: 
12025: directcondval($number) : get current value of a condition; reads from a state
12026: string
12027: 
12028: =item *
12029: 
12030: condval($condidx) : value of condition index based on state
12031: 
12032: =item *
12033: 
12034: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12035: resource's metadata, $what should be either a specific key, or either
12036: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12037: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12038: 
12039: this function automatically caches all requests
12040: 
12041: =item *
12042: 
12043: metadata_query($query,$custom,$customshow) : make a metadata query against the
12044: network of library servers; returns file handle of where SQL and regex results
12045: will be stored for query
12046: 
12047: =item *
12048: 
12049: symbread($filename) : return symbolic list entry (filename argument optional);
12050: returns the data handle
12051: 
12052: =item *
12053: 
12054: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12055: a possible symb for the URL in $thisfn, and if is an encryypted
12056: resource that the user accessed using /enc/ returns a 1 on success, 0
12057: on failure, user must be in a course, as it assumes the existance of
12058: the course initial hash, and uses $env('request.course.id'}
12059: 
12060: 
12061: =item *
12062: 
12063: symbclean($symb) : removes versions numbers from a symb, returns the
12064: cleaned symb
12065: 
12066: =item *
12067: 
12068: is_on_map($uri) : checks if the $uri is somewhere on the current
12069: course map, user must be in a course for it to work.
12070: 
12071: =item *
12072: 
12073: numval($salt) : return random seed value (addend for rndseed)
12074: 
12075: =item *
12076: 
12077: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12078: a random seed, all arguments are optional, if they aren't sent it uses the
12079: environment to derive them. Note: if symb isn't sent and it can't get one
12080: from &symbread it will use the current time as its return value
12081: 
12082: =item *
12083: 
12084: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12085: unfakeable, receipt
12086: 
12087: =item *
12088: 
12089: receipt() : API to ireceipt working off of env values; given out to users
12090: 
12091: =item *
12092: 
12093: countacc($url) : count the number of accesses to a given URL
12094: 
12095: =item *
12096: 
12097: 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
12098: 
12099: =item *
12100: 
12101: 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)
12102: 
12103: =item *
12104: 
12105: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12106: 
12107: =item *
12108: 
12109: devalidate($symb) : devalidate temporary spreadsheet calculations,
12110: forcing spreadsheet to reevaluate the resource scores next time.
12111: 
12112: =back
12113: 
12114: =head2 Storing/Retreiving Data
12115: 
12116: =over 4
12117: 
12118: =item *
12119: 
12120: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12121: for this url; hashref needs to be given and should be a \%hashname; the
12122: remaining args aren't required and if they aren't passed or are '' they will
12123: be derived from the env
12124: 
12125: =item *
12126: 
12127: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12128: uses critical subroutine
12129: 
12130: =item *
12131: 
12132: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12133: all args are optional
12134: 
12135: =item *
12136: 
12137: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12138: dumps the complete (or key matching regexp) namespace into a hash
12139: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12140: normally &store()ed into
12141: 
12142: $range should be either an integer '100' (give me the first 100
12143:                                            matching records)
12144:               or be  two integers sperated by a - with no spaces
12145:                  '30-50' (give me the 30th through the 50th matching
12146:                           records)
12147: 
12148: 
12149: =item *
12150: 
12151: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12152: replaces a &store() version of data with a replacement set of data
12153: for a particular resource in a namespace passed in the $storehash hash 
12154: reference
12155: 
12156: =item *
12157: 
12158: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12159: works very similar to store/cstore, but all data is stored in a
12160: temporary location and can be reset using tmpreset, $storehash should
12161: be a hash reference, returns nothing on success
12162: 
12163: =item *
12164: 
12165: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12166: similar to restore, but all data is stored in a temporary location and
12167: can be reset using tmpreset. Returns a hash of values on success,
12168: error string otherwise.
12169: 
12170: =item *
12171: 
12172: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12173: deltes all keys for $symb form the temporary storage hash.
12174: 
12175: =item *
12176: 
12177: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12178: reference filled in from namesp ($udom and $uname are optional)
12179: 
12180: =item *
12181: 
12182: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12183: namesp ($udom and $uname are optional)
12184: 
12185: =item *
12186: 
12187: dump($namespace,$udom,$uname,$regexp,$range) : 
12188: dumps the complete (or key matching regexp) namespace into a hash
12189: ($udom, $uname, $regexp, $range are optional)
12190: 
12191: $range should be either an integer '100' (give me the first 100
12192:                                            matching records)
12193:               or be  two integers sperated by a - with no spaces
12194:                  '30-50' (give me the 30th through the 50th matching
12195:                           records)
12196: =item *
12197: 
12198: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12199: $store can be a scalar, an array reference, or if the amount to be 
12200: incremented is > 1, a hash reference.
12201: 
12202: ($udom and $uname are optional)
12203: 
12204: =item *
12205: 
12206: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12207: ($udom and $uname are optional)
12208: 
12209: =item *
12210: 
12211: cput($namespace,$storehash,$udom,$uname) : critical put
12212: ($udom and $uname are optional)
12213: 
12214: =item *
12215: 
12216: newput($namespace,$storehash,$udom,$uname) :
12217: 
12218: Attempts to store the items in the $storehash, but only if they don't
12219: currently exist, if this succeeds you can be certain that you have 
12220: successfully created a new key value pair in the $namespace db.
12221: 
12222: 
12223: Args:
12224:  $namespace: name of database to store values to
12225:  $storehash: hashref to store to the db
12226:  $udom: (optional) domain of user containing the db
12227:  $uname: (optional) name of user caontaining the db
12228: 
12229: Returns:
12230:  'ok' -> succeeded in storing all keys of $storehash
12231:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12232:                         least <key> already existed in the db (other
12233:                         requested keys may also already exist)
12234:  'error: <msg>' -> unable to tie the DB or other error occurred
12235:  'con_lost' -> unable to contact request server
12236:  'refused' -> action was not allowed by remote machine
12237: 
12238: 
12239: =item *
12240: 
12241: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12242: reference filled in from namesp (encrypts the return communication)
12243: ($udom and $uname are optional)
12244: 
12245: =item *
12246: 
12247: log($udom,$name,$home,$message) : write to permanent log for user; use
12248: critical subroutine
12249: 
12250: =item *
12251: 
12252: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12253: array reference filled in from namespace found in domain level on either
12254: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12255: 
12256: =item *
12257: 
12258: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12259: domain level either on specified domain server ($uhome) or primary domain 
12260: server ($udom and $uhome are optional)
12261: 
12262: =item * 
12263: 
12264: get_domain_defaults($target_domain) : returns hash with defaults for
12265: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12266: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12267: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12268: Values are retrieved from cache (if current), or from domain's configuration.db
12269: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12270: or lonTabs/domain.tab. 
12271: 
12272: %domdefaults = &get_auth_defaults($target_domain);
12273: 
12274: =back
12275: 
12276: =head2 Network Status Functions
12277: 
12278: =over 4
12279: 
12280: =item *
12281: 
12282: dirlist() : return directory list based on URI (first arg).
12283: 
12284: Inputs: 1 required, 5 optional.
12285: 
12286: =over
12287: 
12288: =item 
12289: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12290: 
12291: =item
12292: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12293: 
12294: =item
12295: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12296: 
12297: =item
12298: $getpropath - boolean: 1 if prepend path using &propath(). 
12299: 
12300: =item
12301: $getuserdir - boolean: 1 if prepend path for "userfiles".
12302: 
12303: =item 
12304: $alternateRoot - path to prepend in place of path from $uri.
12305: 
12306: =back
12307: 
12308: Returns: Array of up to two items.
12309: 
12310: =over
12311: 
12312: a reference to an array of files/subdirectories
12313: 
12314: =over
12315: 
12316: Each element in the array of files/subdirectories is a & separated list of
12317: item name and the result of running stat on the item.  If dirlist was requested
12318: for a file instead of a directory, the item name will be ''. For a directory 
12319: listing, if the item is a metadata file, the element will end &N&M 
12320: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12321: default copyright set (1).  
12322: 
12323: =back
12324: 
12325: a scalar containing error condition (if encountered).
12326: 
12327: =over
12328: 
12329: =item 
12330: no_host (no homeserver identified for $username:$domain).
12331: 
12332: =item 
12333: no_such_host (server contacted for listing not identified as valid host).
12334: 
12335: =item 
12336: con_lost (connection to remote server failed).
12337: 
12338: =item 
12339: refused (invalid $username:$domain received on lond side).
12340: 
12341: =item 
12342: no_such_dir (directory at specified path on lond side does not exist). 
12343: 
12344: =item 
12345: empty (directory at specified path on lond side is empty).
12346: 
12347: =over
12348: 
12349: This is currently not encountered because the &ls3, &ls2, 
12350: &ls (_handler) routines on the lond side do not filter out
12351: . and .. from a directory listing. 
12352: 
12353: =back
12354: 
12355: =back
12356: 
12357: =back
12358: 
12359: =item *
12360: 
12361: spareserver() : find server with least workload from spare.tab
12362: 
12363: 
12364: =item *
12365: 
12366: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12367: if there is no corresponding loncapa host.
12368: 
12369: =back
12370: 
12371: 
12372: =head2 Apache Request
12373: 
12374: =over 4
12375: 
12376: =item *
12377: 
12378: ssi($url,%hash) : server side include, does a complete request cycle on url to
12379: localhost, posts hash
12380: 
12381: =back
12382: 
12383: =head2 Data to String to Data
12384: 
12385: =over 4
12386: 
12387: =item *
12388: 
12389: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12390: and '&' separators, supports elements that are arrayrefs and hashrefs
12391: 
12392: =item *
12393: 
12394: hashref2str($hashref) : convert a hashref into a string complete with
12395: escaping and '=' and '&' separators, supports elements that are
12396: arrayrefs and hashrefs
12397: 
12398: =item *
12399: 
12400: arrayref2str($arrayref) : convert an arrayref into a string complete
12401: with escaping and '&' separators, supports elements that are arrayrefs
12402: and hashrefs
12403: 
12404: =item *
12405: 
12406: str2hash($string) : convert string to hash using unescaping and
12407: splitting on '=' and '&', supports elements that are arrayrefs and
12408: hashrefs
12409: 
12410: =item *
12411: 
12412: str2array($string) : convert string to hash using unescaping and
12413: splitting on '&', supports elements that are arrayrefs and hashrefs
12414: 
12415: =back
12416: 
12417: =head2 Logging Routines
12418: 
12419: 
12420: These routines allow one to make log messages in the lonnet.log and
12421: lonnet.perm logfiles.
12422: 
12423: =over 4
12424: 
12425: =item *
12426: 
12427: logtouch() : make sure the logfile, lonnet.log, exists
12428: 
12429: =item *
12430: 
12431: logthis() : append message to the normal lonnet.log file, it gets
12432: preiodically rolled over and deleted.
12433: 
12434: =item *
12435: 
12436: logperm() : append a permanent message to lonnet.perm.log, this log
12437: file never gets deleted by any automated portion of the system, only
12438: messages of critical importance should go in here.
12439: 
12440: 
12441: =back
12442: 
12443: =head2 General File Helper Routines
12444: 
12445: =over 4
12446: 
12447: =item *
12448: 
12449: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12450: (a) files in /uploaded
12451:   (i) If a local copy of the file exists - 
12452:       compares modification date of local copy with last-modified date for 
12453:       definitive version stored on home server for course. If local copy is 
12454:       stale, requests a new version from the home server and stores it. 
12455:       If the original has been removed from the home server, then local copy 
12456:       is unlinked.
12457:   (ii) If local copy does not exist -
12458:       requests the file from the home server and stores it. 
12459:   
12460:   If $caller is 'uploadrep':  
12461:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12462:     for request for files originally uploaded via DOCS. 
12463:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12464:   
12465:   Otherwise:
12466:      This indicates a call from the content generation phase of the request.
12467:      -  returns the entire contents of the file or -1.
12468:      
12469: (b) files in /res
12470:    - returns the entire contents of a file or -1; 
12471:    it properly subscribes to and replicates the file if neccessary.
12472: 
12473: 
12474: =item *
12475: 
12476: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12477:                   reference
12478: 
12479: returns either a stat() list of data about the file or an empty list
12480: if the file doesn't exist or couldn't find out about it (connection
12481: problems or user unknown)
12482: 
12483: =item *
12484: 
12485: filelocation($dir,$file) : returns file system location of a file
12486: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12487: directory that relative $file lookups are to looked in ($dir of /a/dir
12488: and a file of ../bob will become /a/bob)
12489: 
12490: =item *
12491: 
12492: hreflocation($dir,$file) : returns file system location or a URL; same as
12493: filelocation except for hrefs
12494: 
12495: =item *
12496: 
12497: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12498: 
12499: =back
12500: 
12501: =head2 Usererfile file routines (/uploaded*)
12502: 
12503: =over 4
12504: 
12505: =item *
12506: 
12507: userfileupload(): main rotine for putting a file in a user or course's
12508:                   filespace, arguments are,
12509: 
12510:  formname - required - this is the name of the element in $env where the
12511:            filename, and the contents of the file to create/modifed exist
12512:            the filename is in $env{'form.'.$formname.'.filename'} and the
12513:            contents of the file is located in $env{'form.'.$formname}
12514:  context - if coursedoc, store the file in the course of the active role
12515:              of the current user; 
12516:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12517:            if 'canceloverwrite': delete file in tmp/overwrites directory
12518:  subdir - required - subdirectory to put the file in under ../userfiles/
12519:          if undefined, it will be placed in "unknown"
12520: 
12521:  (This routine calls clean_filename() to remove any dangerous
12522:  characters from the filename, and then calls finuserfileupload() to
12523:  complete the transaction)
12524: 
12525:  returns either the url of the uploaded file (/uploaded/....) if successful
12526:  and /adm/notfound.html if unsuccessful
12527: 
12528: =item *
12529: 
12530: clean_filename(): routine for cleaing a filename up for storage in
12531:                  userfile space, argument is:
12532: 
12533:  filename - proposed filename
12534: 
12535: returns: the new clean filename
12536: 
12537: =item *
12538: 
12539: finishuserfileupload(): routine that creates and sends the file to
12540: userspace, probably shouldn't be called directly
12541: 
12542:   docuname: username or courseid of destination for the file
12543:   docudom: domain of user/course of destination for the file
12544:   formname: same as for userfileupload()
12545:   fname: filename (including subdirectories) for the file
12546:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12547:   allfiles: reference to hash used to store objects found by parser
12548:   codebase: reference to hash used for codebases of java objects found by parser
12549:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12550:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12551:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12552:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12553:   context: if 'overwrite', will move the uploaded file from its temporary location to
12554:             userfiles to facilitate overwriting a previously uploaded file with same name.
12555:   mimetype: reference to scalar to accommodate mime type determined
12556:             from File::MMagic if $parser = parse.
12557: 
12558:  returns either the url of the uploaded file (/uploaded/....) if successful
12559:  and /adm/notfound.html if unsuccessful (or an error message if context 
12560:  was 'overwrite').
12561:  
12562: 
12563: =item *
12564: 
12565: renameuserfile(): renames an existing userfile to a new name
12566: 
12567:   Args:
12568:    docuname: username or courseid of destination for the file
12569:    docudom: domain of user/course of destination for the file
12570:    old: current file name (including any subdirs under userfiles)
12571:    new: desired file name (including any subdirs under userfiles)
12572: 
12573: =item *
12574: 
12575: mkdiruserfile(): creates a directory is a userfiles dir
12576: 
12577:   Args:
12578:    docuname: username or courseid of destination for the file
12579:    docudom: domain of user/course of destination for the file
12580:    dir: dir to create (including any subdirs under userfiles)
12581: 
12582: =item *
12583: 
12584: removeuserfile(): removes a file that exists in userfiles
12585: 
12586:   Args:
12587:    docuname: username or courseid of destination for the file
12588:    docudom: domain of user/course of destination for the file
12589:    fname: filname to delete (including any subdirs under userfiles)
12590: 
12591: =item *
12592: 
12593: removeuploadedurl(): convience function for removeuserfile()
12594: 
12595:   Args:
12596:    url:  a full /uploaded/... url to delete
12597: 
12598: =item * 
12599: 
12600: get_portfile_permissions():
12601:   Args:
12602:     domain: domain of user or course contain the portfolio files
12603:     user: name of user or num of course contain the portfolio files
12604:   Returns:
12605:     hashref of a dump of the proper file_permissions.db
12606:    
12607: 
12608: =item * 
12609: 
12610: get_access_controls():
12611: 
12612: Args:
12613:   current_permissions: the hash ref returned from get_portfile_permissions()
12614:   group: (optional) the group you want the files associated with
12615:   file: (optional) the file you want access info on
12616: 
12617: Returns:
12618:     a hash (keys are file names) of hashes containing
12619:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12620:         values are XML containing access control settings (see below) 
12621: 
12622: Internal notes:
12623: 
12624:  access controls are stored in file_permissions.db as key=value pairs.
12625:     key -> path to file/file_name\0uniqueID:scope_end_start
12626:         where scope -> public,guest,course,group,domains or users.
12627:               end -> UNIX time for end of access (0 -> no end date)
12628:               start -> UNIX time for start of access
12629: 
12630:     value -> XML description of access control
12631:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12632:             <start></start>
12633:             <end></end>
12634: 
12635:             <password></password>  for scope type = guest
12636: 
12637:             <domain></domain>     for scope type = course or group
12638:             <number></number>
12639:             <roles id="">
12640:              <role></role>
12641:              <access></access>
12642:              <section></section>
12643:              <group></group>
12644:             </roles>
12645: 
12646:             <dom></dom>         for scope type = domains
12647: 
12648:             <users>             for scope type = users
12649:              <user>
12650:               <uname></uname>
12651:               <udom></udom>
12652:              </user>
12653:             </users>
12654:            </scope> 
12655:               
12656:  Access data is also aggregated for each file in an additional key=value pair:
12657:  key -> path to file/file_name\0accesscontrol 
12658:  value -> reference to hash
12659:           hash contains key = value pairs
12660:           where key = uniqueID:scope_end_start
12661:                 value = UNIX time record was last updated
12662: 
12663:           Used to improve speed of look-ups of access controls for each file.  
12664:  
12665:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12666: 
12667: modify_access_controls():
12668: 
12669: Modifies access controls for a portfolio file
12670: Args
12671: 1. file name
12672: 2. reference to hash of required changes,
12673: 3. domain
12674: 4. username
12675:   where domain,username are the domain of the portfolio owner 
12676:   (either a user or a course) 
12677: 
12678: Returns:
12679: 1. result of additions or updates ('ok' or 'error', with error message). 
12680: 2. result of deletions ('ok' or 'error', with error message).
12681: 3. reference to hash of any new or updated access controls.
12682: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12683:    key = integer (inbound ID)
12684:    value = uniqueID  
12685: 
12686: =back
12687: 
12688: =head2 HTTP Helper Routines
12689: 
12690: =over 4
12691: 
12692: =item *
12693: 
12694: escape() : unpack non-word characters into CGI-compatible hex codes
12695: 
12696: =item *
12697: 
12698: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12699: 
12700: =back
12701: 
12702: =head1 PRIVATE SUBROUTINES
12703: 
12704: =head2 Underlying communication routines (Shouldn't call)
12705: 
12706: =over 4
12707: 
12708: =item *
12709: 
12710: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12711: 
12712: =item *
12713: 
12714: reply() : uses subreply to send a message to remote machine, logs all failures
12715: 
12716: =item *
12717: 
12718: critical() : passes a critical message to another server; if cannot
12719: get through then place message in connection buffer directory and
12720: returns con_delayed, if incapable of saving message, returns
12721: con_failed
12722: 
12723: =item *
12724: 
12725: reconlonc() : tries to reconnect lonc client processes.
12726: 
12727: =back
12728: 
12729: =head2 Resource Access Logging
12730: 
12731: =over 4
12732: 
12733: =item *
12734: 
12735: flushcourselogs() : flush (save) buffer logs and access logs
12736: 
12737: =item *
12738: 
12739: courselog($what) : save message for course in hash
12740: 
12741: =item *
12742: 
12743: courseacclog($what) : save message for course using &courselog().  Perform
12744: special processing for specific resource types (problems, exams, quizzes, etc).
12745: 
12746: =item *
12747: 
12748: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12749: as a PerlChildExitHandler
12750: 
12751: =back
12752: 
12753: =head2 Other
12754: 
12755: =over 4
12756: 
12757: =item *
12758: 
12759: symblist($mapname,%newhash) : update symbolic storage links
12760: 
12761: =back
12762: 
12763: =cut
12764: 

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