File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1002: download - view: text, annotated - select for diffs
Thu Jun 11 19:02:32 2009 UTC (15 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Usability improvements.
- Reduce need for user to complete logout/login cycle to be able to select roles with 'will' role status (roles with future access which existed at time of last log-in, and are "active"):
  - Display of roles screen causes privs to propagate to %env in the background and become selectable.
  - &gather_roles() routine created (ongoing simplification of monolithic handler() routine).
  - &Apache::lonnet::roles_status() takes new arg ($refresh).
  - New environment variable: user.refresh.time - records when last check was made for 'will' type role.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1002 2009/06/11 19:02:32 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);
   80: 
   81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   84:     %courseownerbuf, %coursetypebuf,$locknum);
   85: 
   86: use IO::Socket;
   87: use GDBM_File;
   88: use HTML::LCParser;
   89: use Fcntl qw(:flock);
   90: use Storable qw(thaw nfreeze);
   91: use Time::HiRes qw( gettimeofday tv_interval );
   92: use Cache::Memcached;
   93: use Digest::MD5;
   94: use Math::Random;
   95: use LONCAPA qw(:DEFAULT :match);
   96: use LONCAPA::Configuration;
   97: 
   98: my $readit;
   99: my $max_connection_retries = 10;     # Or some such value.
  100: 
  101: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  102: 
  103: require Exporter;
  104: 
  105: our @ISA = qw (Exporter);
  106: our @EXPORT = qw(%env);
  107: 
  108: 
  109: # --------------------------------------------------------------------- Logging
  110: {
  111:     my $logid;
  112:     sub instructor_log {
  113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  114:         if (($cnum eq '') || ($cdom eq '')) {
  115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  117:         }
  118: 	$logid++;
  119:         my $now = time();
  120: 	my $id=$now.'00000'.$$.'00000'.$logid;
  121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  122: 				    { $id => {
  123: 					'exe_uname' => $env{'user.name'},
  124: 					'exe_udom'  => $env{'user.domain'},
  125: 					'exe_time'  => $now,
  126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  127: 					'delflag'   => $delflag,
  128: 					'logentry'  => $storehash,
  129: 					'uname'     => $uname,
  130: 					'udom'      => $udom,
  131: 				    }
  132: 				  },$cdom,$cnum);
  133:     }
  134: }
  135: 
  136: sub logtouch {
  137:     my $execdir=$perlvar{'lonDaemons'};
  138:     unless (-e "$execdir/logs/lonnet.log") {	
  139: 	open(my $fh,">>$execdir/logs/lonnet.log");
  140: 	close $fh;
  141:     }
  142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  144: }
  145: 
  146: sub logthis {
  147:     my $message=shift;
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     my $now=time;
  150:     my $local=localtime($now);
  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  153: 	print $fh $logstring;
  154: 	close($fh);
  155:     }
  156:     return 1;
  157: }
  158: 
  159: sub logperm {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  165: 	print $fh "$now:$message:$local\n";
  166: 	close($fh);
  167:     }
  168:     return 1;
  169: }
  170: 
  171: sub create_connection {
  172:     my ($hostname,$lonid) = @_;
  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  174: 				     Type    => SOCK_STREAM,
  175: 				     Timeout => 10);
  176:     return 0 if (!$client);
  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  178:     my $result = <$client>;
  179:     chomp($result);
  180:     return 1 if ($result eq 'done');
  181:     return 0;
  182: }
  183: 
  184: sub get_server_timezone {
  185:     my ($cnum,$cdom) = @_;
  186:     my $home=&homeserver($cnum,$cdom);
  187:     if ($home ne 'no_host') {
  188:         my $cachetime = 24*3600;
  189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  190:         if (defined($cached)) {
  191:             return $timezone;
  192:         } else {
  193:             my $timezone = &reply('servertimezone',$home);
  194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  195:         }
  196:     }
  197: }
  198: 
  199: sub get_server_loncaparev {
  200:     my ($dom,$lonhost) = @_;
  201:     if (defined($lonhost)) {
  202:         if (!defined(&hostname($lonhost))) {
  203:             undef($lonhost);
  204:         }
  205:     }
  206:     if (!defined($lonhost)) {
  207:         if (defined(&domain($dom,'primary'))) {
  208:             $lonhost=&domain($dom,'primary');
  209:             if ($lonhost eq 'no_host') {
  210:                 undef($lonhost);
  211:             }
  212:         }
  213:     }
  214:     if (defined($lonhost)) {
  215:         my $cachetime = 24*3600;
  216:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  217:         if (defined($cached)) {
  218:             return $loncaparev;
  219:         } else {
  220:             my $loncaparev = &reply('serverloncaparev',$lonhost);
  221:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  222:         }
  223:     }
  224: }
  225: 
  226: # -------------------------------------------------- Non-critical communication
  227: sub subreply {
  228:     my ($cmd,$server)=@_;
  229:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  230:     #
  231:     #  With loncnew process trimming, there's a timing hole between lonc server
  232:     #  process exit and the master server picking up the listen on the AF_UNIX
  233:     #  socket.  In that time interval, a lock file will exist:
  234: 
  235:     my $lockfile=$peerfile.".lock";
  236:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  237: 	sleep(1);
  238:     }
  239:     # At this point, either a loncnew parent is listening or an old lonc
  240:     # or loncnew child is listening so we can connect or everything's dead.
  241:     #
  242:     #   We'll give the connection a few tries before abandoning it.  If
  243:     #   connection is not possible, we'll con_lost back to the client.
  244:     #   
  245:     my $client;
  246:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  247: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  248: 				      Type    => SOCK_STREAM,
  249: 				      Timeout => 10);
  250: 	if ($client) {
  251: 	    last;		# Connected!
  252: 	} else {
  253: 	    &create_connection(&hostname($server),$server);
  254: 	}
  255:         sleep(1);		# Try again later if failed connection.
  256:     }
  257:     my $answer;
  258:     if ($client) {
  259: 	print $client "sethost:$server:$cmd\n";
  260: 	$answer=<$client>;
  261: 	if (!$answer) { $answer="con_lost"; }
  262: 	chomp($answer);
  263:     } else {
  264: 	$answer = 'con_lost';	# Failed connection.
  265:     }
  266:     return $answer;
  267: }
  268: 
  269: sub reply {
  270:     my ($cmd,$server)=@_;
  271:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  272:     my $answer=subreply($cmd,$server);
  273:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  274:        &logthis("<font color=\"blue\">WARNING:".
  275:                 " $cmd to $server returned $answer</font>");
  276:     }
  277:     return $answer;
  278: }
  279: 
  280: # ----------------------------------------------------------- Send USR1 to lonc
  281: 
  282: sub reconlonc {
  283:     my ($lonid) = @_;
  284:     my $hostname = &hostname($lonid);
  285:     if ($lonid) {
  286: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  287: 	if ($hostname && -e $peerfile) {
  288: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  289: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  290: 					     Type    => SOCK_STREAM,
  291: 					     Timeout => 10);
  292: 	    if ($client) {
  293: 		print $client ("reset_retries\n");
  294: 		my $answer=<$client>;
  295: 		#reset just this one.
  296: 	    }
  297: 	}
  298: 	return;
  299:     }
  300: 
  301:     &logthis("Trying to reconnect lonc");
  302:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  303:     if (open(my $fh,"<$loncfile")) {
  304: 	my $loncpid=<$fh>;
  305:         chomp($loncpid);
  306:         if (kill 0 => $loncpid) {
  307: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  308:             kill USR1 => $loncpid;
  309:             sleep 1;
  310:          } else {
  311: 	    &logthis(
  312:                "<font color=\"blue\">WARNING:".
  313:                " lonc at pid $loncpid not responding, giving up</font>");
  314:         }
  315:     } else {
  316: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  317:     }
  318: }
  319: 
  320: # ------------------------------------------------------ Critical communication
  321: 
  322: sub critical {
  323:     my ($cmd,$server)=@_;
  324:     unless (&hostname($server)) {
  325:         &logthis("<font color=\"blue\">WARNING:".
  326:                " Critical message to unknown server ($server)</font>");
  327:         return 'no_such_host';
  328:     }
  329:     my $answer=reply($cmd,$server);
  330:     if ($answer eq 'con_lost') {
  331: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  332: 	my $answer=reply($cmd,$server);
  333:         if ($answer eq 'con_lost') {
  334:             my $now=time;
  335:             my $middlename=$cmd;
  336:             $middlename=substr($middlename,0,16);
  337:             $middlename=~s/\W//g;
  338:             my $dfilename=
  339:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  340:             $dumpcount++;
  341:             {
  342: 		my $dfh;
  343: 		if (open($dfh,">$dfilename")) {
  344: 		    print $dfh "$cmd\n"; 
  345: 		    close($dfh);
  346: 		}
  347:             }
  348:             sleep 2;
  349:             my $wcmd='';
  350:             {
  351: 		my $dfh;
  352: 		if (open($dfh,"<$dfilename")) {
  353: 		    $wcmd=<$dfh>; 
  354: 		    close($dfh);
  355: 		}
  356:             }
  357:             chomp($wcmd);
  358:             if ($wcmd eq $cmd) {
  359: 		&logthis("<font color=\"blue\">WARNING: ".
  360:                          "Connection buffer $dfilename: $cmd</font>");
  361:                 &logperm("D:$server:$cmd");
  362: 	        return 'con_delayed';
  363:             } else {
  364:                 &logthis("<font color=\"red\">CRITICAL:"
  365:                         ." Critical connection failed: $server $cmd</font>");
  366:                 &logperm("F:$server:$cmd");
  367:                 return 'con_failed';
  368:             }
  369:         }
  370:     }
  371:     return $answer;
  372: }
  373: 
  374: # ------------------------------------------- check if return value is an error
  375: 
  376: sub error {
  377:     my ($result) = @_;
  378:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  379: 	if ($2 == 2) { return undef; }
  380: 	return $1;
  381:     }
  382:     return undef;
  383: }
  384: 
  385: sub convert_and_load_session_env {
  386:     my ($lonidsdir,$handle)=@_;
  387:     my @profile;
  388:     {
  389: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  390: 	if (!$opened) {
  391: 	    return 0;
  392: 	}
  393: 	flock($idf,LOCK_SH);
  394: 	@profile=<$idf>;
  395: 	close($idf);
  396:     }
  397:     my %temp_env;
  398:     foreach my $line (@profile) {
  399: 	if ($line !~ m/=/) {
  400: 	    return 0;
  401: 	}
  402: 	chomp($line);
  403: 	my ($envname,$envvalue)=split(/=/,$line,2);
  404: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  405:     }
  406:     unlink("$lonidsdir/$handle.id");
  407:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  408: 	    0640)) {
  409: 	%disk_env = %temp_env;
  410: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  411: 	untie(%disk_env);
  412:     }
  413:     return 1;
  414: }
  415: 
  416: # ------------------------------------------- Transfer profile into environment
  417: my $env_loaded;
  418: sub transfer_profile_to_env {
  419:     my ($lonidsdir,$handle,$force_transfer) = @_;
  420:     if (!$force_transfer && $env_loaded) { return; } 
  421: 
  422:     if (!defined($lonidsdir)) {
  423: 	$lonidsdir = $perlvar{'lonIDsDir'};
  424:     }
  425:     if (!defined($handle)) {
  426:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  427:     }
  428: 
  429:     my $convert;
  430:     {
  431:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  432: 	if (!$opened) {
  433: 	    return;
  434: 	}
  435: 	flock($idf,LOCK_SH);
  436: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  437: 		&GDBM_READER(),0640)) {
  438: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  439: 	    untie(%disk_env);
  440: 	} else {
  441: 	    $convert = 1;
  442: 	}
  443:     }
  444:     if ($convert) {
  445: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  446: 	    &logthis("Failed to load session, or convert session.");
  447: 	}
  448:     }
  449: 
  450:     my %remove;
  451:     while ( my $envname = each(%env) ) {
  452:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  453:             if ($time < time-300) {
  454:                 $remove{$key}++;
  455:             }
  456:         }
  457:     }
  458: 
  459:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  460:     $env_loaded=1;
  461:     foreach my $expired_key (keys(%remove)) {
  462:         &delenv($expired_key);
  463:     }
  464: }
  465: 
  466: # ---------------------------------------------------- Check for valid session 
  467: sub check_for_valid_session {
  468:     my ($r) = @_;
  469:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  470:     my $lonid=$cookies{'lonID'};
  471:     return undef if (!$lonid);
  472: 
  473:     my $handle=&LONCAPA::clean_handle($lonid->value);
  474:     my $lonidsdir=$r->dir_config('lonIDsDir');
  475:     return undef if (!-e "$lonidsdir/$handle.id");
  476: 
  477:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  478:     return undef if (!$opened);
  479: 
  480:     flock($idf,LOCK_SH);
  481:     my %disk_env;
  482:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  483: 	    &GDBM_READER(),0640)) {
  484: 	return undef;	
  485:     }
  486: 
  487:     if (!defined($disk_env{'user.name'})
  488: 	|| !defined($disk_env{'user.domain'})) {
  489: 	return undef;
  490:     }
  491:     return $handle;
  492: }
  493: 
  494: sub timed_flock {
  495:     my ($file,$lock_type) = @_;
  496:     my $failed=0;
  497:     eval {
  498: 	local $SIG{__DIE__}='DEFAULT';
  499: 	local $SIG{ALRM}=sub {
  500: 	    $failed=1;
  501: 	    die("failed lock");
  502: 	};
  503: 	alarm(13);
  504: 	flock($file,$lock_type);
  505: 	alarm(0);
  506:     };
  507:     if ($failed) {
  508: 	return undef;
  509:     } else {
  510: 	return 1;
  511:     }
  512: }
  513: 
  514: # ---------------------------------------------------------- Append Environment
  515: 
  516: sub appenv {
  517:     my ($newenv,$roles) = @_;
  518:     if (ref($newenv) eq 'HASH') {
  519:         foreach my $key (keys(%{$newenv})) {
  520:             my $refused = 0;
  521: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  522:                 $refused = 1;
  523:                 if (ref($roles) eq 'ARRAY') {
  524:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  525:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  526:                         $refused = 0;
  527:                     }
  528:                 }
  529:             }
  530:             if ($refused) {
  531:                 &logthis("<font color=\"blue\">WARNING: ".
  532:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  533:                          .'</font>');
  534: 	        delete($newenv->{$key});
  535:             } else {
  536:                 $env{$key}=$newenv->{$key};
  537:             }
  538:         }
  539:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  540:         if ($opened
  541: 	    && &timed_flock($env_file,LOCK_EX)
  542: 	    &&
  543: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  544: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  545: 	    while (my ($key,$value) = each(%{$newenv})) {
  546: 	        $disk_env{$key} = $value;
  547: 	    }
  548: 	    untie(%disk_env);
  549:         }
  550:     }
  551:     return 'ok';
  552: }
  553: # ----------------------------------------------------- Delete from Environment
  554: 
  555: sub delenv {
  556:     my ($delthis,$regexp) = @_;
  557:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  558:         &logthis("<font color=\"blue\">WARNING: ".
  559:                 "Attempt to delete from environment ".$delthis);
  560:         return 'error';
  561:     }
  562:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  563:     if ($opened
  564: 	&& &timed_flock($env_file,LOCK_EX)
  565: 	&&
  566: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  567: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  568: 	foreach my $key (keys(%disk_env)) {
  569: 	    if ($regexp) {
  570:                 if ($key=~/^$delthis/) {
  571:                     delete($env{$key});
  572:                     delete($disk_env{$key});
  573:                 } 
  574:             } else {
  575:                 if ($key=~/^\Q$delthis\E/) {
  576: 		    delete($env{$key});
  577: 		    delete($disk_env{$key});
  578: 	        }
  579:             }
  580: 	}
  581: 	untie(%disk_env);
  582:     }
  583:     return 'ok';
  584: }
  585: 
  586: sub get_env_multiple {
  587:     my ($name) = @_;
  588:     my @values;
  589:     if (defined($env{$name})) {
  590:         # exists is it an array
  591:         if (ref($env{$name})) {
  592:             @values=@{ $env{$name} };
  593:         } else {
  594:             $values[0]=$env{$name};
  595:         }
  596:     }
  597:     return(@values);
  598: }
  599: 
  600: # ------------------------------------------------------------------- Locking
  601: 
  602: sub set_lock {
  603:     my ($text)=@_;
  604:     $locknum++;
  605:     my $id=$$.'-'.$locknum;
  606:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  607:              'session.lock.'.$id => $text});
  608:     return $id;
  609: }
  610: 
  611: sub get_locks {
  612:     my $num=0;
  613:     my %texts=();
  614:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  615:        if ($lock=~/\w/) {
  616:           $num++;
  617:           $texts{$lock}=$env{'session.lock.'.$lock};
  618:        }
  619:    }
  620:    return ($num,%texts);
  621: }
  622: 
  623: sub remove_lock {
  624:     my ($id)=@_;
  625:     my $newlocks='';
  626:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  627:        if (($lock=~/\w/) && ($lock ne $id)) {
  628:           $newlocks.=','.$lock;
  629:        }
  630:     }
  631:     &appenv({'session.locks' => $newlocks});
  632:     &delenv('session.lock.'.$id);
  633: }
  634: 
  635: sub remove_all_locks {
  636:     my $activelocks=$env{'session.locks'};
  637:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  638:        if ($lock=~/\w/) {
  639:           &remove_lock($lock);
  640:        }
  641:     }
  642: }
  643: 
  644: 
  645: # ------------------------------------------ Find out current server userload
  646: sub userload {
  647:     my $numusers=0;
  648:     {
  649: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  650: 	my $filename;
  651: 	my $curtime=time;
  652: 	while ($filename=readdir(LONIDS)) {
  653: 	    next if ($filename eq '.' || $filename eq '..');
  654: 	    next if ($filename =~ /publicuser_\d+\.id/);
  655: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  656: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  657: 	}
  658: 	closedir(LONIDS);
  659:     }
  660:     my $userloadpercent=0;
  661:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  662:     if ($maxuserload) {
  663: 	$userloadpercent=100*$numusers/$maxuserload;
  664:     }
  665:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  666:     return $userloadpercent;
  667: }
  668: 
  669: # ------------------------------------------ Fight off request when overloaded
  670: 
  671: sub overloaderror {
  672:     my ($r,$checkserver)=@_;
  673:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  674:     my $loadavg;
  675:     if ($checkserver eq $perlvar{'lonHostID'}) {
  676:        open(my $loadfile,'/proc/loadavg');
  677:        $loadavg=<$loadfile>;
  678:        $loadavg =~ s/\s.*//g;
  679:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  680:        close($loadfile);
  681:     } else {
  682:        $loadavg=&reply('load',$checkserver);
  683:     }
  684:     my $overload=$loadavg-100;
  685:     if ($overload>0) {
  686: 	$r->err_headers_out->{'Retry-After'}=$overload;
  687:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  688:         return 413;
  689:     }    
  690:     return '';
  691: }
  692: 
  693: # ------------------------------ Find server with least workload from spare.tab
  694: 
  695: sub spareserver {
  696:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  697:     my $spare_server;
  698:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  699:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  700:                                                      :  $userloadpercent;
  701:     
  702:     foreach my $try_server (@{ $spareid{'primary'} }) {
  703: 	($spare_server, $lowest_load) =
  704: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  705:     }
  706: 
  707:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  708: 
  709:     if (!$found_server) {
  710: 	foreach my $try_server (@{ $spareid{'default'} }) {
  711: 	    ($spare_server, $lowest_load) =
  712: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  713: 	}
  714:     }
  715: 
  716:     if (!$want_server_name) {
  717:         my $protocol = 'http';
  718:         if ($protocol{$spare_server} eq 'https') {
  719:             $protocol = $protocol{$spare_server};
  720:         }
  721:         if (defined($spare_server)) {
  722:             my $hostname = &hostname($spare_server);
  723:             if (defined($hostname)) {  
  724: 	        $spare_server = $protocol.'://'.$hostname;
  725:             }
  726:         }
  727:     }
  728:     return $spare_server;
  729: }
  730: 
  731: sub compare_server_load {
  732:     my ($try_server, $spare_server, $lowest_load) = @_;
  733: 
  734:     my $loadans     = &reply('load',    $try_server);
  735:     my $userloadans = &reply('userload',$try_server);
  736: 
  737:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  738: 	next; #didn't get a number from the server
  739:     }
  740: 
  741:     my $load;
  742:     if ($loadans =~ /\d/) {
  743: 	if ($userloadans =~ /\d/) {
  744: 	    #both are numbers, pick the bigger one
  745: 	    $load = ($loadans > $userloadans) ? $loadans 
  746: 		                              : $userloadans;
  747: 	} else {
  748: 	    $load = $loadans;
  749: 	}
  750:     } else {
  751: 	$load = $userloadans;
  752:     }
  753: 
  754:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  755: 	$spare_server = $try_server;
  756: 	$lowest_load  = $load;
  757:     }
  758:     return ($spare_server,$lowest_load);
  759: }
  760: 
  761: # --------------------------- ask offload servers if user already has a session
  762: sub find_existing_session {
  763:     my ($udom,$uname) = @_;
  764:     foreach my $try_server (@{ $spareid{'primary'} },
  765: 			    @{ $spareid{'default'} }) {
  766: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  767:     }
  768:     return;
  769: }
  770: 
  771: # -------------------------------- ask if server already has a session for user
  772: sub has_user_session {
  773:     my ($lonid,$udom,$uname) = @_;
  774:     my $result = &reply(join(':','userhassession',
  775: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  776:     return 1 if ($result eq 'ok');
  777: 
  778:     return 0;
  779: }
  780: 
  781: # --------------------------------------------- Try to change a user's password
  782: 
  783: sub changepass {
  784:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  785:     $currentpass = &escape($currentpass);
  786:     $newpass     = &escape($newpass);
  787:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  788: 		       $server);
  789:     if (! $answer) {
  790: 	&logthis("No reply on password change request to $server ".
  791: 		 "by $uname in domain $udom.");
  792:     } elsif ($answer =~ "^ok") {
  793:         &logthis("$uname in $udom successfully changed their password ".
  794: 		 "on $server.");
  795:     } elsif ($answer =~ "^pwchange_failure") {
  796: 	&logthis("$uname in $udom was unable to change their password ".
  797: 		 "on $server.  The action was blocked by either lcpasswd ".
  798: 		 "or pwchange");
  799:     } elsif ($answer =~ "^non_authorized") {
  800:         &logthis("$uname in $udom did not get their password correct when ".
  801: 		 "attempting to change it on $server.");
  802:     } elsif ($answer =~ "^auth_mode_error") {
  803:         &logthis("$uname in $udom attempted to change their password despite ".
  804: 		 "not being locally or internally authenticated on $server.");
  805:     } elsif ($answer =~ "^unknown_user") {
  806:         &logthis("$uname in $udom attempted to change their password ".
  807: 		 "on $server but were unable to because $server is not ".
  808: 		 "their home server.");
  809:     } elsif ($answer =~ "^refused") {
  810: 	&logthis("$server refused to change $uname in $udom password because ".
  811: 		 "it was sent an unencrypted request to change the password.");
  812:     }
  813:     return $answer;
  814: }
  815: 
  816: # ----------------------- Try to determine user's current authentication scheme
  817: 
  818: sub queryauthenticate {
  819:     my ($uname,$udom)=@_;
  820:     my $uhome=&homeserver($uname,$udom);
  821:     if (!$uhome) {
  822: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  823: 	return 'no_host';
  824:     }
  825:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  826:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  827: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  828:     }
  829:     return $answer;
  830: }
  831: 
  832: # --------- Try to authenticate user from domain's lib servers (first this one)
  833: 
  834: sub authenticate {
  835:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  836:     $upass=&escape($upass);
  837:     $uname= &LONCAPA::clean_username($uname);
  838:     my $uhome=&homeserver($uname,$udom,1);
  839:     my $newhome;
  840:     if ((!$uhome) || ($uhome eq 'no_host')) {
  841: # Maybe the machine was offline and only re-appeared again recently?
  842:         &reconlonc();
  843: # One more
  844: 	$uhome=&homeserver($uname,$udom,1);
  845:         if (($uhome eq 'no_host') && $checkdefauth) {
  846:             if (defined(&domain($udom,'primary'))) {
  847:                 $newhome=&domain($udom,'primary');
  848:             }
  849:             if ($newhome ne '') {
  850:                 $uhome = $newhome;
  851:             }
  852:         }
  853: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  854: 	    &logthis("User $uname at $udom is unknown in authenticate");
  855: 	    return 'no_host';
  856:         }
  857:     }
  858:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  859:     if ($answer eq 'authorized') {
  860:         if ($newhome) {
  861:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  862:             return 'no_account_on_host'; 
  863:         } else {
  864:             &logthis("User $uname at $udom authorized by $uhome");
  865:             return $uhome;
  866:         }
  867:     }
  868:     if ($answer eq 'non_authorized') {
  869: 	&logthis("User $uname at $udom rejected by $uhome");
  870: 	return 'no_host'; 
  871:     }
  872:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  873:     return 'no_host';
  874: }
  875: 
  876: # ---------------------- Find the homebase for a user from domain's lib servers
  877: 
  878: my %homecache;
  879: sub homeserver {
  880:     my ($uname,$udom,$ignoreBadCache)=@_;
  881:     my $index="$uname:$udom";
  882: 
  883:     if (exists($homecache{$index})) { return $homecache{$index}; }
  884: 
  885:     my %servers = &get_servers($udom,'library');
  886:     foreach my $tryserver (keys(%servers)) {
  887:         next if ($ignoreBadCache ne 'true' && 
  888: 		 exists($badServerCache{$tryserver}));
  889: 
  890: 	my $answer=reply("home:$udom:$uname",$tryserver);
  891: 	if ($answer eq 'found') {
  892: 	    delete($badServerCache{$tryserver}); 
  893: 	    return $homecache{$index}=$tryserver;
  894: 	} elsif ($answer eq 'no_host') {
  895: 	    $badServerCache{$tryserver}=1;
  896: 	}
  897:     }    
  898:     return 'no_host';
  899: }
  900: 
  901: # ------------------------------------- Find the usernames behind a list of IDs
  902: 
  903: sub idget {
  904:     my ($udom,@ids)=@_;
  905:     my %returnhash=();
  906:     
  907:     my %servers = &get_servers($udom,'library');
  908:     foreach my $tryserver (keys(%servers)) {
  909: 	my $idlist=join('&',@ids);
  910: 	$idlist=~tr/A-Z/a-z/; 
  911: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  912: 	my @answer=();
  913: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  914: 	    @answer=split(/\&/,$reply);
  915: 	}                    ;
  916: 	my $i;
  917: 	for ($i=0;$i<=$#ids;$i++) {
  918: 	    if ($answer[$i]) {
  919: 		$returnhash{$ids[$i]}=$answer[$i];
  920: 	    } 
  921: 	}
  922:     } 
  923:     return %returnhash;
  924: }
  925: 
  926: # ------------------------------------- Find the IDs behind a list of usernames
  927: 
  928: sub idrget {
  929:     my ($udom,@unames)=@_;
  930:     my %returnhash=();
  931:     foreach my $uname (@unames) {
  932:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  933:     }
  934:     return %returnhash;
  935: }
  936: 
  937: # ------------------------------- Store away a list of names and associated IDs
  938: 
  939: sub idput {
  940:     my ($udom,%ids)=@_;
  941:     my %servers=();
  942:     foreach my $uname (keys(%ids)) {
  943: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  944:         my $uhom=&homeserver($uname,$udom);
  945:         if ($uhom ne 'no_host') {
  946:             my $id=&escape($ids{$uname});
  947:             $id=~tr/A-Z/a-z/;
  948:             my $esc_unam=&escape($uname);
  949: 	    if ($servers{$uhom}) {
  950: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  951:             } else {
  952:                 $servers{$uhom}=$id.'='.$esc_unam;
  953:             }
  954:         }
  955:     }
  956:     foreach my $server (keys(%servers)) {
  957:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  958:     }
  959: }
  960: 
  961: # ------------------------------------------- get items from domain db files   
  962: 
  963: sub get_dom {
  964:     my ($namespace,$storearr,$udom,$uhome)=@_;
  965:     my $items='';
  966:     foreach my $item (@$storearr) {
  967:         $items.=&escape($item).'&';
  968:     }
  969:     $items=~s/\&$//;
  970:     if (!$udom) {
  971:         $udom=$env{'user.domain'};
  972:         if (defined(&domain($udom,'primary'))) {
  973:             $uhome=&domain($udom,'primary');
  974:         } else {
  975:             undef($uhome);
  976:         }
  977:     } else {
  978:         if (!$uhome) {
  979:             if (defined(&domain($udom,'primary'))) {
  980:                 $uhome=&domain($udom,'primary');
  981:             }
  982:         }
  983:     }
  984:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  985:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  986:         my %returnhash;
  987:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  988:             return %returnhash;
  989:         }
  990:         my @pairs=split(/\&/,$rep);
  991:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  992:             return @pairs;
  993:         }
  994:         my $i=0;
  995:         foreach my $item (@$storearr) {
  996:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  997:             $i++;
  998:         }
  999:         return %returnhash;
 1000:     } else {
 1001:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1002:     }
 1003: }
 1004: 
 1005: # -------------------------------------------- put items in domain db files 
 1006: 
 1007: sub put_dom {
 1008:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1009:     if (!$udom) {
 1010:         $udom=$env{'user.domain'};
 1011:         if (defined(&domain($udom,'primary'))) {
 1012:             $uhome=&domain($udom,'primary');
 1013:         } else {
 1014:             undef($uhome);
 1015:         }
 1016:     } else {
 1017:         if (!$uhome) {
 1018:             if (defined(&domain($udom,'primary'))) {
 1019:                 $uhome=&domain($udom,'primary');
 1020:             }
 1021:         }
 1022:     } 
 1023:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1024:         my $items='';
 1025:         foreach my $item (keys(%$storehash)) {
 1026:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1027:         }
 1028:         $items=~s/\&$//;
 1029:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1030:     } else {
 1031:         &logthis("put_dom failed - no homeserver and/or domain");
 1032:     }
 1033: }
 1034: 
 1035: sub retrieve_inst_usertypes {
 1036:     my ($udom) = @_;
 1037:     my (%returnhash,@order);
 1038:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1039:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1040:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1041:         %returnhash = %{$domdefs{'inststatustypes'}};
 1042:         @order = @{$domdefs{'inststatusorder'}};
 1043:     } else {
 1044:         if (defined(&domain($udom,'primary'))) {
 1045:             my $uhome=&domain($udom,'primary');
 1046:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1047:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1048:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1049:                 return (\%returnhash,\@order);
 1050:             }
 1051:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1052:             my @pairs=split(/\&/,$hashitems);
 1053:             foreach my $item (@pairs) {
 1054:                 my ($key,$value)=split(/=/,$item,2);
 1055:                 $key = &unescape($key);
 1056:                 next if ($key =~ /^error: 2 /);
 1057:                 $returnhash{$key}=&thaw_unescape($value);
 1058:             }
 1059:             my @esc_order = split(/\&/,$orderitems);
 1060:             foreach my $item (@esc_order) {
 1061:                 push(@order,&unescape($item));
 1062:             }
 1063:         } else {
 1064:             &logthis("get_dom failed - no primary domain server for $udom");
 1065:         }
 1066:     }
 1067:     return (\%returnhash,\@order);
 1068: }
 1069: 
 1070: sub is_domainimage {
 1071:     my ($url) = @_;
 1072:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1073:         if (&domain($1) ne '') {
 1074:             return '1';
 1075:         }
 1076:     }
 1077:     return;
 1078: }
 1079: 
 1080: sub inst_directory_query {
 1081:     my ($srch) = @_;
 1082:     my $udom = $srch->{'srchdomain'};
 1083:     my %results;
 1084:     my $homeserver = &domain($udom,'primary');
 1085:     my $outcome;
 1086:     if ($homeserver ne '') {
 1087: 	my $queryid=&reply("querysend:instdirsearch:".
 1088: 			   &escape($srch->{'srchby'}).':'.
 1089: 			   &escape($srch->{'srchterm'}).':'.
 1090: 			   &escape($srch->{'srchtype'}),$homeserver);
 1091: 	my $host=&hostname($homeserver);
 1092: 	if ($queryid !~/^\Q$host\E\_/) {
 1093: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1094: 	    return;
 1095: 	}
 1096: 	my $response = &get_query_reply($queryid);
 1097: 	my $maxtries = 5;
 1098: 	my $tries = 1;
 1099: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1100: 	    $response = &get_query_reply($queryid);
 1101: 	    $tries ++;
 1102: 	}
 1103: 
 1104:         if (!&error($response) && $response ne 'refused') {
 1105:             if ($response eq 'unavailable') {
 1106:                 $outcome = $response;
 1107:             } else {
 1108:                 $outcome = 'ok';
 1109:                 my @matches = split(/\n/,$response);
 1110:                 foreach my $match (@matches) {
 1111:                     my ($key,$value) = split(/=/,$match);
 1112:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1113:                 }
 1114:             }
 1115:         }
 1116:     }
 1117:     return ($outcome,%results);
 1118: }
 1119: 
 1120: sub usersearch {
 1121:     my ($srch) = @_;
 1122:     my $dom = $srch->{'srchdomain'};
 1123:     my %results;
 1124:     my %libserv = &all_library();
 1125:     my $query = 'usersearch';
 1126:     foreach my $tryserver (keys(%libserv)) {
 1127:         if (&host_domain($tryserver) eq $dom) {
 1128:             my $host=&hostname($tryserver);
 1129:             my $queryid=
 1130:                 &reply("querysend:".&escape($query).':'.
 1131:                        &escape($srch->{'srchby'}).':'.
 1132:                        &escape($srch->{'srchtype'}).':'.
 1133:                        &escape($srch->{'srchterm'}),$tryserver);
 1134:             if ($queryid !~/^\Q$host\E\_/) {
 1135:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1136:                 next;
 1137:             }
 1138:             my $reply = &get_query_reply($queryid);
 1139:             my $maxtries = 1;
 1140:             my $tries = 1;
 1141:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1142:                 $reply = &get_query_reply($queryid);
 1143:                 $tries ++;
 1144:             }
 1145:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1146:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1147:             } else {
 1148:                 my @matches;
 1149:                 if ($reply =~ /\n/) {
 1150:                     @matches = split(/\n/,$reply);
 1151:                 } else {
 1152:                     @matches = split(/\&/,$reply);
 1153:                 }
 1154:                 foreach my $match (@matches) {
 1155:                     my ($uname,$udom,%userhash);
 1156:                     foreach my $entry (split(/:/,$match)) {
 1157:                         my ($key,$value) =
 1158:                             map {&unescape($_);} split(/=/,$entry);
 1159:                         $userhash{$key} = $value;
 1160:                         if ($key eq 'username') {
 1161:                             $uname = $value;
 1162:                         } elsif ($key eq 'domain') {
 1163:                             $udom = $value;
 1164:                         }
 1165:                     }
 1166:                     $results{$uname.':'.$udom} = \%userhash;
 1167:                 }
 1168:             }
 1169:         }
 1170:     }
 1171:     return %results;
 1172: }
 1173: 
 1174: sub get_instuser {
 1175:     my ($udom,$uname,$id) = @_;
 1176:     my $homeserver = &domain($udom,'primary');
 1177:     my ($outcome,%results);
 1178:     if ($homeserver ne '') {
 1179:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1180:                            &escape($id).':'.&escape($udom),$homeserver);
 1181:         my $host=&hostname($homeserver);
 1182:         if ($queryid !~/^\Q$host\E\_/) {
 1183:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1184:             return;
 1185:         }
 1186:         my $response = &get_query_reply($queryid);
 1187:         my $maxtries = 5;
 1188:         my $tries = 1;
 1189:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1190:             $response = &get_query_reply($queryid);
 1191:             $tries ++;
 1192:         }
 1193:         if (!&error($response) && $response ne 'refused') {
 1194:             if ($response eq 'unavailable') {
 1195:                 $outcome = $response;
 1196:             } else {
 1197:                 $outcome = 'ok';
 1198:                 my @matches = split(/\n/,$response);
 1199:                 foreach my $match (@matches) {
 1200:                     my ($key,$value) = split(/=/,$match);
 1201:                     $results{&unescape($key)} = &thaw_unescape($value);
 1202:                 }
 1203:             }
 1204:         }
 1205:     }
 1206:     my %userinfo;
 1207:     if (ref($results{$uname}) eq 'HASH') {
 1208:         %userinfo = %{$results{$uname}};
 1209:     } 
 1210:     return ($outcome,%userinfo);
 1211: }
 1212: 
 1213: sub inst_rulecheck {
 1214:     my ($udom,$uname,$id,$item,$rules) = @_;
 1215:     my %returnhash;
 1216:     if ($udom ne '') {
 1217:         if (ref($rules) eq 'ARRAY') {
 1218:             @{$rules} = map {&escape($_);} (@{$rules});
 1219:             my $rulestr = join(':',@{$rules});
 1220:             my $homeserver=&domain($udom,'primary');
 1221:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1222:                 my $response;
 1223:                 if ($item eq 'username') {                
 1224:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1225:                                               ':'.&escape($uname).':'.$rulestr,
 1226:                                               $homeserver));
 1227:                 } elsif ($item eq 'id') {
 1228:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1229:                                               ':'.&escape($id).':'.$rulestr,
 1230:                                               $homeserver));
 1231:                 } elsif ($item eq 'selfcreate') {
 1232:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1233:                                                &escape($udom).':'.&escape($uname).
 1234:                                               ':'.$rulestr,$homeserver));
 1235:                 }
 1236:                 if ($response ne 'refused') {
 1237:                     my @pairs=split(/\&/,$response);
 1238:                     foreach my $item (@pairs) {
 1239:                         my ($key,$value)=split(/=/,$item,2);
 1240:                         $key = &unescape($key);
 1241:                         next if ($key =~ /^error: 2 /);
 1242:                         $returnhash{$key}=&thaw_unescape($value);
 1243:                     }
 1244:                 }
 1245:             }
 1246:         }
 1247:     }
 1248:     return %returnhash;
 1249: }
 1250: 
 1251: sub inst_userrules {
 1252:     my ($udom,$check) = @_;
 1253:     my (%ruleshash,@ruleorder);
 1254:     if ($udom ne '') {
 1255:         my $homeserver=&domain($udom,'primary');
 1256:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1257:             my $response;
 1258:             if ($check eq 'id') {
 1259:                 $response=&reply('instidrules:'.&escape($udom),
 1260:                                  $homeserver);
 1261:             } elsif ($check eq 'email') {
 1262:                 $response=&reply('instemailrules:'.&escape($udom),
 1263:                                  $homeserver);
 1264:             } else {
 1265:                 $response=&reply('instuserrules:'.&escape($udom),
 1266:                                  $homeserver);
 1267:             }
 1268:             if (($response ne 'refused') && ($response ne 'error') && 
 1269:                 ($response ne 'unknown_cmd') && 
 1270:                 ($response ne 'no_such_host')) {
 1271:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1272:                 my @pairs=split(/\&/,$hashitems);
 1273:                 foreach my $item (@pairs) {
 1274:                     my ($key,$value)=split(/=/,$item,2);
 1275:                     $key = &unescape($key);
 1276:                     next if ($key =~ /^error: 2 /);
 1277:                     $ruleshash{$key}=&thaw_unescape($value);
 1278:                 }
 1279:                 my @esc_order = split(/\&/,$orderitems);
 1280:                 foreach my $item (@esc_order) {
 1281:                     push(@ruleorder,&unescape($item));
 1282:                 }
 1283:             }
 1284:         }
 1285:     }
 1286:     return (\%ruleshash,\@ruleorder);
 1287: }
 1288: 
 1289: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1290: 
 1291: sub get_domain_defaults {
 1292:     my ($domain) = @_;
 1293:     my $cachetime = 60*60*24;
 1294:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1295:     if (defined($cached)) {
 1296:         if (ref($result) eq 'HASH') {
 1297:             return %{$result};
 1298:         }
 1299:     }
 1300:     my %domdefaults;
 1301:     my %domconfig =
 1302:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1303:                                   'requestcourses','inststatus'],$domain);
 1304:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1305:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1306:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1307:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1308:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1309:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1310:     } else {
 1311:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1312:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1313:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1314:     }
 1315:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1316:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1317:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1318:         } else {
 1319:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1320:         } 
 1321:         my @usertools = ('aboutme','blog','portfolio');
 1322:         foreach my $item (@usertools) {
 1323:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1324:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1325:             }
 1326:         }
 1327:     }
 1328:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1329:         foreach my $item ('official','unofficial') {
 1330:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1331:         }
 1332:     }
 1333:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1334:         foreach my $item ('inststatustypes','inststatusorder') {
 1335:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1336:         }
 1337:     }
 1338:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1339:                                   $cachetime);
 1340:     return %domdefaults;
 1341: }
 1342: 
 1343: # --------------------------------------------------- Assign a key to a student
 1344: 
 1345: sub assign_access_key {
 1346: #
 1347: # a valid key looks like uname:udom#comments
 1348: # comments are being appended
 1349: #
 1350:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1351:     $kdom=
 1352:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1353:     $knum=
 1354:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1355:     $cdom=
 1356:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1357:     $cnum=
 1358:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1359:     $udom=$env{'user.name'} unless (defined($udom));
 1360:     $uname=$env{'user.domain'} unless (defined($uname));
 1361:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1362:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1363:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1364:                                                   # assigned to this person
 1365:                                                   # - this should not happen,
 1366:                                                   # unless something went wrong
 1367:                                                   # the first time around
 1368: # ready to assign
 1369:         $logentry=$1.'; '.$logentry;
 1370:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1371:                                                  $kdom,$knum) eq 'ok') {
 1372: # key now belongs to user
 1373: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1374:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1375:                 &appenv({'environment.'.$envkey => $ckey});
 1376:                 return 'ok';
 1377:             } else {
 1378:                 return 
 1379:   'error: Count not permanently assign key, will need to be re-entered later.';
 1380: 	    }
 1381:         } else {
 1382:             return 'error: Could not assign key, try again later.';
 1383:         }
 1384:     } elsif (!$existing{$ckey}) {
 1385: # the key does not exist
 1386: 	return 'error: The key does not exist';
 1387:     } else {
 1388: # the key is somebody else's
 1389: 	return 'error: The key is already in use';
 1390:     }
 1391: }
 1392: 
 1393: # ------------------------------------------ put an additional comment on a key
 1394: 
 1395: sub comment_access_key {
 1396: #
 1397: # a valid key looks like uname:udom#comments
 1398: # comments are being appended
 1399: #
 1400:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1401:     $cdom=
 1402:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1403:     $cnum=
 1404:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1405:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1406:     if ($existing{$ckey}) {
 1407:         $existing{$ckey}.='; '.$logentry;
 1408: # ready to assign
 1409:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1410:                                                  $cdom,$cnum) eq 'ok') {
 1411: 	    return 'ok';
 1412:         } else {
 1413: 	    return 'error: Count not store comment.';
 1414:         }
 1415:     } else {
 1416: # the key does not exist
 1417: 	return 'error: The key does not exist';
 1418:     }
 1419: }
 1420: 
 1421: # ------------------------------------------------------ Generate a set of keys
 1422: 
 1423: sub generate_access_keys {
 1424:     my ($number,$cdom,$cnum,$logentry)=@_;
 1425:     $cdom=
 1426:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1427:     $cnum=
 1428:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1429:     unless (&allowed('mky',$cdom)) { return 0; }
 1430:     unless (($cdom) && ($cnum)) { return 0; }
 1431:     if ($number>10000) { return 0; }
 1432:     sleep(2); # make sure don't get same seed twice
 1433:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1434:     my $total=0;
 1435:     for (my $i=1;$i<=$number;$i++) {
 1436:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1437:                   sprintf("%lx",int(100000*rand)).'-'.
 1438:                   sprintf("%lx",int(100000*rand));
 1439:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1440:        $newkey=~s/0/h/g; # and also 0 and O
 1441:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1442:        if ($existing{$newkey}) {
 1443:            $i--;
 1444:        } else {
 1445: 	  if (&put('accesskeys',
 1446:               { $newkey => '# generated '.localtime().
 1447:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1448:                            '; '.$logentry },
 1449: 		   $cdom,$cnum) eq 'ok') {
 1450:               $total++;
 1451: 	  }
 1452:        }
 1453:     }
 1454:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1455:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1456:     return $total;
 1457: }
 1458: 
 1459: # ------------------------------------------------------- Validate an accesskey
 1460: 
 1461: sub validate_access_key {
 1462:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1463:     $cdom=
 1464:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1465:     $cnum=
 1466:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1467:     $udom=$env{'user.domain'} unless (defined($udom));
 1468:     $uname=$env{'user.name'} unless (defined($uname));
 1469:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1470:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1471: }
 1472: 
 1473: # ------------------------------------- Find the section of student in a course
 1474: sub devalidate_getsection_cache {
 1475:     my ($udom,$unam,$courseid)=@_;
 1476:     my $hashid="$udom:$unam:$courseid";
 1477:     &devalidate_cache_new('getsection',$hashid);
 1478: }
 1479: 
 1480: sub courseid_to_courseurl {
 1481:     my ($courseid) = @_;
 1482:     #already url style courseid
 1483:     return $courseid if ($courseid =~ m{^/});
 1484: 
 1485:     if (exists($env{'course.'.$courseid.'.num'})) {
 1486: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1487: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1488: 	return "/$cdom/$cnum";
 1489:     }
 1490: 
 1491:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1492:     if (exists($courseinfo{'num'})) {
 1493: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1494:     }
 1495: 
 1496:     return undef;
 1497: }
 1498: 
 1499: sub getsection {
 1500:     my ($udom,$unam,$courseid)=@_;
 1501:     my $cachetime=1800;
 1502: 
 1503:     my $hashid="$udom:$unam:$courseid";
 1504:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1505:     if (defined($cached)) { return $result; }
 1506: 
 1507:     my %Pending; 
 1508:     my %Expired;
 1509:     #
 1510:     # Each role can either have not started yet (pending), be active, 
 1511:     #    or have expired.
 1512:     #
 1513:     # If there is an active role, we are done.
 1514:     #
 1515:     # If there is more than one role which has not started yet, 
 1516:     #     choose the one which will start sooner
 1517:     # If there is one role which has not started yet, return it.
 1518:     #
 1519:     # If there is more than one expired role, choose the one which ended last.
 1520:     # If there is a role which has expired, return it.
 1521:     #
 1522:     $courseid = &courseid_to_courseurl($courseid);
 1523:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1524:     foreach my $key (keys(%roleshash)) {
 1525:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1526:         my $section=$1;
 1527:         if ($key eq $courseid.'_st') { $section=''; }
 1528:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1529:         my $now=time;
 1530:         if (defined($end) && $end && ($now > $end)) {
 1531:             $Expired{$end}=$section;
 1532:             next;
 1533:         }
 1534:         if (defined($start) && $start && ($now < $start)) {
 1535:             $Pending{$start}=$section;
 1536:             next;
 1537:         }
 1538:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1539:     }
 1540:     #
 1541:     # Presumedly there will be few matching roles from the above
 1542:     # loop and the sorting time will be negligible.
 1543:     if (scalar(keys(%Pending))) {
 1544:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1545:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1546:     } 
 1547:     if (scalar(keys(%Expired))) {
 1548:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1549:         my $time = pop(@sorted);
 1550:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1551:     }
 1552:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1553: }
 1554: 
 1555: sub save_cache {
 1556:     &purge_remembered();
 1557:     #&Apache::loncommon::validate_page();
 1558:     undef(%env);
 1559:     undef($env_loaded);
 1560: }
 1561: 
 1562: my $to_remember=-1;
 1563: my %remembered;
 1564: my %accessed;
 1565: my $kicks=0;
 1566: my $hits=0;
 1567: sub make_key {
 1568:     my ($name,$id) = @_;
 1569:     if (length($id) > 65 
 1570: 	&& length(&escape($id)) > 200) {
 1571: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1572:     }
 1573:     return &escape($name.':'.$id);
 1574: }
 1575: 
 1576: sub devalidate_cache_new {
 1577:     my ($name,$id,$debug) = @_;
 1578:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1579:     $id=&make_key($name,$id);
 1580:     $memcache->delete($id);
 1581:     delete($remembered{$id});
 1582:     delete($accessed{$id});
 1583: }
 1584: 
 1585: sub is_cached_new {
 1586:     my ($name,$id,$debug) = @_;
 1587:     $id=&make_key($name,$id);
 1588:     if (exists($remembered{$id})) {
 1589: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1590: 	$accessed{$id}=[&gettimeofday()];
 1591: 	$hits++;
 1592: 	return ($remembered{$id},1);
 1593:     }
 1594:     my $value = $memcache->get($id);
 1595:     if (!(defined($value))) {
 1596: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1597: 	return (undef,undef);
 1598:     }
 1599:     if ($value eq '__undef__') {
 1600: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1601: 	$value=undef;
 1602:     }
 1603:     &make_room($id,$value,$debug);
 1604:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1605:     return ($value,1);
 1606: }
 1607: 
 1608: sub do_cache_new {
 1609:     my ($name,$id,$value,$time,$debug) = @_;
 1610:     $id=&make_key($name,$id);
 1611:     my $setvalue=$value;
 1612:     if (!defined($setvalue)) {
 1613: 	$setvalue='__undef__';
 1614:     }
 1615:     if (!defined($time) ) {
 1616: 	$time=600;
 1617:     }
 1618:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1619:     my $result = $memcache->set($id,$setvalue,$time);
 1620:     if (! $result) {
 1621: 	&logthis("caching of id -> $id  failed");
 1622: 	$memcache->disconnect_all();
 1623:     }
 1624:     # need to make a copy of $value
 1625:     &make_room($id,$value,$debug);
 1626:     return $value;
 1627: }
 1628: 
 1629: sub make_room {
 1630:     my ($id,$value,$debug)=@_;
 1631: 
 1632:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1633:                                     : $value;
 1634:     if ($to_remember<0) { return; }
 1635:     $accessed{$id}=[&gettimeofday()];
 1636:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1637:     my $to_kick;
 1638:     my $max_time=0;
 1639:     foreach my $other (keys(%accessed)) {
 1640: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1641: 	    $to_kick=$other;
 1642: 	    $max_time=&tv_interval($accessed{$other});
 1643: 	}
 1644:     }
 1645:     delete($remembered{$to_kick});
 1646:     delete($accessed{$to_kick});
 1647:     $kicks++;
 1648:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1649:     return;
 1650: }
 1651: 
 1652: sub purge_remembered {
 1653:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1654:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1655:     undef(%remembered);
 1656:     undef(%accessed);
 1657: }
 1658: # ------------------------------------- Read an entry from a user's environment
 1659: 
 1660: sub userenvironment {
 1661:     my ($udom,$unam,@what)=@_;
 1662:     my $items;
 1663:     foreach my $item (@what) {
 1664:         $items.=&escape($item).'&';
 1665:     }
 1666:     $items=~s/\&$//;
 1667:     my %returnhash=();
 1668:     my @answer=split(/\&/,
 1669:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1670:                       &homeserver($unam,$udom)));
 1671:     my $i;
 1672:     for ($i=0;$i<=$#what;$i++) {
 1673: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1674:     }
 1675:     return %returnhash;
 1676: }
 1677: 
 1678: # ---------------------------------------------------------- Get a studentphoto
 1679: sub studentphoto {
 1680:     my ($udom,$unam,$ext) = @_;
 1681:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1682:     if (defined($env{'request.course.id'})) {
 1683:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1684:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1685:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1686:             } else {
 1687:                 my ($result,$perm_reqd)=
 1688: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1689:                 if ($result eq 'ok') {
 1690:                     if (!($perm_reqd eq 'yes')) {
 1691:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1692:                     }
 1693:                 }
 1694:             }
 1695:         }
 1696:     } else {
 1697:         my ($result,$perm_reqd) = 
 1698: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1699:         if ($result eq 'ok') {
 1700:             if (!($perm_reqd eq 'yes')) {
 1701:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1702:             }
 1703:         }
 1704:     }
 1705:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1706: }
 1707: 
 1708: sub retrievestudentphoto {
 1709:     my ($udom,$unam,$ext,$type) = @_;
 1710:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1711:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1712:     if ($ret eq 'ok') {
 1713:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1714:         if ($type eq 'thumbnail') {
 1715:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1716:         }
 1717:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1718:         return $tokenurl;
 1719:     } else {
 1720:         if ($type eq 'thumbnail') {
 1721:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1722:         } else { 
 1723:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1724:         }
 1725:     }
 1726: }
 1727: 
 1728: # -------------------------------------------------------------------- New chat
 1729: 
 1730: sub chatsend {
 1731:     my ($newentry,$anon,$group)=@_;
 1732:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1733:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1734:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1735:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1736: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1737: 		   &escape($newentry)).':'.$group,$chome);
 1738: }
 1739: 
 1740: # ------------------------------------------ Find current version of a resource
 1741: 
 1742: sub getversion {
 1743:     my $fname=&clutter(shift);
 1744:     unless ($fname=~/^\/res\//) { return -1; }
 1745:     return &currentversion(&filelocation('',$fname));
 1746: }
 1747: 
 1748: sub currentversion {
 1749:     my $fname=shift;
 1750:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1751:     if (defined($cached)) { return $result; }
 1752:     my $author=$fname;
 1753:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1754:     my ($udom,$uname)=split(/\//,$author);
 1755:     my $home=homeserver($uname,$udom);
 1756:     if ($home eq 'no_host') { 
 1757:         return -1; 
 1758:     }
 1759:     my $answer=reply("currentversion:$fname",$home);
 1760:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1761: 	return -1;
 1762:     }
 1763:     return &do_cache_new('resversion',$fname,$answer,600);
 1764: }
 1765: 
 1766: # ----------------------------- Subscribe to a resource, return URL if possible
 1767: 
 1768: sub subscribe {
 1769:     my $fname=shift;
 1770:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1771:     $fname=~s/[\n\r]//g;
 1772:     my $author=$fname;
 1773:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1774:     my ($udom,$uname)=split(/\//,$author);
 1775:     my $home=homeserver($uname,$udom);
 1776:     if ($home eq 'no_host') {
 1777:         return 'not_found';
 1778:     }
 1779:     my $answer=reply("sub:$fname",$home);
 1780:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1781: 	$answer.=' by '.$home;
 1782:     }
 1783:     return $answer;
 1784: }
 1785:     
 1786: # -------------------------------------------------------------- Replicate file
 1787: 
 1788: sub repcopy {
 1789:     my $filename=shift;
 1790:     $filename=~s/\/+/\//g;
 1791:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1792:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1793:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1794: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1795: 	return &repcopy_userfile($filename);
 1796:     }
 1797:     $filename=~s/[\n\r]//g;
 1798:     my $transname="$filename.in.transfer";
 1799: # FIXME: this should flock
 1800:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1801:     my $remoteurl=subscribe($filename);
 1802:     if ($remoteurl =~ /^con_lost by/) {
 1803: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1804:            return 'unavailable';
 1805:     } elsif ($remoteurl eq 'not_found') {
 1806: 	   #&logthis("Subscribe returned not_found: $filename");
 1807: 	   return 'not_found';
 1808:     } elsif ($remoteurl =~ /^rejected by/) {
 1809: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1810:            return 'forbidden';
 1811:     } elsif ($remoteurl eq 'directory') {
 1812:            return 'ok';
 1813:     } else {
 1814:         my $author=$filename;
 1815:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1816:         my ($udom,$uname)=split(/\//,$author);
 1817:         my $home=homeserver($uname,$udom);
 1818:         unless ($home eq $perlvar{'lonHostID'}) {
 1819:            my @parts=split(/\//,$filename);
 1820:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1821:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1822:                &logthis("Malconfiguration for replication: $filename");
 1823: 	       return 'bad_request';
 1824:            }
 1825:            my $count;
 1826:            for ($count=5;$count<$#parts;$count++) {
 1827:                $path.="/$parts[$count]";
 1828:                if ((-e $path)!=1) {
 1829: 		   mkdir($path,0777);
 1830:                }
 1831:            }
 1832:            my $ua=new LWP::UserAgent;
 1833:            my $request=new HTTP::Request('GET',"$remoteurl");
 1834:            my $response=$ua->request($request,$transname);
 1835:            if ($response->is_error()) {
 1836: 	       unlink($transname);
 1837:                my $message=$response->status_line;
 1838:                &logthis("<font color=\"blue\">WARNING:"
 1839:                        ." LWP get: $message: $filename</font>");
 1840:                return 'unavailable';
 1841:            } else {
 1842: 	       if ($remoteurl!~/\.meta$/) {
 1843:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1844:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1845:                   if ($mresponse->is_error()) {
 1846: 		      unlink($filename.'.meta');
 1847:                       &logthis(
 1848:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1849:                   }
 1850: 	       }
 1851:                rename($transname,$filename);
 1852:                return 'ok';
 1853:            }
 1854:        }
 1855:     }
 1856: }
 1857: 
 1858: # ------------------------------------------------ Get server side include body
 1859: sub ssi_body {
 1860:     my ($filelink,%form)=@_;
 1861:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1862:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1863:     }
 1864:     my $output='';
 1865:     my $response;
 1866:     if ($filelink=~/^https?\:/) {
 1867:        ($output,$response)=&externalssi($filelink);
 1868:     } else {
 1869:        ($output,$response)=&ssi($filelink,%form);
 1870:     }
 1871:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1872:     $output=~s/^.*?\<body[^\>]*\>//si;
 1873:     $output=~s/\<\/body\s*\>.*?$//si;
 1874:     if (wantarray) {
 1875:         return ($output, $response);
 1876:     } else {
 1877:         return $output;
 1878:     }
 1879: }
 1880: 
 1881: # --------------------------------------------------------- Server Side Include
 1882: 
 1883: sub absolute_url {
 1884:     my ($host_name) = @_;
 1885:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1886:     if ($host_name eq '') {
 1887: 	$host_name = $ENV{'SERVER_NAME'};
 1888:     }
 1889:     return $protocol.$host_name;
 1890: }
 1891: 
 1892: #
 1893: #   Server side include.
 1894: # Parameters:
 1895: #  fn     Possibly encrypted resource name/id.
 1896: #  form   Hash that describes how the rendering should be done
 1897: #         and other things.
 1898: # Returns:
 1899: #   Scalar context: The content of the response.
 1900: #   Array context:  2 element list of the content and the full response object.
 1901: #     
 1902: sub ssi {
 1903: 
 1904:     my ($fn,%form)=@_;
 1905:     my $ua=new LWP::UserAgent;
 1906:     my $request;
 1907: 
 1908:     $form{'no_update_last_known'}=1;
 1909:     &Apache::lonenc::check_encrypt(\$fn);
 1910:     if (%form) {
 1911:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1912:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1913:     } else {
 1914:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1915:     }
 1916: 
 1917:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1918:     my $response=$ua->request($request);
 1919: 
 1920:     if (wantarray) {
 1921: 	return ($response->content, $response);
 1922:     } else {
 1923: 	return $response->content;
 1924:     }
 1925: }
 1926: 
 1927: sub externalssi {
 1928:     my ($url)=@_;
 1929:     my $ua=new LWP::UserAgent;
 1930:     my $request=new HTTP::Request('GET',$url);
 1931:     my $response=$ua->request($request);
 1932:     if (wantarray) {
 1933:         return ($response->content, $response);
 1934:     } else {
 1935:         return $response->content;
 1936:     }
 1937: }
 1938: 
 1939: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1940: 
 1941: sub allowuploaded {
 1942:     my ($srcurl,$url)=@_;
 1943:     $url=&clutter(&declutter($url));
 1944:     my $dir=$url;
 1945:     $dir=~s/\/[^\/]+$//;
 1946:     my %httpref=();
 1947:     my $httpurl=&hreflocation('',$url);
 1948:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1949:     &Apache::lonnet::appenv(\%httpref);
 1950: }
 1951: 
 1952: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1953: # input: action, courseID, current domain, intended
 1954: #        path to file, source of file, instruction to parse file for objects,
 1955: #        ref to hash for embedded objects,
 1956: #        ref to hash for codebase of java objects.
 1957: #
 1958: # output: url to file (if action was uploaddoc), 
 1959: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1960: #
 1961: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1962: # course.
 1963: #
 1964: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1965: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1966: #          course's home server.
 1967: #
 1968: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1969: #          be copied from $source (current location) to 
 1970: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1971: #         and will then be copied to
 1972: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1973: #         course's home server.
 1974: #
 1975: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1976: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1977: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1978: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1979: #         in course's home server.
 1980: #
 1981: 
 1982: sub process_coursefile {
 1983:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1984:     my $fetchresult;
 1985:     my $home=&homeserver($docuname,$docudom);
 1986:     if ($action eq 'propagate') {
 1987:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1988: 			     $home);
 1989:     } else {
 1990:         my $fpath = '';
 1991:         my $fname = $file;
 1992:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1993:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1994:         my $filepath = &build_filepath($fpath);
 1995:         if ($action eq 'copy') {
 1996:             if ($source eq '') {
 1997:                 $fetchresult = 'no source file';
 1998:                 return $fetchresult;
 1999:             } else {
 2000:                 my $destination = $filepath.'/'.$fname;
 2001:                 rename($source,$destination);
 2002:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2003:                                  $home);
 2004:             }
 2005:         } elsif ($action eq 'uploaddoc') {
 2006:             open(my $fh,'>'.$filepath.'/'.$fname);
 2007:             print $fh $env{'form.'.$source};
 2008:             close($fh);
 2009:             if ($parser eq 'parse') {
 2010:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2011:                 unless ($parse_result eq 'ok') {
 2012:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2013:                 }
 2014:             }
 2015:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2016:                                  $home);
 2017:             if ($fetchresult eq 'ok') {
 2018:                 return '/uploaded/'.$fpath.'/'.$fname;
 2019:             } else {
 2020:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2021:                         ' to host '.$home.': '.$fetchresult);
 2022:                 return '/adm/notfound.html';
 2023:             }
 2024:         }
 2025:     }
 2026:     unless ( $fetchresult eq 'ok') {
 2027:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2028:              ' to host '.$home.': '.$fetchresult);
 2029:     }
 2030:     return $fetchresult;
 2031: }
 2032: 
 2033: sub build_filepath {
 2034:     my ($fpath) = @_;
 2035:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2036:     unless ($fpath eq '') {
 2037:         my @parts=split('/',$fpath);
 2038:         foreach my $part (@parts) {
 2039:             $filepath.= '/'.$part;
 2040:             if ((-e $filepath)!=1) {
 2041:                 mkdir($filepath,0777);
 2042:             }
 2043:         }
 2044:     }
 2045:     return $filepath;
 2046: }
 2047: 
 2048: sub store_edited_file {
 2049:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2050:     my $file = $primary_url;
 2051:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2052:     my $fpath = '';
 2053:     my $fname = $file;
 2054:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2055:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2056:     my $filepath = &build_filepath($fpath);
 2057:     open(my $fh,'>'.$filepath.'/'.$fname);
 2058:     print $fh $content;
 2059:     close($fh);
 2060:     my $home=&homeserver($docuname,$docudom);
 2061:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2062: 			  $home);
 2063:     if ($$fetchresult eq 'ok') {
 2064:         return '/uploaded/'.$fpath.'/'.$fname;
 2065:     } else {
 2066:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2067: 		 ' to host '.$home.': '.$$fetchresult);
 2068:         return '/adm/notfound.html';
 2069:     }
 2070: }
 2071: 
 2072: sub clean_filename {
 2073:     my ($fname,$args)=@_;
 2074: # Replace Windows backslashes by forward slashes
 2075:     $fname=~s/\\/\//g;
 2076:     if (!$args->{'keep_path'}) {
 2077:         # Get rid of everything but the actual filename
 2078: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2079:     }
 2080: # Replace spaces by underscores
 2081:     $fname=~s/\s+/\_/g;
 2082: # Replace all other weird characters by nothing
 2083:     $fname=~s{[^/\w\.\-]}{}g;
 2084: # Replace all .\d. sequences with _\d. so they no longer look like version
 2085: # numbers
 2086:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2087:     return $fname;
 2088: }
 2089: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2090: sub resizeImage {
 2091: 	my($img_url) = @_;	
 2092: 	my $ima = Image::Magick->new;                       
 2093:         $ima->Read($img_url);
 2094: 	if($ima->Get('width') > 400)
 2095: 	{
 2096: 		my $factor = $ima->Get('width')/400;
 2097:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2098: 	}
 2099: 	if($ima->Get('height') > 500)
 2100:         {
 2101:         	my $factor = $ima->Get('height')/500;
 2102:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2103:         } 
 2104: 		
 2105: 	$ima->Write($img_url);
 2106: }
 2107: 
 2108: #Wrapper function for userphotoupload
 2109: sub userphotoupload
 2110: {
 2111: 	my($formname,$subdir) = @_;
 2112: 	$upload_photo_form = 1;
 2113: 	return &userfileupload($formname,undef,$subdir);
 2114: }
 2115: 
 2116: # --------------- Take an uploaded file and put it into the userfiles directory
 2117: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2118: #                    the desired filenam is in $env{"form.$formname.filename"}
 2119: #        $coursedoc - if true up to the current course
 2120: #                     if false
 2121: #        $subdir - directory in userfile to store the file into
 2122: #        $parser - instruction to parse file for objects ($parser = parse)    
 2123: #        $allfiles - reference to hash for embedded objects
 2124: #        $codebase - reference to hash for codebase of java objects
 2125: #        $desuname - username for permanent storage of uploaded file
 2126: #        $dsetudom - domain for permanaent storage of uploaded file
 2127: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2128: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2129: # 
 2130: # output: url of file in userspace, or error: <message> 
 2131: #             or /adm/notfound.html if failure to upload occurse
 2132: 
 2133: 
 2134: sub userfileupload {
 2135:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2136:         $destudom,$thumbwidth,$thumbheight)=@_;
 2137:     if (!defined($subdir)) { $subdir='unknown'; }
 2138:     my $fname=$env{'form.'.$formname.'.filename'};
 2139:     $fname=&clean_filename($fname);
 2140: # See if there is anything left
 2141:     unless ($fname) { return 'error: no uploaded file'; }
 2142:     chop($env{'form.'.$formname});
 2143:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2144:         my $now = time;
 2145:         my $filepath = 'tmp/helprequests/'.$now;
 2146:         my @parts=split(/\//,$filepath);
 2147:         my $fullpath = $perlvar{'lonDaemons'};
 2148:         for (my $i=0;$i<@parts;$i++) {
 2149:             $fullpath .= '/'.$parts[$i];
 2150:             if ((-e $fullpath)!=1) {
 2151:                 mkdir($fullpath,0777);
 2152:             }
 2153:         }
 2154:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2155:         print $fh $env{'form.'.$formname};
 2156:         close($fh);
 2157:         return $fullpath.'/'.$fname;
 2158:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2159:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2160:                        '_'.$env{'user.domain'}.'/pending';
 2161:         my @parts=split(/\//,$filepath);
 2162:         my $fullpath = $perlvar{'lonDaemons'};
 2163:         for (my $i=0;$i<@parts;$i++) {
 2164:             $fullpath .= '/'.$parts[$i];
 2165:             if ((-e $fullpath)!=1) {
 2166:                 mkdir($fullpath,0777);
 2167:             }
 2168:         }
 2169:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2170:         print $fh $env{'form.'.$formname};
 2171:         close($fh);
 2172:         return $fullpath.'/'.$fname;
 2173:     }
 2174:     if ($subdir eq 'scantron') {
 2175:         $fname = 'scantron_orig_'.$fname;
 2176:     } else {   
 2177: # Create the directory if not present
 2178:         $fname="$subdir/$fname";
 2179:     }
 2180:     if ($coursedoc) {
 2181: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2182: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2183:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2184:             return &finishuserfileupload($docuname,$docudom,
 2185: 					 $formname,$fname,$parser,$allfiles,
 2186: 					 $codebase,$thumbwidth,$thumbheight);
 2187:         } else {
 2188:             $fname=$env{'form.folder'}.'/'.$fname;
 2189:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2190: 				       $fname,$formname,$parser,
 2191: 				       $allfiles,$codebase);
 2192:         }
 2193:     } elsif (defined($destuname)) {
 2194:         my $docuname=$destuname;
 2195:         my $docudom=$destudom;
 2196: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2197: 				     $parser,$allfiles,$codebase,
 2198:                                      $thumbwidth,$thumbheight);
 2199:         
 2200:     } else {
 2201:         my $docuname=$env{'user.name'};
 2202:         my $docudom=$env{'user.domain'};
 2203:         if (exists($env{'form.group'})) {
 2204:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2205:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2206:         }
 2207: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2208: 				     $parser,$allfiles,$codebase,
 2209:                                      $thumbwidth,$thumbheight);
 2210:     }
 2211: }
 2212: 
 2213: sub finishuserfileupload {
 2214:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2215:         $thumbwidth,$thumbheight) = @_;
 2216:     my $path=$docudom.'/'.$docuname.'/';
 2217:     my $filepath=$perlvar{'lonDocRoot'};
 2218:   
 2219:     my ($fnamepath,$file,$fetchthumb);
 2220:     $file=$fname;
 2221:     if ($fname=~m|/|) {
 2222:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2223: 	$path.=$fnamepath.'/';
 2224:     }
 2225:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2226:     my $count;
 2227:     for ($count=4;$count<=$#parts;$count++) {
 2228:         $filepath.="/$parts[$count]";
 2229:         if ((-e $filepath)!=1) {
 2230: 	    mkdir($filepath,0777);
 2231:         }
 2232:     }
 2233: 
 2234: # Save the file
 2235:     {
 2236: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2237: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2238: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2239: 	    return '/adm/notfound.html';
 2240: 	}
 2241: 	if (!print FH ($env{'form.'.$formname})) {
 2242: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2243: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2244: 	    return '/adm/notfound.html';
 2245: 	}
 2246: 	close(FH);
 2247: 	if($upload_photo_form==1)
 2248: 	{
 2249: 		resizeImage($filepath.'/'.$file);		
 2250: 		$upload_photo_form = 0;
 2251: 	}
 2252:     }
 2253:     if ($parser eq 'parse') {
 2254:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2255: 						   $codebase);
 2256:         unless ($parse_result eq 'ok') {
 2257:             &logthis('Failed to parse '.$filepath.$file.
 2258: 		     ' for embedded media: '.$parse_result); 
 2259:         }
 2260:     }
 2261:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2262:         my $input = $filepath.'/'.$file;
 2263:         my $output = $filepath.'/'.'tn-'.$file;
 2264:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2265:         system("convert -sample $thumbsize $input $output");
 2266:         if (-e $filepath.'/'.'tn-'.$file) {
 2267:             $fetchthumb  = 1; 
 2268:         }
 2269:     }
 2270:  
 2271: # Notify homeserver to grep it
 2272: #
 2273:     my $docuhome=&homeserver($docuname,$docudom);	
 2274:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2275:     if ($fetchresult eq 'ok') {
 2276:         if ($fetchthumb) {
 2277:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2278:             if ($thumbresult ne 'ok') {
 2279:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2280:                          $docuhome.': '.$thumbresult);
 2281:             }
 2282:         }
 2283: #
 2284: # Return the URL to it
 2285:         return '/uploaded/'.$path.$file;
 2286:     } else {
 2287:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2288: 		 ': '.$fetchresult);
 2289:         return '/adm/notfound.html';
 2290:     }
 2291: }
 2292: 
 2293: sub extract_embedded_items {
 2294:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2295:     my @state = ();
 2296:     my %javafiles = (
 2297:                       codebase => '',
 2298:                       code => '',
 2299:                       archive => ''
 2300:                     );
 2301:     my %mediafiles = (
 2302:                       src => '',
 2303:                       movie => '',
 2304:                      );
 2305:     my $p;
 2306:     if ($content) {
 2307:         $p = HTML::LCParser->new($content);
 2308:     } else {
 2309:         $p = HTML::LCParser->new($fullpath);
 2310:     }
 2311:     while (my $t=$p->get_token()) {
 2312: 	if ($t->[0] eq 'S') {
 2313: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2314: 	    push(@state, $tagname);
 2315:             if (lc($tagname) eq 'allow') {
 2316:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2317:             }
 2318: 	    if (lc($tagname) eq 'img') {
 2319: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2320: 	    }
 2321: 	    if (lc($tagname) eq 'a') {
 2322: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2323: 	    }
 2324:             if (lc($tagname) eq 'script') {
 2325:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2326:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2327:                 } else {
 2328:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2329:                 }
 2330:             }
 2331:             if (lc($tagname) eq 'link') {
 2332:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2333:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2334:                 }
 2335:             }
 2336: 	    if (lc($tagname) eq 'object' ||
 2337: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2338: 		foreach my $item (keys(%javafiles)) {
 2339: 		    $javafiles{$item} = '';
 2340: 		}
 2341: 	    }
 2342: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2343: 		my $name = lc($attr->{'name'});
 2344: 		foreach my $item (keys(%javafiles)) {
 2345: 		    if ($name eq $item) {
 2346: 			$javafiles{$item} = $attr->{'value'};
 2347: 			last;
 2348: 		    }
 2349: 		}
 2350: 		foreach my $item (keys(%mediafiles)) {
 2351: 		    if ($name eq $item) {
 2352: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2353: 			last;
 2354: 		    }
 2355: 		}
 2356: 	    }
 2357: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2358: 		foreach my $item (keys(%javafiles)) {
 2359: 		    if ($attr->{$item}) {
 2360: 			$javafiles{$item} = $attr->{$item};
 2361: 			last;
 2362: 		    }
 2363: 		}
 2364: 		foreach my $item (keys(%mediafiles)) {
 2365: 		    if ($attr->{$item}) {
 2366: 			&add_filetype($allfiles,$attr->{$item},$item);
 2367: 			last;
 2368: 		    }
 2369: 		}
 2370: 	    }
 2371: 	} elsif ($t->[0] eq 'E') {
 2372: 	    my ($tagname) = ($t->[1]);
 2373: 	    if ($javafiles{'codebase'} ne '') {
 2374: 		$javafiles{'codebase'} .= '/';
 2375: 	    }  
 2376: 	    if (lc($tagname) eq 'applet' ||
 2377: 		lc($tagname) eq 'object' ||
 2378: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2379: 		) {
 2380: 		foreach my $item (keys(%javafiles)) {
 2381: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2382: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2383: 			&add_filetype($allfiles,$file,$item);
 2384: 		    }
 2385: 		}
 2386: 	    } 
 2387: 	    pop @state;
 2388: 	}
 2389:     }
 2390:     return 'ok';
 2391: }
 2392: 
 2393: sub add_filetype {
 2394:     my ($allfiles,$file,$type)=@_;
 2395:     if (exists($allfiles->{$file})) {
 2396: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2397: 	    push(@{$allfiles->{$file}}, &escape($type));
 2398: 	}
 2399:     } else {
 2400: 	@{$allfiles->{$file}} = (&escape($type));
 2401:     }
 2402: }
 2403: 
 2404: sub removeuploadedurl {
 2405:     my ($url)=@_;	
 2406:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2407:     return &removeuserfile($uname,$udom,$fname);
 2408: }
 2409: 
 2410: sub removeuserfile {
 2411:     my ($docuname,$docudom,$fname)=@_;
 2412:     my $home=&homeserver($docuname,$docudom);    
 2413:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2414:     if ($result eq 'ok') {	
 2415:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2416:             my $metafile = $fname.'.meta';
 2417:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2418: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2419:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2420:             my $sqlresult = 
 2421:                 &update_portfolio_table($docuname,$docudom,$file,
 2422:                                         'portfolio_metadata',$group,
 2423:                                         'delete');
 2424:         }
 2425:     }
 2426:     return $result;
 2427: }
 2428: 
 2429: sub mkdiruserfile {
 2430:     my ($docuname,$docudom,$dir)=@_;
 2431:     my $home=&homeserver($docuname,$docudom);
 2432:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2433: }
 2434: 
 2435: sub renameuserfile {
 2436:     my ($docuname,$docudom,$old,$new)=@_;
 2437:     my $home=&homeserver($docuname,$docudom);
 2438:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2439:                         &escape("$old").':'.&escape("$new"),$home);
 2440:     if ($result eq 'ok') {
 2441:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2442:             my $oldmeta = $old.'.meta';
 2443:             my $newmeta = $new.'.meta';
 2444:             my $metaresult = 
 2445:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2446: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2447:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2448:             my $sqlresult = 
 2449:                 &update_portfolio_table($docuname,$docudom,$file,
 2450:                                         'portfolio_metadata',$group,
 2451:                                         'delete');
 2452:         }
 2453:     }
 2454:     return $result;
 2455: }
 2456: 
 2457: # ------------------------------------------------------------------------- Log
 2458: 
 2459: sub log {
 2460:     my ($dom,$nam,$hom,$what)=@_;
 2461:     return critical("log:$dom:$nam:$what",$hom);
 2462: }
 2463: 
 2464: # ------------------------------------------------------------------ Course Log
 2465: #
 2466: # This routine flushes several buffers of non-mission-critical nature
 2467: #
 2468: 
 2469: sub flushcourselogs {
 2470:     &logthis('Flushing log buffers');
 2471: #
 2472: # course logs
 2473: # This is a log of all transactions in a course, which can be used
 2474: # for data mining purposes
 2475: #
 2476: # It also collects the courseid database, which lists last transaction
 2477: # times and course titles for all courseids
 2478: #
 2479:     my %courseidbuffer=();
 2480:     foreach my $crsid (keys(%courselogs)) {
 2481:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2482: 		          &escape($courselogs{$crsid}),
 2483: 		          $coursehombuf{$crsid}) eq 'ok') {
 2484: 	    delete $courselogs{$crsid};
 2485:         } else {
 2486:             &logthis('Failed to flush log buffer for '.$crsid);
 2487:             if (length($courselogs{$crsid})>40000) {
 2488:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2489:                         " exceeded maximum size, deleting.</font>");
 2490:                delete $courselogs{$crsid};
 2491:             }
 2492:         }
 2493:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2494:             'description' => $coursedescrbuf{$crsid},
 2495:             'inst_code'    => $courseinstcodebuf{$crsid},
 2496:             'type'        => $coursetypebuf{$crsid},
 2497:             'owner'       => $courseownerbuf{$crsid},
 2498:         };
 2499:     }
 2500: #
 2501: # Write course id database (reverse lookup) to homeserver of courses 
 2502: # Is used in pickcourse
 2503: #
 2504:     foreach my $crs_home (keys(%courseidbuffer)) {
 2505:         my $response = &courseidput(&host_domain($crs_home),
 2506:                                     $courseidbuffer{$crs_home},
 2507:                                     $crs_home,'timeonly');
 2508:     }
 2509: #
 2510: # File accesses
 2511: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2512: #
 2513:     foreach my $entry (keys(%accesshash)) {
 2514:         if ($entry =~ /___count$/) {
 2515:             my ($dom,$name);
 2516:             ($dom,$name,undef)=
 2517: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2518:             if (! defined($dom) || $dom eq '' || 
 2519:                 ! defined($name) || $name eq '') {
 2520:                 my $cid = $env{'request.course.id'};
 2521:                 $dom  = $env{'request.'.$cid.'.domain'};
 2522:                 $name = $env{'request.'.$cid.'.num'};
 2523:             }
 2524:             my $value = $accesshash{$entry};
 2525:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2526:             my %temphash=($url => $value);
 2527:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2528:             if ($result eq 'ok') {
 2529:                 delete $accesshash{$entry};
 2530:             } elsif ($result eq 'unknown_cmd') {
 2531:                 # Target server has old code running on it.
 2532:                 my %temphash=($entry => $value);
 2533:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2534:                     delete $accesshash{$entry};
 2535:                 }
 2536:             }
 2537:         } else {
 2538:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2539:             my %temphash=($entry => $accesshash{$entry});
 2540:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2541:                 delete $accesshash{$entry};
 2542:             }
 2543:         }
 2544:     }
 2545: #
 2546: # Roles
 2547: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2548: #
 2549:     foreach my $entry (keys(%userrolehash)) {
 2550:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2551: 	    split(/\:/,$entry);
 2552:         if (&Apache::lonnet::put('nohist_userroles',
 2553:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2554:                 $rudom,$runame) eq 'ok') {
 2555: 	    delete $userrolehash{$entry};
 2556:         }
 2557:     }
 2558: #
 2559: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2560: #
 2561:     my %domrolebuffer = ();
 2562:     foreach my $entry (keys(%domainrolehash)) {
 2563:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2564:         if ($domrolebuffer{$rudom}) {
 2565:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2566:                       '='.&escape($domainrolehash{$entry});
 2567:         } else {
 2568:             $domrolebuffer{$rudom}.=&escape($entry).
 2569:                       '='.&escape($domainrolehash{$entry});
 2570:         }
 2571:         delete $domainrolehash{$entry};
 2572:     }
 2573:     foreach my $dom (keys(%domrolebuffer)) {
 2574: 	my %servers = &get_servers($dom,'library');
 2575: 	foreach my $tryserver (keys(%servers)) {
 2576: 	    unless (&reply('domroleput:'.$dom.':'.
 2577: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2578: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2579: 	    }
 2580:         }
 2581:     }
 2582:     $dumpcount++;
 2583: }
 2584: 
 2585: sub courselog {
 2586:     my $what=shift;
 2587:     $what=time.':'.$what;
 2588:     unless ($env{'request.course.id'}) { return ''; }
 2589:     $coursedombuf{$env{'request.course.id'}}=
 2590:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2591:     $coursenumbuf{$env{'request.course.id'}}=
 2592:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2593:     $coursehombuf{$env{'request.course.id'}}=
 2594:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2595:     $coursedescrbuf{$env{'request.course.id'}}=
 2596:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2597:     $courseinstcodebuf{$env{'request.course.id'}}=
 2598:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2599:     $courseownerbuf{$env{'request.course.id'}}=
 2600:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2601:     $coursetypebuf{$env{'request.course.id'}}=
 2602:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2603:     if (defined $courselogs{$env{'request.course.id'}}) {
 2604: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2605:     } else {
 2606: 	$courselogs{$env{'request.course.id'}}.=$what;
 2607:     }
 2608:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2609: 	&flushcourselogs();
 2610:     }
 2611: }
 2612: 
 2613: sub courseacclog {
 2614:     my $fnsymb=shift;
 2615:     unless ($env{'request.course.id'}) { return ''; }
 2616:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2617:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2618:         $what.=':POST';
 2619:         # FIXME: Probably ought to escape things....
 2620: 	foreach my $key (keys(%env)) {
 2621:             if ($key=~/^form\.(.*)/) {
 2622:                 my $formitem = $1;
 2623:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2624:                     $what.=':'.$formitem.'='.$env{$key};
 2625:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2626:                     $what.=':'.$formitem.'='.$env{$key};
 2627:                 }
 2628:             }
 2629:         }
 2630:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2631:         # FIXME: We should not be depending on a form parameter that someone
 2632:         # editing lonsearchcat.pm might change in the future.
 2633:         if ($env{'form.phase'} eq 'course_search') {
 2634:             $what.= ':POST';
 2635:             # FIXME: Probably ought to escape things....
 2636:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2637:                                  'crsdiscuss') {
 2638:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2639:             }
 2640:         }
 2641:     }
 2642:     &courselog($what);
 2643: }
 2644: 
 2645: sub countacc {
 2646:     my $url=&declutter(shift);
 2647:     return if (! defined($url) || $url eq '');
 2648:     unless ($env{'request.course.id'}) { return ''; }
 2649:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2650:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2651:     $accesshash{$key}++;
 2652: }
 2653: 
 2654: sub linklog {
 2655:     my ($from,$to)=@_;
 2656:     $from=&declutter($from);
 2657:     $to=&declutter($to);
 2658:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2659:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2660: }
 2661:   
 2662: sub userrolelog {
 2663:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2664:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2665:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2666:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2667:         ($trole=~/^ta/)) {
 2668:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2669:        $userrolehash
 2670:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2671:                     =$tend.':'.$tstart;
 2672:     }
 2673:     if (($env{'request.role'} =~ /dc\./) &&
 2674: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2675: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2676: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2677:        $userrolehash
 2678:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2679:                     =$tend.':'.$tstart;
 2680:     }
 2681:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2682:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2683:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2684:         ($trole=~/^sc/)) {
 2685:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2686:        $domainrolehash
 2687:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2688:                     = $tend.':'.$tstart;
 2689:     }
 2690: }
 2691: 
 2692: sub courserolelog {
 2693:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2694:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2695:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2696:         ($trole eq 'ta') || ($trole eq 'st') ||
 2697:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2698:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2699:             my $cdom = $1;
 2700:             my $cnum = $2;
 2701:             my $sec = $3;
 2702:             my $namespace = 'rolelog';
 2703:             my %storehash = (
 2704:                                role    => $trole,
 2705:                                start   => $tstart,
 2706:                                end     => $tend,
 2707:                                selfenroll => $selfenroll,
 2708:                                context    => $context,
 2709:                             );
 2710:             if ($trole eq 'gr') {
 2711:                 $namespace = 'groupslog';
 2712:                 $storehash{'group'} = $sec;
 2713:             } else {
 2714:                 $storehash{'section'} = $sec;
 2715:             }
 2716:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2717:             if (($trole ne 'st') || ($sec ne '')) {
 2718:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2719:             }
 2720:         }
 2721:     }
 2722:     return;
 2723: }
 2724: 
 2725: sub get_course_adv_roles {
 2726:     my ($cid,$codes) = @_;
 2727:     $cid=$env{'request.course.id'} unless (defined($cid));
 2728:     my %coursehash=&coursedescription($cid);
 2729:     my $crstype = &Apache::loncommon::course_type($cid);
 2730:     my %nothide=();
 2731:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2732:         if ($user !~ /:/) {
 2733: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2734:         } else {
 2735:             $nothide{$user}=1;
 2736:         }
 2737:     }
 2738:     my %returnhash=();
 2739:     my %dumphash=
 2740:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2741:     my $now=time;
 2742:     my %privileged;
 2743:     foreach my $entry (keys(%dumphash)) {
 2744: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2745:         if (($tstart) && ($tstart<0)) { next; }
 2746:         if (($tend) && ($tend<$now)) { next; }
 2747:         if (($tstart) && ($now<$tstart)) { next; }
 2748:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2749: 	if ($username eq '' || $domain eq '') { next; }
 2750:         unless (ref($privileged{$domain}) eq 'HASH') {
 2751:             my %dompersonnel =
 2752:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2753:             $privileged{$domain} = {};
 2754:             foreach my $server (keys(%dompersonnel)) {
 2755:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2756:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2757:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2758:                         $privileged{$udom}{$uname} = 1;
 2759:                     }
 2760:                 }
 2761:             }
 2762:         }
 2763:         if ((exists($privileged{$domain}{$username})) && 
 2764:             (!$nothide{$username.':'.$domain})) { next; }
 2765: 	if ($role eq 'cr') { next; }
 2766:         if ($codes) {
 2767:             if ($section) { $role .= ':'.$section; }
 2768:             if ($returnhash{$role}) {
 2769:                 $returnhash{$role}.=','.$username.':'.$domain;
 2770:             } else {
 2771:                 $returnhash{$role}=$username.':'.$domain;
 2772:             }
 2773:         } else {
 2774:             my $key=&plaintext($role,$crstype);
 2775:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2776:             if ($returnhash{$key}) {
 2777: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2778:             } else {
 2779:                 $returnhash{$key}=$username.':'.$domain;
 2780:             }
 2781:         }
 2782:     }
 2783:     return %returnhash;
 2784: }
 2785: 
 2786: sub get_my_roles {
 2787:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2788:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2789:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2790:     my (%dumphash,%nothide);
 2791:     if ($context eq 'userroles') { 
 2792:         %dumphash = &dump('roles',$udom,$uname);
 2793:     } else {
 2794:         %dumphash=
 2795:             &dump('nohist_userroles',$udom,$uname);
 2796:         if ($hidepriv) {
 2797:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2798:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2799:                 if ($user !~ /:/) {
 2800:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2801:                 } else {
 2802:                     $nothide{$user} = 1;
 2803:                 }
 2804:             }
 2805:         }
 2806:     }
 2807:     my %returnhash=();
 2808:     my $now=time;
 2809:     my %privileged;
 2810:     foreach my $entry (keys(%dumphash)) {
 2811:         my ($role,$tend,$tstart);
 2812:         if ($context eq 'userroles') {
 2813: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2814:         } else {
 2815:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2816:         }
 2817:         if (($tstart) && ($tstart<0)) { next; }
 2818:         my $status = 'active';
 2819:         if (($tend) && ($tend<=$now)) {
 2820:             $status = 'previous';
 2821:         } 
 2822:         if (($tstart) && ($now<$tstart)) {
 2823:             $status = 'future';
 2824:         }
 2825:         if (ref($types) eq 'ARRAY') {
 2826:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2827:                 next;
 2828:             } 
 2829:         } else {
 2830:             if ($status ne 'active') {
 2831:                 next;
 2832:             }
 2833:         }
 2834:         my ($rolecode,$username,$domain,$section,$area);
 2835:         if ($context eq 'userroles') {
 2836:             ($area,$rolecode) = split(/_/,$entry);
 2837:             (undef,$domain,$username,$section) = split(/\//,$area);
 2838:         } else {
 2839:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2840:         }
 2841:         if (ref($roledoms) eq 'ARRAY') {
 2842:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2843:                 next;
 2844:             }
 2845:         }
 2846:         if (ref($roles) eq 'ARRAY') {
 2847:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2848:                 if ($role =~ /^cr\//) {
 2849:                     if (!grep(/^cr$/,@{$roles})) {
 2850:                         next;
 2851:                     }
 2852:                 } else {
 2853:                     next;
 2854:                 }
 2855:             }
 2856:         }
 2857:         if ($hidepriv) {
 2858:             if ($context eq 'userroles') {
 2859:                 if ((&privileged($username,$domain)) &&
 2860:                     (!$nothide{$username.':'.$domain})) {
 2861:                     next;
 2862:                 }
 2863:             } else {
 2864:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2865:                     my %dompersonnel =
 2866:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2867:                     $privileged{$domain} = {};
 2868:                     if (keys(%dompersonnel)) {
 2869:                         foreach my $server (keys(%dompersonnel)) {
 2870:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2871:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2872:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2873:                                     $privileged{$udom}{$uname} = $trole;
 2874:                                 }
 2875:                             }
 2876:                         }
 2877:                     }
 2878:                 }
 2879:                 if (exists($privileged{$domain}{$username})) {
 2880:                     if (!$nothide{$username.':'.$domain}) {
 2881:                         next;
 2882:                     }
 2883:                 }
 2884:             }
 2885:         }
 2886:         if ($withsec) {
 2887:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2888:                 $tstart.':'.$tend;
 2889:         } else {
 2890:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2891:         }
 2892:     }
 2893:     return %returnhash;
 2894: }
 2895: 
 2896: # ----------------------------------------------------- Frontpage Announcements
 2897: #
 2898: #
 2899: 
 2900: sub postannounce {
 2901:     my ($server,$text)=@_;
 2902:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2903:     unless ($text=~/\w/) { $text=''; }
 2904:     return &reply('setannounce:'.&escape($text),$server);
 2905: }
 2906: 
 2907: sub getannounce {
 2908: 
 2909:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2910: 	my $announcement='';
 2911: 	while (my $line = <$fh>) { $announcement .= $line; }
 2912: 	close($fh);
 2913: 	if ($announcement=~/\w/) { 
 2914: 	    return 
 2915:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2916:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2917: 	} else {
 2918: 	    return '';
 2919: 	}
 2920:     } else {
 2921: 	return '';
 2922:     }
 2923: }
 2924: 
 2925: # ---------------------------------------------------------- Course ID routines
 2926: # Deal with domain's nohist_courseid.db files
 2927: #
 2928: 
 2929: sub courseidput {
 2930:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2931:     my $outcome;
 2932:     if ($caller eq 'timeonly') {
 2933:         my $cids = '';
 2934:         foreach my $item (keys(%$storehash)) {
 2935:             $cids.=&escape($item).'&';
 2936:         }
 2937:         $cids=~s/\&$//;
 2938:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2939:                           $coursehome);       
 2940:     } else {
 2941:         my $items = '';
 2942:         foreach my $item (keys(%$storehash)) {
 2943:             $items.= &escape($item).'='.
 2944:                      &freeze_escape($$storehash{$item}).'&';
 2945:         }
 2946:         $items=~s/\&$//;
 2947:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2948:                           $coursehome);
 2949:     }
 2950:     if ($outcome eq 'unknown_cmd') {
 2951:         my $what;
 2952:         foreach my $cid (keys(%$storehash)) {
 2953:             $what .= &escape($cid).'=';
 2954:             foreach my $item ('description','inst_code','owner','type') {
 2955:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2956:             }
 2957:             $what =~ s/\:$/&/;
 2958:         }
 2959:         $what =~ s/\&$//;  
 2960:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2961:     } else {
 2962:         return $outcome;
 2963:     }
 2964: }
 2965: 
 2966: sub courseiddump {
 2967:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2968:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2969:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2970:     my $as_hash = 1;
 2971:     my %returnhash;
 2972:     if (!$domfilter) { $domfilter=''; }
 2973:     my %libserv = &all_library();
 2974:     foreach my $tryserver (keys(%libserv)) {
 2975:         if ( (  $hostidflag == 1 
 2976: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2977: 	     || (!defined($hostidflag)) ) {
 2978: 
 2979: 	    if (($domfilter eq '') ||
 2980: 		(&host_domain($tryserver) eq $domfilter)) {
 2981:                 my $rep = 
 2982:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2983:                          $sincefilter.':'.&escape($descfilter).':'.
 2984:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2985:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2986:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2987:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2988:                          $showhidden.':'.$caller,$tryserver);
 2989:                 my @pairs=split(/\&/,$rep);
 2990:                 foreach my $item (@pairs) {
 2991:                     my ($key,$value)=split(/\=/,$item,2);
 2992:                     $key = &unescape($key);
 2993:                     next if ($key =~ /^error: 2 /);
 2994:                     my $result = &thaw_unescape($value);
 2995:                     if (ref($result) eq 'HASH') {
 2996:                         $returnhash{$key}=$result;
 2997:                     } else {
 2998:                         my @responses = split(/:/,$value);
 2999:                         my @items = ('description','inst_code','owner','type');
 3000:                         for (my $i=0; $i<@responses; $i++) {
 3001:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3002:                         }
 3003:                     } 
 3004:                 }
 3005:             }
 3006:         }
 3007:     }
 3008:     return %returnhash;
 3009: }
 3010: 
 3011: # ---------------------------------------------------------- DC e-mail
 3012: 
 3013: sub dcmailput {
 3014:     my ($domain,$msgid,$message,$server)=@_;
 3015:     my $status = &Apache::lonnet::critical(
 3016:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3017:        &escape($message),$server);
 3018:     return $status;
 3019: }
 3020: 
 3021: sub dcmaildump {
 3022:     my ($dom,$startdate,$enddate,$senders) = @_;
 3023:     my %returnhash=();
 3024: 
 3025:     if (defined(&domain($dom,'primary'))) {
 3026:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3027:                                                          &escape($enddate).':';
 3028: 	my @esc_senders=map { &escape($_)} @$senders;
 3029: 	$cmd.=&escape(join('&',@esc_senders));
 3030: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3031:             my ($key,$value) = split(/\=/,$line,2);
 3032:             if (($key) && ($value)) {
 3033:                 $returnhash{&unescape($key)} = &unescape($value);
 3034:             }
 3035:         }
 3036:     }
 3037:     return %returnhash;
 3038: }
 3039: # ---------------------------------------------------------- Domain roles
 3040: 
 3041: sub get_domain_roles {
 3042:     my ($dom,$roles,$startdate,$enddate)=@_;
 3043:     if (undef($startdate) || $startdate eq '') {
 3044:         $startdate = '.';
 3045:     }
 3046:     if (undef($enddate) || $enddate eq '') {
 3047:         $enddate = '.';
 3048:     }
 3049:     my $rolelist;
 3050:     if (ref($roles) eq 'ARRAY') {
 3051:         $rolelist = join(':',@{$roles});
 3052:     }
 3053:     my %personnel = ();
 3054: 
 3055:     my %servers = &get_servers($dom,'library');
 3056:     foreach my $tryserver (keys(%servers)) {
 3057: 	%{$personnel{$tryserver}}=();
 3058: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3059: 					    &escape($startdate).':'.
 3060: 					    &escape($enddate).':'.
 3061: 					    &escape($rolelist), $tryserver))) {
 3062: 	    my ($key,$value) = split(/\=/,$line,2);
 3063: 	    if (($key) && ($value)) {
 3064: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3065: 	    }
 3066: 	}
 3067:     }
 3068:     return %personnel;
 3069: }
 3070: 
 3071: # ----------------------------------------------------------- Check out an item
 3072: 
 3073: sub get_first_access {
 3074:     my ($type,$argsymb)=@_;
 3075:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3076:     if ($argsymb) { $symb=$argsymb; }
 3077:     my ($map,$id,$res)=&decode_symb($symb);
 3078:     if ($type eq 'course') {
 3079: 	$res='course';
 3080:     } elsif ($type eq 'map') {
 3081: 	$res=&symbread($map);
 3082:     } else {
 3083: 	$res=$symb;
 3084:     }
 3085:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3086:     return $times{"$courseid\0$res"};
 3087: }
 3088: 
 3089: sub set_first_access {
 3090:     my ($type)=@_;
 3091:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3092:     my ($map,$id,$res)=&decode_symb($symb);
 3093:     if ($type eq 'course') {
 3094: 	$res='course';
 3095:     } elsif ($type eq 'map') {
 3096: 	$res=&symbread($map);
 3097:     } else {
 3098: 	$res=$symb;
 3099:     }
 3100:     my $firstaccess=&get_first_access($type,$symb);
 3101:     if (!$firstaccess) {
 3102: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3103:     }
 3104:     return 'already_set';
 3105: }
 3106: 
 3107: sub checkout {
 3108:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3109:     my $now=time;
 3110:     my $lonhost=$perlvar{'lonHostID'};
 3111:     my $infostr=&escape(
 3112:                  'CHECKOUTTOKEN&'.
 3113:                  $tuname.'&'.
 3114:                  $tudom.'&'.
 3115:                  $tcrsid.'&'.
 3116:                  $symb.'&'.
 3117: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3118:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3119:     if ($token=~/^error\:/) { 
 3120:         &logthis("<font color=\"blue\">WARNING: ".
 3121:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3122:                  "</font>");
 3123:         return ''; 
 3124:     }
 3125: 
 3126:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3127:     $token=~tr/a-z/A-Z/;
 3128: 
 3129:     my %infohash=('resource.0.outtoken' => $token,
 3130:                   'resource.0.checkouttime' => $now,
 3131:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3132: 
 3133:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3134:        return '';
 3135:     } else {
 3136:         &logthis("<font color=\"blue\">WARNING: ".
 3137:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3138:                  "</font>");
 3139:     }    
 3140: 
 3141:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3142:                          &escape('Checkout '.$infostr.' - '.
 3143:                                                  $token)) ne 'ok') {
 3144: 	return '';
 3145:     } else {
 3146:         &logthis("<font color=\"blue\">WARNING: ".
 3147:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3148:                  "</font>");
 3149:     }
 3150:     return $token;
 3151: }
 3152: 
 3153: # ------------------------------------------------------------ Check in an item
 3154: 
 3155: sub checkin {
 3156:     my $token=shift;
 3157:     my $now=time;
 3158:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3159:     $lonhost=~tr/A-Z/a-z/;
 3160:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3161:     $dtoken=~s/\W/\_/g;
 3162:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3163:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3164: 
 3165:     unless (($tuname) && ($tudom)) {
 3166:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3167:         return '';
 3168:     }
 3169:     
 3170:     unless (&allowed('mgr',$tcrsid)) {
 3171:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3172:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3173:         return '';
 3174:     }
 3175: 
 3176:     my %infohash=('resource.0.intoken' => $token,
 3177:                   'resource.0.checkintime' => $now,
 3178:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3179: 
 3180:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3181:        return '';
 3182:     }    
 3183: 
 3184:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3185:                          &escape('Checkin - '.$token)) ne 'ok') {
 3186: 	return '';
 3187:     }
 3188: 
 3189:     return ($symb,$tuname,$tudom,$tcrsid);    
 3190: }
 3191: 
 3192: # --------------------------------------------- Set Expire Date for Spreadsheet
 3193: 
 3194: sub expirespread {
 3195:     my ($uname,$udom,$stype,$usymb)=@_;
 3196:     my $cid=$env{'request.course.id'}; 
 3197:     if ($cid) {
 3198:        my $now=time;
 3199:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3200:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3201:                             $env{'course.'.$cid.'.num'}.
 3202: 	        	    ':nohist_expirationdates:'.
 3203:                             &escape($key).'='.$now,
 3204:                             $env{'course.'.$cid.'.home'})
 3205:     }
 3206:     return 'ok';
 3207: }
 3208: 
 3209: # ----------------------------------------------------- Devalidate Spreadsheets
 3210: 
 3211: sub devalidate {
 3212:     my ($symb,$uname,$udom)=@_;
 3213:     my $cid=$env{'request.course.id'}; 
 3214:     if ($cid) {
 3215:         # delete the stored spreadsheets for
 3216:         # - the student level sheet of this user in course's homespace
 3217:         # - the assessment level sheet for this resource 
 3218:         #   for this user in user's homespace
 3219: 	# - current conditional state info
 3220: 	my $key=$uname.':'.$udom.':';
 3221:         my $status=
 3222: 	    &del('nohist_calculatedsheets',
 3223: 		 [$key.'studentcalc:'],
 3224: 		 $env{'course.'.$cid.'.domain'},
 3225: 		 $env{'course.'.$cid.'.num'})
 3226: 		.' '.
 3227: 	    &del('nohist_calculatedsheets_'.$cid,
 3228: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3229:         unless ($status eq 'ok ok') {
 3230:            &logthis('Could not devalidate spreadsheet '.
 3231:                     $uname.' at '.$udom.' for '.
 3232: 		    $symb.': '.$status);
 3233:         }
 3234: 	&delenv('user.state.'.$cid);
 3235:     }
 3236: }
 3237: 
 3238: sub get_scalar {
 3239:     my ($string,$end) = @_;
 3240:     my $value;
 3241:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3242: 	$value = $1;
 3243:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3244: 	$value = $1;
 3245:     }
 3246:     return &unescape($value);
 3247: }
 3248: 
 3249: sub array2str {
 3250:   my (@array) = @_;
 3251:   my $result=&arrayref2str(\@array);
 3252:   $result=~s/^__ARRAY_REF__//;
 3253:   $result=~s/__END_ARRAY_REF__$//;
 3254:   return $result;
 3255: }
 3256: 
 3257: sub arrayref2str {
 3258:   my ($arrayref) = @_;
 3259:   my $result='__ARRAY_REF__';
 3260:   foreach my $elem (@$arrayref) {
 3261:     if(ref($elem) eq 'ARRAY') {
 3262:       $result.=&arrayref2str($elem).'&';
 3263:     } elsif(ref($elem) eq 'HASH') {
 3264:       $result.=&hashref2str($elem).'&';
 3265:     } elsif(ref($elem)) {
 3266:       #print("Got a ref of ".(ref($elem))." skipping.");
 3267:     } else {
 3268:       $result.=&escape($elem).'&';
 3269:     }
 3270:   }
 3271:   $result=~s/\&$//;
 3272:   $result .= '__END_ARRAY_REF__';
 3273:   return $result;
 3274: }
 3275: 
 3276: sub hash2str {
 3277:   my (%hash) = @_;
 3278:   my $result=&hashref2str(\%hash);
 3279:   $result=~s/^__HASH_REF__//;
 3280:   $result=~s/__END_HASH_REF__$//;
 3281:   return $result;
 3282: }
 3283: 
 3284: sub hashref2str {
 3285:   my ($hashref)=@_;
 3286:   my $result='__HASH_REF__';
 3287:   foreach my $key (sort(keys(%$hashref))) {
 3288:     if (ref($key) eq 'ARRAY') {
 3289:       $result.=&arrayref2str($key).'=';
 3290:     } elsif (ref($key) eq 'HASH') {
 3291:       $result.=&hashref2str($key).'=';
 3292:     } elsif (ref($key)) {
 3293:       $result.='=';
 3294:       #print("Got a ref of ".(ref($key))." skipping.");
 3295:     } else {
 3296: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3297:     }
 3298: 
 3299:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3300:       $result.=&arrayref2str($hashref->{$key}).'&';
 3301:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3302:       $result.=&hashref2str($hashref->{$key}).'&';
 3303:     } elsif(ref($hashref->{$key})) {
 3304:        $result.='&';
 3305:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3306:     } else {
 3307:       $result.=&escape($hashref->{$key}).'&';
 3308:     }
 3309:   }
 3310:   $result=~s/\&$//;
 3311:   $result .= '__END_HASH_REF__';
 3312:   return $result;
 3313: }
 3314: 
 3315: sub str2hash {
 3316:     my ($string)=@_;
 3317:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3318:     return %$hash;
 3319: }
 3320: 
 3321: sub str2hashref {
 3322:   my ($string) = @_;
 3323: 
 3324:   my %hash;
 3325: 
 3326:   if($string !~ /^__HASH_REF__/) {
 3327:       if (! ($string eq '' || !defined($string))) {
 3328: 	  $hash{'error'}='Not hash reference';
 3329:       }
 3330:       return (\%hash, $string);
 3331:   }
 3332: 
 3333:   $string =~ s/^__HASH_REF__//;
 3334: 
 3335:   while($string !~ /^__END_HASH_REF__/) {
 3336:       #key
 3337:       my $key='';
 3338:       if($string =~ /^__HASH_REF__/) {
 3339:           ($key, $string)=&str2hashref($string);
 3340:           if(defined($key->{'error'})) {
 3341:               $hash{'error'}='Bad data';
 3342:               return (\%hash, $string);
 3343:           }
 3344:       } elsif($string =~ /^__ARRAY_REF__/) {
 3345:           ($key, $string)=&str2arrayref($string);
 3346:           if($key->[0] eq 'Array reference error') {
 3347:               $hash{'error'}='Bad data';
 3348:               return (\%hash, $string);
 3349:           }
 3350:       } else {
 3351:           $string =~ s/^(.*?)=//;
 3352: 	  $key=&unescape($1);
 3353:       }
 3354:       $string =~ s/^=//;
 3355: 
 3356:       #value
 3357:       my $value='';
 3358:       if($string =~ /^__HASH_REF__/) {
 3359:           ($value, $string)=&str2hashref($string);
 3360:           if(defined($value->{'error'})) {
 3361:               $hash{'error'}='Bad data';
 3362:               return (\%hash, $string);
 3363:           }
 3364:       } elsif($string =~ /^__ARRAY_REF__/) {
 3365:           ($value, $string)=&str2arrayref($string);
 3366:           if($value->[0] eq 'Array reference error') {
 3367:               $hash{'error'}='Bad data';
 3368:               return (\%hash, $string);
 3369:           }
 3370:       } else {
 3371: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3372:       }
 3373:       $string =~ s/^&//;
 3374: 
 3375:       $hash{$key}=$value;
 3376:   }
 3377: 
 3378:   $string =~ s/^__END_HASH_REF__//;
 3379: 
 3380:   return (\%hash, $string);
 3381: }
 3382: 
 3383: sub str2array {
 3384:     my ($string)=@_;
 3385:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3386:     return @$array;
 3387: }
 3388: 
 3389: sub str2arrayref {
 3390:   my ($string) = @_;
 3391:   my @array;
 3392: 
 3393:   if($string !~ /^__ARRAY_REF__/) {
 3394:       if (! ($string eq '' || !defined($string))) {
 3395: 	  $array[0]='Array reference error';
 3396:       }
 3397:       return (\@array, $string);
 3398:   }
 3399: 
 3400:   $string =~ s/^__ARRAY_REF__//;
 3401: 
 3402:   while($string !~ /^__END_ARRAY_REF__/) {
 3403:       my $value='';
 3404:       if($string =~ /^__HASH_REF__/) {
 3405:           ($value, $string)=&str2hashref($string);
 3406:           if(defined($value->{'error'})) {
 3407:               $array[0] ='Array reference error';
 3408:               return (\@array, $string);
 3409:           }
 3410:       } elsif($string =~ /^__ARRAY_REF__/) {
 3411:           ($value, $string)=&str2arrayref($string);
 3412:           if($value->[0] eq 'Array reference error') {
 3413:               $array[0] ='Array reference error';
 3414:               return (\@array, $string);
 3415:           }
 3416:       } else {
 3417: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3418:       }
 3419:       $string =~ s/^&//;
 3420: 
 3421:       push(@array, $value);
 3422:   }
 3423: 
 3424:   $string =~ s/^__END_ARRAY_REF__//;
 3425: 
 3426:   return (\@array, $string);
 3427: }
 3428: 
 3429: # -------------------------------------------------------------------Temp Store
 3430: 
 3431: sub tmpreset {
 3432:   my ($symb,$namespace,$domain,$stuname) = @_;
 3433:   if (!$symb) {
 3434:     $symb=&symbread();
 3435:     if (!$symb) { $symb= $env{'request.url'}; }
 3436:   }
 3437:   $symb=escape($symb);
 3438: 
 3439:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3440:   $namespace=~s/\//\_/g;
 3441:   $namespace=~s/\W//g;
 3442: 
 3443:   if (!$domain) { $domain=$env{'user.domain'}; }
 3444:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3445:   if ($domain eq 'public' && $stuname eq 'public') {
 3446:       $stuname=$ENV{'REMOTE_ADDR'};
 3447:   }
 3448:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3449:   my %hash;
 3450:   if (tie(%hash,'GDBM_File',
 3451: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3452: 	  &GDBM_WRCREAT(),0640)) {
 3453:     foreach my $key (keys(%hash)) {
 3454:       if ($key=~ /:$symb/) {
 3455: 	delete($hash{$key});
 3456:       }
 3457:     }
 3458:   }
 3459: }
 3460: 
 3461: sub tmpstore {
 3462:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3463: 
 3464:   if (!$symb) {
 3465:     $symb=&symbread();
 3466:     if (!$symb) { $symb= $env{'request.url'}; }
 3467:   }
 3468:   $symb=escape($symb);
 3469: 
 3470:   if (!$namespace) {
 3471:     # I don't think we would ever want to store this for a course.
 3472:     # it seems this will only be used if we don't have a course.
 3473:     #$namespace=$env{'request.course.id'};
 3474:     #if (!$namespace) {
 3475:       $namespace=$env{'request.state'};
 3476:     #}
 3477:   }
 3478:   $namespace=~s/\//\_/g;
 3479:   $namespace=~s/\W//g;
 3480:   if (!$domain) { $domain=$env{'user.domain'}; }
 3481:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3482:   if ($domain eq 'public' && $stuname eq 'public') {
 3483:       $stuname=$ENV{'REMOTE_ADDR'};
 3484:   }
 3485:   my $now=time;
 3486:   my %hash;
 3487:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3488:   if (tie(%hash,'GDBM_File',
 3489: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3490: 	  &GDBM_WRCREAT(),0640)) {
 3491:     $hash{"version:$symb"}++;
 3492:     my $version=$hash{"version:$symb"};
 3493:     my $allkeys=''; 
 3494:     foreach my $key (keys(%$storehash)) {
 3495:       $allkeys.=$key.':';
 3496:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3497:     }
 3498:     $hash{"$version:$symb:timestamp"}=$now;
 3499:     $allkeys.='timestamp';
 3500:     $hash{"$version:keys:$symb"}=$allkeys;
 3501:     if (untie(%hash)) {
 3502:       return 'ok';
 3503:     } else {
 3504:       return "error:$!";
 3505:     }
 3506:   } else {
 3507:     return "error:$!";
 3508:   }
 3509: }
 3510: 
 3511: # -----------------------------------------------------------------Temp Restore
 3512: 
 3513: sub tmprestore {
 3514:   my ($symb,$namespace,$domain,$stuname) = @_;
 3515: 
 3516:   if (!$symb) {
 3517:     $symb=&symbread();
 3518:     if (!$symb) { $symb= $env{'request.url'}; }
 3519:   }
 3520:   $symb=escape($symb);
 3521: 
 3522:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3523: 
 3524:   if (!$domain) { $domain=$env{'user.domain'}; }
 3525:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3526:   if ($domain eq 'public' && $stuname eq 'public') {
 3527:       $stuname=$ENV{'REMOTE_ADDR'};
 3528:   }
 3529:   my %returnhash;
 3530:   $namespace=~s/\//\_/g;
 3531:   $namespace=~s/\W//g;
 3532:   my %hash;
 3533:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3534:   if (tie(%hash,'GDBM_File',
 3535: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3536: 	  &GDBM_READER(),0640)) {
 3537:     my $version=$hash{"version:$symb"};
 3538:     $returnhash{'version'}=$version;
 3539:     my $scope;
 3540:     for ($scope=1;$scope<=$version;$scope++) {
 3541:       my $vkeys=$hash{"$scope:keys:$symb"};
 3542:       my @keys=split(/:/,$vkeys);
 3543:       my $key;
 3544:       $returnhash{"$scope:keys"}=$vkeys;
 3545:       foreach $key (@keys) {
 3546: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3547: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3548:       }
 3549:     }
 3550:     if (!(untie(%hash))) {
 3551:       return "error:$!";
 3552:     }
 3553:   } else {
 3554:     return "error:$!";
 3555:   }
 3556:   return %returnhash;
 3557: }
 3558: 
 3559: # ----------------------------------------------------------------------- Store
 3560: 
 3561: sub store {
 3562:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3563:     my $home='';
 3564: 
 3565:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3566: 
 3567:     $symb=&symbclean($symb);
 3568:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3569: 
 3570:     if (!$domain) { $domain=$env{'user.domain'}; }
 3571:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3572: 
 3573:     &devalidate($symb,$stuname,$domain);
 3574: 
 3575:     $symb=escape($symb);
 3576:     if (!$namespace) { 
 3577:        unless ($namespace=$env{'request.course.id'}) { 
 3578:           return ''; 
 3579:        } 
 3580:     }
 3581:     if (!$home) { $home=$env{'user.home'}; }
 3582: 
 3583:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3584:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3585: 
 3586:     my $namevalue='';
 3587:     foreach my $key (keys(%$storehash)) {
 3588:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3589:     }
 3590:     $namevalue=~s/\&$//;
 3591:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3592:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3593: }
 3594: 
 3595: # -------------------------------------------------------------- Critical Store
 3596: 
 3597: sub cstore {
 3598:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3599:     my $home='';
 3600: 
 3601:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3602: 
 3603:     $symb=&symbclean($symb);
 3604:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3605: 
 3606:     if (!$domain) { $domain=$env{'user.domain'}; }
 3607:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3608: 
 3609:     &devalidate($symb,$stuname,$domain);
 3610: 
 3611:     $symb=escape($symb);
 3612:     if (!$namespace) { 
 3613:        unless ($namespace=$env{'request.course.id'}) { 
 3614:           return ''; 
 3615:        } 
 3616:     }
 3617:     if (!$home) { $home=$env{'user.home'}; }
 3618: 
 3619:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3620:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3621: 
 3622:     my $namevalue='';
 3623:     foreach my $key (keys(%$storehash)) {
 3624:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3625:     }
 3626:     $namevalue=~s/\&$//;
 3627:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3628:     return critical
 3629:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3630: }
 3631: 
 3632: # --------------------------------------------------------------------- Restore
 3633: 
 3634: sub restore {
 3635:     my ($symb,$namespace,$domain,$stuname) = @_;
 3636:     my $home='';
 3637: 
 3638:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3639: 
 3640:     if (!$symb) {
 3641:       unless ($symb=escape(&symbread())) { return ''; }
 3642:     } else {
 3643:       $symb=&escape(&symbclean($symb));
 3644:     }
 3645:     if (!$namespace) { 
 3646:        unless ($namespace=$env{'request.course.id'}) { 
 3647:           return ''; 
 3648:        } 
 3649:     }
 3650:     if (!$domain) { $domain=$env{'user.domain'}; }
 3651:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3652:     if (!$home) { $home=$env{'user.home'}; }
 3653:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3654: 
 3655:     my %returnhash=();
 3656:     foreach my $line (split(/\&/,$answer)) {
 3657: 	my ($name,$value)=split(/\=/,$line);
 3658:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3659:     }
 3660:     my $version;
 3661:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3662:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3663:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3664:        }
 3665:     }
 3666:     return %returnhash;
 3667: }
 3668: 
 3669: # ---------------------------------------------------------- Course Description
 3670: 
 3671: sub coursedescription {
 3672:     my ($courseid,$args)=@_;
 3673:     $courseid=~s/^\///;
 3674:     $courseid=~s/\_/\//g;
 3675:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3676:     my $chome=&homeserver($cnum,$cdomain);
 3677:     my $normalid=$cdomain.'_'.$cnum;
 3678:     # need to always cache even if we get errors otherwise we keep 
 3679:     # trying and trying and trying to get the course description.
 3680:     my %envhash=();
 3681:     my %returnhash=();
 3682:     
 3683:     my $expiretime=600;
 3684:     if ($env{'request.course.id'} eq $normalid) {
 3685: 	$expiretime=120;
 3686:     }
 3687: 
 3688:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3689:     if (!$args->{'freshen_cache'}
 3690: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3691: 	foreach my $key (keys(%env)) {
 3692: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3693: 	    my ($setting) = $1;
 3694: 	    $returnhash{$setting} = $env{$key};
 3695: 	}
 3696: 	return %returnhash;
 3697:     }
 3698: 
 3699:     # get the data agin
 3700:     if (!$args->{'one_time'}) {
 3701: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3702:     }
 3703: 
 3704:     if ($chome ne 'no_host') {
 3705:        %returnhash=&dump('environment',$cdomain,$cnum);
 3706:        if (!exists($returnhash{'con_lost'})) {
 3707:            $returnhash{'home'}= $chome;
 3708: 	   $returnhash{'domain'} = $cdomain;
 3709: 	   $returnhash{'num'} = $cnum;
 3710:            if (!defined($returnhash{'type'})) {
 3711:                $returnhash{'type'} = 'Course';
 3712:            }
 3713:            while (my ($name,$value) = each %returnhash) {
 3714:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3715:            }
 3716:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3717:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3718: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3719:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3720:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3721:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3722:        }
 3723:     }
 3724:     if (!$args->{'one_time'}) {
 3725: 	&appenv(\%envhash);
 3726:     }
 3727:     return %returnhash;
 3728: }
 3729: 
 3730: # -------------------------------------------------See if a user is privileged
 3731: 
 3732: sub privileged {
 3733:     my ($username,$domain)=@_;
 3734:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3735: 			&homeserver($username,$domain));
 3736:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3737:     my $now=time;
 3738:     if ($rolesdump ne '') {
 3739:         foreach my $entry (split(/&/,$rolesdump)) {
 3740: 	    if ($entry!~/^rolesdef_/) {
 3741: 		my ($area,$role)=split(/=/,$entry);
 3742: 		$area=~s/\_\w\w$//;
 3743: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3744: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3745: 		    my $active=1;
 3746: 		    if ($tend) {
 3747: 			if ($tend<$now) { $active=0; }
 3748: 		    }
 3749: 		    if ($tstart) {
 3750: 			if ($tstart>$now) { $active=0; }
 3751: 		    }
 3752: 		    if ($active) { return 1; }
 3753: 		}
 3754: 	    }
 3755: 	}
 3756:     }
 3757:     return 0;
 3758: }
 3759: 
 3760: # -------------------------------------------------------- Get user privileges
 3761: 
 3762: sub rolesinit {
 3763:     my ($domain,$username,$authhost)=@_;
 3764:     my %userroles;
 3765:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3766:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3767:     my %allroles=();
 3768:     my %allgroups=();   
 3769:     my $now=time;
 3770:     %userroles = ('user.login.time' => $now);
 3771:     my $group_privs;
 3772: 
 3773:     if ($rolesdump ne '') {
 3774:         foreach my $entry (split(/&/,$rolesdump)) {
 3775: 	  if ($entry!~/^rolesdef_/) {
 3776:             my ($area,$role)=split(/=/,$entry);
 3777: 	    $area=~s/\_\w\w$//;
 3778:             my ($trole,$tend,$tstart,$group_privs);
 3779: 	    if ($role=~/^cr/) { 
 3780: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3781: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3782: 		    ($tend,$tstart)=split('_',$trest);
 3783: 		} else {
 3784: 		    $trole=$role;
 3785: 		}
 3786:             } elsif ($role =~ m|^gr/|) {
 3787:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3788:                 ($trole,$group_privs) = split(/\//,$trole);
 3789:                 $group_privs = &unescape($group_privs);
 3790: 	    } else {
 3791: 		($trole,$tend,$tstart)=split(/_/,$role);
 3792: 	    }
 3793: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3794: 					 $username);
 3795: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3796:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3797:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3798:             if (($area ne '') && ($trole ne '')) {
 3799: 		my $spec=$trole.'.'.$area;
 3800: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3801: 		if ($trole =~ /^cr\//) {
 3802:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3803:                 } elsif ($trole eq 'gr') {
 3804:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3805: 		} else {
 3806:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3807: 		}
 3808:             }
 3809:           }
 3810:         }
 3811:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3812:         $userroles{'user.adv'}    = $adv;
 3813: 	$userroles{'user.author'} = $author;
 3814:         $env{'user.adv'}=$adv;
 3815:     }
 3816:     return \%userroles;  
 3817: }
 3818: 
 3819: sub set_arearole {
 3820:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3821: # log the associated role with the area
 3822:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3823:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3824: }
 3825: 
 3826: sub custom_roleprivs {
 3827:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3828:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3829:     my $homsvr=homeserver($rauthor,$rdomain);
 3830:     if (&hostname($homsvr) ne '') {
 3831:         my ($rdummy,$roledef)=
 3832:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3833:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3834:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3835:             if (defined($syspriv)) {
 3836:                 $$allroles{'cm./'}.=':'.$syspriv;
 3837:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3838:             }
 3839:             if ($tdomain ne '') {
 3840:                 if (defined($dompriv)) {
 3841:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3842:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3843:                 }
 3844:                 if (($trest ne '') && (defined($coursepriv))) {
 3845:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3846:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3847:                 }
 3848:             }
 3849:         }
 3850:     }
 3851: }
 3852: 
 3853: sub group_roleprivs {
 3854:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3855:     my $access = 1;
 3856:     my $now = time;
 3857:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3858:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3859:     if ($access) {
 3860:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3861:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3862:     }
 3863: }
 3864: 
 3865: sub standard_roleprivs {
 3866:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3867:     if (defined($pr{$trole.':s'})) {
 3868:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3869:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3870:     }
 3871:     if ($tdomain ne '') {
 3872:         if (defined($pr{$trole.':d'})) {
 3873:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3874:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3875:         }
 3876:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3877:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3878:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3879:         }
 3880:     }
 3881: }
 3882: 
 3883: sub set_userprivs {
 3884:     my ($userroles,$allroles,$allgroups) = @_; 
 3885:     my $author=0;
 3886:     my $adv=0;
 3887:     my %grouproles = ();
 3888:     if (keys(%{$allgroups}) > 0) {
 3889:         foreach my $role (keys(%{$allroles})) {
 3890:             my ($trole,$area,$sec,$extendedarea);
 3891:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3892:                 $trole = $1;
 3893:                 $area = $2;
 3894:                 $sec = $3;
 3895:                 $extendedarea = $area.$sec;
 3896:                 if (exists($$allgroups{$area})) {
 3897:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3898:                         my $spec = $trole.'.'.$extendedarea;
 3899:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3900:                                                 $$allgroups{$area}{$group};
 3901:                     }
 3902:                 }
 3903:             }
 3904:         }
 3905:     }
 3906:     foreach my $group (keys(%grouproles)) {
 3907:         $$allroles{$group} = $grouproles{$group};
 3908:     }
 3909:     foreach my $role (keys(%{$allroles})) {
 3910:         my %thesepriv;
 3911:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3912:         foreach my $item (split(/:/,$$allroles{$role})) {
 3913:             if ($item ne '') {
 3914:                 my ($privilege,$restrictions)=split(/&/,$item);
 3915:                 if ($restrictions eq '') {
 3916:                     $thesepriv{$privilege}='F';
 3917:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3918:                     $thesepriv{$privilege}.=$restrictions;
 3919:                 }
 3920:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3921:             }
 3922:         }
 3923:         my $thesestr='';
 3924:         foreach my $priv (keys(%thesepriv)) {
 3925: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3926: 	}
 3927:         $userroles->{'user.priv.'.$role} = $thesestr;
 3928:     }
 3929:     return ($author,$adv);
 3930: }
 3931: 
 3932: sub role_status {
 3933:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 3934:     my @pwhere = ();
 3935:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 3936:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 3937:         unless (!defined($$role) || $$role eq '') {
 3938:             $$where=join('.',@pwhere);
 3939:             $$trolecode=$$role.'.'.$$where;
 3940:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 3941:             $$tstatus='is';
 3942:             if ($$tstart && $$tstart>$then) {
 3943:                 $$tstatus='future';
 3944:                 if ($$tstart && $$tstart>$refresh) {
 3945:                     if ($$tstart<$now) {
 3946:                         if (($$where ne '') && ($$role ne '')) {
 3947:                             my (%allroles,%allgroups,$group_privs);
 3948:                             my %userroles = (
 3949:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 3950:                             );
 3951:                             my $spec=$$role.'.'.$$where;
 3952:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 3953:                             if ($$role eq 'gr') {
 3954:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 3955:                                                     $env{'user.name'})=@_;
 3956:                                 my ($trole) = split('_',$role,1);
 3957:                                 (undef,my $group_privs) = split(/\//,$trole);
 3958:                                 $group_privs = &unescape($group_privs);
 3959:                             }
 3960:                             if ($$role =~ /^cr\//) {
 3961:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 3962:                             } elsif ($$role eq 'gr') {
 3963:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 3964:                                                     $env{'user.name'});
 3965:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 3966:                                 (undef,my $group_privs) = split(/\//,$trole);
 3967:                                 $group_privs = &unescape($group_privs);
 3968:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 3969:                             } else {
 3970:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 3971:                             }
 3972:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3973:                             &appenv(\%userroles,[$$role,'cm']);
 3974:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 3975:                             $$tstatus = 'is';
 3976:                         }
 3977:                     }
 3978:                 }
 3979:             }
 3980:             if ($$tend) {
 3981:                 if ($$tend<$then) {
 3982:                     $$tstatus='expired';
 3983:                 } elsif ($$tend<$now) {
 3984:                     $$tstatus='will_not';
 3985:                 }
 3986:             }
 3987:         }
 3988:     }
 3989: }
 3990: 
 3991: sub check_adhoc_privs {
 3992:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 3993:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 3994:     if ($env{$cckey}) {
 3995:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 3996:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 3997:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 3998:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 3999:         }
 4000:     } else {
 4001:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4002:     }
 4003: }
 4004: 
 4005: sub set_adhoc_privileges {
 4006: # role can be cc or ca
 4007:     my ($dcdom,$pickedcourse,$role) = @_;
 4008:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4009:     my $spec = $role.'.'.$area;
 4010:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4011:                                   $env{'user.name'});
 4012:     my %ccrole = ();
 4013:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4014:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4015:     &appenv(\%userroles,[$role,'cm']);
 4016:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4017:     &appenv( {'request.role'        => $spec,
 4018:               'request.role.domain' => $dcdom,
 4019:               'request.course.sec'  => ''
 4020:              }
 4021:            );
 4022:     my $tadv=0;
 4023:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4024:     &appenv({'request.role.adv'    => $tadv});
 4025: }
 4026: 
 4027: # --------------------------------------------------------------- get interface
 4028: 
 4029: sub get {
 4030:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4031:    my $items='';
 4032:    foreach my $item (@$storearr) {
 4033:        $items.=&escape($item).'&';
 4034:    }
 4035:    $items=~s/\&$//;
 4036:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4037:    if (!$uname) { $uname=$env{'user.name'}; }
 4038:    my $uhome=&homeserver($uname,$udomain);
 4039: 
 4040:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4041:    my @pairs=split(/\&/,$rep);
 4042:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4043:      return @pairs;
 4044:    }
 4045:    my %returnhash=();
 4046:    my $i=0;
 4047:    foreach my $item (@$storearr) {
 4048:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4049:       $i++;
 4050:    }
 4051:    return %returnhash;
 4052: }
 4053: 
 4054: # --------------------------------------------------------------- del interface
 4055: 
 4056: sub del {
 4057:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4058:    my $items='';
 4059:    foreach my $item (@$storearr) {
 4060:        $items.=&escape($item).'&';
 4061:    }
 4062: 
 4063:    $items=~s/\&$//;
 4064:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4065:    if (!$uname) { $uname=$env{'user.name'}; }
 4066:    my $uhome=&homeserver($uname,$udomain);
 4067:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4068: }
 4069: 
 4070: # -------------------------------------------------------------- dump interface
 4071: 
 4072: sub dump {
 4073:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4074:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4075:     if (!$uname) { $uname=$env{'user.name'}; }
 4076:     my $uhome=&homeserver($uname,$udomain);
 4077:     if ($regexp) {
 4078: 	$regexp=&escape($regexp);
 4079:     } else {
 4080: 	$regexp='.';
 4081:     }
 4082:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4083:     my @pairs=split(/\&/,$rep);
 4084:     my %returnhash=();
 4085:     foreach my $item (@pairs) {
 4086: 	my ($key,$value)=split(/=/,$item,2);
 4087: 	$key = &unescape($key);
 4088: 	next if ($key =~ /^error: 2 /);
 4089: 	$returnhash{$key}=&thaw_unescape($value);
 4090:     }
 4091:     return %returnhash;
 4092: }
 4093: 
 4094: # --------------------------------------------------------- dumpstore interface
 4095: 
 4096: sub dumpstore {
 4097:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4099:    if (!$uname) { $uname=$env{'user.name'}; }
 4100:    my $uhome=&homeserver($uname,$udomain);
 4101:    if ($regexp) {
 4102:        $regexp=&escape($regexp);
 4103:    } else {
 4104:        $regexp='.';
 4105:    }
 4106:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4107:    my @pairs=split(/\&/,$rep);
 4108:    my %returnhash=();
 4109:    foreach my $item (@pairs) {
 4110:        my ($key,$value)=split(/=/,$item,2);
 4111:        next if ($key =~ /^error: 2 /);
 4112:        $returnhash{$key}=&thaw_unescape($value);
 4113:    }
 4114:    return %returnhash;
 4115: }
 4116: 
 4117: # -------------------------------------------------------------- keys interface
 4118: 
 4119: sub getkeys {
 4120:    my ($namespace,$udomain,$uname)=@_;
 4121:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4122:    if (!$uname) { $uname=$env{'user.name'}; }
 4123:    my $uhome=&homeserver($uname,$udomain);
 4124:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4125:    my @keyarray=();
 4126:    foreach my $key (split(/\&/,$rep)) {
 4127:       next if ($key =~ /^error: 2 /);
 4128:       push(@keyarray,&unescape($key));
 4129:    }
 4130:    return @keyarray;
 4131: }
 4132: 
 4133: # --------------------------------------------------------------- currentdump
 4134: sub currentdump {
 4135:    my ($courseid,$sdom,$sname)=@_;
 4136:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4137:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4138:    $sname    = $env{'user.name'}         if (! defined($sname));
 4139:    my $uhome = &homeserver($sname,$sdom);
 4140:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4141:    return if ($rep =~ /^(error:|no_such_host)/);
 4142:    #
 4143:    my %returnhash=();
 4144:    #
 4145:    if ($rep eq "unknown_cmd") { 
 4146:        # an old lond will not know currentdump
 4147:        # Do a dump and make it look like a currentdump
 4148:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4149:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4150:        my %hash = @tmp;
 4151:        @tmp=();
 4152:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4153:    } else {
 4154:        my @pairs=split(/\&/,$rep);
 4155:        foreach my $pair (@pairs) {
 4156:            my ($key,$value)=split(/=/,$pair,2);
 4157:            my ($symb,$param) = split(/:/,$key);
 4158:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4159:                                                         &thaw_unescape($value);
 4160:        }
 4161:    }
 4162:    return %returnhash;
 4163: }
 4164: 
 4165: sub convert_dump_to_currentdump{
 4166:     my %hash = %{shift()};
 4167:     my %returnhash;
 4168:     # Code ripped from lond, essentially.  The only difference
 4169:     # here is the unescaping done by lonnet::dump().  Conceivably
 4170:     # we might run in to problems with parameter names =~ /^v\./
 4171:     while (my ($key,$value) = each(%hash)) {
 4172:         my ($v,$symb,$param) = split(/:/,$key);
 4173: 	$symb  = &unescape($symb);
 4174: 	$param = &unescape($param);
 4175:         next if ($v eq 'version' || $symb eq 'keys');
 4176:         next if (exists($returnhash{$symb}) &&
 4177:                  exists($returnhash{$symb}->{$param}) &&
 4178:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4179:         $returnhash{$symb}->{$param}=$value;
 4180:         $returnhash{$symb}->{'v.'.$param}=$v;
 4181:     }
 4182:     #
 4183:     # Remove all of the keys in the hashes which keep track of
 4184:     # the version of the parameter.
 4185:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4186:         # use a foreach because we are going to delete from the hash.
 4187:         foreach my $key (keys(%$param_hash)) {
 4188:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4189:         }
 4190:     }
 4191:     return \%returnhash;
 4192: }
 4193: 
 4194: # ------------------------------------------------------ critical inc interface
 4195: 
 4196: sub cinc {
 4197:     return &inc(@_,'critical');
 4198: }
 4199: 
 4200: # --------------------------------------------------------------- inc interface
 4201: 
 4202: sub inc {
 4203:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4204:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4205:     if (!$uname) { $uname=$env{'user.name'}; }
 4206:     my $uhome=&homeserver($uname,$udomain);
 4207:     my $items='';
 4208:     if (! ref($store)) {
 4209:         # got a single value, so use that instead
 4210:         $items = &escape($store).'=&';
 4211:     } elsif (ref($store) eq 'SCALAR') {
 4212:         $items = &escape($$store).'=&';        
 4213:     } elsif (ref($store) eq 'ARRAY') {
 4214:         $items = join('=&',map {&escape($_);} @{$store});
 4215:     } elsif (ref($store) eq 'HASH') {
 4216:         while (my($key,$value) = each(%{$store})) {
 4217:             $items.= &escape($key).'='.&escape($value).'&';
 4218:         }
 4219:     }
 4220:     $items=~s/\&$//;
 4221:     if ($critical) {
 4222: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4223:     } else {
 4224: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4225:     }
 4226: }
 4227: 
 4228: # --------------------------------------------------------------- put interface
 4229: 
 4230: sub put {
 4231:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4232:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4233:    if (!$uname) { $uname=$env{'user.name'}; }
 4234:    my $uhome=&homeserver($uname,$udomain);
 4235:    my $items='';
 4236:    foreach my $item (keys(%$storehash)) {
 4237:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4238:    }
 4239:    $items=~s/\&$//;
 4240:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4241: }
 4242: 
 4243: # ------------------------------------------------------------ newput interface
 4244: 
 4245: sub newput {
 4246:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4247:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4248:    if (!$uname) { $uname=$env{'user.name'}; }
 4249:    my $uhome=&homeserver($uname,$udomain);
 4250:    my $items='';
 4251:    foreach my $key (keys(%$storehash)) {
 4252:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4253:    }
 4254:    $items=~s/\&$//;
 4255:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4256: }
 4257: 
 4258: # ---------------------------------------------------------  putstore interface
 4259: 
 4260: sub putstore {
 4261:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4262:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4263:    if (!$uname) { $uname=$env{'user.name'}; }
 4264:    my $uhome=&homeserver($uname,$udomain);
 4265:    my $items='';
 4266:    foreach my $key (keys(%$storehash)) {
 4267:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4268:    }
 4269:    $items=~s/\&$//;
 4270:    my $esc_symb=&escape($symb);
 4271:    my $esc_v=&escape($version);
 4272:    my $reply =
 4273:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4274: 	      $uhome);
 4275:    if ($reply eq 'unknown_cmd') {
 4276:        # gfall back to way things use to be done
 4277:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4278: 			    $uname);
 4279:    }
 4280:    return $reply;
 4281: }
 4282: 
 4283: sub old_putstore {
 4284:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4285:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4286:     if (!$uname) { $uname=$env{'user.name'}; }
 4287:     my $uhome=&homeserver($uname,$udomain);
 4288:     my %newstorehash;
 4289:     foreach my $item (keys(%$storehash)) {
 4290: 	my $key = $version.':'.&escape($symb).':'.$item;
 4291: 	$newstorehash{$key} = $storehash->{$item};
 4292:     }
 4293:     my $items='';
 4294:     my %allitems = ();
 4295:     foreach my $item (keys(%newstorehash)) {
 4296: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4297: 	    my $key = $1.':keys:'.$2;
 4298: 	    $allitems{$key} .= $3.':';
 4299: 	}
 4300: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4301:     }
 4302:     foreach my $item (keys(%allitems)) {
 4303: 	$allitems{$item} =~ s/\:$//;
 4304: 	$items.= $item.'='.$allitems{$item}.'&';
 4305:     }
 4306:     $items=~s/\&$//;
 4307:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4308: }
 4309: 
 4310: # ------------------------------------------------------ critical put interface
 4311: 
 4312: sub cput {
 4313:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4314:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4315:    if (!$uname) { $uname=$env{'user.name'}; }
 4316:    my $uhome=&homeserver($uname,$udomain);
 4317:    my $items='';
 4318:    foreach my $item (keys(%$storehash)) {
 4319:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4320:    }
 4321:    $items=~s/\&$//;
 4322:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4323: }
 4324: 
 4325: # -------------------------------------------------------------- eget interface
 4326: 
 4327: sub eget {
 4328:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4329:    my $items='';
 4330:    foreach my $item (@$storearr) {
 4331:        $items.=&escape($item).'&';
 4332:    }
 4333:    $items=~s/\&$//;
 4334:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4335:    if (!$uname) { $uname=$env{'user.name'}; }
 4336:    my $uhome=&homeserver($uname,$udomain);
 4337:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4338:    my @pairs=split(/\&/,$rep);
 4339:    my %returnhash=();
 4340:    my $i=0;
 4341:    foreach my $item (@$storearr) {
 4342:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4343:       $i++;
 4344:    }
 4345:    return %returnhash;
 4346: }
 4347: 
 4348: # ------------------------------------------------------------ tmpput interface
 4349: sub tmpput {
 4350:     my ($storehash,$server,$context)=@_;
 4351:     my $items='';
 4352:     foreach my $item (keys(%$storehash)) {
 4353: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4354:     }
 4355:     $items=~s/\&$//;
 4356:     if (defined($context)) {
 4357:         $items .= ':'.&escape($context);
 4358:     }
 4359:     return &reply("tmpput:$items",$server);
 4360: }
 4361: 
 4362: # ------------------------------------------------------------ tmpget interface
 4363: sub tmpget {
 4364:     my ($token,$server)=@_;
 4365:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4366:     my $rep=&reply("tmpget:$token",$server);
 4367:     my %returnhash;
 4368:     foreach my $item (split(/\&/,$rep)) {
 4369: 	my ($key,$value)=split(/=/,$item);
 4370:         next if ($key =~ /^error: 2 /);
 4371: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4372:     }
 4373:     return %returnhash;
 4374: }
 4375: 
 4376: # ------------------------------------------------------------ tmpget interface
 4377: sub tmpdel {
 4378:     my ($token,$server)=@_;
 4379:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4380:     return &reply("tmpdel:$token",$server);
 4381: }
 4382: 
 4383: # -------------------------------------------------- portfolio access checking
 4384: 
 4385: sub portfolio_access {
 4386:     my ($requrl) = @_;
 4387:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4388:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4389:     if ($result) {
 4390:         my %setters;
 4391:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4392:             my ($startblock,$endblock) =
 4393:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4394:             if ($startblock && $endblock) {
 4395:                 return 'B';
 4396:             }
 4397:         } else {
 4398:             my ($startblock,$endblock) =
 4399:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4400:             if ($startblock && $endblock) {
 4401:                 return 'B';
 4402:             }
 4403:         }
 4404:     }
 4405:     if ($result eq 'ok') {
 4406:        return 'F';
 4407:     } elsif ($result =~ /^[^:]+:guest_/) {
 4408:        return 'A';
 4409:     }
 4410:     return '';
 4411: }
 4412: 
 4413: sub get_portfolio_access {
 4414:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4415: 
 4416:     if (!ref($access_hash)) {
 4417: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4418: 	my %access_controls = &get_access_controls($current_perms,$group,
 4419: 						   $file_name);
 4420: 	$access_hash = $access_controls{$file_name};
 4421:     }
 4422: 
 4423:     my ($public,$guest,@domains,@users,@courses,@groups);
 4424:     my $now = time;
 4425:     if (ref($access_hash) eq 'HASH') {
 4426:         foreach my $key (keys(%{$access_hash})) {
 4427:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4428:             if ($start > $now) {
 4429:                 next;
 4430:             }
 4431:             if ($end && $end<$now) {
 4432:                 next;
 4433:             }
 4434:             if ($scope eq 'public') {
 4435:                 $public = $key;
 4436:                 last;
 4437:             } elsif ($scope eq 'guest') {
 4438:                 $guest = $key;
 4439:             } elsif ($scope eq 'domains') {
 4440:                 push(@domains,$key);
 4441:             } elsif ($scope eq 'users') {
 4442:                 push(@users,$key);
 4443:             } elsif ($scope eq 'course') {
 4444:                 push(@courses,$key);
 4445:             } elsif ($scope eq 'group') {
 4446:                 push(@groups,$key);
 4447:             }
 4448:         }
 4449:         if ($public) {
 4450:             return 'ok';
 4451:         }
 4452:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4453:             if ($guest) {
 4454:                 return $guest;
 4455:             }
 4456:         } else {
 4457:             if (@domains > 0) {
 4458:                 foreach my $domkey (@domains) {
 4459:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4460:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4461:                             return 'ok';
 4462:                         }
 4463:                     }
 4464:                 }
 4465:             }
 4466:             if (@users > 0) {
 4467:                 foreach my $userkey (@users) {
 4468:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4469:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4470:                             if (ref($item) eq 'HASH') {
 4471:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4472:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4473:                                     return 'ok';
 4474:                                 }
 4475:                             }
 4476:                         }
 4477:                     } 
 4478:                 }
 4479:             }
 4480:             my %roleshash;
 4481:             my @courses_and_groups = @courses;
 4482:             push(@courses_and_groups,@groups); 
 4483:             if (@courses_and_groups > 0) {
 4484:                 my (%allgroups,%allroles); 
 4485:                 my ($start,$end,$role,$sec,$group);
 4486:                 foreach my $envkey (%env) {
 4487:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4488:                         my $cid = $2.'_'.$3; 
 4489:                         if ($1 eq 'gr') {
 4490:                             $group = $4;
 4491:                             $allgroups{$cid}{$group} = $env{$envkey};
 4492:                         } else {
 4493:                             if ($4 eq '') {
 4494:                                 $sec = 'none';
 4495:                             } else {
 4496:                                 $sec = $4;
 4497:                             }
 4498:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4499:                         }
 4500:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4501:                         my $cid = $2.'_'.$3;
 4502:                         if ($4 eq '') {
 4503:                             $sec = 'none';
 4504:                         } else {
 4505:                             $sec = $4;
 4506:                         }
 4507:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4508:                     }
 4509:                 }
 4510:                 if (keys(%allroles) == 0) {
 4511:                     return;
 4512:                 }
 4513:                 foreach my $key (@courses_and_groups) {
 4514:                     my %content = %{$$access_hash{$key}};
 4515:                     my $cnum = $content{'number'};
 4516:                     my $cdom = $content{'domain'};
 4517:                     my $cid = $cdom.'_'.$cnum;
 4518:                     if (!exists($allroles{$cid})) {
 4519:                         next;
 4520:                     }    
 4521:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4522:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4523:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4524:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4525:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4526:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4527:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4528:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4529:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4530:                                         if (grep/^all$/,@sections) {
 4531:                                             return 'ok';
 4532:                                         } else {
 4533:                                             if (grep/^$sec$/,@sections) {
 4534:                                                 return 'ok';
 4535:                                             }
 4536:                                         }
 4537:                                     }
 4538:                                 }
 4539:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4540:                                     if (grep/^none$/,@groups) {
 4541:                                         return 'ok';
 4542:                                     }
 4543:                                 } else {
 4544:                                     if (grep/^all$/,@groups) {
 4545:                                         return 'ok';
 4546:                                     } 
 4547:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4548:                                         if (grep/^$group$/,@groups) {
 4549:                                             return 'ok';
 4550:                                         }
 4551:                                     }
 4552:                                 } 
 4553:                             }
 4554:                         }
 4555:                     }
 4556:                 }
 4557:             }
 4558:             if ($guest) {
 4559:                 return $guest;
 4560:             }
 4561:         }
 4562:     }
 4563:     return;
 4564: }
 4565: 
 4566: sub course_group_datechecker {
 4567:     my ($dates,$now,$status) = @_;
 4568:     my ($start,$end) = split(/\./,$dates);
 4569:     if (!$start && !$end) {
 4570:         return 'ok';
 4571:     }
 4572:     if (grep/^active$/,@{$status}) {
 4573:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4574:             return 'ok';
 4575:         }
 4576:     }
 4577:     if (grep/^previous$/,@{$status}) {
 4578:         if ($end > $now ) {
 4579:             return 'ok';
 4580:         }
 4581:     }
 4582:     if (grep/^future$/,@{$status}) {
 4583:         if ($start > $now) {
 4584:             return 'ok';
 4585:         }
 4586:     }
 4587:     return; 
 4588: }
 4589: 
 4590: sub parse_portfolio_url {
 4591:     my ($url) = @_;
 4592: 
 4593:     my ($type,$udom,$unum,$group,$file_name);
 4594:     
 4595:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4596: 	$type = 1;
 4597:         $udom = $1;
 4598:         $unum = $2;
 4599:         $file_name = $3;
 4600:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4601: 	$type = 2;
 4602:         $udom = $1;
 4603:         $unum = $2;
 4604:         $group = $3;
 4605:         $file_name = $3.'/'.$4;
 4606:     }
 4607:     if (wantarray) {
 4608: 	return ($type,$udom,$unum,$file_name,$group);
 4609:     }
 4610:     return $type;
 4611: }
 4612: 
 4613: sub is_portfolio_url {
 4614:     my ($url) = @_;
 4615:     return scalar(&parse_portfolio_url($url));
 4616: }
 4617: 
 4618: sub is_portfolio_file {
 4619:     my ($file) = @_;
 4620:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4621:         return 1;
 4622:     }
 4623:     return;
 4624: }
 4625: 
 4626: sub usertools_access {
 4627:     my ($uname,$udom,$tool,$action,$context) = @_;
 4628:     my ($access,%tools);
 4629:     if ($context eq '') {
 4630:         $context = 'tools';
 4631:     }
 4632:     if ($context eq 'requestcourses') {
 4633:         %tools = (
 4634:                       official   => 1,
 4635:                       unofficial => 1,
 4636:                  );
 4637:     } else {
 4638:         %tools = (
 4639:                       aboutme   => 1,
 4640:                       blog      => 1,
 4641:                       portfolio => 1,
 4642:                  );
 4643:     }
 4644:     return if (!defined($tools{$tool}));
 4645: 
 4646:     if ((!defined($udom)) || (!defined($uname))) {
 4647:         $udom = $env{'user.domain'};
 4648:         $uname = $env{'user.name'};
 4649:     }
 4650: 
 4651:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4652:         if ($action ne 'reload') {
 4653:             if ($context eq 'requestcourses') {
 4654:                 return $env{'environment.canrequest.'.$tool};
 4655:             } else {
 4656:                 return $env{'environment.availabletools.'.$tool};
 4657:             }
 4658:         }
 4659:     }
 4660: 
 4661:     my ($toolstatus,$inststatus);
 4662: 
 4663:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4664:          ($action ne 'reload')) {
 4665:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4666:         $inststatus = $env{'environment.inststatus'};
 4667:     } else {
 4668:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4669:         $toolstatus = $userenv{$context.'.'.$tool};
 4670:         $inststatus = $userenv{'inststatus'};
 4671:     }
 4672: 
 4673:     if ($toolstatus ne '') {
 4674:         if ($toolstatus) {
 4675:             $access = 1;
 4676:         } else {
 4677:             $access = 0;
 4678:         }
 4679:         return $access;
 4680:     }
 4681: 
 4682:     my $is_adv = &is_advanced_user($udom,$uname);
 4683:     my %domdef = &get_domain_defaults($udom);
 4684:     if (ref($domdef{$tool}) eq 'HASH') {
 4685:         if ($is_adv) {
 4686:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4687:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4688:                     $access = 1;
 4689:                 } else {
 4690:                     $access = 0;
 4691:                 }
 4692:                 return $access;
 4693:             }
 4694:         }
 4695:         if ($inststatus ne '') {
 4696:             my ($hasaccess,$hasnoaccess);
 4697:             foreach my $affiliation (split(/:/,$inststatus)) {
 4698:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4699:                     if ($domdef{$tool}{$affiliation}) {
 4700:                         $hasaccess = 1;
 4701:                     } else {
 4702:                         $hasnoaccess = 1;
 4703:                     }
 4704:                 }
 4705:             }
 4706:             if ($hasaccess || $hasnoaccess) {
 4707:                 if ($hasaccess) {
 4708:                     $access = 1;
 4709:                 } elsif ($hasnoaccess) {
 4710:                     $access = 0; 
 4711:                 }
 4712:                 return $access;
 4713:             }
 4714:         } else {
 4715:             if ($domdef{$tool}{'default'} ne '') {
 4716:                 if ($domdef{$tool}{'default'}) {
 4717:                     $access = 1;
 4718:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4719:                     $access = 0;
 4720:                 }
 4721:                 return $access;
 4722:             }
 4723:         }
 4724:     } else {
 4725:         if ($context eq 'tools') {
 4726:             $access = 1;
 4727:         } else {
 4728:             $access = 0;
 4729:         }
 4730:         return $access;
 4731:     }
 4732: }
 4733: 
 4734: sub is_advanced_user {
 4735:     my ($udom,$uname) = @_;
 4736:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4737:     my %allroles;
 4738:     my $is_adv;
 4739:     foreach my $role (keys(%roleshash)) {
 4740:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4741:         my $area = '/'.$tdomain.'/'.$trest;
 4742:         if ($sec ne '') {
 4743:             $area .= '/'.$sec;
 4744:         }
 4745:         if (($area ne '') && ($trole ne '')) {
 4746:             my $spec=$trole.'.'.$area;
 4747:             if ($trole =~ /^cr\//) {
 4748:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4749:             } elsif ($trole ne 'gr') {
 4750:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4751:             }
 4752:         }
 4753:     }
 4754:     foreach my $role (keys(%allroles)) {
 4755:         last if ($is_adv);
 4756:         foreach my $item (split(/:/,$allroles{$role})) {
 4757:             if ($item ne '') {
 4758:                 my ($privilege,$restrictions)=split(/&/,$item);
 4759:                 if ($privilege eq 'adv') {
 4760:                     $is_adv = 1;
 4761:                     last;
 4762:                 }
 4763:             }
 4764:         }
 4765:     }
 4766:     return $is_adv;
 4767: }
 4768: 
 4769: # ---------------------------------------------- Custom access rule evaluation
 4770: 
 4771: sub customaccess {
 4772:     my ($priv,$uri)=@_;
 4773:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4774:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4775:     $udom = &LONCAPA::clean_domain($udom);
 4776:     $ucrs = &LONCAPA::clean_username($ucrs);
 4777:     my $access=0;
 4778:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4779: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4780: 	if ($type eq 'user') {
 4781: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4782: 		my ($tdom,$tuname)=split(m{/},$scope);
 4783: 		if ($tdom) {
 4784: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4785: 		}
 4786: 		if ($tuname) {
 4787: 		    if ($tuname ne $env{'user.name'}) { next; }
 4788: 		}
 4789: 		$access=($effect eq 'allow');
 4790: 		last;
 4791: 	    }
 4792: 	} else {
 4793: 	    if ($role) {
 4794: 		if ($role ne $urole) { next; }
 4795: 	    }
 4796: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4797: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4798: 		if ($tdom) {
 4799: 		    if ($tdom ne $udom) { next; }
 4800: 		}
 4801: 		if ($tcrs) {
 4802: 		    if ($tcrs ne $ucrs) { next; }
 4803: 		}
 4804: 		if ($tsec) {
 4805: 		    if ($tsec ne $usec) { next; }
 4806: 		}
 4807: 		$access=($effect eq 'allow');
 4808: 		last;
 4809: 	    }
 4810: 	    if ($realm eq '' && $role eq '') {
 4811: 		$access=($effect eq 'allow');
 4812: 	    }
 4813: 	}
 4814:     }
 4815:     return $access;
 4816: }
 4817: 
 4818: # ------------------------------------------------- Check for a user privilege
 4819: 
 4820: sub allowed {
 4821:     my ($priv,$uri,$symb,$role)=@_;
 4822:     my $ver_orguri=$uri;
 4823:     $uri=&deversion($uri);
 4824:     my $orguri=$uri;
 4825:     $uri=&declutter($uri);
 4826: 
 4827:     if ($priv eq 'evb') {
 4828: # Evade communication block restrictions for specified role in a course
 4829:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4830:             return $1;
 4831:         } else {
 4832:             return;
 4833:         }
 4834:     }
 4835: 
 4836:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4837: # Free bre access to adm and meta resources
 4838:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4839: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4840: 	&& ($priv eq 'bre')) {
 4841: 	return 'F';
 4842:     }
 4843: 
 4844: # Free bre access to user's own portfolio contents
 4845:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4846:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4847: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4848:         my %setters;
 4849:         my ($startblock,$endblock) = 
 4850:             &Apache::loncommon::blockcheck(\%setters,'port');
 4851:         if ($startblock && $endblock) {
 4852:             return 'B';
 4853:         } else {
 4854:             return 'F';
 4855:         }
 4856:     }
 4857: 
 4858: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4859:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4860:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4861:         if (exists($env{'request.course.id'})) {
 4862:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4863:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4864:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4865:                 my $courseprivid=$env{'request.course.id'};
 4866:                 $courseprivid=~s/\_/\//;
 4867:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4868:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4869:                     return $1; 
 4870:                 } else {
 4871:                     if ($env{'request.course.sec'}) {
 4872:                         $courseprivid.='/'.$env{'request.course.sec'};
 4873:                     }
 4874:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4875:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4876:                         return $2;
 4877:                     }
 4878:                 }
 4879:             }
 4880:         }
 4881:     }
 4882: 
 4883: # Free bre to public access
 4884: 
 4885:     if ($priv eq 'bre') {
 4886:         my $copyright=&metadata($uri,'copyright');
 4887: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4888:            return 'F'; 
 4889:         }
 4890:         if ($copyright eq 'priv') {
 4891:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4892: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4893: 		return '';
 4894:             }
 4895:         }
 4896:         if ($copyright eq 'domain') {
 4897:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4898: 	    unless (($env{'user.domain'} eq $1) ||
 4899:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4900: 		return '';
 4901:             }
 4902:         }
 4903:         if ($env{'request.role'}=~ /li\.\//) {
 4904:             # Library role, so allow browsing of resources in this domain.
 4905:             return 'F';
 4906:         }
 4907:         if ($copyright eq 'custom') {
 4908: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4909:         }
 4910:     }
 4911:     # Domain coordinator is trying to create a course
 4912:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4913:         # uri is the requested domain in this case.
 4914:         # comparison to 'request.role.domain' shows if the user has selected
 4915:         # a role of dc for the domain in question.
 4916:         return 'F' if ($uri eq $env{'request.role.domain'});
 4917:     }
 4918: 
 4919:     my $thisallowed='';
 4920:     my $statecond=0;
 4921:     my $courseprivid='';
 4922: 
 4923: # Course
 4924: 
 4925:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4926:        $thisallowed.=$1;
 4927:     }
 4928: 
 4929: # Domain
 4930: 
 4931:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4932:        =~/\Q$priv\E\&([^\:]*)/) {
 4933:        $thisallowed.=$1;
 4934:     }
 4935: 
 4936: # Course: uri itself is a course
 4937:     my $courseuri=$uri;
 4938:     $courseuri=~s/\_(\d)/\/$1/;
 4939:     $courseuri=~s/^([^\/])/\/$1/;
 4940: 
 4941:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4942:        =~/\Q$priv\E\&([^\:]*)/) {
 4943:        $thisallowed.=$1;
 4944:     }
 4945: 
 4946: # URI is an uploaded document for this course, default permissions don't matter
 4947: # not allowing 'edit' access (editupload) to uploaded course docs
 4948:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4949: 	$thisallowed='';
 4950:         my ($match)=&is_on_map($uri);
 4951:         if ($match) {
 4952:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4953:                   =~/\Q$priv\E\&([^\:]*)/) {
 4954:                 $thisallowed.=$1;
 4955:             }
 4956:         } else {
 4957:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4958:             if ($refuri) {
 4959:                 if ($refuri =~ m|^/adm/|) {
 4960:                     $thisallowed='F';
 4961:                 } else {
 4962:                     $refuri=&declutter($refuri);
 4963:                     my ($match) = &is_on_map($refuri);
 4964:                     if ($match) {
 4965:                         $thisallowed='F';
 4966:                     }
 4967:                 }
 4968:             }
 4969:         }
 4970:     }
 4971: 
 4972:     if ($priv eq 'bre'
 4973: 	&& $thisallowed ne 'F' 
 4974: 	&& $thisallowed ne '2'
 4975: 	&& &is_portfolio_url($uri)) {
 4976: 	$thisallowed = &portfolio_access($uri);
 4977:     }
 4978:     
 4979: # Full access at system, domain or course-wide level? Exit.
 4980:     if ($thisallowed=~/F/) {
 4981: 	return 'F';
 4982:     }
 4983: 
 4984: # If this is generating or modifying users, exit with special codes
 4985: 
 4986:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4987: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4988: 	    my ($audom,$auname)=split('/',$uri);
 4989: # no author name given, so this just checks on the general right to make a co-author in this domain
 4990: 	    unless ($auname) { return $thisallowed; }
 4991: # an author name is given, so we are about to actually make a co-author for a certain account
 4992: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4993: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4994: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4995: 	}
 4996: 	return $thisallowed;
 4997:     }
 4998: #
 4999: # Gathered so far: system, domain and course wide privileges
 5000: #
 5001: # Course: See if uri or referer is an individual resource that is part of 
 5002: # the course
 5003: 
 5004:     if ($env{'request.course.id'}) {
 5005: 
 5006:        $courseprivid=$env{'request.course.id'};
 5007:        if ($env{'request.course.sec'}) {
 5008:           $courseprivid.='/'.$env{'request.course.sec'};
 5009:        }
 5010:        $courseprivid=~s/\_/\//;
 5011:        my $checkreferer=1;
 5012:        my ($match,$cond)=&is_on_map($uri);
 5013:        if ($match) {
 5014:            $statecond=$cond;
 5015:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5016:                =~/\Q$priv\E\&([^\:]*)/) {
 5017:                $thisallowed.=$1;
 5018:                $checkreferer=0;
 5019:            }
 5020:        }
 5021:        
 5022:        if ($checkreferer) {
 5023: 	  my $refuri=$env{'httpref.'.$orguri};
 5024:             unless ($refuri) {
 5025:                 foreach my $key (keys(%env)) {
 5026: 		    if ($key=~/^httpref\..*\*/) {
 5027: 			my $pattern=$key;
 5028:                         $pattern=~s/^httpref\.\/res\///;
 5029:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5030:                         $pattern=~s/\//\\\//g;
 5031:                         if ($orguri=~/$pattern/) {
 5032: 			    $refuri=$env{$key};
 5033:                         }
 5034:                     }
 5035:                 }
 5036:             }
 5037: 
 5038:          if ($refuri) { 
 5039: 	  $refuri=&declutter($refuri);
 5040:           my ($match,$cond)=&is_on_map($refuri);
 5041:             if ($match) {
 5042:               my $refstatecond=$cond;
 5043:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5044:                   =~/\Q$priv\E\&([^\:]*)/) {
 5045:                   $thisallowed.=$1;
 5046:                   $uri=$refuri;
 5047:                   $statecond=$refstatecond;
 5048:               }
 5049:           }
 5050:         }
 5051:        }
 5052:    }
 5053: 
 5054: #
 5055: # Gathered now: all privileges that could apply, and condition number
 5056: # 
 5057: #
 5058: # Full or no access?
 5059: #
 5060: 
 5061:     if ($thisallowed=~/F/) {
 5062: 	return 'F';
 5063:     }
 5064: 
 5065:     unless ($thisallowed) {
 5066:         return '';
 5067:     }
 5068: 
 5069: # Restrictions exist, deal with them
 5070: #
 5071: #   C:according to course preferences
 5072: #   R:according to resource settings
 5073: #   L:unless locked
 5074: #   X:according to user session state
 5075: #
 5076: 
 5077: # Possibly locked functionality, check all courses
 5078: # Locks might take effect only after 10 minutes cache expiration for other
 5079: # courses, and 2 minutes for current course
 5080: 
 5081:     my $envkey;
 5082:     if ($thisallowed=~/L/) {
 5083:         foreach $envkey (keys(%env)) {
 5084:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5085:                my $courseid=$2;
 5086:                my $roleid=$1.'.'.$2;
 5087:                $courseid=~s/^\///;
 5088:                my $expiretime=600;
 5089:                if ($env{'request.role'} eq $roleid) {
 5090: 		  $expiretime=120;
 5091:                }
 5092: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5093:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5094:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5095: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5096:                }
 5097:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5098:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5099: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5100:                        &log($env{'user.domain'},$env{'user.name'},
 5101:                             $env{'user.home'},
 5102:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5103:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5104:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5105: 		       return '';
 5106:                    }
 5107:                }
 5108:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5109:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5110: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5111:                        &log($env{'user.domain'},$env{'user.name'},
 5112:                             $env{'user.home'},
 5113:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5114:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5115:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5116: 		       return '';
 5117:                    }
 5118:                }
 5119: 	   }
 5120:        }
 5121:     }
 5122:    
 5123: #
 5124: # Rest of the restrictions depend on selected course
 5125: #
 5126: 
 5127:     unless ($env{'request.course.id'}) {
 5128: 	if ($thisallowed eq 'A') {
 5129: 	    return 'A';
 5130:         } elsif ($thisallowed eq 'B') {
 5131:             return 'B';
 5132: 	} else {
 5133: 	    return '1';
 5134: 	}
 5135:     }
 5136: 
 5137: #
 5138: # Now user is definitely in a course
 5139: #
 5140: 
 5141: 
 5142: # Course preferences
 5143: 
 5144:    if ($thisallowed=~/C/) {
 5145:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5146:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5147:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5148: 	   =~/\Q$rolecode\E/) {
 5149: 	   if ($priv ne 'pch') { 
 5150: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5151: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5152: 			$env{'request.course.id'});
 5153: 	   }
 5154:            return '';
 5155:        }
 5156: 
 5157:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5158: 	   =~/\Q$unamedom\E/) {
 5159: 	   if ($priv ne 'pch') { 
 5160: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5161: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5162: 			$env{'request.course.id'});
 5163: 	   }
 5164:            return '';
 5165:        }
 5166:    }
 5167: 
 5168: # Resource preferences
 5169: 
 5170:    if ($thisallowed=~/R/) {
 5171:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5172:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5173: 	   if ($priv ne 'pch') { 
 5174: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5175: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5176: 	   }
 5177: 	   return '';
 5178:        }
 5179:    }
 5180: 
 5181: # Restricted by state or randomout?
 5182: 
 5183:    if ($thisallowed=~/X/) {
 5184:       if ($env{'acc.randomout'}) {
 5185: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5186:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5187:             return ''; 
 5188:          }
 5189:       }
 5190:       if (&condval($statecond)) {
 5191: 	 return '2';
 5192:       } else {
 5193:          return '';
 5194:       }
 5195:    }
 5196: 
 5197:     if ($thisallowed eq 'A') {
 5198: 	return 'A';
 5199:     } elsif ($thisallowed eq 'B') {
 5200:         return 'B';
 5201:     }
 5202:    return 'F';
 5203: }
 5204: 
 5205: sub split_uri_for_cond {
 5206:     my $uri=&deversion(&declutter(shift));
 5207:     my @uriparts=split(/\//,$uri);
 5208:     my $filename=pop(@uriparts);
 5209:     my $pathname=join('/',@uriparts);
 5210:     return ($pathname,$filename);
 5211: }
 5212: # --------------------------------------------------- Is a resource on the map?
 5213: 
 5214: sub is_on_map {
 5215:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5216:     #Trying to find the conditional for the file
 5217:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5218: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5219:     if ($match) {
 5220: 	return (1,$1);
 5221:     } else {
 5222: 	return (0,0);
 5223:     }
 5224: }
 5225: 
 5226: # --------------------------------------------------------- Get symb from alias
 5227: 
 5228: sub get_symb_from_alias {
 5229:     my $symb=shift;
 5230:     my ($map,$resid,$url)=&decode_symb($symb);
 5231: # Already is a symb
 5232:     if ($url) { return $symb; }
 5233: # Must be an alias
 5234:     my $aliassymb='';
 5235:     my %bighash;
 5236:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5237:                             &GDBM_READER(),0640)) {
 5238:         my $rid=$bighash{'mapalias_'.$symb};
 5239: 	if ($rid) {
 5240: 	    my ($mapid,$resid)=split(/\./,$rid);
 5241: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5242: 				    $resid,$bighash{'src_'.$rid});
 5243: 	}
 5244:         untie %bighash;
 5245:     }
 5246:     return $aliassymb;
 5247: }
 5248: 
 5249: # ----------------------------------------------------------------- Define Role
 5250: 
 5251: sub definerole {
 5252:   if (allowed('mcr','/')) {
 5253:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5254:     foreach my $role (split(':',$sysrole)) {
 5255: 	my ($crole,$cqual)=split(/\&/,$role);
 5256:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5257:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5258: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5259:                return "refused:s:$crole&$cqual"; 
 5260:             }
 5261:         }
 5262:     }
 5263:     foreach my $role (split(':',$domrole)) {
 5264: 	my ($crole,$cqual)=split(/\&/,$role);
 5265:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5266:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5267: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5268:                return "refused:d:$crole&$cqual"; 
 5269:             }
 5270:         }
 5271:     }
 5272:     foreach my $role (split(':',$courole)) {
 5273: 	my ($crole,$cqual)=split(/\&/,$role);
 5274:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5275:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5276: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5277:                return "refused:c:$crole&$cqual"; 
 5278:             }
 5279:         }
 5280:     }
 5281:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5282:                 "$env{'user.domain'}:$env{'user.name'}:".
 5283: 	        "rolesdef_$rolename=".
 5284:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5285:     return reply($command,$env{'user.home'});
 5286:   } else {
 5287:     return 'refused';
 5288:   }
 5289: }
 5290: 
 5291: # ---------------- Make a metadata query against the network of library servers
 5292: 
 5293: sub metadata_query {
 5294:     my ($query,$custom,$customshow,$server_array)=@_;
 5295:     my %rhash;
 5296:     my %libserv = &all_library();
 5297:     my @server_list = (defined($server_array) ? @$server_array
 5298:                                               : keys(%libserv) );
 5299:     for my $server (@server_list) {
 5300: 	unless ($custom or $customshow) {
 5301: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5302: 	    $rhash{$server}=$reply;
 5303: 	}
 5304: 	else {
 5305: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5306: 			     &escape($custom).':'.&escape($customshow),
 5307: 			     $server);
 5308: 	    $rhash{$server}=$reply;
 5309: 	}
 5310:     }
 5311:     return \%rhash;
 5312: }
 5313: 
 5314: # ----------------------------------------- Send log queries and wait for reply
 5315: 
 5316: sub log_query {
 5317:     my ($uname,$udom,$query,%filters)=@_;
 5318:     my $uhome=&homeserver($uname,$udom);
 5319:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5320:     my $uhost=&hostname($uhome);
 5321:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5322:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5323:                        $uhome);
 5324:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5325:     return get_query_reply($queryid);
 5326: }
 5327: 
 5328: # -------------------------- Update MySQL table for portfolio file
 5329: 
 5330: sub update_portfolio_table {
 5331:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5332:     if ($group ne '') {
 5333:         $file_name =~s /^\Q$group\E//;
 5334:     }
 5335:     my $homeserver = &homeserver($uname,$udom);
 5336:     my $queryid=
 5337:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5338:                ':'.&escape($file_name).':'.$action,$homeserver);
 5339:     my $reply = &get_query_reply($queryid);
 5340:     return $reply;
 5341: }
 5342: 
 5343: # -------------------------- Update MySQL allusers table
 5344: 
 5345: sub update_allusers_table {
 5346:     my ($uname,$udom,$names) = @_;
 5347:     my $homeserver = &homeserver($uname,$udom);
 5348:     my $queryid=
 5349:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5350:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5351:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5352:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5353:                'generation='.&escape($names->{'generation'}).'%%'.
 5354:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5355:                'id='.&escape($names->{'id'}),$homeserver);
 5356:     my $reply = &get_query_reply($queryid);
 5357:     return $reply;
 5358: }
 5359: 
 5360: # ------- Request retrieval of institutional classlists for course(s)
 5361: 
 5362: sub fetch_enrollment_query {
 5363:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5364:     my $homeserver;
 5365:     my $maxtries = 1;
 5366:     if ($context eq 'automated') {
 5367:         $homeserver = $perlvar{'lonHostID'};
 5368:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5369:     } else {
 5370:         $homeserver = &homeserver($cnum,$dom);
 5371:     }
 5372:     my $host=&hostname($homeserver);
 5373:     my $cmd = '';
 5374:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5375:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5376:     }
 5377:     $cmd =~ s/%%$//;
 5378:     $cmd = &escape($cmd);
 5379:     my $query = 'fetchenrollment';
 5380:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5381:     unless ($queryid=~/^\Q$host\E\_/) { 
 5382:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5383:         return 'error: '.$queryid;
 5384:     }
 5385:     my $reply = &get_query_reply($queryid);
 5386:     my $tries = 1;
 5387:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5388:         $reply = &get_query_reply($queryid);
 5389:         $tries ++;
 5390:     }
 5391:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5392:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5393:     } else {
 5394:         my @responses = split(/:/,$reply);
 5395:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5396:             foreach my $line (@responses) {
 5397:                 my ($key,$value) = split(/=/,$line,2);
 5398:                 $$replyref{$key} = $value;
 5399:             }
 5400:         } else {
 5401:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5402:             foreach my $line (@responses) {
 5403:                 my ($key,$value) = split(/=/,$line);
 5404:                 $$replyref{$key} = $value;
 5405:                 if ($value > 0) {
 5406:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5407:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5408:                         my $destname = $pathname.'/'.$filename;
 5409:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5410:                         if ($xml_classlist =~ /^error/) {
 5411:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5412:                         } else {
 5413:                             if ( open(FILE,">$destname") ) {
 5414:                                 print FILE &unescape($xml_classlist);
 5415:                                 close(FILE);
 5416:                             } else {
 5417:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5418:                             }
 5419:                         }
 5420:                     }
 5421:                 }
 5422:             }
 5423:         }
 5424:         return 'ok';
 5425:     }
 5426:     return 'error';
 5427: }
 5428: 
 5429: sub get_query_reply {
 5430:     my $queryid=shift;
 5431:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5432:     my $reply='';
 5433:     for (1..100) {
 5434: 	sleep 2;
 5435:         if (-e $replyfile.'.end') {
 5436: 	    if (open(my $fh,$replyfile)) {
 5437: 		$reply = join('',<$fh>);
 5438: 		close($fh);
 5439: 	   } else { return 'error: reply_file_error'; }
 5440:            return &unescape($reply);
 5441: 	}
 5442:     }
 5443:     return 'timeout:'.$queryid;
 5444: }
 5445: 
 5446: sub courselog_query {
 5447: #
 5448: # possible filters:
 5449: # url: url or symb
 5450: # username
 5451: # domain
 5452: # action: view, submit, grade
 5453: # start: timestamp
 5454: # end: timestamp
 5455: #
 5456:     my (%filters)=@_;
 5457:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5458:     if ($filters{'url'}) {
 5459: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5460:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5461:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5462:     }
 5463:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5464:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5465:     return &log_query($cname,$cdom,'courselog',%filters);
 5466: }
 5467: 
 5468: sub userlog_query {
 5469: #
 5470: # possible filters:
 5471: # action: log check role
 5472: # start: timestamp
 5473: # end: timestamp
 5474: #
 5475:     my ($uname,$udom,%filters)=@_;
 5476:     return &log_query($uname,$udom,'userlog',%filters);
 5477: }
 5478: 
 5479: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5480: 
 5481: sub auto_run {
 5482:     my ($cnum,$cdom) = @_;
 5483:     my $response = 0;
 5484:     my $settings;
 5485:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5486:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5487:         $settings = $domconfig{'autoenroll'};
 5488:         if ($settings->{'run'} eq '1') {
 5489:             $response = 1;
 5490:         }
 5491:     } else {
 5492:         my $homeserver;
 5493:         if (&is_course($cdom,$cnum)) {
 5494:             $homeserver = &homeserver($cnum,$cdom);
 5495:         } else {
 5496:             $homeserver = &domain($cdom,'primary');
 5497:         }
 5498:         if ($homeserver ne 'no_host') {
 5499:             $response = &reply('autorun:'.$cdom,$homeserver);
 5500:         }
 5501:     }
 5502:     return $response;
 5503: }
 5504: 
 5505: sub auto_get_sections {
 5506:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5507:     my $homeserver = &homeserver($cnum,$cdom);
 5508:     my @secs = ();
 5509:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5510:     unless ($response eq 'refused') {
 5511:         @secs = split(/:/,$response);
 5512:     }
 5513:     return @secs;
 5514: }
 5515: 
 5516: sub auto_new_course {
 5517:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5518:     my $homeserver = &homeserver($cnum,$cdom);
 5519:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5520:     return $response;
 5521: }
 5522: 
 5523: sub auto_validate_courseID {
 5524:     my ($cnum,$cdom,$inst_course_id) = @_;
 5525:     my $homeserver = &homeserver($cnum,$cdom);
 5526:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5527:     return $response;
 5528: }
 5529: 
 5530: sub auto_create_password {
 5531:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5532:     my ($homeserver,$response);
 5533:     my $create_passwd = 0;
 5534:     my $authchk = '';
 5535:     if ($udom =~ /^$match_domain$/) {
 5536:         $homeserver = &domain($udom,'primary');
 5537:     }
 5538:     if ($homeserver eq '') {
 5539:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5540:             $homeserver = &homeserver($cnum,$cdom);
 5541:         }
 5542:     }
 5543:     if ($homeserver eq '') {
 5544:         $authchk = 'nodomain';
 5545:     } else {
 5546:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5547:         if ($response eq 'refused') {
 5548:             $authchk = 'refused';
 5549:         } else {
 5550:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5551:         }
 5552:     }
 5553:     return ($authparam,$create_passwd,$authchk);
 5554: }
 5555: 
 5556: sub auto_photo_permission {
 5557:     my ($cnum,$cdom,$students) = @_;
 5558:     my $homeserver = &homeserver($cnum,$cdom);
 5559:     my ($outcome,$perm_reqd,$conditions) = 
 5560: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5561:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5562: 	return (undef,undef);
 5563:     }
 5564:     return ($outcome,$perm_reqd,$conditions);
 5565: }
 5566: 
 5567: sub auto_checkphotos {
 5568:     my ($uname,$udom,$pid) = @_;
 5569:     my $homeserver = &homeserver($uname,$udom);
 5570:     my ($result,$resulttype);
 5571:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5572: 				   &escape($uname).':'.&escape($pid),
 5573: 				   $homeserver));
 5574:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5575: 	return (undef,undef);
 5576:     }
 5577:     if ($outcome) {
 5578:         ($result,$resulttype) = split(/:/,$outcome);
 5579:     } 
 5580:     return ($result,$resulttype);
 5581: }
 5582: 
 5583: sub auto_photochoice {
 5584:     my ($cnum,$cdom) = @_;
 5585:     my $homeserver = &homeserver($cnum,$cdom);
 5586:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5587: 						       &escape($cdom),
 5588: 						       $homeserver)));
 5589:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5590: 	return (undef,undef);
 5591:     }
 5592:     return ($update,$comment);
 5593: }
 5594: 
 5595: sub auto_photoupdate {
 5596:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5597:     my $homeserver = &homeserver($cnum,$dom);
 5598:     my $host=&hostname($homeserver);
 5599:     my $cmd = '';
 5600:     my $maxtries = 1;
 5601:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5602:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5603:     }
 5604:     $cmd =~ s/%%$//;
 5605:     $cmd = &escape($cmd);
 5606:     my $query = 'institutionalphotos';
 5607:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5608:     unless ($queryid=~/^\Q$host\E\_/) {
 5609:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5610:         return 'error: '.$queryid;
 5611:     }
 5612:     my $reply = &get_query_reply($queryid);
 5613:     my $tries = 1;
 5614:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5615:         $reply = &get_query_reply($queryid);
 5616:         $tries ++;
 5617:     }
 5618:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5619:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5620:     } else {
 5621:         my @responses = split(/:/,$reply);
 5622:         my $outcome = shift(@responses); 
 5623:         foreach my $item (@responses) {
 5624:             my ($key,$value) = split(/=/,$item);
 5625:             $$photo{$key} = $value;
 5626:         }
 5627:         return $outcome;
 5628:     }
 5629:     return 'error';
 5630: }
 5631: 
 5632: sub auto_instcode_format {
 5633:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5634: 	$cat_order) = @_;
 5635:     my $courses = '';
 5636:     my @homeservers;
 5637:     if ($caller eq 'global') {
 5638: 	my %servers = &get_servers($codedom,'library');
 5639: 	foreach my $tryserver (keys(%servers)) {
 5640: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5641: 		push(@homeservers,$tryserver);
 5642: 	    }
 5643:         }
 5644:     } else {
 5645:         push(@homeservers,&homeserver($caller,$codedom));
 5646:     }
 5647:     foreach my $code (keys(%{$instcodes})) {
 5648:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5649:     }
 5650:     chop($courses);
 5651:     my $ok_response = 0;
 5652:     my $response;
 5653:     while (@homeservers > 0 && $ok_response == 0) {
 5654:         my $server = shift(@homeservers); 
 5655:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5656:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5657:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5658: 		split(/:/,$response);
 5659:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5660:             push(@{$codetitles},&str2array($codetitles_str));
 5661:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5662:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5663:             $ok_response = 1;
 5664:         }
 5665:     }
 5666:     if ($ok_response) {
 5667:         return 'ok';
 5668:     } else {
 5669:         return $response;
 5670:     }
 5671: }
 5672: 
 5673: sub auto_instcode_defaults {
 5674:     my ($domain,$returnhash,$code_order) = @_;
 5675:     my @homeservers;
 5676: 
 5677:     my %servers = &get_servers($domain,'library');
 5678:     foreach my $tryserver (keys(%servers)) {
 5679: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5680: 	    push(@homeservers,$tryserver);
 5681: 	}
 5682:     }
 5683: 
 5684:     my $response;
 5685:     foreach my $server (@homeservers) {
 5686:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5687:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5688: 	
 5689: 	foreach my $pair (split(/\&/,$response)) {
 5690: 	    my ($name,$value)=split(/\=/,$pair);
 5691: 	    if ($name eq 'code_order') {
 5692: 		@{$code_order} = split(/\&/,&unescape($value));
 5693: 	    } else {
 5694: 		$returnhash->{&unescape($name)}=&unescape($value);
 5695: 	    }
 5696: 	}
 5697: 	return 'ok';
 5698:     }
 5699: 
 5700:     return $response;
 5701: } 
 5702: 
 5703: sub auto_validate_class_sec {
 5704:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5705:     my $homeserver = &homeserver($cnum,$cdom);
 5706:     my $ownerlist;
 5707:     if (ref($owners) eq 'ARRAY') {
 5708:         $ownerlist = join(',',@{$owners});
 5709:     } else {
 5710:         $ownerlist = $owners;
 5711:     }
 5712:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5713:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5714:     return $response;
 5715: }
 5716: 
 5717: # ------------------------------------------------------- Course Group routines
 5718: 
 5719: sub get_coursegroups {
 5720:     my ($cdom,$cnum,$group,$namespace) = @_;
 5721:     return(&dump($namespace,$cdom,$cnum,$group));
 5722: }
 5723: 
 5724: sub modify_coursegroup {
 5725:     my ($cdom,$cnum,$groupsettings) = @_;
 5726:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5727: }
 5728: 
 5729: sub toggle_coursegroup_status {
 5730:     my ($cdom,$cnum,$group,$action) = @_;
 5731:     my ($from_namespace,$to_namespace);
 5732:     if ($action eq 'delete') {
 5733:         $from_namespace = 'coursegroups';
 5734:         $to_namespace = 'deleted_groups';
 5735:     } else {
 5736:         $from_namespace = 'deleted_groups';
 5737:         $to_namespace = 'coursegroups';
 5738:     }
 5739:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5740:     if (my $tmp = &error(%curr_group)) {
 5741:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5742:         return ('read error',$tmp);
 5743:     } else {
 5744:         my %savedsettings = %curr_group; 
 5745:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5746:         my $deloutcome;
 5747:         if ($result eq 'ok') {
 5748:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5749:         } else {
 5750:             return ('write error',$result);
 5751:         }
 5752:         if ($deloutcome eq 'ok') {
 5753:             return 'ok';
 5754:         } else {
 5755:             return ('delete error',$deloutcome);
 5756:         }
 5757:     }
 5758: }
 5759: 
 5760: sub modify_group_roles {
 5761:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5762:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5763:     my $role = 'gr/'.&escape($userprivs);
 5764:     my ($uname,$udom) = split(/:/,$user);
 5765:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5766:     if ($result eq 'ok') {
 5767:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5768:     }
 5769:     return $result;
 5770: }
 5771: 
 5772: sub modify_coursegroup_membership {
 5773:     my ($cdom,$cnum,$membership) = @_;
 5774:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5775:     return $result;
 5776: }
 5777: 
 5778: sub get_active_groups {
 5779:     my ($udom,$uname,$cdom,$cnum) = @_;
 5780:     my $now = time;
 5781:     my %groups = ();
 5782:     foreach my $key (keys(%env)) {
 5783:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5784:             my ($start,$end) = split(/\./,$env{$key});
 5785:             if (($end!=0) && ($end<$now)) { next; }
 5786:             if (($start!=0) && ($start>$now)) { next; }
 5787:             if ($1 eq $cdom && $2 eq $cnum) {
 5788:                 $groups{$3} = $env{$key} ;
 5789:             }
 5790:         }
 5791:     }
 5792:     return %groups;
 5793: }
 5794: 
 5795: sub get_group_membership {
 5796:     my ($cdom,$cnum,$group) = @_;
 5797:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5798: }
 5799: 
 5800: sub get_users_groups {
 5801:     my ($udom,$uname,$courseid) = @_;
 5802:     my @usersgroups;
 5803:     my $cachetime=1800;
 5804: 
 5805:     my $hashid="$udom:$uname:$courseid";
 5806:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5807:     if (defined($cached)) {
 5808:         @usersgroups = split(/:/,$grouplist);
 5809:     } else {  
 5810:         $grouplist = '';
 5811:         my $courseurl = &courseid_to_courseurl($courseid);
 5812:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5813:         my $access_end = $env{'course.'.$courseid.
 5814:                               '.default_enrollment_end_date'};
 5815:         my $now = time;
 5816:         foreach my $key (keys(%roleshash)) {
 5817:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5818:                 my $group = $1;
 5819:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5820:                     my $start = $2;
 5821:                     my $end = $1;
 5822:                     if ($start == -1) { next; } # deleted from group
 5823:                     if (($start!=0) && ($start>$now)) { next; }
 5824:                     if (($end!=0) && ($end<$now)) {
 5825:                         if ($access_end && $access_end < $now) {
 5826:                             if ($access_end - $end < 86400) {
 5827:                                 push(@usersgroups,$group);
 5828:                             }
 5829:                         }
 5830:                         next;
 5831:                     }
 5832:                     push(@usersgroups,$group);
 5833:                 }
 5834:             }
 5835:         }
 5836:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5837:         $grouplist = join(':',@usersgroups);
 5838:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5839:     }
 5840:     return @usersgroups;
 5841: }
 5842: 
 5843: sub devalidate_getgroups_cache {
 5844:     my ($udom,$uname,$cdom,$cnum)=@_;
 5845:     my $courseid = $cdom.'_'.$cnum;
 5846: 
 5847:     my $hashid="$udom:$uname:$courseid";
 5848:     &devalidate_cache_new('getgroups',$hashid);
 5849: }
 5850: 
 5851: # ------------------------------------------------------------------ Plain Text
 5852: 
 5853: sub plaintext {
 5854:     my ($short,$type,$cid,$forcedefault) = @_;
 5855:     if ($short =~ /^cr/) {
 5856: 	return (split('/',$short))[-1];
 5857:     }
 5858:     if (!defined($cid)) {
 5859:         $cid = $env{'request.course.id'};
 5860:     }
 5861:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 5862:         unless ($forcedefault) {
 5863:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 5864:             &Apache::lonlocal::mt_escape(\$roletext);
 5865:             return &Apache::lonlocal::mt($roletext);
 5866:         }
 5867:     }
 5868:     my %rolenames = (
 5869:                       Course => 'std',
 5870:                       Group => 'alt1',
 5871:                     );
 5872:     if (defined($type) && 
 5873:          defined($rolenames{$type}) && 
 5874:          defined($prp{$short}{$rolenames{$type}})) {
 5875:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5876:     } else {
 5877:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5878:     }
 5879: }
 5880: 
 5881: # ----------------------------------------------------------------- Assign Role
 5882: 
 5883: sub assignrole {
 5884:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5885:         $context)=@_;
 5886:     my $mrole;
 5887:     if ($role =~ /^cr\//) {
 5888:         my $cwosec=$url;
 5889:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5890: 	unless (&allowed('ccr',$cwosec)) {
 5891:            &logthis('Refused custom assignrole: '.
 5892:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5893: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5894:            return 'refused'; 
 5895:         }
 5896:         $mrole='cr';
 5897:     } elsif ($role =~ /^gr\//) {
 5898:         my $cwogrp=$url;
 5899:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5900:         unless (&allowed('mdg',$cwogrp)) {
 5901:             &logthis('Refused group assignrole: '.
 5902:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5903:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5904:             return 'refused';
 5905:         }
 5906:         $mrole='gr';
 5907:     } else {
 5908:         my $cwosec=$url;
 5909:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5910:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5911:             my $refused;
 5912:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5913:                 if (!(&allowed('c'.$role,$url))) {
 5914:                     $refused = 1;
 5915:                 }
 5916:             } else {
 5917:                 $refused = 1;
 5918:             }
 5919:             if ($refused) {
 5920:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5921:                     $refused = '';
 5922:                 } else {
 5923:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5924:                              ' '.$role.' '.$end.' '.$start.' by '.
 5925: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5926:                     return 'refused';
 5927:                 }
 5928:             }
 5929:         }
 5930:         $mrole=$role;
 5931:     }
 5932:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5933:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5934:     if ($end) { $command.='_'.$end; }
 5935:     if ($start) {
 5936: 	if ($end) { 
 5937:            $command.='_'.$start; 
 5938:         } else {
 5939:            $command.='_0_'.$start;
 5940:         }
 5941:     }
 5942:     my $origstart = $start;
 5943:     my $origend = $end;
 5944:     my $delflag;
 5945: # actually delete
 5946:     if ($deleteflag) {
 5947: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5948: # modify command to delete the role
 5949:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5950:                 "$udom:$uname:$url".'_'."$mrole";
 5951: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5952: # set start and finish to negative values for userrolelog
 5953:            $start=-1;
 5954:            $end=-1;
 5955:            $delflag = 1;
 5956:         }
 5957:     }
 5958: # send command
 5959:     my $answer=&reply($command,&homeserver($uname,$udom));
 5960: # log new user role if status is ok
 5961:     if ($answer eq 'ok') {
 5962: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5963: # for course roles, perform group memberships changes triggered by role change.
 5964:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5965:         unless ($role =~ /^gr/) {
 5966:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5967:                                              $origstart,$selfenroll,$context);
 5968:         }
 5969:     }
 5970:     return $answer;
 5971: }
 5972: 
 5973: # -------------------------------------------------- Modify user authentication
 5974: # Overrides without validation
 5975: 
 5976: sub modifyuserauth {
 5977:     my ($udom,$uname,$umode,$upass)=@_;
 5978:     my $uhome=&homeserver($uname,$udom);
 5979:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5980:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5981:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5982:              ' in domain '.$env{'request.role.domain'});  
 5983:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5984: 		     &escape($upass),$uhome);
 5985:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5986:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5987:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5988:     &log($udom,,$uname,$uhome,
 5989:         'Authentication changed by '.$env{'user.domain'}.', '.
 5990:                                      $env{'user.name'}.', '.$umode.
 5991:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5992:     unless ($reply eq 'ok') {
 5993:         &logthis('Authentication mode error: '.$reply);
 5994: 	return 'error: '.$reply;
 5995:     }   
 5996:     return 'ok';
 5997: }
 5998: 
 5999: # --------------------------------------------------------------- Modify a user
 6000: 
 6001: sub modifyuser {
 6002:     my ($udom,    $uname, $uid,
 6003:         $umode,   $upass, $first,
 6004:         $middle,  $last,  $gene,
 6005:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6006:     $udom= &LONCAPA::clean_domain($udom);
 6007:     $uname=&LONCAPA::clean_username($uname);
 6008:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6009:              $umode.', '.$first.', '.$middle.', '.
 6010: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6011:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6012:                                      ' desiredhome not specified'). 
 6013:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6014:              ' in domain '.$env{'request.role.domain'});
 6015:     my $uhome=&homeserver($uname,$udom,'true');
 6016: # ----------------------------------------------------------------- Create User
 6017:     if (($uhome eq 'no_host') && 
 6018: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6019:         my $unhome='';
 6020:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6021:             $unhome = $desiredhome;
 6022: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6023: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6024:         } else { # load balancing routine for determining $unhome
 6025:             my $loadm=10000000;
 6026: 	    my %servers = &get_servers($udom,'library');
 6027: 	    foreach my $tryserver (keys(%servers)) {
 6028: 		my $answer=reply('load',$tryserver);
 6029: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6030: 		    $loadm=$answer;
 6031: 		    $unhome=$tryserver;
 6032: 		}
 6033: 	    }
 6034:         }
 6035:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6036: 	    return 'error: unable to find a home server for '.$uname.
 6037:                    ' in domain '.$udom;
 6038:         }
 6039:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6040:                          &escape($upass),$unhome);
 6041: 	unless ($reply eq 'ok') {
 6042:             return 'error: '.$reply;
 6043:         }   
 6044:         $uhome=&homeserver($uname,$udom,'true');
 6045:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6046: 	    return 'error: unable verify users home machine.';
 6047:         }
 6048:     }   # End of creation of new user
 6049: # ---------------------------------------------------------------------- Add ID
 6050:     if ($uid) {
 6051:        $uid=~tr/A-Z/a-z/;
 6052:        my %uidhash=&idrget($udom,$uname);
 6053:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6054:          && (!$forceid)) {
 6055: 	  unless ($uid eq $uidhash{$uname}) {
 6056: 	      return 'error: user id "'.$uid.'" does not match '.
 6057:                   'current user id "'.$uidhash{$uname}.'".';
 6058:           }
 6059:        } else {
 6060: 	  &idput($udom,($uname => $uid));
 6061:        }
 6062:     }
 6063: # -------------------------------------------------------------- Add names, etc
 6064:     my @tmp=&get('environment',
 6065: 		   ['firstname','middlename','lastname','generation','id',
 6066:                     'permanentemail','inststatus'],
 6067: 		   $udom,$uname);
 6068:     my %names;
 6069:     if ($tmp[0] =~ m/^error:.*/) { 
 6070:         %names=(); 
 6071:     } else {
 6072:         %names = @tmp;
 6073:     }
 6074: #
 6075: # Make sure to not trash student environment if instructor does not bother
 6076: # to supply name and email information
 6077: #
 6078:     if ($first)  { $names{'firstname'}  = $first; }
 6079:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6080:     if ($last)   { $names{'lastname'}   = $last; }
 6081:     if (defined($gene))   { $names{'generation'} = $gene; }
 6082:     if ($email) {
 6083:        $email=~s/[^\w\@\.\-\,]//gs;
 6084:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6085:     }
 6086:     if ($uid) { $names{'id'}  = $uid; }
 6087:     if (defined($inststatus)) {
 6088:         $names{'inststatus'} = '';
 6089:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6090:         if (ref($usertypes) eq 'HASH') {
 6091:             my @okstatuses; 
 6092:             foreach my $item (split(/:/,$inststatus)) {
 6093:                 if (defined($usertypes->{$item})) {
 6094:                     push(@okstatuses,$item);  
 6095:                 }
 6096:             }
 6097:             if (@okstatuses) {
 6098:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6099:             }
 6100:         }
 6101:     }
 6102:     my $reply = &put('environment', \%names, $udom,$uname);
 6103:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6104:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6105:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6106:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6107:                  $umode.', '.$first.', '.$middle.', '.
 6108: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6109:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6110:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6111:     } else {
 6112:         $logmsg .= ' during self creation';
 6113:     }
 6114:     &logthis($logmsg);
 6115:     return 'ok';
 6116: }
 6117: 
 6118: # -------------------------------------------------------------- Modify student
 6119: 
 6120: sub modifystudent {
 6121:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6122:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6123:         $selfenroll,$context,$inststatus)=@_;
 6124:     if (!$cid) {
 6125: 	unless ($cid=$env{'request.course.id'}) {
 6126: 	    return 'not_in_class';
 6127: 	}
 6128:     }
 6129: # --------------------------------------------------------------- Make the user
 6130:     my $reply=&modifyuser
 6131: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6132:          $desiredhome,$email,$inststatus);
 6133:     unless ($reply eq 'ok') { return $reply; }
 6134:     # This will cause &modify_student_enrollment to get the uid from the
 6135:     # students environment
 6136:     $uid = undef if (!$forceid);
 6137:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6138: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6139:     return $reply;
 6140: }
 6141: 
 6142: sub modify_student_enrollment {
 6143:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6144:     my ($cdom,$cnum,$chome);
 6145:     if (!$cid) {
 6146: 	unless ($cid=$env{'request.course.id'}) {
 6147: 	    return 'not_in_class';
 6148: 	}
 6149: 	$cdom=$env{'course.'.$cid.'.domain'};
 6150: 	$cnum=$env{'course.'.$cid.'.num'};
 6151:     } else {
 6152: 	($cdom,$cnum)=split(/_/,$cid);
 6153:     }
 6154:     $chome=$env{'course.'.$cid.'.home'};
 6155:     if (!$chome) {
 6156: 	$chome=&homeserver($cnum,$cdom);
 6157:     }
 6158:     if (!$chome) { return 'unknown_course'; }
 6159:     # Make sure the user exists
 6160:     my $uhome=&homeserver($uname,$udom);
 6161:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6162: 	return 'error: no such user';
 6163:     }
 6164:     # Get student data if we were not given enough information
 6165:     if (!defined($first)  || $first  eq '' || 
 6166:         !defined($last)   || $last   eq '' || 
 6167:         !defined($uid)    || $uid    eq '' || 
 6168:         !defined($middle) || $middle eq '' || 
 6169:         !defined($gene)   || $gene   eq '') {
 6170:         # They did not supply us with enough data to enroll the student, so
 6171:         # we need to pick up more information.
 6172:         my %tmp = &get('environment',
 6173:                        ['firstname','middlename','lastname', 'generation','id']
 6174:                        ,$udom,$uname);
 6175: 
 6176:         #foreach my $key (keys(%tmp)) {
 6177:         #    &logthis("key $key = ".$tmp{$key});
 6178:         #}
 6179:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6180:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6181:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6182:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6183:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6184:     }
 6185:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6186:     my $reply=cput('classlist',
 6187: 		   {"$uname:$udom" => 
 6188: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6189: 		   $cdom,$cnum);
 6190:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6191: 	return 'error: '.$reply;
 6192:     } else {
 6193: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6194:     }
 6195:     # Add student role to user
 6196:     my $uurl='/'.$cid;
 6197:     $uurl=~s/\_/\//g;
 6198:     if ($usec) {
 6199: 	$uurl.='/'.$usec;
 6200:     }
 6201:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6202: }
 6203: 
 6204: sub format_name {
 6205:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6206:     my $name;
 6207:     if ($first ne 'lastname') {
 6208: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6209:     } else {
 6210: 	if ($lastname=~/\S/) {
 6211: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6212: 	    $name=~s/\s+,/,/;
 6213: 	} else {
 6214: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6215: 	}
 6216:     }
 6217:     $name=~s/^\s+//;
 6218:     $name=~s/\s+$//;
 6219:     $name=~s/\s+/ /g;
 6220:     return $name;
 6221: }
 6222: 
 6223: # ------------------------------------------------- Write to course preferences
 6224: 
 6225: sub writecoursepref {
 6226:     my ($courseid,%prefs)=@_;
 6227:     $courseid=~s/^\///;
 6228:     $courseid=~s/\_/\//g;
 6229:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6230:     my $chome=homeserver($cnum,$cdomain);
 6231:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6232: 	return 'error: no such course';
 6233:     }
 6234:     my $cstring='';
 6235:     foreach my $pref (keys(%prefs)) {
 6236: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6237:     }
 6238:     $cstring=~s/\&$//;
 6239:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6240: }
 6241: 
 6242: # ---------------------------------------------------------- Make/modify course
 6243: 
 6244: sub createcourse {
 6245:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6246:         $course_owner,$crstype)=@_;
 6247:     $url=&declutter($url);
 6248:     my $cid='';
 6249:     unless (&allowed('ccc',$udom)) {
 6250:         return 'refused';
 6251:     }
 6252: # ------------------------------------------------------------------- Create ID
 6253:    my $uname=int(1+rand(9)).
 6254:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6255:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6256:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6257: # ----------------------------------------------- Make sure that does not exist
 6258:    my $uhome=&homeserver($uname,$udom,'true');
 6259:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6260:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6261:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6262:        $uhome=&homeserver($uname,$udom,'true');       
 6263:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6264:            return 'error: unable to generate unique course-ID';
 6265:        } 
 6266:    }
 6267: # ------------------------------------------------ Check supplied server name
 6268:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6269:     if (! &is_library($course_server)) {
 6270:         return 'error:bad server name '.$course_server;
 6271:     }
 6272: # ------------------------------------------------------------- Make the course
 6273:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6274:                       $course_server);
 6275:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6276:     $uhome=&homeserver($uname,$udom,'true');
 6277:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6278: 	return 'error: no such course';
 6279:     }
 6280: # ----------------------------------------------------------------- Course made
 6281: # log existence
 6282:     my $newcourse = {
 6283:                     $udom.'_'.$uname => {
 6284:                                      description => $description,
 6285:                                      inst_code   => $inst_code,
 6286:                                      owner       => $course_owner,
 6287:                                      type        => $crstype,
 6288:                                                 },
 6289:                     };
 6290:     &courseidput($udom,$newcourse,$uhome,'notime');
 6291: # set toplevel url
 6292:     my $topurl=$url;
 6293:     unless ($nonstandard) {
 6294: # ------------------------------------------ For standard courses, make top url
 6295:         my $mapurl=&clutter($url);
 6296:         if ($mapurl eq '/res/') { $mapurl=''; }
 6297:         $env{'form.initmap'}=(<<ENDINITMAP);
 6298: <map>
 6299: <resource id="1" type="start"></resource>
 6300: <resource id="2" src="$mapurl"></resource>
 6301: <resource id="3" type="finish"></resource>
 6302: <link index="1" from="1" to="2"></link>
 6303: <link index="2" from="2" to="3"></link>
 6304: </map>
 6305: ENDINITMAP
 6306:         $topurl=&declutter(
 6307:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6308:                           );
 6309:     }
 6310: # ----------------------------------------------------------- Write preferences
 6311:     &writecoursepref($udom.'_'.$uname,
 6312:                      ('description' => $description,
 6313:                       'url'         => $topurl));
 6314:     return '/'.$udom.'/'.$uname;
 6315: }
 6316: 
 6317: sub is_course {
 6318:     my ($cdom,$cnum) = @_;
 6319:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6320: 				undef,'.');
 6321:     if (exists($courses{$cdom.'_'.$cnum})) {
 6322:         return 1;
 6323:     }
 6324:     return 0;
 6325: }
 6326: 
 6327: # ---------------------------------------------------------- Assign Custom Role
 6328: 
 6329: sub assigncustomrole {
 6330:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6331:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6332:                        $end,$start,$deleteflag,$selfenroll,$context);
 6333: }
 6334: 
 6335: # ----------------------------------------------------------------- Revoke Role
 6336: 
 6337: sub revokerole {
 6338:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6339:     my $now=time;
 6340:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6341: }
 6342: 
 6343: # ---------------------------------------------------------- Revoke Custom Role
 6344: 
 6345: sub revokecustomrole {
 6346:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6347:     my $now=time;
 6348:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6349:            $deleteflag,$selfenroll,$context);
 6350: }
 6351: 
 6352: # ------------------------------------------------------------ Disk usage
 6353: sub diskusage {
 6354:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6355:     $directorypath =~ s/\/$//;
 6356:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6357:                        .&escape($getpropath).':'.&escape($uname).':'
 6358:                        .&escape($udom),homeserver($uname,$udom));
 6359:     if ($listing eq 'unknown_cmd') {
 6360:         if ($getpropath) {
 6361:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6362:         }
 6363:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6364:     }
 6365:     return $listing;
 6366: }
 6367: 
 6368: sub is_locked {
 6369:     my ($file_name, $domain, $user) = @_;
 6370:     my @check;
 6371:     my $is_locked;
 6372:     push @check, $file_name;
 6373:     my %locked = &get('file_permissions',\@check,
 6374: 		      $env{'user.domain'},$env{'user.name'});
 6375:     my ($tmp)=keys(%locked);
 6376:     if ($tmp=~/^error:/) { undef(%locked); }
 6377:     
 6378:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6379:         $is_locked = 'false';
 6380:         foreach my $entry (@{$locked{$file_name}}) {
 6381:            if (ref($entry) eq 'ARRAY') { 
 6382:                $is_locked = 'true';
 6383:                last;
 6384:            }
 6385:        }
 6386:     } else {
 6387:         $is_locked = 'false';
 6388:     }
 6389: }
 6390: 
 6391: sub declutter_portfile {
 6392:     my ($file) = @_;
 6393:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6394:     return $file;
 6395: }
 6396: 
 6397: # ------------------------------------------------------------- Mark as Read Only
 6398: 
 6399: sub mark_as_readonly {
 6400:     my ($domain,$user,$files,$what) = @_;
 6401:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6402:     my ($tmp)=keys(%current_permissions);
 6403:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6404:     foreach my $file (@{$files}) {
 6405: 	$file = &declutter_portfile($file);
 6406:         push(@{$current_permissions{$file}},$what);
 6407:     }
 6408:     &put('file_permissions',\%current_permissions,$domain,$user);
 6409:     return;
 6410: }
 6411: 
 6412: # ------------------------------------------------------------Save Selected Files
 6413: 
 6414: sub save_selected_files {
 6415:     my ($user, $path, @files) = @_;
 6416:     my $filename = $user."savedfiles";
 6417:     my @other_files = &files_not_in_path($user, $path);
 6418:     open (OUT, '>'.$tmpdir.$filename);
 6419:     foreach my $file (@files) {
 6420:         print (OUT $env{'form.currentpath'}.$file."\n");
 6421:     }
 6422:     foreach my $file (@other_files) {
 6423:         print (OUT $file."\n");
 6424:     }
 6425:     close (OUT);
 6426:     return 'ok';
 6427: }
 6428: 
 6429: sub clear_selected_files {
 6430:     my ($user) = @_;
 6431:     my $filename = $user."savedfiles";
 6432:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6433:     print (OUT undef);
 6434:     close (OUT);
 6435:     return ("ok");    
 6436: }
 6437: 
 6438: sub files_in_path {
 6439:     my ($user, $path) = @_;
 6440:     my $filename = $user."savedfiles";
 6441:     my %return_files;
 6442:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6443:     while (my $line_in = <IN>) {
 6444:         chomp ($line_in);
 6445:         my @paths_and_file = split (m!/!, $line_in);
 6446:         my $file_part = pop (@paths_and_file);
 6447:         my $path_part = join ('/', @paths_and_file);
 6448:         $path_part.='/';
 6449:         my $path_and_file = $path_part.$file_part;
 6450:         if ($path_part eq $path) {
 6451:             $return_files{$file_part}= 'selected';
 6452:         }
 6453:     }
 6454:     close (IN);
 6455:     return (\%return_files);
 6456: }
 6457: 
 6458: # called in portfolio select mode, to show files selected NOT in current directory
 6459: sub files_not_in_path {
 6460:     my ($user, $path) = @_;
 6461:     my $filename = $user."savedfiles";
 6462:     my @return_files;
 6463:     my $path_part;
 6464:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6465:     while (my $line = <IN>) {
 6466:         #ok, I know it's clunky, but I want it to work
 6467:         my @paths_and_file = split(m|/|, $line);
 6468:         my $file_part = pop(@paths_and_file);
 6469:         chomp($file_part);
 6470:         my $path_part = join('/', @paths_and_file);
 6471:         $path_part .= '/';
 6472:         my $path_and_file = $path_part.$file_part;
 6473:         if ($path_part ne $path) {
 6474:             push(@return_files, ($path_and_file));
 6475:         }
 6476:     }
 6477:     close(OUT);
 6478:     return (@return_files);
 6479: }
 6480: 
 6481: #----------------------------------------------Get portfolio file permissions
 6482: 
 6483: sub get_portfile_permissions {
 6484:     my ($domain,$user) = @_;
 6485:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6486:     my ($tmp)=keys(%current_permissions);
 6487:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6488:     return \%current_permissions;
 6489: }
 6490: 
 6491: #---------------------------------------------Get portfolio file access controls
 6492: 
 6493: sub get_access_controls {
 6494:     my ($current_permissions,$group,$file) = @_;
 6495:     my %access;
 6496:     my $real_file = $file;
 6497:     $file =~ s/\.meta$//;
 6498:     if (defined($file)) {
 6499:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6500:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6501:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6502:             }
 6503:         }
 6504:     } else {
 6505:         foreach my $key (keys(%{$current_permissions})) {
 6506:             if ($key =~ /\0accesscontrol$/) {
 6507:                 if (defined($group)) {
 6508:                     if ($key !~ m-^\Q$group\E/-) {
 6509:                         next;
 6510:                     }
 6511:                 }
 6512:                 my ($fullpath) = split(/\0/,$key);
 6513:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6514:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6515:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6516:                     }
 6517:                 }
 6518:             }
 6519:         }
 6520:     }
 6521:     return %access;
 6522: }
 6523: 
 6524: sub modify_access_controls {
 6525:     my ($file_name,$changes,$domain,$user)=@_;
 6526:     my ($outcome,$deloutcome);
 6527:     my %store_permissions;
 6528:     my %new_values;
 6529:     my %new_control;
 6530:     my %translation;
 6531:     my @deletions = ();
 6532:     my $now = time;
 6533:     if (exists($$changes{'activate'})) {
 6534:         if (ref($$changes{'activate'}) eq 'HASH') {
 6535:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6536:             my $numnew = scalar(@newitems);
 6537:             for (my $i=0; $i<$numnew; $i++) {
 6538:                 my $newkey = $newitems[$i];
 6539:                 my $newid = &Apache::loncommon::get_cgi_id();
 6540:                 if ($newkey =~ /^\d+:/) { 
 6541:                     $newkey =~ s/^(\d+)/$newid/;
 6542:                     $translation{$1} = $newid;
 6543:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6544:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6545:                     $translation{$1} = $newid;
 6546:                 }
 6547:                 $new_values{$file_name."\0".$newkey} = 
 6548:                                           $$changes{'activate'}{$newitems[$i]};
 6549:                 $new_control{$newkey} = $now;
 6550:             }
 6551:         }
 6552:     }
 6553:     my %todelete;
 6554:     my %changed_items;
 6555:     foreach my $action ('delete','update') {
 6556:         if (exists($$changes{$action})) {
 6557:             if (ref($$changes{$action}) eq 'HASH') {
 6558:                 foreach my $key (keys(%{$$changes{$action}})) {
 6559:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6560:                     if ($action eq 'delete') { 
 6561:                         $todelete{$itemnum} = 1;
 6562:                     } else {
 6563:                         $changed_items{$itemnum} = $key;
 6564:                     }
 6565:                 }
 6566:             }
 6567:         }
 6568:     }
 6569:     # get lock on access controls for file.
 6570:     my $lockhash = {
 6571:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6572:                                                        ':'.$env{'user.domain'},
 6573:                    }; 
 6574:     my $tries = 0;
 6575:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6576:    
 6577:     while (($gotlock ne 'ok') && $tries <3) {
 6578:         $tries ++;
 6579:         sleep 1;
 6580:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6581:     }
 6582:     if ($gotlock eq 'ok') {
 6583:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6584:         my ($tmp)=keys(%curr_permissions);
 6585:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6586:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6587:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6588:             if (ref($curr_controls) eq 'HASH') {
 6589:                 foreach my $control_item (keys(%{$curr_controls})) {
 6590:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6591:                     if (defined($todelete{$itemnum})) {
 6592:                         push(@deletions,$file_name."\0".$control_item);
 6593:                     } else {
 6594:                         if (defined($changed_items{$itemnum})) {
 6595:                             $new_control{$changed_items{$itemnum}} = $now;
 6596:                             push(@deletions,$file_name."\0".$control_item);
 6597:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6598:                         } else {
 6599:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6600:                         }
 6601:                     }
 6602:                 }
 6603:             }
 6604:         }
 6605:         my ($group);
 6606:         if (&is_course($domain,$user)) {
 6607:             ($group,my $file) = split(/\//,$file_name,2);
 6608:         }
 6609:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6610:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6611:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6612:         #  remove lock
 6613:         my @del_lock = ($file_name."\0".'locked_access_records');
 6614:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6615:         my $sqlresult =
 6616:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6617:                                     $group);
 6618:     } else {
 6619:         $outcome = "error: could not obtain lockfile\n";  
 6620:     }
 6621:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6622: }
 6623: 
 6624: sub make_public_indefinitely {
 6625:     my ($requrl) = @_;
 6626:     my $now = time;
 6627:     my $action = 'activate';
 6628:     my $aclnum = 0;
 6629:     if (&is_portfolio_url($requrl)) {
 6630:         my (undef,$udom,$unum,$file_name,$group) =
 6631:             &parse_portfolio_url($requrl);
 6632:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6633:         my %access_controls = &get_access_controls($current_perms,
 6634:                                                    $group,$file_name);
 6635:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6636:             my ($num,$scope,$end,$start) = 
 6637:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6638:             if ($scope eq 'public') {
 6639:                 if ($start <= $now && $end == 0) {
 6640:                     $action = 'none';
 6641:                 } else {
 6642:                     $action = 'update';
 6643:                     $aclnum = $num;
 6644:                 }
 6645:                 last;
 6646:             }
 6647:         }
 6648:         if ($action eq 'none') {
 6649:              return 'ok';
 6650:         } else {
 6651:             my %changes;
 6652:             my $newend = 0;
 6653:             my $newstart = $now;
 6654:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6655:             $changes{$action}{$newkey} = {
 6656:                 type => 'public',
 6657:                 time => {
 6658:                     start => $newstart,
 6659:                     end   => $newend,
 6660:                 },
 6661:             };
 6662:             my ($outcome,$deloutcome,$new_values,$translation) =
 6663:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6664:             return $outcome;
 6665:         }
 6666:     } else {
 6667:         return 'invalid';
 6668:     }
 6669: }
 6670: 
 6671: #------------------------------------------------------Get Marked as Read Only
 6672: 
 6673: sub get_marked_as_readonly {
 6674:     my ($domain,$user,$what,$group) = @_;
 6675:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6676:     my @readonly_files;
 6677:     my $cmp1=$what;
 6678:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6679:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6680:         if (defined($group)) {
 6681:             if ($file_name !~ m-^\Q$group\E/-) {
 6682:                 next;
 6683:             }
 6684:         }
 6685:         if (ref($value) eq "ARRAY"){
 6686:             foreach my $stored_what (@{$value}) {
 6687:                 my $cmp2=$stored_what;
 6688:                 if (ref($stored_what) eq 'ARRAY') {
 6689:                     $cmp2=join('',@{$stored_what});
 6690:                 }
 6691:                 if ($cmp1 eq $cmp2) {
 6692:                     push(@readonly_files, $file_name);
 6693:                     last;
 6694:                 } elsif (!defined($what)) {
 6695:                     push(@readonly_files, $file_name);
 6696:                     last;
 6697:                 }
 6698:             }
 6699:         }
 6700:     }
 6701:     return @readonly_files;
 6702: }
 6703: #-----------------------------------------------------------Get Marked as Read Only Hash
 6704: 
 6705: sub get_marked_as_readonly_hash {
 6706:     my ($current_permissions,$group,$what) = @_;
 6707:     my %readonly_files;
 6708:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6709:         if (defined($group)) {
 6710:             if ($file_name !~ m-^\Q$group\E/-) {
 6711:                 next;
 6712:             }
 6713:         }
 6714:         if (ref($value) eq "ARRAY"){
 6715:             foreach my $stored_what (@{$value}) {
 6716:                 if (ref($stored_what) eq 'ARRAY') {
 6717:                     foreach my $lock_descriptor(@{$stored_what}) {
 6718:                         if ($lock_descriptor eq 'graded') {
 6719:                             $readonly_files{$file_name} = 'graded';
 6720:                         } elsif ($lock_descriptor eq 'handback') {
 6721:                             $readonly_files{$file_name} = 'handback';
 6722:                         } else {
 6723:                             if (!exists($readonly_files{$file_name})) {
 6724:                                 $readonly_files{$file_name} = 'locked';
 6725:                             }
 6726:                         }
 6727:                     }
 6728:                 } 
 6729:             }
 6730:         } 
 6731:     }
 6732:     return %readonly_files;
 6733: }
 6734: # ------------------------------------------------------------ Unmark as Read Only
 6735: 
 6736: sub unmark_as_readonly {
 6737:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6738:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6739:     my ($domain,$user,$what,$file_name,$group) = @_;
 6740:     $file_name = &declutter_portfile($file_name);
 6741:     my $symb_crs = $what;
 6742:     if (ref($what)) { $symb_crs=join('',@$what); }
 6743:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6744:     my ($tmp)=keys(%current_permissions);
 6745:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6746:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6747:     foreach my $file (@readonly_files) {
 6748: 	my $clean_file = &declutter_portfile($file);
 6749: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6750: 	my $current_locks = $current_permissions{$file};
 6751:         my @new_locks;
 6752:         my @del_keys;
 6753:         if (ref($current_locks) eq "ARRAY"){
 6754:             foreach my $locker (@{$current_locks}) {
 6755:                 my $compare=$locker;
 6756:                 if (ref($locker) eq 'ARRAY') {
 6757:                     $compare=join('',@{$locker});
 6758:                     if ($compare ne $symb_crs) {
 6759:                         push(@new_locks, $locker);
 6760:                     }
 6761:                 }
 6762:             }
 6763:             if (scalar(@new_locks) > 0) {
 6764:                 $current_permissions{$file} = \@new_locks;
 6765:             } else {
 6766:                 push(@del_keys, $file);
 6767:                 &del('file_permissions',\@del_keys, $domain, $user);
 6768:                 delete($current_permissions{$file});
 6769:             }
 6770:         }
 6771:     }
 6772:     &put('file_permissions',\%current_permissions,$domain,$user);
 6773:     return;
 6774: }
 6775: 
 6776: # ------------------------------------------------------------ Directory lister
 6777: 
 6778: sub dirlist {
 6779:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6780:     $uri=~s/^\///;
 6781:     $uri=~s/\/$//;
 6782:     my ($udom, $uname);
 6783:     if ($getuserdir) {
 6784:         $udom = $userdomain;
 6785:         $uname = $username;
 6786:     } else {
 6787:         (undef,$udom,$uname)=split(/\//,$uri);
 6788:         if(defined($userdomain)) {
 6789:             $udom = $userdomain;
 6790:         }
 6791:         if(defined($username)) {
 6792:             $uname = $username;
 6793:         }
 6794:     }
 6795:     my ($dirRoot,$listing,@listing_results);
 6796: 
 6797:     $dirRoot = $perlvar{'lonDocRoot'};
 6798:     if (defined($getpropath)) {
 6799:         $dirRoot = &propath($udom,$uname);
 6800:         $dirRoot =~ s/\/$//;
 6801:     } elsif (defined($getuserdir)) {
 6802:         my $subdir=$uname.'__';
 6803:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6804:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6805:                    ."/$udom/$subdir/$uname";
 6806:     } elsif (defined($alternateRoot)) {
 6807:         $dirRoot = $alternateRoot;
 6808:     }
 6809: 
 6810:     if($udom) {
 6811:         if($uname) {
 6812:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6813:                               .$getuserdir.':'.&escape($dirRoot)
 6814:                               .':'.&escape($uname).':'.&escape($udom),
 6815:                               &homeserver($uname,$udom));
 6816:             if ($listing eq 'unknown_cmd') {
 6817:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6818:                                   &homeserver($uname,$udom));
 6819:             } else {
 6820:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6821:             }
 6822:             if ($listing eq 'unknown_cmd') {
 6823:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6824: 				  &homeserver($uname,$udom));
 6825:                 @listing_results = split(/:/,$listing);
 6826:             } else {
 6827:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6828:             }
 6829:             return @listing_results;
 6830:         } elsif(!$alternateRoot) {
 6831:             my %allusers;
 6832: 	    my %servers = &get_servers($udom,'library');
 6833:  	    foreach my $tryserver (keys(%servers)) {
 6834:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6835:                                   &escape($udom),$tryserver);
 6836:                 if ($listing eq 'unknown_cmd') {
 6837: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6838: 				      $udom, $tryserver);
 6839:                 } else {
 6840:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6841:                 }
 6842: 		if ($listing eq 'unknown_cmd') {
 6843: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6844: 				      $udom, $tryserver);
 6845: 		    @listing_results = split(/:/,$listing);
 6846: 		} else {
 6847: 		    @listing_results =
 6848: 			map { &unescape($_); } split(/:/,$listing);
 6849: 		}
 6850: 		if ($listing_results[0] ne 'no_such_dir' && 
 6851: 		    $listing_results[0] ne 'empty'       &&
 6852: 		    $listing_results[0] ne 'con_lost') {
 6853: 		    foreach my $line (@listing_results) {
 6854: 			my ($entry) = split(/&/,$line,2);
 6855: 			$allusers{$entry} = 1;
 6856: 		    }
 6857: 		}
 6858:             }
 6859:             my $alluserstr='';
 6860:             foreach my $user (sort(keys(%allusers))) {
 6861:                 $alluserstr.=$user.'&user:';
 6862:             }
 6863:             $alluserstr=~s/:$//;
 6864:             return split(/:/,$alluserstr);
 6865:         } else {
 6866:             return ('missing user name');
 6867:         }
 6868:     } elsif(!defined($getpropath)) {
 6869:         my @all_domains = sort(&all_domains());
 6870:         foreach my $domain (@all_domains) {
 6871:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6872:         }
 6873:         return @all_domains;
 6874:     } else {
 6875:         return ('missing domain');
 6876:     }
 6877: }
 6878: 
 6879: # --------------------------------------------- GetFileTimestamp
 6880: # This function utilizes dirlist and returns the date stamp for
 6881: # when it was last modified.  It will also return an error of -1
 6882: # if an error occurs
 6883: 
 6884: sub GetFileTimestamp {
 6885:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6886:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6887:     $studentName   = &LONCAPA::clean_username($studentName);
 6888:     my ($fileStat) = 
 6889:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6890:                                  undef,$getuserdir);
 6891:     my @stats = split('&', $fileStat);
 6892:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6893:         # @stats contains first the filename, then the stat output
 6894:         return $stats[10]; # so this is 10 instead of 9.
 6895:     } else {
 6896:         return -1;
 6897:     }
 6898: }
 6899: 
 6900: sub stat_file {
 6901:     my ($uri) = @_;
 6902:     $uri = &clutter_with_no_wrapper($uri);
 6903: 
 6904:     my ($udom,$uname,$file);
 6905:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6906: 	($udom,$uname,$file) =
 6907: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6908: 	$file = 'userfiles/'.$file;
 6909:     }
 6910:     if ($uri =~ m-^/res/-) {
 6911: 	($udom,$uname) = 
 6912: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6913: 	$file = $uri;
 6914:     }
 6915: 
 6916:     if (!$udom || !$uname || !$file) {
 6917: 	# unable to handle the uri
 6918: 	return ();
 6919:     }
 6920:     my $getpropath;
 6921:     if ($file =~ /^userfiles\//) {
 6922:         $getpropath = 1;
 6923:     }
 6924:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6925:     my @stats = split('&', $result);
 6926:     
 6927:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6928: 	shift(@stats); #filename is first
 6929: 	return @stats;
 6930:     }
 6931:     return ();
 6932: }
 6933: 
 6934: # -------------------------------------------------------- Value of a Condition
 6935: 
 6936: # gets the value of a specific preevaluated condition
 6937: #    stored in the string  $env{user.state.<cid>}
 6938: # or looks up a condition reference in the bighash and if if hasn't
 6939: # already been evaluated recurses into docondval to get the value of
 6940: # the condition, then memoizing it to 
 6941: #   $env{user.state.<cid>.<condition>}
 6942: sub directcondval {
 6943:     my $number=shift;
 6944:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6945: 	&Apache::lonuserstate::evalstate();
 6946:     }
 6947:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6948: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6949:     } elsif ($number =~ /^_/) {
 6950: 	my $sub_condition;
 6951: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6952: 		&GDBM_READER(),0640)) {
 6953: 	    $sub_condition=$bighash{'conditions'.$number};
 6954: 	    untie(%bighash);
 6955: 	}
 6956: 	my $value = &docondval($sub_condition);
 6957: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6958: 	return $value;
 6959:     }
 6960:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6961:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6962:     } else {
 6963:        return 2;
 6964:     }
 6965: }
 6966: 
 6967: # get the collection of conditions for this resource
 6968: sub condval {
 6969:     my $condidx=shift;
 6970:     my $allpathcond='';
 6971:     foreach my $cond (split(/\|/,$condidx)) {
 6972: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6973: 	    $allpathcond.=
 6974: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6975: 	}
 6976:     }
 6977:     $allpathcond=~s/\|$//;
 6978:     return &docondval($allpathcond);
 6979: }
 6980: 
 6981: #evaluates an expression of conditions
 6982: sub docondval {
 6983:     my ($allpathcond) = @_;
 6984:     my $result=0;
 6985:     if ($env{'request.course.id'}
 6986: 	&& defined($allpathcond)) {
 6987: 	my $operand='|';
 6988: 	my @stack;
 6989: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6990: 	    if ($chunk eq '(') {
 6991: 		push @stack,($operand,$result);
 6992: 	    } elsif ($chunk eq ')') {
 6993: 		my $before=pop @stack;
 6994: 		if (pop @stack eq '&') {
 6995: 		    $result=$result>$before?$before:$result;
 6996: 		} else {
 6997: 		    $result=$result>$before?$result:$before;
 6998: 		}
 6999: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7000: 		$operand=$chunk;
 7001: 	    } else {
 7002: 		my $new=directcondval($chunk);
 7003: 		if ($operand eq '&') {
 7004: 		    $result=$result>$new?$new:$result;
 7005: 		} else {
 7006: 		    $result=$result>$new?$result:$new;
 7007: 		}
 7008: 	    }
 7009: 	}
 7010:     }
 7011:     return $result;
 7012: }
 7013: 
 7014: # ---------------------------------------------------- Devalidate courseresdata
 7015: 
 7016: sub devalidatecourseresdata {
 7017:     my ($coursenum,$coursedomain)=@_;
 7018:     my $hashid=$coursenum.':'.$coursedomain;
 7019:     &devalidate_cache_new('courseres',$hashid);
 7020: }
 7021: 
 7022: 
 7023: # --------------------------------------------------- Course Resourcedata Query
 7024: #
 7025: #  Parameters:
 7026: #      $coursenum    - Number of the course.
 7027: #      $coursedomain - Domain at which the course was created.
 7028: #  Returns:
 7029: #     A hash of the course parameters along (I think) with timestamps
 7030: #     and version info.
 7031: 
 7032: sub get_courseresdata {
 7033:     my ($coursenum,$coursedomain)=@_;
 7034:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7035:     my $hashid=$coursenum.':'.$coursedomain;
 7036:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7037:     my %dumpreply;
 7038:     unless (defined($cached)) {
 7039: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7040: 	$result=\%dumpreply;
 7041: 	my ($tmp) = keys(%dumpreply);
 7042: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7043: 	    &do_cache_new('courseres',$hashid,$result,600);
 7044: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7045: 	    return $tmp;
 7046: 	} elsif ($tmp =~ /^(error)/) {
 7047: 	    $result=undef;
 7048: 	    &do_cache_new('courseres',$hashid,$result,600);
 7049: 	}
 7050:     }
 7051:     return $result;
 7052: }
 7053: 
 7054: sub devalidateuserresdata {
 7055:     my ($uname,$udom)=@_;
 7056:     my $hashid="$udom:$uname";
 7057:     &devalidate_cache_new('userres',$hashid);
 7058: }
 7059: 
 7060: sub get_userresdata {
 7061:     my ($uname,$udom)=@_;
 7062:     #most student don\'t have any data set, check if there is some data
 7063:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7064: 
 7065:     my $hashid="$udom:$uname";
 7066:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7067:     if (!defined($cached)) {
 7068: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7069: 	$result=\%resourcedata;
 7070: 	&do_cache_new('userres',$hashid,$result,600);
 7071:     }
 7072:     my ($tmp)=keys(%$result);
 7073:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7074: 	return $result;
 7075:     }
 7076:     #error 2 occurs when the .db doesn't exist
 7077:     if ($tmp!~/error: 2 /) {
 7078: 	&logthis("<font color=\"blue\">WARNING:".
 7079: 		 " Trying to get resource data for ".
 7080: 		 $uname." at ".$udom.": ".
 7081: 		 $tmp."</font>");
 7082:     } elsif ($tmp=~/error: 2 /) {
 7083: 	#&EXT_cache_set($udom,$uname);
 7084: 	&do_cache_new('userres',$hashid,undef,600);
 7085: 	undef($tmp); # not really an error so don't send it back
 7086:     }
 7087:     return $tmp;
 7088: }
 7089: #----------------------------------------------- resdata - return resource data
 7090: #  Purpose:
 7091: #    Return resource data for either users or for a course.
 7092: #  Parameters:
 7093: #     $name      - Course/user name.
 7094: #     $domain    - Name of the domain the user/course is registered on.
 7095: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7096: #     @which     - Array of names of resources desired.
 7097: #  Returns:
 7098: #     The value of the first reasource in @which that is found in the
 7099: #     resource hash.
 7100: #  Exceptional Conditions:
 7101: #     If the $type passed in is not valid (not the string 'course' or 
 7102: #     'user', an undefined  reference is returned.
 7103: #     If none of the resources are found, an undef is returned
 7104: sub resdata {
 7105:     my ($name,$domain,$type,@which)=@_;
 7106:     my $result;
 7107:     if ($type eq 'course') {
 7108: 	$result=&get_courseresdata($name,$domain);
 7109:     } elsif ($type eq 'user') {
 7110: 	$result=&get_userresdata($name,$domain);
 7111:     }
 7112:     if (!ref($result)) { return $result; }    
 7113:     foreach my $item (@which) {
 7114: 	if (defined($result->{$item->[0]})) {
 7115: 	    return [$result->{$item->[0]},$item->[1]];
 7116: 	}
 7117:     }
 7118:     return undef;
 7119: }
 7120: 
 7121: #
 7122: # EXT resource caching routines
 7123: #
 7124: 
 7125: sub clear_EXT_cache_status {
 7126:     &delenv('cache.EXT.');
 7127: }
 7128: 
 7129: sub EXT_cache_status {
 7130:     my ($target_domain,$target_user) = @_;
 7131:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7132:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7133:         # We know already the user has no data
 7134:         return 1;
 7135:     } else {
 7136:         return 0;
 7137:     }
 7138: }
 7139: 
 7140: sub EXT_cache_set {
 7141:     my ($target_domain,$target_user) = @_;
 7142:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7143:     #&appenv({$cachename => time});
 7144: }
 7145: 
 7146: # --------------------------------------------------------- Value of a Variable
 7147: sub EXT {
 7148: 
 7149:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7150:     unless ($varname) { return ''; }
 7151:     #get real user name/domain, courseid and symb
 7152:     my $courseid;
 7153:     my $publicuser;
 7154:     if ($symbparm) {
 7155: 	$symbparm=&get_symb_from_alias($symbparm);
 7156:     }
 7157:     if (!($uname && $udom)) {
 7158:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7159:       if (!$symbparm) {	$symbparm=$cursymb; }
 7160:     } else {
 7161: 	$courseid=$env{'request.course.id'};
 7162:     }
 7163:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7164:     my $rest;
 7165:     if (defined($therest[0])) {
 7166:        $rest=join('.',@therest);
 7167:     } else {
 7168:        $rest='';
 7169:     }
 7170: 
 7171:     my $qualifierrest=$qualifier;
 7172:     if ($rest) { $qualifierrest.='.'.$rest; }
 7173:     my $spacequalifierrest=$space;
 7174:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7175:     if ($realm eq 'user') {
 7176: # --------------------------------------------------------------- user.resource
 7177: 	if ($space eq 'resource') {
 7178: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7179: 		  || defined($Apache::lonhomework::parsing_a_task))
 7180: 		 &&
 7181: 		 ($symbparm eq &symbread()) ) {	
 7182: 		# if we are in the middle of processing the resource the
 7183: 		# get the value we are planning on committing
 7184:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7185:                     return $Apache::lonhomework::results{$qualifierrest};
 7186:                 } else {
 7187:                     return $Apache::lonhomework::history{$qualifierrest};
 7188:                 }
 7189: 	    } else {
 7190: 		my %restored;
 7191: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7192: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7193: 		} else {
 7194: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7195: 		}
 7196: 		return $restored{$qualifierrest};
 7197: 	    }
 7198: # ----------------------------------------------------------------- user.access
 7199:         } elsif ($space eq 'access') {
 7200: 	    # FIXME - not supporting calls for a specific user
 7201:             return &allowed($qualifier,$rest);
 7202: # ------------------------------------------ user.preferences, user.environment
 7203:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7204: 	    if (($uname eq $env{'user.name'}) &&
 7205: 		($udom eq $env{'user.domain'})) {
 7206: 		return $env{join('.',('environment',$qualifierrest))};
 7207: 	    } else {
 7208: 		my %returnhash;
 7209: 		if (!$publicuser) {
 7210: 		    %returnhash=&userenvironment($udom,$uname,
 7211: 						 $qualifierrest);
 7212: 		}
 7213: 		return $returnhash{$qualifierrest};
 7214: 	    }
 7215: # ----------------------------------------------------------------- user.course
 7216:         } elsif ($space eq 'course') {
 7217: 	    # FIXME - not supporting calls for a specific user
 7218:             return $env{join('.',('request.course',$qualifier))};
 7219: # ------------------------------------------------------------------- user.role
 7220:         } elsif ($space eq 'role') {
 7221: 	    # FIXME - not supporting calls for a specific user
 7222:             my ($role,$where)=split(/\./,$env{'request.role'});
 7223:             if ($qualifier eq 'value') {
 7224: 		return $role;
 7225:             } elsif ($qualifier eq 'extent') {
 7226:                 return $where;
 7227:             }
 7228: # ----------------------------------------------------------------- user.domain
 7229:         } elsif ($space eq 'domain') {
 7230:             return $udom;
 7231: # ------------------------------------------------------------------- user.name
 7232:         } elsif ($space eq 'name') {
 7233:             return $uname;
 7234: # ---------------------------------------------------- Any other user namespace
 7235:         } else {
 7236: 	    my %reply;
 7237: 	    if (!$publicuser) {
 7238: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7239: 	    }
 7240: 	    return $reply{$qualifierrest};
 7241:         }
 7242:     } elsif ($realm eq 'query') {
 7243: # ---------------------------------------------- pull stuff out of query string
 7244:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7245: 						[$spacequalifierrest]);
 7246: 	return $env{'form.'.$spacequalifierrest}; 
 7247:    } elsif ($realm eq 'request') {
 7248: # ------------------------------------------------------------- request.browser
 7249:         if ($space eq 'browser') {
 7250: 	    if ($qualifier eq 'textremote') {
 7251: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7252: 		    return 1;
 7253: 		} else {
 7254: 		    return 0;
 7255: 		}
 7256: 	    } else {
 7257: 		return $env{'browser.'.$qualifier};
 7258: 	    }
 7259: # ------------------------------------------------------------ request.filename
 7260:         } else {
 7261:             return $env{'request.'.$spacequalifierrest};
 7262:         }
 7263:     } elsif ($realm eq 'course') {
 7264: # ---------------------------------------------------------- course.description
 7265:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7266:     } elsif ($realm eq 'resource') {
 7267: 
 7268: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7269: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7270: 	}
 7271: 
 7272: 	if ($space eq 'title') {
 7273: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7274: 	    return &gettitle($symbparm);
 7275: 	}
 7276: 	
 7277: 	if ($space eq 'map') {
 7278: 	    my ($map) = &decode_symb($symbparm);
 7279: 	    return &symbread($map);
 7280: 	}
 7281: 	if ($space eq 'filename') {
 7282: 	    if ($symbparm) {
 7283: 		return &clutter((&decode_symb($symbparm))[2]);
 7284: 	    }
 7285: 	    return &hreflocation('',$env{'request.filename'});
 7286: 	}
 7287: 
 7288: 	my ($section, $group, @groups);
 7289: 	my ($courselevelm,$courselevel);
 7290: 	if ($symbparm && defined($courseid) && 
 7291: 	    $courseid eq $env{'request.course.id'}) {
 7292: 
 7293: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7294: 
 7295: # ----------------------------------------------------- Cascading lookup scheme
 7296: 	    my $symbp=$symbparm;
 7297: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7298: 
 7299: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7300: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7301: 
 7302: 	    if (($env{'user.name'} eq $uname) &&
 7303: 		($env{'user.domain'} eq $udom)) {
 7304: 		$section=$env{'request.course.sec'};
 7305:                 @groups = split(/:/,$env{'request.course.groups'});  
 7306:                 @groups=&sort_course_groups($courseid,@groups); 
 7307: 	    } else {
 7308: 		if (! defined($usection)) {
 7309: 		    $section=&getsection($udom,$uname,$courseid);
 7310: 		} else {
 7311: 		    $section = $usection;
 7312: 		}
 7313:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7314: 	    }
 7315: 
 7316: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7317: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7318: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7319: 
 7320: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7321: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7322: 	    $courselevelm=$courseid.'.'.$mapparm;
 7323: 
 7324: # ----------------------------------------------------------- first, check user
 7325: 
 7326: 	    my $userreply=&resdata($uname,$udom,'user',
 7327: 				       ([$courselevelr,'resource'],
 7328: 					[$courselevelm,'map'     ],
 7329: 					[$courselevel, 'course'  ]));
 7330: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7331: 
 7332: # ------------------------------------------------ second, check some of course
 7333:             my $coursereply;
 7334:             if (@groups > 0) {
 7335:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7336:                                        $mapparm,$spacequalifierrest);
 7337:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7338:             }
 7339: 
 7340: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7341: 				  $env{'course.'.$courseid.'.domain'},
 7342: 				  'course',
 7343: 				  ([$seclevelr,   'resource'],
 7344: 				   [$seclevelm,   'map'     ],
 7345: 				   [$seclevel,    'course'  ],
 7346: 				   [$courselevelr,'resource']));
 7347: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7348: 
 7349: # ------------------------------------------------------ third, check map parms
 7350: 	    my %parmhash=();
 7351: 	    my $thisparm='';
 7352: 	    if (tie(%parmhash,'GDBM_File',
 7353: 		    $env{'request.course.fn'}.'_parms.db',
 7354: 		    &GDBM_READER(),0640)) {
 7355: 		$thisparm=$parmhash{$symbparm};
 7356: 		untie(%parmhash);
 7357: 	    }
 7358: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7359: 	}
 7360: # ------------------------------------------ fourth, look in resource metadata
 7361: 
 7362: 	$spacequalifierrest=~s/\./\_/;
 7363: 	my $filename;
 7364: 	if (!$symbparm) { $symbparm=&symbread(); }
 7365: 	if ($symbparm) {
 7366: 	    $filename=(&decode_symb($symbparm))[2];
 7367: 	} else {
 7368: 	    $filename=$env{'request.filename'};
 7369: 	}
 7370: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7371: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7372: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7373: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7374: 
 7375: # ---------------------------------------------- fourth, look in rest of course
 7376: 	if ($symbparm && defined($courseid) && 
 7377: 	    $courseid eq $env{'request.course.id'}) {
 7378: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7379: 				     $env{'course.'.$courseid.'.domain'},
 7380: 				     'course',
 7381: 				     ([$courselevelm,'map'   ],
 7382: 				      [$courselevel, 'course']));
 7383: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7384: 	}
 7385: # ------------------------------------------------------------------ Cascade up
 7386: 	unless ($space eq '0') {
 7387: 	    my @parts=split(/_/,$space);
 7388: 	    my $id=pop(@parts);
 7389: 	    my $part=join('_',@parts);
 7390: 	    if ($part eq '') { $part='0'; }
 7391: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7392: 				 $symbparm,$udom,$uname,$section,1);
 7393: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7394: 	}
 7395: 	if ($recurse) { return undef; }
 7396: 	my $pack_def=&packages_tab_default($filename,$varname);
 7397: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7398: # ---------------------------------------------------- Any other user namespace
 7399:     } elsif ($realm eq 'environment') {
 7400: # ----------------------------------------------------------------- environment
 7401: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7402: 	    return $env{'environment.'.$spacequalifierrest};
 7403: 	} else {
 7404: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7405: 		return '';
 7406: 	    }
 7407: 	    my %returnhash=&userenvironment($udom,$uname,
 7408: 					    $spacequalifierrest);
 7409: 	    return $returnhash{$spacequalifierrest};
 7410: 	}
 7411:     } elsif ($realm eq 'system') {
 7412: # ----------------------------------------------------------------- system.time
 7413: 	if ($space eq 'time') {
 7414: 	    return time;
 7415:         }
 7416:     } elsif ($realm eq 'server') {
 7417: # ----------------------------------------------------------------- system.time
 7418: 	if ($space eq 'name') {
 7419: 	    return $ENV{'SERVER_NAME'};
 7420:         }
 7421:     }
 7422:     return '';
 7423: }
 7424: 
 7425: sub get_reply {
 7426:     my ($reply_value) = @_;
 7427:     if (ref($reply_value) eq 'ARRAY') {
 7428:         if (wantarray) {
 7429: 	    return @$reply_value;
 7430:         }
 7431:         return $reply_value->[0];
 7432:     } else {
 7433:         return $reply_value;
 7434:     }
 7435: }
 7436: 
 7437: sub check_group_parms {
 7438:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7439:     my @groupitems = ();
 7440:     my $resultitem;
 7441:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7442:     foreach my $group (@{$groups}) {
 7443:         foreach my $level (@levels) {
 7444:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7445:              push(@groupitems,[$item,$level->[1]]);
 7446:         }
 7447:     }
 7448:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7449:                             $env{'course.'.$courseid.'.domain'},
 7450:                                      'course',@groupitems);
 7451:     return $coursereply;
 7452: }
 7453: 
 7454: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7455:     my ($courseid,@groups) = @_;
 7456:     @groups = sort(@groups);
 7457:     return @groups;
 7458: }
 7459: 
 7460: sub packages_tab_default {
 7461:     my ($uri,$varname)=@_;
 7462:     my (undef,$part,$name)=split(/\./,$varname);
 7463: 
 7464:     my (@extension,@specifics,$do_default);
 7465:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7466: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7467: 	if ($pack_type eq 'default') {
 7468: 	    $do_default=1;
 7469: 	} elsif ($pack_type eq 'extension') {
 7470: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7471: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7472: 	    # only look at packages defaults for packages that this id is
 7473: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7474: 	}
 7475:     }
 7476:     # first look for a package that matches the requested part id
 7477:     foreach my $package (@specifics) {
 7478: 	my (undef,$pack_type,$pack_part)=@{$package};
 7479: 	next if ($pack_part ne $part);
 7480: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7481: 	    return $packagetab{"$pack_type&$name&default"};
 7482: 	}
 7483:     }
 7484:     # look for any possible matching non extension_ package
 7485:     foreach my $package (@specifics) {
 7486: 	my (undef,$pack_type,$pack_part)=@{$package};
 7487: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7488: 	    return $packagetab{"$pack_type&$name&default"};
 7489: 	}
 7490: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7491: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7492: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7493: 	}
 7494:     }
 7495:     # look for any posible extension_ match
 7496:     foreach my $package (@extension) {
 7497: 	my ($package,$pack_type)=@{$package};
 7498: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7499: 	    return $packagetab{"$pack_type&$name&default"};
 7500: 	}
 7501: 	if (defined($packagetab{$package."&$name&default"})) {
 7502: 	    return $packagetab{$package."&$name&default"};
 7503: 	}
 7504:     }
 7505:     # look for a global default setting
 7506:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7507: 	return $packagetab{"default&$name&default"};
 7508:     }
 7509:     return undef;
 7510: }
 7511: 
 7512: sub add_prefix_and_part {
 7513:     my ($prefix,$part)=@_;
 7514:     my $keyroot;
 7515:     if (defined($prefix) && $prefix !~ /^__/) {
 7516: 	# prefix that has a part already
 7517: 	$keyroot=$prefix;
 7518:     } elsif (defined($prefix)) {
 7519: 	# prefix that is missing a part
 7520: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7521:     } else {
 7522: 	# no prefix at all
 7523: 	if (defined($part)) { $keyroot='_'.$part; }
 7524:     }
 7525:     return $keyroot;
 7526: }
 7527: 
 7528: # ---------------------------------------------------------------- Get metadata
 7529: 
 7530: my %metaentry;
 7531: sub metadata {
 7532:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7533:     $uri=&declutter($uri);
 7534:     # if it is a non metadata possible uri return quickly
 7535:     if (($uri eq '') || 
 7536: 	(($uri =~ m|^/*adm/|) && 
 7537: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7538:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7539: 	return undef;
 7540:     }
 7541:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7542: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7543: 	return undef;
 7544:     }
 7545:     my $filename=$uri;
 7546:     $uri=~s/\.meta$//;
 7547: #
 7548: # Is the metadata already cached?
 7549: # Look at timestamp of caching
 7550: # Everything is cached by the main uri, libraries are never directly cached
 7551: #
 7552:     if (!defined($liburi)) {
 7553: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7554: 	if (defined($cached)) { return $result->{':'.$what}; }
 7555:     }
 7556:     {
 7557: #
 7558: # Is this a recursive call for a library?
 7559: #
 7560: #	if (! exists($metacache{$uri})) {
 7561: #	    $metacache{$uri}={};
 7562: #	}
 7563: 	my $cachetime = 60*60;
 7564:         if ($liburi) {
 7565: 	    $liburi=&declutter($liburi);
 7566:             $filename=$liburi;
 7567:         } else {
 7568: 	    &devalidate_cache_new('meta',$uri);
 7569: 	    undef(%metaentry);
 7570: 	}
 7571:         my %metathesekeys=();
 7572:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7573: 	my $metastring;
 7574: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7575: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7576: 	    $metastring = 
 7577: 		&Apache::lonnet::ssi_body($which,
 7578: 					  ('grade_target' => 'meta'));
 7579: 	    $cachetime = 1; # only want this cached in the child not long term
 7580: 	} elsif ($uri !~ m -^(editupload)/-) {
 7581: 	    my $file=&filelocation('',&clutter($filename));
 7582: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7583: 	    $metastring=&getfile($file);
 7584: 	}
 7585:         my $parser=HTML::LCParser->new(\$metastring);
 7586:         my $token;
 7587:         undef %metathesekeys;
 7588:         while ($token=$parser->get_token) {
 7589: 	    if ($token->[0] eq 'S') {
 7590: 		if (defined($token->[2]->{'package'})) {
 7591: #
 7592: # This is a package - get package info
 7593: #
 7594: 		    my $package=$token->[2]->{'package'};
 7595: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7596: 		    if (defined($token->[2]->{'id'})) { 
 7597: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7598: 		    }
 7599: 		    if ($metaentry{':packages'}) {
 7600: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7601: 		    } else {
 7602: 			$metaentry{':packages'}=$package.$keyroot;
 7603: 		    }
 7604: 		    foreach my $pack_entry (keys(%packagetab)) {
 7605: 			my $part=$keyroot;
 7606: 			$part=~s/^\_//;
 7607: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7608: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7609: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7610: 			    # ignore package.tab specified default values
 7611:                             # here &package_tab_default() will fetch those
 7612: 			    if ($subp eq 'default') { next; }
 7613: 			    my $value=$packagetab{$pack_entry};
 7614: 			    my $unikey;
 7615: 			    if ($pack =~ /_0$/) {
 7616: 				$unikey='parameter_0_'.$name;
 7617: 				$part=0;
 7618: 			    } else {
 7619: 				$unikey='parameter'.$keyroot.'_'.$name;
 7620: 			    }
 7621: 			    if ($subp eq 'display') {
 7622: 				$value.=' [Part: '.$part.']';
 7623: 			    }
 7624: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7625: 			    $metathesekeys{$unikey}=1;
 7626: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7627: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7628: 			    }
 7629: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7630: 				$metaentry{':'.$unikey}=
 7631: 				    $metaentry{':'.$unikey.'.default'};
 7632: 			    }
 7633: 			}
 7634: 		    }
 7635: 		} else {
 7636: #
 7637: # This is not a package - some other kind of start tag
 7638: #
 7639: 		    my $entry=$token->[1];
 7640: 		    my $unikey;
 7641: 		    if ($entry eq 'import') {
 7642: 			$unikey='';
 7643: 		    } else {
 7644: 			$unikey=$entry;
 7645: 		    }
 7646: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7647: 
 7648: 		    if (defined($token->[2]->{'id'})) { 
 7649: 			$unikey.='_'.$token->[2]->{'id'}; 
 7650: 		    }
 7651: 
 7652: 		    if ($entry eq 'import') {
 7653: #
 7654: # Importing a library here
 7655: #
 7656: 			if ($depthcount<20) {
 7657: 			    my $location=$parser->get_text('/import');
 7658: 			    my $dir=$filename;
 7659: 			    $dir=~s|[^/]*$||;
 7660: 			    $location=&filelocation($dir,$location);
 7661: 			    my $metadata = 
 7662: 				&metadata($uri,'keys', $location,$unikey,
 7663: 					  $depthcount+1);
 7664: 			    foreach my $meta (split(',',$metadata)) {
 7665: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7666: 				$metathesekeys{$meta}=1;
 7667: 			    }
 7668: 			}
 7669: 		    } else { 
 7670: 			
 7671: 			if (defined($token->[2]->{'name'})) { 
 7672: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7673: 			}
 7674: 			$metathesekeys{$unikey}=1;
 7675: 			foreach my $param (@{$token->[3]}) {
 7676: 			    $metaentry{':'.$unikey.'.'.$param} =
 7677: 				$token->[2]->{$param};
 7678: 			}
 7679: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7680: 			my $default=$metaentry{':'.$unikey.'.default'};
 7681: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7682: 		 # only ws inside the tag, and not in default, so use default
 7683: 		 # as value
 7684: 			    $metaentry{':'.$unikey}=$default;
 7685: 			} elsif ( $internaltext =~ /\S/ ) {
 7686: 		  # something interesting inside the tag
 7687: 			    $metaentry{':'.$unikey}=$internaltext;
 7688: 			} else {
 7689: 		  # no interesting values, don't set a default
 7690: 			}
 7691: # end of not-a-package not-a-library import
 7692: 		    }
 7693: # end of not-a-package start tag
 7694: 		}
 7695: # the next is the end of "start tag"
 7696: 	    }
 7697: 	}
 7698: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7699: 	$extension = lc($extension);
 7700: 	if ($extension eq 'htm') { $extension='html'; }
 7701: 
 7702: 	foreach my $key (keys(%packagetab)) {
 7703: 	    #no specific packages #how's our extension
 7704: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7705: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7706: 					 \%metathesekeys);
 7707: 	}
 7708: 
 7709: 	if (!exists($metaentry{':packages'})
 7710: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7711: 	    foreach my $key (keys(%packagetab)) {
 7712: 		#no specific packages well let's get default then
 7713: 		if ($key!~/^default&/) { next; }
 7714: 		&metadata_create_package_def($uri,$key,'default',
 7715: 					     \%metathesekeys);
 7716: 	    }
 7717: 	}
 7718: # are there custom rights to evaluate
 7719: 	if ($metaentry{':copyright'} eq 'custom') {
 7720: 
 7721:     #
 7722:     # Importing a rights file here
 7723:     #
 7724: 	    unless ($depthcount) {
 7725: 		my $location=$metaentry{':customdistributionfile'};
 7726: 		my $dir=$filename;
 7727: 		$dir=~s|[^/]*$||;
 7728: 		$location=&filelocation($dir,$location);
 7729: 		my $rights_metadata =
 7730: 		    &metadata($uri,'keys',$location,'_rights',
 7731: 			      $depthcount+1);
 7732: 		foreach my $rights (split(',',$rights_metadata)) {
 7733: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7734: 		    $metathesekeys{$rights}=1;
 7735: 		}
 7736: 	    }
 7737: 	}
 7738: 	# uniqifiy package listing
 7739: 	my %seen;
 7740: 	my @uniq_packages =
 7741: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7742: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7743: 
 7744: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7745: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7746: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7747: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7748: # this is the end of "was not already recently cached
 7749:     }
 7750:     return $metaentry{':'.$what};
 7751: }
 7752: 
 7753: sub metadata_create_package_def {
 7754:     my ($uri,$key,$package,$metathesekeys)=@_;
 7755:     my ($pack,$name,$subp)=split(/\&/,$key);
 7756:     if ($subp eq 'default') { next; }
 7757:     
 7758:     if (defined($metaentry{':packages'})) {
 7759: 	$metaentry{':packages'}.=','.$package;
 7760:     } else {
 7761: 	$metaentry{':packages'}=$package;
 7762:     }
 7763:     my $value=$packagetab{$key};
 7764:     my $unikey;
 7765:     $unikey='parameter_0_'.$name;
 7766:     $metaentry{':'.$unikey.'.part'}=0;
 7767:     $$metathesekeys{$unikey}=1;
 7768:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7769: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7770:     }
 7771:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7772: 	$metaentry{':'.$unikey}=
 7773: 	    $metaentry{':'.$unikey.'.default'};
 7774:     }
 7775: }
 7776: 
 7777: sub metadata_generate_part0 {
 7778:     my ($metadata,$metacache,$uri) = @_;
 7779:     my %allnames;
 7780:     foreach my $metakey (keys(%$metadata)) {
 7781: 	if ($metakey=~/^parameter\_(.*)/) {
 7782: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7783: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7784: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7785: 	    $allnames{$name}=$part;
 7786: 	  }
 7787: 	}
 7788:     }
 7789:     foreach my $name (keys(%allnames)) {
 7790:       $$metadata{"parameter_0_$name"}=1;
 7791:       my $key=":parameter_0_$name";
 7792:       $$metacache{"$key.part"}='0';
 7793:       $$metacache{"$key.name"}=$name;
 7794:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7795: 					   $allnames{$name}.'_'.$name.
 7796: 					   '.type'};
 7797:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7798: 			     '.display'};
 7799:       my $expr='[Part: '.$allnames{$name}.']';
 7800:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7801:       $$metacache{"$key.display"}=$olddis;
 7802:     }
 7803: }
 7804: 
 7805: # ------------------------------------------------------ Devalidate title cache
 7806: 
 7807: sub devalidate_title_cache {
 7808:     my ($url)=@_;
 7809:     if (!$env{'request.course.id'}) { return; }
 7810:     my $symb=&symbread($url);
 7811:     if (!$symb) { return; }
 7812:     my $key=$env{'request.course.id'}."\0".$symb;
 7813:     &devalidate_cache_new('title',$key);
 7814: }
 7815: 
 7816: # ------------------------------------------------- Get the title of a resource
 7817: 
 7818: sub gettitle {
 7819:     my $urlsymb=shift;
 7820:     my $symb=&symbread($urlsymb);
 7821:     if ($symb) {
 7822: 	my $key=$env{'request.course.id'}."\0".$symb;
 7823: 	my ($result,$cached)=&is_cached_new('title',$key);
 7824: 	if (defined($cached)) { 
 7825: 	    return $result;
 7826: 	}
 7827: 	my ($map,$resid,$url)=&decode_symb($symb);
 7828: 	my $title='';
 7829: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7830: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7831: 	} else {
 7832: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7833: 		    &GDBM_READER(),0640)) {
 7834: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7835: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7836: 		untie(%bighash);
 7837: 	    }
 7838: 	}
 7839: 	$title=~s/\&colon\;/\:/gs;
 7840: 	if ($title) {
 7841: 	    return &do_cache_new('title',$key,$title,600);
 7842: 	}
 7843: 	$urlsymb=$url;
 7844:     }
 7845:     my $title=&metadata($urlsymb,'title');
 7846:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7847:     return $title;
 7848: }
 7849: 
 7850: sub get_slot {
 7851:     my ($which,$cnum,$cdom)=@_;
 7852:     if (!$cnum || !$cdom) {
 7853: 	(undef,my $courseid)=&whichuser();
 7854: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7855: 	$cnum=$env{'course.'.$courseid.'.num'};
 7856:     }
 7857:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7858:     my %slotinfo;
 7859:     if (exists($remembered{$key})) {
 7860: 	$slotinfo{$which} = $remembered{$key};
 7861:     } else {
 7862: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7863: 	&Apache::lonhomework::showhash(%slotinfo);
 7864: 	my ($tmp)=keys(%slotinfo);
 7865: 	if ($tmp=~/^error:/) { return (); }
 7866: 	$remembered{$key} = $slotinfo{$which};
 7867:     }
 7868:     if (ref($slotinfo{$which}) eq 'HASH') {
 7869: 	return %{$slotinfo{$which}};
 7870:     }
 7871:     return $slotinfo{$which};
 7872: }
 7873: # ------------------------------------------------- Update symbolic store links
 7874: 
 7875: sub symblist {
 7876:     my ($mapname,%newhash)=@_;
 7877:     $mapname=&deversion(&declutter($mapname));
 7878:     my %hash;
 7879:     if (($env{'request.course.fn'}) && (%newhash)) {
 7880:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7881:                       &GDBM_WRCREAT(),0640)) {
 7882: 	    foreach my $url (keys(%newhash)) {
 7883: 		next if ($url eq 'last_known'
 7884: 			 && $env{'form.no_update_last_known'});
 7885: 		$hash{declutter($url)}=&encode_symb($mapname,
 7886: 						    $newhash{$url}->[1],
 7887: 						    $newhash{$url}->[0]);
 7888:             }
 7889:             if (untie(%hash)) {
 7890: 		return 'ok';
 7891:             }
 7892:         }
 7893:     }
 7894:     return 'error';
 7895: }
 7896: 
 7897: # --------------------------------------------------------------- Verify a symb
 7898: 
 7899: sub symbverify {
 7900:     my ($symb,$thisurl)=@_;
 7901:     my $thisfn=$thisurl;
 7902:     $thisfn=&declutter($thisfn);
 7903: # direct jump to resource in page or to a sequence - will construct own symbs
 7904:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7905: # check URL part
 7906:     my ($map,$resid,$url)=&decode_symb($symb);
 7907: 
 7908:     unless ($url eq $thisfn) { return 0; }
 7909: 
 7910:     $symb=&symbclean($symb);
 7911:     $thisurl=&deversion($thisurl);
 7912:     $thisfn=&deversion($thisfn);
 7913: 
 7914:     my %bighash;
 7915:     my $okay=0;
 7916: 
 7917:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7918:                             &GDBM_READER(),0640)) {
 7919:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7920:         unless ($ids) { 
 7921:            $ids=$bighash{'ids_/'.$thisurl};
 7922:         }
 7923:         if ($ids) {
 7924: # ------------------------------------------------------------------- Has ID(s)
 7925: 	    foreach my $id (split(/\,/,$ids)) {
 7926: 	       my ($mapid,$resid)=split(/\./,$id);
 7927:                if (
 7928:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7929:    eq $symb) { 
 7930: 		   if (($env{'request.role.adv'}) ||
 7931: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7932: 		       $okay=1; 
 7933: 		   }
 7934: 	       }
 7935: 	   }
 7936:         }
 7937: 	untie(%bighash);
 7938:     }
 7939:     return $okay;
 7940: }
 7941: 
 7942: # --------------------------------------------------------------- Clean-up symb
 7943: 
 7944: sub symbclean {
 7945:     my $symb=shift;
 7946:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7947: # remove version from map
 7948:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7949: 
 7950: # remove version from URL
 7951:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7952: 
 7953: # remove wrapper
 7954: 
 7955:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7956:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7957:     return $symb;
 7958: }
 7959: 
 7960: # ---------------------------------------------- Split symb to find map and url
 7961: 
 7962: sub encode_symb {
 7963:     my ($map,$resid,$url)=@_;
 7964:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7965: }
 7966: 
 7967: sub decode_symb {
 7968:     my $symb=shift;
 7969:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7970:     my ($map,$resid,$url)=split(/___/,$symb);
 7971:     return (&fixversion($map),$resid,&fixversion($url));
 7972: }
 7973: 
 7974: sub fixversion {
 7975:     my $fn=shift;
 7976:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7977:     my %bighash;
 7978:     my $uri=&clutter($fn);
 7979:     my $key=$env{'request.course.id'}.'_'.$uri;
 7980: # is this cached?
 7981:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7982:     if (defined($cached)) { return $result; }
 7983: # unfortunately not cached, or expired
 7984:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7985: 	    &GDBM_READER(),0640)) {
 7986:  	if ($bighash{'version_'.$uri}) {
 7987:  	    my $version=$bighash{'version_'.$uri};
 7988:  	    unless (($version eq 'mostrecent') || 
 7989: 		    ($version==&getversion($uri))) {
 7990:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7991:  	    }
 7992:  	}
 7993:  	untie %bighash;
 7994:     }
 7995:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7996: }
 7997: 
 7998: sub deversion {
 7999:     my $url=shift;
 8000:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8001:     return $url;
 8002: }
 8003: 
 8004: # ------------------------------------------------------ Return symb list entry
 8005: 
 8006: sub symbread {
 8007:     my ($thisfn,$donotrecurse)=@_;
 8008:     my $cache_str='request.symbread.cached.'.$thisfn;
 8009:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8010: # no filename provided? try from environment
 8011:     unless ($thisfn) {
 8012:         if ($env{'request.symb'}) {
 8013: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8014: 	}
 8015: 	$thisfn=$env{'request.filename'};
 8016:     }
 8017:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8018: # is that filename actually a symb? Verify, clean, and return
 8019:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8020: 	if (&symbverify($thisfn,$1)) {
 8021: 	    return $env{$cache_str}=&symbclean($thisfn);
 8022: 	}
 8023:     }
 8024:     $thisfn=declutter($thisfn);
 8025:     my %hash;
 8026:     my %bighash;
 8027:     my $syval='';
 8028:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8029:         my $targetfn = $thisfn;
 8030:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8031:             $targetfn = 'adm/wrapper/'.$thisfn;
 8032:         }
 8033: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8034: 	    $targetfn=$1;
 8035: 	}
 8036:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8037:                       &GDBM_READER(),0640)) {
 8038: 	    $syval=$hash{$targetfn};
 8039:             untie(%hash);
 8040:         }
 8041: # ---------------------------------------------------------- There was an entry
 8042:         if ($syval) {
 8043: 	    #unless ($syval=~/\_\d+$/) {
 8044: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8045: 		    #&appenv({'request.ambiguous' => $thisfn});
 8046: 		    #return $env{$cache_str}='';
 8047: 		#}    
 8048: 		#$syval.=$1;
 8049: 	    #}
 8050:         } else {
 8051: # ------------------------------------------------------- Was not in symb table
 8052:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8053:                             &GDBM_READER(),0640)) {
 8054: # ---------------------------------------------- Get ID(s) for current resource
 8055:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8056:               unless ($ids) { 
 8057:                  $ids=$bighash{'ids_/'.$thisfn};
 8058:               }
 8059:               unless ($ids) {
 8060: # alias?
 8061: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8062:               }
 8063:               if ($ids) {
 8064: # ------------------------------------------------------------------- Has ID(s)
 8065:                  my @possibilities=split(/\,/,$ids);
 8066:                  if ($#possibilities==0) {
 8067: # ----------------------------------------------- There is only one possibility
 8068: 		     my ($mapid,$resid)=split(/\./,$ids);
 8069: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8070: 						    $resid,$thisfn);
 8071:                  } elsif (!$donotrecurse) {
 8072: # ------------------------------------------ There is more than one possibility
 8073:                      my $realpossible=0;
 8074:                      foreach my $id (@possibilities) {
 8075: 			 my $file=$bighash{'src_'.$id};
 8076:                          if (&allowed('bre',$file)) {
 8077:          		    my ($mapid,$resid)=split(/\./,$id);
 8078:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8079: 				$realpossible++;
 8080:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8081: 						    $resid,$thisfn);
 8082:                             }
 8083: 			 }
 8084:                      }
 8085: 		     if ($realpossible!=1) { $syval=''; }
 8086:                  } else {
 8087:                      $syval='';
 8088:                  }
 8089: 	      }
 8090:               untie(%bighash)
 8091:            }
 8092:         }
 8093:         if ($syval) {
 8094: 	    return $env{$cache_str}=$syval;
 8095:         }
 8096:     }
 8097:     &appenv({'request.ambiguous' => $thisfn});
 8098:     return $env{$cache_str}='';
 8099: }
 8100: 
 8101: # ---------------------------------------------------------- Return random seed
 8102: 
 8103: sub numval {
 8104:     my $txt=shift;
 8105:     $txt=~tr/A-J/0-9/;
 8106:     $txt=~tr/a-j/0-9/;
 8107:     $txt=~tr/K-T/0-9/;
 8108:     $txt=~tr/k-t/0-9/;
 8109:     $txt=~tr/U-Z/0-5/;
 8110:     $txt=~tr/u-z/0-5/;
 8111:     $txt=~s/\D//g;
 8112:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8113:     return int($txt);
 8114: }
 8115: 
 8116: sub numval2 {
 8117:     my $txt=shift;
 8118:     $txt=~tr/A-J/0-9/;
 8119:     $txt=~tr/a-j/0-9/;
 8120:     $txt=~tr/K-T/0-9/;
 8121:     $txt=~tr/k-t/0-9/;
 8122:     $txt=~tr/U-Z/0-5/;
 8123:     $txt=~tr/u-z/0-5/;
 8124:     $txt=~s/\D//g;
 8125:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8126:     my $total;
 8127:     foreach my $val (@txts) { $total+=$val; }
 8128:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8129:     return int($total);
 8130: }
 8131: 
 8132: sub numval3 {
 8133:     use integer;
 8134:     my $txt=shift;
 8135:     $txt=~tr/A-J/0-9/;
 8136:     $txt=~tr/a-j/0-9/;
 8137:     $txt=~tr/K-T/0-9/;
 8138:     $txt=~tr/k-t/0-9/;
 8139:     $txt=~tr/U-Z/0-5/;
 8140:     $txt=~tr/u-z/0-5/;
 8141:     $txt=~s/\D//g;
 8142:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8143:     my $total;
 8144:     foreach my $val (@txts) { $total+=$val; }
 8145:     if ($_64bit) { $total=(($total<<32)>>32); }
 8146:     return $total;
 8147: }
 8148: 
 8149: sub digest {
 8150:     my ($data)=@_;
 8151:     my $digest=&Digest::MD5::md5($data);
 8152:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8153:     my ($e,$f);
 8154:     {
 8155:         use integer;
 8156:         $e=($a+$b);
 8157:         $f=($c+$d);
 8158:         if ($_64bit) {
 8159:             $e=(($e<<32)>>32);
 8160:             $f=(($f<<32)>>32);
 8161:         }
 8162:     }
 8163:     if (wantarray) {
 8164: 	return ($e,$f);
 8165:     } else {
 8166: 	my $g;
 8167: 	{
 8168: 	    use integer;
 8169: 	    $g=($e+$f);
 8170: 	    if ($_64bit) {
 8171: 		$g=(($g<<32)>>32);
 8172: 	    }
 8173: 	}
 8174: 	return $g;
 8175:     }
 8176: }
 8177: 
 8178: sub latest_rnd_algorithm_id {
 8179:     return '64bit5';
 8180: }
 8181: 
 8182: sub get_rand_alg {
 8183:     my ($courseid)=@_;
 8184:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8185:     if ($courseid) {
 8186: 	return $env{"course.$courseid.rndseed"};
 8187:     }
 8188:     return &latest_rnd_algorithm_id();
 8189: }
 8190: 
 8191: sub validCODE {
 8192:     my ($CODE)=@_;
 8193:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8194:     return 0;
 8195: }
 8196: 
 8197: sub getCODE {
 8198:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8199:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8200: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8201: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8202: 	return $Apache::lonhomework::history{'resource.CODE'};
 8203:     }
 8204:     return undef;
 8205: }
 8206: 
 8207: sub rndseed {
 8208:     my ($symb,$courseid,$domain,$username)=@_;
 8209:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8210:     if (!defined($symb)) {
 8211: 	unless ($symb=$wsymb) { return time; }
 8212:     }
 8213:     if (!$courseid) { $courseid=$wcourseid; }
 8214:     if (!$domain) { $domain=$wdomain; }
 8215:     if (!$username) { $username=$wusername }
 8216:     my $which=&get_rand_alg();
 8217: 
 8218:     if (defined(&getCODE())) {
 8219: 	if ($which eq '64bit5') {
 8220: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8221: 	} elsif ($which eq '64bit4') {
 8222: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8223: 	} else {
 8224: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8225: 	}
 8226:     } elsif ($which eq '64bit5') {
 8227: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8228:     } elsif ($which eq '64bit4') {
 8229: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8230:     } elsif ($which eq '64bit3') {
 8231: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8232:     } elsif ($which eq '64bit2') {
 8233: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8234:     } elsif ($which eq '64bit') {
 8235: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8236:     }
 8237:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8238: }
 8239: 
 8240: sub rndseed_32bit {
 8241:     my ($symb,$courseid,$domain,$username)=@_;
 8242:     {
 8243: 	use integer;
 8244: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8245: 	my $symbseed=numval($symb) << 22;
 8246: 	my $namechck=unpack("%32C*",$username) << 17;
 8247: 	my $nameseed=numval($username) << 12;
 8248: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8249: 	my $courseseed=unpack("%32C*",$courseid);
 8250: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8251: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8252: 	#&logthis("rndseed :$num:$symb");
 8253: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8254: 	return $num;
 8255:     }
 8256: }
 8257: 
 8258: sub rndseed_64bit {
 8259:     my ($symb,$courseid,$domain,$username)=@_;
 8260:     {
 8261: 	use integer;
 8262: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8263: 	my $symbseed=numval($symb) << 10;
 8264: 	my $namechck=unpack("%32S*",$username);
 8265: 	
 8266: 	my $nameseed=numval($username) << 21;
 8267: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8268: 	my $courseseed=unpack("%32S*",$courseid);
 8269: 	
 8270: 	my $num1=$symbchck+$symbseed+$namechck;
 8271: 	my $num2=$nameseed+$domainseed+$courseseed;
 8272: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8273: 	#&logthis("rndseed :$num:$symb");
 8274: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8275: 	return "$num1,$num2";
 8276:     }
 8277: }
 8278: 
 8279: sub rndseed_64bit2 {
 8280:     my ($symb,$courseid,$domain,$username)=@_;
 8281:     {
 8282: 	use integer;
 8283: 	# strings need to be an even # of cahracters long, it it is odd the
 8284:         # last characters gets thrown away
 8285: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8286: 	my $symbseed=numval($symb) << 10;
 8287: 	my $namechck=unpack("%32S*",$username.' ');
 8288: 	
 8289: 	my $nameseed=numval($username) << 21;
 8290: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8291: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8292: 	
 8293: 	my $num1=$symbchck+$symbseed+$namechck;
 8294: 	my $num2=$nameseed+$domainseed+$courseseed;
 8295: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8296: 	#&logthis("rndseed :$num:$symb");
 8297: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8298: 	return "$num1,$num2";
 8299:     }
 8300: }
 8301: 
 8302: sub rndseed_64bit3 {
 8303:     my ($symb,$courseid,$domain,$username)=@_;
 8304:     {
 8305: 	use integer;
 8306: 	# strings need to be an even # of cahracters long, it it is odd the
 8307:         # last characters gets thrown away
 8308: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8309: 	my $symbseed=numval2($symb) << 10;
 8310: 	my $namechck=unpack("%32S*",$username.' ');
 8311: 	
 8312: 	my $nameseed=numval2($username) << 21;
 8313: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8314: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8315: 	
 8316: 	my $num1=$symbchck+$symbseed+$namechck;
 8317: 	my $num2=$nameseed+$domainseed+$courseseed;
 8318: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8319: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8320: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8321: 	
 8322: 	return "$num1:$num2";
 8323:     }
 8324: }
 8325: 
 8326: sub rndseed_64bit4 {
 8327:     my ($symb,$courseid,$domain,$username)=@_;
 8328:     {
 8329: 	use integer;
 8330: 	# strings need to be an even # of cahracters long, it it is odd the
 8331:         # last characters gets thrown away
 8332: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8333: 	my $symbseed=numval3($symb) << 10;
 8334: 	my $namechck=unpack("%32S*",$username.' ');
 8335: 	
 8336: 	my $nameseed=numval3($username) << 21;
 8337: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8338: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8339: 	
 8340: 	my $num1=$symbchck+$symbseed+$namechck;
 8341: 	my $num2=$nameseed+$domainseed+$courseseed;
 8342: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8343: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8344: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8345: 	
 8346: 	return "$num1:$num2";
 8347:     }
 8348: }
 8349: 
 8350: sub rndseed_64bit5 {
 8351:     my ($symb,$courseid,$domain,$username)=@_;
 8352:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8353:     return "$num1:$num2";
 8354: }
 8355: 
 8356: sub rndseed_CODE_64bit {
 8357:     my ($symb,$courseid,$domain,$username)=@_;
 8358:     {
 8359: 	use integer;
 8360: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8361: 	my $symbseed=numval2($symb);
 8362: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8363: 	my $CODEseed=numval(&getCODE());
 8364: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8365: 	my $num1=$symbseed+$CODEchck;
 8366: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8367: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8368: 	#&logthis("rndseed :$num1:$num2:$symb");
 8369: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8370: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8371: 	return "$num1:$num2";
 8372:     }
 8373: }
 8374: 
 8375: sub rndseed_CODE_64bit4 {
 8376:     my ($symb,$courseid,$domain,$username)=@_;
 8377:     {
 8378: 	use integer;
 8379: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8380: 	my $symbseed=numval3($symb);
 8381: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8382: 	my $CODEseed=numval3(&getCODE());
 8383: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8384: 	my $num1=$symbseed+$CODEchck;
 8385: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8386: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8387: 	#&logthis("rndseed :$num1:$num2:$symb");
 8388: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8389: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8390: 	return "$num1:$num2";
 8391:     }
 8392: }
 8393: 
 8394: sub rndseed_CODE_64bit5 {
 8395:     my ($symb,$courseid,$domain,$username)=@_;
 8396:     my $code = &getCODE();
 8397:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8398:     return "$num1:$num2";
 8399: }
 8400: 
 8401: sub setup_random_from_rndseed {
 8402:     my ($rndseed)=@_;
 8403:     if ($rndseed =~/([,:])/) {
 8404: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8405: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8406:     } else {
 8407: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8408:     }
 8409: }
 8410: 
 8411: sub latest_receipt_algorithm_id {
 8412:     return 'receipt3';
 8413: }
 8414: 
 8415: sub recunique {
 8416:     my $fucourseid=shift;
 8417:     my $unique;
 8418:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8419: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8420: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8421:     } else {
 8422: 	$unique=$perlvar{'lonReceipt'};
 8423:     }
 8424:     return unpack("%32C*",$unique);
 8425: }
 8426: 
 8427: sub recprefix {
 8428:     my $fucourseid=shift;
 8429:     my $prefix;
 8430:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8431: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8432: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8433:     } else {
 8434: 	$prefix=$perlvar{'lonHostID'};
 8435:     }
 8436:     return unpack("%32C*",$prefix);
 8437: }
 8438: 
 8439: sub ireceipt {
 8440:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8441: 
 8442:     my $return =&recprefix($fucourseid).'-';
 8443: 
 8444:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8445: 	$env{'request.state'} eq 'construct') {
 8446: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8447: 	return $return;
 8448:     }
 8449: 
 8450:     my $cuname=unpack("%32C*",$funame);
 8451:     my $cudom=unpack("%32C*",$fudom);
 8452:     my $cucourseid=unpack("%32C*",$fucourseid);
 8453:     my $cusymb=unpack("%32C*",$fusymb);
 8454:     my $cunique=&recunique($fucourseid);
 8455:     my $cpart=unpack("%32S*",$part);
 8456:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8457: 
 8458: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8459: 			       
 8460: 	$return.= ($cunique%$cuname+
 8461: 		   $cunique%$cudom+
 8462: 		   $cusymb%$cuname+
 8463: 		   $cusymb%$cudom+
 8464: 		   $cucourseid%$cuname+
 8465: 		   $cucourseid%$cudom+
 8466: 		   $cpart%$cuname+
 8467: 		   $cpart%$cudom);
 8468:     } else {
 8469: 	$return.= ($cunique%$cuname+
 8470: 		   $cunique%$cudom+
 8471: 		   $cusymb%$cuname+
 8472: 		   $cusymb%$cudom+
 8473: 		   $cucourseid%$cuname+
 8474: 		   $cucourseid%$cudom);
 8475:     }
 8476:     return $return;
 8477: }
 8478: 
 8479: sub receipt {
 8480:     my ($part)=@_;
 8481:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8482:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8483: }
 8484: 
 8485: sub whichuser {
 8486:     my ($passedsymb)=@_;
 8487:     my ($symb,$courseid,$domain,$name,$publicuser);
 8488:     if (defined($env{'form.grade_symb'})) {
 8489: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8490: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8491: 	if (!$allowed &&
 8492: 	    exists($env{'request.course.sec'}) &&
 8493: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8494: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8495: 			      '/'.$env{'request.course.sec'});
 8496: 	}
 8497: 	if ($allowed) {
 8498: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8499: 	    $courseid=$tmp_courseid;
 8500: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8501: 	    ($name)=&get_env_multiple('form.grade_username');
 8502: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8503: 	}
 8504:     }
 8505:     if (!$passedsymb) {
 8506: 	$symb=&symbread();
 8507:     } else {
 8508: 	$symb=$passedsymb;
 8509:     }
 8510:     $courseid=$env{'request.course.id'};
 8511:     $domain=$env{'user.domain'};
 8512:     $name=$env{'user.name'};
 8513:     if ($name eq 'public' && $domain eq 'public') {
 8514: 	if (!defined($env{'form.username'})) {
 8515: 	    $env{'form.username'}.=time.rand(10000000);
 8516: 	}
 8517: 	$name.=$env{'form.username'};
 8518:     }
 8519:     return ($symb,$courseid,$domain,$name,$publicuser);
 8520: 
 8521: }
 8522: 
 8523: # ------------------------------------------------------------ Serves up a file
 8524: # returns either the contents of the file or 
 8525: # -1 if the file doesn't exist
 8526: #
 8527: # if the target is a file that was uploaded via DOCS, 
 8528: # a check will be made to see if a current copy exists on the local server,
 8529: # if it does this will be served, otherwise a copy will be retrieved from
 8530: # the home server for the course and stored in /home/httpd/html/userfiles on
 8531: # the local server.   
 8532: 
 8533: sub getfile {
 8534:     my ($file) = @_;
 8535:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8536:     &repcopy($file);
 8537:     return &readfile($file);
 8538: }
 8539: 
 8540: sub repcopy_userfile {
 8541:     my ($file)=@_;
 8542:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8543:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8544:     my ($cdom,$cnum,$filename) = 
 8545: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8546:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8547:     if (-e "$file") {
 8548: # we already have a local copy, check it out
 8549: 	my @fileinfo = stat($file);
 8550: 	my $rtncode;
 8551: 	my $info;
 8552: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8553: 	if ($lwpresp ne 'ok') {
 8554: # there is no such file anymore, even though we had a local copy
 8555: 	    if ($rtncode eq '404') {
 8556: 		unlink($file);
 8557: 	    }
 8558: 	    return -1;
 8559: 	}
 8560: 	if ($info < $fileinfo[9]) {
 8561: # nice, the file we have is up-to-date, just say okay
 8562: 	    return 'ok';
 8563: 	} else {
 8564: # the file is outdated, get rid of it
 8565: 	    unlink($file);
 8566: 	}
 8567:     }
 8568: # one way or the other, at this point, we don't have the file
 8569: # construct the correct path for the file
 8570:     my @parts = ($cdom,$cnum); 
 8571:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8572: 	push @parts, split(/\//,$1);
 8573:     }
 8574:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8575:     foreach my $part (@parts) {
 8576: 	$path .= '/'.$part;
 8577: 	if (!-e $path) {
 8578: 	    mkdir($path,0770);
 8579: 	}
 8580:     }
 8581: # now the path exists for sure
 8582: # get a user agent
 8583:     my $ua=new LWP::UserAgent;
 8584:     my $transferfile=$file.'.in.transfer';
 8585: # FIXME: this should flock
 8586:     if (-e $transferfile) { return 'ok'; }
 8587:     my $request;
 8588:     $uri=~s/^\///;
 8589:     my $homeserver = &homeserver($cnum,$cdom);
 8590:     my $protocol = $protocol{$homeserver};
 8591:     $protocol = 'http' if ($protocol ne 'https');
 8592:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8593:     my $response=$ua->request($request,$transferfile);
 8594: # did it work?
 8595:     if ($response->is_error()) {
 8596: 	unlink($transferfile);
 8597: 	&logthis("Userfile repcopy failed for $uri");
 8598: 	return -1;
 8599:     }
 8600: # worked, rename the transfer file
 8601:     rename($transferfile,$file);
 8602:     return 'ok';
 8603: }
 8604: 
 8605: sub tokenwrapper {
 8606:     my $uri=shift;
 8607:     $uri=~s|^https?\://([^/]+)||;
 8608:     $uri=~s|^/||;
 8609:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8610:     my $token=$1;
 8611:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8612:     if ($udom && $uname && $file) {
 8613: 	$file=~s|(\?\.*)*$||;
 8614:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8615:         my $homeserver = &homeserver($uname,$udom);
 8616:         my $protocol = $protocol{$homeserver};
 8617:         $protocol = 'http' if ($protocol ne 'https');
 8618:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8619:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8620:                                '&tokenissued='.$perlvar{'lonHostID'};
 8621:     } else {
 8622:         return '/adm/notfound.html';
 8623:     }
 8624: }
 8625: 
 8626: # call with reqtype HEAD: get last modification time
 8627: # call with reqtype GET: get the file contents
 8628: # Do not call this with reqtype GET for large files! It loads everything into memory
 8629: #
 8630: sub getuploaded {
 8631:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8632:     $uri=~s/^\///;
 8633:     my $homeserver = &homeserver($cnum,$cdom);
 8634:     my $protocol = $protocol{$homeserver};
 8635:     $protocol = 'http' if ($protocol ne 'https');
 8636:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8637:     my $ua=new LWP::UserAgent;
 8638:     my $request=new HTTP::Request($reqtype,$uri);
 8639:     my $response=$ua->request($request);
 8640:     $$rtncode = $response->code;
 8641:     if (! $response->is_success()) {
 8642: 	return 'failed';
 8643:     }      
 8644:     if ($reqtype eq 'HEAD') {
 8645: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8646:     } elsif ($reqtype eq 'GET') {
 8647: 	$$info = $response->content;
 8648:     }
 8649:     return 'ok';
 8650: }
 8651: 
 8652: sub readfile {
 8653:     my $file = shift;
 8654:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8655:     my $fh;
 8656:     open($fh,"<$file");
 8657:     my $a='';
 8658:     while (my $line = <$fh>) { $a .= $line; }
 8659:     return $a;
 8660: }
 8661: 
 8662: sub filelocation {
 8663:     my ($dir,$file) = @_;
 8664:     my $location;
 8665:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8666: 
 8667:     if ($file =~ m-^/adm/-) {
 8668: 	$file=~s-^/adm/wrapper/-/-;
 8669: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8670:     }
 8671: 
 8672:     if ($file=~m:^/~:) { # is a contruction space reference
 8673:         $location = $file;
 8674:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8675:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8676: 	# is a correct contruction space reference
 8677:         $location = $file;
 8678:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8679:         $location = $file;
 8680:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8681:         my ($udom,$uname,$filename)=
 8682:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8683:         my $home=&homeserver($uname,$udom);
 8684:         my $is_me=0;
 8685:         my @ids=&current_machine_ids();
 8686:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8687:         if ($is_me) {
 8688:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8689:         } else {
 8690:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8691:   	      $udom.'/'.$uname.'/'.$filename;
 8692:         }
 8693:     } elsif ($file =~ m-^/adm/-) {
 8694: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8695:     } else {
 8696:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8697:         $file=~s:^/res/:/:;
 8698:         if ( !( $file =~ m:^/:) ) {
 8699:             $location = $dir. '/'.$file;
 8700:         } else {
 8701:             $location = '/home/httpd/html/res'.$file;
 8702:         }
 8703:     }
 8704:     $location=~s://+:/:g; # remove duplicate /
 8705:     while ($location=~m{/\.\./}) {
 8706: 	if ($location =~ m{/[^/]+/\.\./}) {
 8707: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8708: 	} else {
 8709: 	    $location=~ s{/\.\./}{/}g;
 8710: 	}
 8711:     } #remove dir/..
 8712:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8713:     return $location;
 8714: }
 8715: 
 8716: sub hreflocation {
 8717:     my ($dir,$file)=@_;
 8718:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8719: 	$file=filelocation($dir,$file);
 8720:     } elsif ($file=~m-^/adm/-) {
 8721: 	$file=~s-^/adm/wrapper/-/-;
 8722: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8723:     }
 8724:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8725: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8726:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8727: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8728:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8729: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8730: 	    -/uploaded/$1/$2/-x;
 8731:     }
 8732:     if ($file=~ m{^/userfiles/}) {
 8733: 	$file =~ s{^/userfiles/}{/uploaded/};
 8734:     }
 8735:     return $file;
 8736: }
 8737: 
 8738: sub current_machine_domains {
 8739:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8740: }
 8741: 
 8742: sub machine_domains {
 8743:     my ($hostname) = @_;
 8744:     my @domains;
 8745:     my %hostname = &all_hostnames();
 8746:     while( my($id, $name) = each(%hostname)) {
 8747: #	&logthis("-$id-$name-$hostname-");
 8748: 	if ($hostname eq $name) {
 8749: 	    push(@domains,&host_domain($id));
 8750: 	}
 8751:     }
 8752:     return @domains;
 8753: }
 8754: 
 8755: sub current_machine_ids {
 8756:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8757: }
 8758: 
 8759: sub machine_ids {
 8760:     my ($hostname) = @_;
 8761:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8762:     my @ids;
 8763:     my %name_to_host = &all_names();
 8764:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8765: 	return @{ $name_to_host{$hostname} };
 8766:     }
 8767:     return;
 8768: }
 8769: 
 8770: sub additional_machine_domains {
 8771:     my @domains;
 8772:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8773:     while( my $line = <$fh>) {
 8774:         $line =~ s/\s//g;
 8775:         push(@domains,$line);
 8776:     }
 8777:     return @domains;
 8778: }
 8779: 
 8780: sub default_login_domain {
 8781:     my $domain = $perlvar{'lonDefDomain'};
 8782:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8783:     foreach my $posdom (&current_machine_domains(),
 8784:                         &additional_machine_domains()) {
 8785:         if (lc($posdom) eq lc($testdomain)) {
 8786:             $domain=$posdom;
 8787:             last;
 8788:         }
 8789:     }
 8790:     return $domain;
 8791: }
 8792: 
 8793: # ------------------------------------------------------------- Declutters URLs
 8794: 
 8795: sub declutter {
 8796:     my $thisfn=shift;
 8797:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8798:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8799:     $thisfn=~s/^\///;
 8800:     $thisfn=~s|^adm/wrapper/||;
 8801:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8802:     $thisfn=~s/^res\///;
 8803:     $thisfn=~s/\?.+$//;
 8804:     return $thisfn;
 8805: }
 8806: 
 8807: # ------------------------------------------------------------- Clutter up URLs
 8808: 
 8809: sub clutter {
 8810:     my $thisfn='/'.&declutter(shift);
 8811:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8812: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8813:        $thisfn='/res'.$thisfn; 
 8814:     }
 8815:     if ($thisfn !~m|/adm|) {
 8816: 	if ($thisfn =~ m|/ext/|) {
 8817: 	    $thisfn='/adm/wrapper'.$thisfn;
 8818: 	} else {
 8819: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8820: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8821: 	    if ($embstyle eq 'ssi'
 8822: 		|| ($embstyle eq 'hdn')
 8823: 		|| ($embstyle eq 'rat')
 8824: 		|| ($embstyle eq 'prv')
 8825: 		|| ($embstyle eq 'ign')) {
 8826: 		#do nothing with these
 8827: 	    } elsif (($embstyle eq 'img') 
 8828: 		|| ($embstyle eq 'emb')
 8829: 		|| ($embstyle eq 'wrp')) {
 8830: 		$thisfn='/adm/wrapper'.$thisfn;
 8831: 	    } elsif ($embstyle eq 'unk'
 8832: 		     && $thisfn!~/\.(sequence|page)$/) {
 8833: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8834: 	    } else {
 8835: #		&logthis("Got a blank emb style");
 8836: 	    }
 8837: 	}
 8838:     }
 8839:     return $thisfn;
 8840: }
 8841: 
 8842: sub clutter_with_no_wrapper {
 8843:     my $uri = &clutter(shift);
 8844:     if ($uri =~ m-^/adm/-) {
 8845: 	$uri =~ s-^/adm/wrapper/-/-;
 8846: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8847:     }
 8848:     return $uri;
 8849: }
 8850: 
 8851: sub freeze_escape {
 8852:     my ($value)=@_;
 8853:     if (ref($value)) {
 8854: 	$value=&nfreeze($value);
 8855: 	return '__FROZEN__'.&escape($value);
 8856:     }
 8857:     return &escape($value);
 8858: }
 8859: 
 8860: 
 8861: sub thaw_unescape {
 8862:     my ($value)=@_;
 8863:     if ($value =~ /^__FROZEN__/) {
 8864: 	substr($value,0,10,undef);
 8865: 	$value=&unescape($value);
 8866: 	return &thaw($value);
 8867:     }
 8868:     return &unescape($value);
 8869: }
 8870: 
 8871: sub correct_line_ends {
 8872:     my ($result)=@_;
 8873:     $$result =~s/\r\n/\n/mg;
 8874:     $$result =~s/\r/\n/mg;
 8875: }
 8876: # ================================================================ Main Program
 8877: 
 8878: sub goodbye {
 8879:    &logthis("Starting Shut down");
 8880: #not converted to using infrastruture and probably shouldn't be
 8881:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8882: #converted
 8883: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8884:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8885: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8886: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8887: #1.1 only
 8888: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8889: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8890: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8891: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8892:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8893:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8894:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8895:    &flushcourselogs();
 8896:    &logthis("Shutting down");
 8897: }
 8898: 
 8899: sub get_dns {
 8900:     my ($url,$func,$ignore_cache) = @_;
 8901:     if (!$ignore_cache) {
 8902: 	my ($content,$cached)=
 8903: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8904: 	if ($cached) {
 8905: 	    &$func($content);
 8906: 	    return;
 8907: 	}
 8908:     }
 8909: 
 8910:     my %alldns;
 8911:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8912:     foreach my $dns (<$config>) {
 8913: 	next if ($dns !~ /^\^(\S*)/x);
 8914:         my $line = $1;
 8915:         my ($host,$protocol) = split(/:/,$line);
 8916:         if ($protocol ne 'https') {
 8917:             $protocol = 'http';
 8918:         }
 8919: 	$alldns{$host} = $protocol;
 8920:     }
 8921:     while (%alldns) {
 8922: 	my ($dns) = keys(%alldns);
 8923: 	my $ua=new LWP::UserAgent;
 8924: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8925: 	my $response=$ua->request($request);
 8926:         delete($alldns{$dns});
 8927: 	next if ($response->is_error());
 8928: 	my @content = split("\n",$response->content);
 8929: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8930: 	&$func(\@content);
 8931: 	return;
 8932:     }
 8933:     close($config);
 8934:     my $which = (split('/',$url))[3];
 8935:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8936:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8937:     my @content = <$config>;
 8938:     &$func(\@content);
 8939:     return;
 8940: }
 8941: # ------------------------------------------------------------ Read domain file
 8942: {
 8943:     my $loaded;
 8944:     my %domain;
 8945: 
 8946:     sub parse_domain_tab {
 8947: 	my ($lines) = @_;
 8948: 	foreach my $line (@$lines) {
 8949: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8950: 
 8951: 	    chomp($line);
 8952: 	    my ($name,@elements) = split(/:/,$line,9);
 8953: 	    my %this_domain;
 8954: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8955: 			       'lang_def', 'city', 'longi', 'lati',
 8956: 			       'primary') {
 8957: 		$this_domain{$field} = shift(@elements);
 8958: 	    }
 8959: 	    $domain{$name} = \%this_domain;
 8960: 	}
 8961:     }
 8962: 
 8963:     sub reset_domain_info {
 8964: 	undef($loaded);
 8965: 	undef(%domain);
 8966:     }
 8967: 
 8968:     sub load_domain_tab {
 8969: 	my ($ignore_cache) = @_;
 8970: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8971: 	my $fh;
 8972: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8973: 	    my @lines = <$fh>;
 8974: 	    &parse_domain_tab(\@lines);
 8975: 	}
 8976: 	close($fh);
 8977: 	$loaded = 1;
 8978:     }
 8979: 
 8980:     sub domain {
 8981: 	&load_domain_tab() if (!$loaded);
 8982: 
 8983: 	my ($name,$what) = @_;
 8984: 	return if ( !exists($domain{$name}) );
 8985: 
 8986: 	if (!$what) {
 8987: 	    return $domain{$name}{'description'};
 8988: 	}
 8989: 	return $domain{$name}{$what};
 8990:     }
 8991: 
 8992:     sub domain_info {
 8993:         &load_domain_tab() if (!$loaded);
 8994:         return %domain;
 8995:     }
 8996: 
 8997: }
 8998: 
 8999: 
 9000: # ------------------------------------------------------------- Read hosts file
 9001: {
 9002:     my %hostname;
 9003:     my %hostdom;
 9004:     my %libserv;
 9005:     my $loaded;
 9006:     my %name_to_host;
 9007: 
 9008:     sub parse_hosts_tab {
 9009: 	my ($file) = @_;
 9010: 	foreach my $configline (@$file) {
 9011: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9012: 	    next if ($configline =~ /^\^/);
 9013: 	    chomp($configline);
 9014: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9015: 	    $name=~s/\s//g;
 9016: 	    if ($id && $domain && $role && $name) {
 9017: 		$hostname{$id}=$name;
 9018: 		push(@{$name_to_host{$name}}, $id);
 9019: 		$hostdom{$id}=$domain;
 9020: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9021:                 if (defined($protocol)) {
 9022:                     if ($protocol eq 'https') {
 9023:                         $protocol{$id} = $protocol;
 9024:                     } else {
 9025:                         $protocol{$id} = 'http'; 
 9026:                     }
 9027:                 } else {
 9028:                     $protocol{$id} = 'http';
 9029:                 }
 9030: 	    }
 9031: 	}
 9032:     }
 9033:     
 9034:     sub reset_hosts_info {
 9035: 	&purge_remembered();
 9036: 	&reset_domain_info();
 9037: 	&reset_hosts_ip_info();
 9038: 	undef(%name_to_host);
 9039: 	undef(%hostname);
 9040: 	undef(%hostdom);
 9041: 	undef(%libserv);
 9042: 	undef($loaded);
 9043:     }
 9044: 
 9045:     sub load_hosts_tab {
 9046: 	my ($ignore_cache) = @_;
 9047: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9048: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9049: 	my @config = <$config>;
 9050: 	&parse_hosts_tab(\@config);
 9051: 	close($config);
 9052: 	$loaded=1;
 9053:     }
 9054: 
 9055:     sub hostname {
 9056: 	&load_hosts_tab() if (!$loaded);
 9057: 
 9058: 	my ($lonid) = @_;
 9059: 	return $hostname{$lonid};
 9060:     }
 9061: 
 9062:     sub all_hostnames {
 9063: 	&load_hosts_tab() if (!$loaded);
 9064: 
 9065: 	return %hostname;
 9066:     }
 9067: 
 9068:     sub all_names {
 9069: 	&load_hosts_tab() if (!$loaded);
 9070: 
 9071: 	return %name_to_host;
 9072:     }
 9073: 
 9074:     sub all_host_domain {
 9075:         &load_hosts_tab() if (!$loaded);
 9076:         return %hostdom;
 9077:     }
 9078: 
 9079:     sub is_library {
 9080: 	&load_hosts_tab() if (!$loaded);
 9081: 
 9082: 	return exists($libserv{$_[0]});
 9083:     }
 9084: 
 9085:     sub all_library {
 9086: 	&load_hosts_tab() if (!$loaded);
 9087: 
 9088: 	return %libserv;
 9089:     }
 9090: 
 9091:     sub get_servers {
 9092: 	&load_hosts_tab() if (!$loaded);
 9093: 
 9094: 	my ($domain,$type) = @_;
 9095: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9096: 	                                          : %hostname;
 9097: 	my %result;
 9098: 	if (ref($domain) eq 'ARRAY') {
 9099: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9100: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9101: 		    $result{$host} = $hostname;
 9102: 		}
 9103: 	    }
 9104: 	} else {
 9105: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9106: 		if ($hostdom{$host} eq $domain) {
 9107: 		    $result{$host} = $hostname;
 9108: 		}
 9109: 	    }
 9110: 	}
 9111: 	return %result;
 9112:     }
 9113: 
 9114:     sub host_domain {
 9115: 	&load_hosts_tab() if (!$loaded);
 9116: 
 9117: 	my ($lonid) = @_;
 9118: 	return $hostdom{$lonid};
 9119:     }
 9120: 
 9121:     sub all_domains {
 9122: 	&load_hosts_tab() if (!$loaded);
 9123: 
 9124: 	my %seen;
 9125: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9126: 	return @uniq;
 9127:     }
 9128: }
 9129: 
 9130: { 
 9131:     my %iphost;
 9132:     my %name_to_ip;
 9133:     my %lonid_to_ip;
 9134: 
 9135:     sub get_hosts_from_ip {
 9136: 	my ($ip) = @_;
 9137: 	my %iphosts = &get_iphost();
 9138: 	if (ref($iphosts{$ip})) {
 9139: 	    return @{$iphosts{$ip}};
 9140: 	}
 9141: 	return;
 9142:     }
 9143:     
 9144:     sub reset_hosts_ip_info {
 9145: 	undef(%iphost);
 9146: 	undef(%name_to_ip);
 9147: 	undef(%lonid_to_ip);
 9148:     }
 9149: 
 9150:     sub get_host_ip {
 9151: 	my ($lonid) = @_;
 9152: 	if (exists($lonid_to_ip{$lonid})) {
 9153: 	    return $lonid_to_ip{$lonid};
 9154: 	}
 9155: 	my $name=&hostname($lonid);
 9156:    	my $ip = gethostbyname($name);
 9157: 	return if (!$ip || length($ip) ne 4);
 9158: 	$ip=inet_ntoa($ip);
 9159: 	$name_to_ip{$name}   = $ip;
 9160: 	$lonid_to_ip{$lonid} = $ip;
 9161: 	return $ip;
 9162:     }
 9163:     
 9164:     sub get_iphost {
 9165: 	my ($ignore_cache) = @_;
 9166: 
 9167: 	if (!$ignore_cache) {
 9168: 	    if (%iphost) {
 9169: 		return %iphost;
 9170: 	    }
 9171: 	    my ($ip_info,$cached)=
 9172: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9173: 	    if ($cached) {
 9174: 		%iphost      = %{$ip_info->[0]};
 9175: 		%name_to_ip  = %{$ip_info->[1]};
 9176: 		%lonid_to_ip = %{$ip_info->[2]};
 9177: 		return %iphost;
 9178: 	    }
 9179: 	}
 9180: 
 9181: 	# get yesterday's info for fallback
 9182: 	my %old_name_to_ip;
 9183: 	my ($ip_info,$cached)=
 9184: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9185: 	if ($cached) {
 9186: 	    %old_name_to_ip = %{$ip_info->[1]};
 9187: 	}
 9188: 
 9189: 	my %name_to_host = &all_names();
 9190: 	foreach my $name (keys(%name_to_host)) {
 9191: 	    my $ip;
 9192: 	    if (!exists($name_to_ip{$name})) {
 9193: 		$ip = gethostbyname($name);
 9194: 		if (!$ip || length($ip) ne 4) {
 9195: 		    if (defined($old_name_to_ip{$name})) {
 9196: 			$ip = $old_name_to_ip{$name};
 9197: 			&logthis("Can't find $name defaulting to old $ip");
 9198: 		    } else {
 9199: 			&logthis("Name $name no IP found");
 9200: 			next;
 9201: 		    }
 9202: 		} else {
 9203: 		    $ip=inet_ntoa($ip);
 9204: 		}
 9205: 		$name_to_ip{$name} = $ip;
 9206: 	    } else {
 9207: 		$ip = $name_to_ip{$name};
 9208: 	    }
 9209: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9210: 		$lonid_to_ip{$id} = $ip;
 9211: 	    }
 9212: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9213: 	}
 9214: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9215: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9216: 				      48*60*60);
 9217: 
 9218: 	return %iphost;
 9219:     }
 9220: 
 9221:     #
 9222:     #  Given a DNS returns the loncapa host name for that DNS 
 9223:     # 
 9224:     sub host_from_dns {
 9225:         my ($dns) = @_;
 9226:         my @hosts;
 9227:         my $ip;
 9228: 
 9229:         if (exists($name_to_ip{$dns})) {
 9230:             $ip = $name_to_ip{$dns};
 9231:         }
 9232:         if (!$ip) {
 9233:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9234:             if (length($ip) == 4) { 
 9235: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9236:             }
 9237:         }
 9238:         if ($ip) {
 9239: 	    @hosts = get_hosts_from_ip($ip);
 9240: 	    return $hosts[0];
 9241:         }
 9242:         return undef;
 9243:     }
 9244: 
 9245: }
 9246: 
 9247: BEGIN {
 9248: 
 9249: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9250:     unless ($readit) {
 9251: {
 9252:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9253:     %perlvar = (%perlvar,%{$configvars});
 9254: }
 9255: 
 9256: 
 9257: # ------------------------------------------------------ Read spare server file
 9258: {
 9259:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9260: 
 9261:     while (my $configline=<$config>) {
 9262:        chomp($configline);
 9263:        if ($configline) {
 9264: 	   my ($host,$type) = split(':',$configline,2);
 9265: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9266: 	   push(@{ $spareid{$type} }, $host);
 9267:        }
 9268:     }
 9269:     close($config);
 9270: }
 9271: # ------------------------------------------------------------ Read permissions
 9272: {
 9273:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9274: 
 9275:     while (my $configline=<$config>) {
 9276: 	chomp($configline);
 9277: 	if ($configline) {
 9278: 	    my ($role,$perm)=split(/ /,$configline);
 9279: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9280: 	}
 9281:     }
 9282:     close($config);
 9283: }
 9284: 
 9285: # -------------------------------------------- Read plain texts for permissions
 9286: {
 9287:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9288: 
 9289:     while (my $configline=<$config>) {
 9290: 	chomp($configline);
 9291: 	if ($configline) {
 9292: 	    my ($short,@plain)=split(/:/,$configline);
 9293:             %{$prp{$short}} = ();
 9294: 	    if (@plain > 0) {
 9295:                 $prp{$short}{'std'} = $plain[0];
 9296:                 for (my $i=1; $i<@plain; $i++) {
 9297:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9298:                 }
 9299:             }
 9300: 	}
 9301:     }
 9302:     close($config);
 9303: }
 9304: 
 9305: # ---------------------------------------------------------- Read package table
 9306: {
 9307:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9308: 
 9309:     while (my $configline=<$config>) {
 9310: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9311: 	chomp($configline);
 9312: 	my ($short,$plain)=split(/:/,$configline);
 9313: 	my ($pack,$name)=split(/\&/,$short);
 9314: 	if ($plain ne '') {
 9315: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9316: 	    $packagetab{$short}=$plain; 
 9317: 	}
 9318:     }
 9319:     close($config);
 9320: }
 9321: 
 9322: # ------------- set up temporary directory
 9323: {
 9324:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9325: 
 9326: }
 9327: 
 9328: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9329: 				'compress_threshold'=> 20_000,
 9330:  			        });
 9331: 
 9332: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9333: $dumpcount=0;
 9334: $locknum=0;
 9335: 
 9336: &logtouch();
 9337: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9338: $readit=1;
 9339:     {
 9340: 	use integer;
 9341: 	my $test=(2**32)+1;
 9342: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9343: 	&logthis(" Detected 64bit platform ($_64bit)");
 9344:     }
 9345: }
 9346: }
 9347: 
 9348: 1;
 9349: __END__
 9350: 
 9351: =pod
 9352: 
 9353: =head1 NAME
 9354: 
 9355: Apache::lonnet - Subroutines to ask questions about things in the network.
 9356: 
 9357: =head1 SYNOPSIS
 9358: 
 9359: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9360: 
 9361:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9362: 
 9363: Common parameters:
 9364: 
 9365: =over 4
 9366: 
 9367: =item *
 9368: 
 9369: $uname : an internal username (if $cname expecting a course Id specifically)
 9370: 
 9371: =item *
 9372: 
 9373: $udom : a domain (if $cdom expecting a course's domain specifically)
 9374: 
 9375: =item *
 9376: 
 9377: $symb : a resource instance identifier
 9378: 
 9379: =item *
 9380: 
 9381: $namespace : the name of a .db file that contains the data needed or
 9382: being set.
 9383: 
 9384: =back
 9385: 
 9386: =head1 OVERVIEW
 9387: 
 9388: lonnet provides subroutines which interact with the
 9389: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9390: about classes, users, and resources.
 9391: 
 9392: For many of these objects you can also use this to store data about
 9393: them or modify them in various ways.
 9394: 
 9395: =head2 Symbs
 9396: 
 9397: To identify a specific instance of a resource, LON-CAPA uses symbols
 9398: or "symbs"X<symb>. These identifiers are built from the URL of the
 9399: map, the resource number of the resource in the map, and the URL of
 9400: the resource itself. The latter is somewhat redundant, but might help
 9401: if maps change.
 9402: 
 9403: An example is
 9404: 
 9405:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9406: 
 9407: The respective map entry is
 9408: 
 9409:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9410:   title="Problem 2">
 9411:  </resource>
 9412: 
 9413: Symbs are used by the random number generator, as well as to store and
 9414: restore data specific to a certain instance of for example a problem.
 9415: 
 9416: =head2 Storing And Retrieving Data
 9417: 
 9418: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9419: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9420: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9421: is is the non-critical message twin of cstore. These functions are for
 9422: handlers to store a perl hash to a user's permanent data space in an
 9423: easy manner, and to retrieve it again on another call. It is expected
 9424: that a handler would use this once at the beginning to retrieve data,
 9425: and then again once at the end to send only the new data back.
 9426: 
 9427: The data is stored in the user's data directory on the user's
 9428: homeserver under the ID of the course.
 9429: 
 9430: The hash that is returned by restore will have all of the previous
 9431: value for all of the elements of the hash.
 9432: 
 9433: Example:
 9434: 
 9435:  #creating a hash
 9436:  my %hash;
 9437:  $hash{'foo'}='bar';
 9438: 
 9439:  #storing it
 9440:  &Apache::lonnet::cstore(\%hash);
 9441: 
 9442:  #changing a value
 9443:  $hash{'foo'}='notbar';
 9444: 
 9445:  #adding a new value
 9446:  $hash{'bar'}='foo';
 9447:  &Apache::lonnet::cstore(\%hash);
 9448: 
 9449:  #retrieving the hash
 9450:  my %history=&Apache::lonnet::restore();
 9451: 
 9452:  #print the hash
 9453:  foreach my $key (sort(keys(%history))) {
 9454:    print("\%history{$key} = $history{$key}");
 9455:  }
 9456: 
 9457: Will print out:
 9458: 
 9459:  %history{1:foo} = bar
 9460:  %history{1:keys} = foo:timestamp
 9461:  %history{1:timestamp} = 990455579
 9462:  %history{2:bar} = foo
 9463:  %history{2:foo} = notbar
 9464:  %history{2:keys} = foo:bar:timestamp
 9465:  %history{2:timestamp} = 990455580
 9466:  %history{bar} = foo
 9467:  %history{foo} = notbar
 9468:  %history{timestamp} = 990455580
 9469:  %history{version} = 2
 9470: 
 9471: Note that the special hash entries C<keys>, C<version> and
 9472: C<timestamp> were added to the hash. C<version> will be equal to the
 9473: total number of versions of the data that have been stored. The
 9474: C<timestamp> attribute will be the UNIX time the hash was
 9475: stored. C<keys> is available in every historical section to list which
 9476: keys were added or changed at a specific historical revision of a
 9477: hash.
 9478: 
 9479: B<Warning>: do not store the hash that restore returns directly. This
 9480: will cause a mess since it will restore the historical keys as if the
 9481: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9482: 
 9483: Calling convention:
 9484: 
 9485:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9486:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9487: 
 9488: For more detailed information, see lonnet specific documentation.
 9489: 
 9490: =head1 RETURN MESSAGES
 9491: 
 9492: =over 4
 9493: 
 9494: =item * B<con_lost>: unable to contact remote host
 9495: 
 9496: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9497: when the connection is brought back up
 9498: 
 9499: =item * B<con_failed>: unable to contact remote host and unable to save message
 9500: for later delivery
 9501: 
 9502: =item * B<error:>: an error a occurred, a description of the error follows the :
 9503: 
 9504: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9505: that was requested
 9506: 
 9507: =back
 9508: 
 9509: =head1 PUBLIC SUBROUTINES
 9510: 
 9511: =head2 Session Environment Functions
 9512: 
 9513: =over 4
 9514: 
 9515: =item * 
 9516: X<appenv()>
 9517: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9518: the user envirnoment file, and will be restored for each access this
 9519: user makes during this session, also modifies the %env for the current
 9520: process. Optional rolesarrayref - if defined contains a reference to an array
 9521: of roles which are exempt from the restriction on modifying user.role entries 
 9522: in the user's environment.db and in %env.    
 9523: 
 9524: =item *
 9525: X<delenv()>
 9526: B<delenv($delthis,$regexp)>: removes all items from the session
 9527: environment file that begin with $delthis. If the 
 9528: optional second arg - $regexp - is true, $delthis is treated as a 
 9529: regular expression, otherwise \Q$delthis\E is used. 
 9530: The values are also deleted from the current processes %env.
 9531: 
 9532: =item * get_env_multiple($name) 
 9533: 
 9534: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9535: values may be defined and end up as an array ref.
 9536: 
 9537: returns an array of values
 9538: 
 9539: =back
 9540: 
 9541: =head2 User Information
 9542: 
 9543: =over 4
 9544: 
 9545: =item *
 9546: X<queryauthenticate()>
 9547: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9548: authentication scheme
 9549: 
 9550: =item *
 9551: X<authenticate()>
 9552: B<authenticate($uname,$upass,$udom)>: try to
 9553: authenticate user from domain's lib servers (first use the current
 9554: one). C<$upass> should be the users password.
 9555: 
 9556: =item *
 9557: X<homeserver()>
 9558: B<homeserver($uname,$udom)>: find the server which has
 9559: the user's directory and files (there must be only one), this caches
 9560: the answer, and also caches if there is a borken connection.
 9561: 
 9562: =item *
 9563: X<idget()>
 9564: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9565: (IDs are a unique resource in a domain, there must be only 1 ID per
 9566: username, and only 1 username per ID in a specific domain) (returns
 9567: hash: id=>name,id=>name)
 9568: 
 9569: =item *
 9570: X<idrget()>
 9571: B<idrget($udom,@unames)>: find the IDs behind a list of
 9572: usernames (returns hash: name=>id,name=>id)
 9573: 
 9574: =item *
 9575: X<idput()>
 9576: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9577: 
 9578: =item *
 9579: X<rolesinit()>
 9580: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9581: 
 9582: =item *
 9583: X<getsection()>
 9584: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9585: course $cname, return section name/number or '' for "not in course"
 9586: and '-1' for "no section"
 9587: 
 9588: =item *
 9589: X<userenvironment()>
 9590: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9591: passed in @what from the requested user's environment, returns a hash
 9592: 
 9593: =item * 
 9594: X<userlog_query()>
 9595: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9596: activity.log file. %filters defines filters applied when parsing the
 9597: log file. These can be start or end timestamps, or the type of action
 9598: - log to look for Login or Logout events, check for Checkin or
 9599: Checkout, role for role selection. The response is in the form
 9600: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9601: escaped strings of the action recorded in the activity.log file.
 9602: 
 9603: =back
 9604: 
 9605: =head2 User Roles
 9606: 
 9607: =over 4
 9608: 
 9609: =item *
 9610: 
 9611: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9612:  F: full access
 9613:  U,I,K: authentication modes (cxx only)
 9614:  '': forbidden
 9615:  1: user needs to choose course
 9616:  2: browse allowed
 9617:  A: passphrase authentication needed
 9618: 
 9619: =item *
 9620: 
 9621: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9622: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9623: and course level
 9624: 
 9625: =item *
 9626: 
 9627: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9628: (rolesplain.tab); plain text explanation of a user role term.
 9629: $type is Course (default) or Group.
 9630: If $forcedefault evaluates to true, text returned will be default 
 9631: text for $type. Otherwise, if this is a course, the text returned 
 9632: will be a custom name for the role (if defined in the course's 
 9633: environment).  If no custom name is defined the default is returned.
 9634:    
 9635: =item *
 9636: 
 9637: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9638: All arguments are optional. Returns a hash of a roles, either for
 9639: co-author/assistant author roles for a user's Construction Space
 9640: (default), or if $context is 'userroles', roles for the user himself,
 9641: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9642: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9643: For each key, value is set to colon-separated start and end times for
 9644: the role.  If no username and domain are specified, will default to
 9645: current user/domain. Types, roles, and roledoms are references to arrays
 9646: of role statuses (active, future or previous), roles 
 9647: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9648: to restrict the list of roles reported. If no array ref is 
 9649: provided for types, will default to return only active roles.
 9650: 
 9651: =back
 9652: 
 9653: =head2 User Modification
 9654: 
 9655: =over 4
 9656: 
 9657: =item *
 9658: 
 9659: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9660: user for the level given by URL.  Optional start and end dates (leave empty
 9661: string or zero for "no date")
 9662: 
 9663: =item *
 9664: 
 9665: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9666: change a users, password, possible return values are: ok,
 9667: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9668: refused
 9669: 
 9670: =item *
 9671: 
 9672: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9673: 
 9674: =item *
 9675: 
 9676: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9677:            $forceid,$desiredhome,$email,$inststatus) : 
 9678: modify user
 9679: 
 9680: =item *
 9681: 
 9682: modifystudent
 9683: 
 9684: modify a student's enrollment and identification information.
 9685: The course id is resolved based on the current users environment.  
 9686: This means the envoking user must be a course coordinator or otherwise
 9687: associated with a course.
 9688: 
 9689: This call is essentially a wrapper for lonnet::modifyuser and
 9690: lonnet::modify_student_enrollment
 9691: 
 9692: Inputs: 
 9693: 
 9694: =over 4
 9695: 
 9696: =item B<$udom> Student's loncapa domain
 9697: 
 9698: =item B<$uname> Student's loncapa login name
 9699: 
 9700: =item B<$uid> Student/Employee ID
 9701: 
 9702: =item B<$umode> Student's authentication mode
 9703: 
 9704: =item B<$upass> Student's password
 9705: 
 9706: =item B<$first> Student's first name
 9707: 
 9708: =item B<$middle> Student's middle name
 9709: 
 9710: =item B<$last> Student's last name
 9711: 
 9712: =item B<$gene> Student's generation
 9713: 
 9714: =item B<$usec> Student's section in course
 9715: 
 9716: =item B<$end> Unix time of the roles expiration
 9717: 
 9718: =item B<$start> Unix time of the roles start date
 9719: 
 9720: =item B<$forceid> If defined, allow $uid to be changed
 9721: 
 9722: =item B<$desiredhome> server to use as home server for student
 9723: 
 9724: =item B<$email> Student's permanent e-mail address
 9725: 
 9726: =item B<$type> Type of enrollment (auto or manual)
 9727: 
 9728: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9729: 
 9730: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9731: 
 9732: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9733: 
 9734: =item B<$context> role change context (shown in User Management Logs display in a course)
 9735: 
 9736: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9737: 
 9738: =back
 9739: 
 9740: =item *
 9741: 
 9742: modify_student_enrollment
 9743: 
 9744: Change a students enrollment status in a class.  The environment variable
 9745: 'role.request.course' must be defined for this function to proceed.
 9746: 
 9747: Inputs:
 9748: 
 9749: =over 4
 9750: 
 9751: =item $udom, students domain
 9752: 
 9753: =item $uname, students name
 9754: 
 9755: =item $uid, students user id
 9756: 
 9757: =item $first, students first name
 9758: 
 9759: =item $middle
 9760: 
 9761: =item $last
 9762: 
 9763: =item $gene
 9764: 
 9765: =item $usec
 9766: 
 9767: =item $end
 9768: 
 9769: =item $start
 9770: 
 9771: =item $type
 9772: 
 9773: =item $locktype
 9774: 
 9775: =item $cid
 9776: 
 9777: =item $selfenroll
 9778: 
 9779: =item $context
 9780: 
 9781: =back
 9782: 
 9783: 
 9784: =item *
 9785: 
 9786: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9787: custom role; give a custom role to a user for the level given by URL.  Specify
 9788: name and domain of role author, and role name
 9789: 
 9790: =item *
 9791: 
 9792: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9793: 
 9794: =item *
 9795: 
 9796: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9797: 
 9798: =back
 9799: 
 9800: =head2 Course Infomation
 9801: 
 9802: =over 4
 9803: 
 9804: =item *
 9805: 
 9806: coursedescription($courseid) : returns a hash of information about the
 9807: specified course id, including all environment settings for the
 9808: course, the description of the course will be in the hash under the
 9809: key 'description'
 9810: 
 9811: =item *
 9812: 
 9813: resdata($name,$domain,$type,@which) : request for current parameter
 9814: setting for a specific $type, where $type is either 'course' or 'user',
 9815: @what should be a list of parameters to ask about. This routine caches
 9816: answers for 5 minutes.
 9817: 
 9818: =item *
 9819: 
 9820: get_courseresdata($courseid, $domain) : dump the entire course resource
 9821: data base, returning a hash that is keyed by the resource name and has
 9822: values that are the resource value.  I believe that the timestamps and
 9823: versions are also returned.
 9824: 
 9825: 
 9826: =back
 9827: 
 9828: =head2 Course Modification
 9829: 
 9830: =over 4
 9831: 
 9832: =item *
 9833: 
 9834: writecoursepref($courseid,%prefs) : write preferences (environment
 9835: database) for a course
 9836: 
 9837: =item *
 9838: 
 9839: createcourse($udom,$description,$url) : make/modify course
 9840: 
 9841: =back
 9842: 
 9843: =head2 Resource Subroutines
 9844: 
 9845: =over 4
 9846: 
 9847: =item *
 9848: 
 9849: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9850: 
 9851: =item *
 9852: 
 9853: repcopy($filename) : subscribes to the requested file, and attempts to
 9854: replicate from the owning library server, Might return
 9855: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9856: 'bad_request', also attempts to grab the metadata for the
 9857: resource. Expects the local filesystem pathname
 9858: (/home/httpd/html/res/....)
 9859: 
 9860: =back
 9861: 
 9862: =head2 Resource Information
 9863: 
 9864: =over 4
 9865: 
 9866: =item *
 9867: 
 9868: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9869: a vairety of different possible values, $varname should be a request
 9870: string, and the other parameters can be used to specify who and what
 9871: one is asking about.
 9872: 
 9873: Possible values for $varname are environment.lastname (or other item
 9874: from the envirnment hash), user.name (or someother aspect about the
 9875: user), resource.0.maxtries (or some other part and parameter of a
 9876: resource)
 9877: 
 9878: =item *
 9879: 
 9880: directcondval($number) : get current value of a condition; reads from a state
 9881: string
 9882: 
 9883: =item *
 9884: 
 9885: condval($condidx) : value of condition index based on state
 9886: 
 9887: =item *
 9888: 
 9889: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9890: resource's metadata, $what should be either a specific key, or either
 9891: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9892: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9893: 
 9894: this function automatically caches all requests
 9895: 
 9896: =item *
 9897: 
 9898: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9899: network of library servers; returns file handle of where SQL and regex results
 9900: will be stored for query
 9901: 
 9902: =item *
 9903: 
 9904: symbread($filename) : return symbolic list entry (filename argument optional);
 9905: returns the data handle
 9906: 
 9907: =item *
 9908: 
 9909: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9910: a possible symb for the URL in $thisfn, and if is an encryypted
 9911: resource that the user accessed using /enc/ returns a 1 on success, 0
 9912: on failure, user must be in a course, as it assumes the existance of
 9913: the course initial hash, and uses $env('request.course.id'}
 9914: 
 9915: 
 9916: =item *
 9917: 
 9918: symbclean($symb) : removes versions numbers from a symb, returns the
 9919: cleaned symb
 9920: 
 9921: =item *
 9922: 
 9923: is_on_map($uri) : checks if the $uri is somewhere on the current
 9924: course map, user must be in a course for it to work.
 9925: 
 9926: =item *
 9927: 
 9928: numval($salt) : return random seed value (addend for rndseed)
 9929: 
 9930: =item *
 9931: 
 9932: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9933: a random seed, all arguments are optional, if they aren't sent it uses the
 9934: environment to derive them. Note: if symb isn't sent and it can't get one
 9935: from &symbread it will use the current time as its return value
 9936: 
 9937: =item *
 9938: 
 9939: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9940: unfakeable, receipt
 9941: 
 9942: =item *
 9943: 
 9944: receipt() : API to ireceipt working off of env values; given out to users
 9945: 
 9946: =item *
 9947: 
 9948: countacc($url) : count the number of accesses to a given URL
 9949: 
 9950: =item *
 9951: 
 9952: 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
 9953: 
 9954: =item *
 9955: 
 9956: 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)
 9957: 
 9958: =item *
 9959: 
 9960: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9961: 
 9962: =item *
 9963: 
 9964: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9965: forcing spreadsheet to reevaluate the resource scores next time.
 9966: 
 9967: =back
 9968: 
 9969: =head2 Storing/Retreiving Data
 9970: 
 9971: =over 4
 9972: 
 9973: =item *
 9974: 
 9975: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9976: for this url; hashref needs to be given and should be a \%hashname; the
 9977: remaining args aren't required and if they aren't passed or are '' they will
 9978: be derived from the env
 9979: 
 9980: =item *
 9981: 
 9982: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9983: uses critical subroutine
 9984: 
 9985: =item *
 9986: 
 9987: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9988: all args are optional
 9989: 
 9990: =item *
 9991: 
 9992: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9993: dumps the complete (or key matching regexp) namespace into a hash
 9994: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9995: normally &store()ed into
 9996: 
 9997: $range should be either an integer '100' (give me the first 100
 9998:                                            matching records)
 9999:               or be  two integers sperated by a - with no spaces
10000:                  '30-50' (give me the 30th through the 50th matching
10001:                           records)
10002: 
10003: 
10004: =item *
10005: 
10006: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10007: replaces a &store() version of data with a replacement set of data
10008: for a particular resource in a namespace passed in the $storehash hash 
10009: reference
10010: 
10011: =item *
10012: 
10013: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10014: works very similar to store/cstore, but all data is stored in a
10015: temporary location and can be reset using tmpreset, $storehash should
10016: be a hash reference, returns nothing on success
10017: 
10018: =item *
10019: 
10020: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10021: similar to restore, but all data is stored in a temporary location and
10022: can be reset using tmpreset. Returns a hash of values on success,
10023: error string otherwise.
10024: 
10025: =item *
10026: 
10027: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10028: deltes all keys for $symb form the temporary storage hash.
10029: 
10030: =item *
10031: 
10032: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10033: reference filled in from namesp ($udom and $uname are optional)
10034: 
10035: =item *
10036: 
10037: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10038: namesp ($udom and $uname are optional)
10039: 
10040: =item *
10041: 
10042: dump($namespace,$udom,$uname,$regexp,$range) : 
10043: dumps the complete (or key matching regexp) namespace into a hash
10044: ($udom, $uname, $regexp, $range are optional)
10045: 
10046: $range should be either an integer '100' (give me the first 100
10047:                                            matching records)
10048:               or be  two integers sperated by a - with no spaces
10049:                  '30-50' (give me the 30th through the 50th matching
10050:                           records)
10051: =item *
10052: 
10053: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10054: $store can be a scalar, an array reference, or if the amount to be 
10055: incremented is > 1, a hash reference.
10056: 
10057: ($udom and $uname are optional)
10058: 
10059: =item *
10060: 
10061: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10062: ($udom and $uname are optional)
10063: 
10064: =item *
10065: 
10066: cput($namespace,$storehash,$udom,$uname) : critical put
10067: ($udom and $uname are optional)
10068: 
10069: =item *
10070: 
10071: newput($namespace,$storehash,$udom,$uname) :
10072: 
10073: Attempts to store the items in the $storehash, but only if they don't
10074: currently exist, if this succeeds you can be certain that you have 
10075: successfully created a new key value pair in the $namespace db.
10076: 
10077: 
10078: Args:
10079:  $namespace: name of database to store values to
10080:  $storehash: hashref to store to the db
10081:  $udom: (optional) domain of user containing the db
10082:  $uname: (optional) name of user caontaining the db
10083: 
10084: Returns:
10085:  'ok' -> succeeded in storing all keys of $storehash
10086:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10087:                         least <key> already existed in the db (other
10088:                         requested keys may also already exist)
10089:  'error: <msg>' -> unable to tie the DB or other error occurred
10090:  'con_lost' -> unable to contact request server
10091:  'refused' -> action was not allowed by remote machine
10092: 
10093: 
10094: =item *
10095: 
10096: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10097: reference filled in from namesp (encrypts the return communication)
10098: ($udom and $uname are optional)
10099: 
10100: =item *
10101: 
10102: log($udom,$name,$home,$message) : write to permanent log for user; use
10103: critical subroutine
10104: 
10105: =item *
10106: 
10107: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10108: array reference filled in from namespace found in domain level on either
10109: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10110: 
10111: =item *
10112: 
10113: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10114: domain level either on specified domain server ($uhome) or primary domain 
10115: server ($udom and $uhome are optional)
10116: 
10117: =item * 
10118: 
10119: get_domain_defaults($target_domain) : returns hash with defaults for
10120: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10121: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10122: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10123: Values are retrieved from cache (if current), or from domain's configuration.db
10124: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10125: or lonTabs/domain.tab. 
10126: 
10127: %domdefaults = &get_auth_defaults($target_domain);
10128: 
10129: =back
10130: 
10131: =head2 Network Status Functions
10132: 
10133: =over 4
10134: 
10135: =item *
10136: 
10137: dirlist($uri) : return directory list based on URI
10138: 
10139: =item *
10140: 
10141: spareserver() : find server with least workload from spare.tab
10142: 
10143: 
10144: =item *
10145: 
10146: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10147: if there is no corresponding loncapa host.
10148: 
10149: =back
10150: 
10151: 
10152: =head2 Apache Request
10153: 
10154: =over 4
10155: 
10156: =item *
10157: 
10158: ssi($url,%hash) : server side include, does a complete request cycle on url to
10159: localhost, posts hash
10160: 
10161: =back
10162: 
10163: =head2 Data to String to Data
10164: 
10165: =over 4
10166: 
10167: =item *
10168: 
10169: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10170: and '&' separators, supports elements that are arrayrefs and hashrefs
10171: 
10172: =item *
10173: 
10174: hashref2str($hashref) : convert a hashref into a string complete with
10175: escaping and '=' and '&' separators, supports elements that are
10176: arrayrefs and hashrefs
10177: 
10178: =item *
10179: 
10180: arrayref2str($arrayref) : convert an arrayref into a string complete
10181: with escaping and '&' separators, supports elements that are arrayrefs
10182: and hashrefs
10183: 
10184: =item *
10185: 
10186: str2hash($string) : convert string to hash using unescaping and
10187: splitting on '=' and '&', supports elements that are arrayrefs and
10188: hashrefs
10189: 
10190: =item *
10191: 
10192: str2array($string) : convert string to hash using unescaping and
10193: splitting on '&', supports elements that are arrayrefs and hashrefs
10194: 
10195: =back
10196: 
10197: =head2 Logging Routines
10198: 
10199: =over 4
10200: 
10201: These routines allow one to make log messages in the lonnet.log and
10202: lonnet.perm logfiles.
10203: 
10204: =item *
10205: 
10206: logtouch() : make sure the logfile, lonnet.log, exists
10207: 
10208: =item *
10209: 
10210: logthis() : append message to the normal lonnet.log file, it gets
10211: preiodically rolled over and deleted.
10212: 
10213: =item *
10214: 
10215: logperm() : append a permanent message to lonnet.perm.log, this log
10216: file never gets deleted by any automated portion of the system, only
10217: messages of critical importance should go in here.
10218: 
10219: =back
10220: 
10221: =head2 General File Helper Routines
10222: 
10223: =over 4
10224: 
10225: =item *
10226: 
10227: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10228: (a) files in /uploaded
10229:   (i) If a local copy of the file exists - 
10230:       compares modification date of local copy with last-modified date for 
10231:       definitive version stored on home server for course. If local copy is 
10232:       stale, requests a new version from the home server and stores it. 
10233:       If the original has been removed from the home server, then local copy 
10234:       is unlinked.
10235:   (ii) If local copy does not exist -
10236:       requests the file from the home server and stores it. 
10237:   
10238:   If $caller is 'uploadrep':  
10239:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10240:     for request for files originally uploaded via DOCS. 
10241:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10242:   
10243:   Otherwise:
10244:      This indicates a call from the content generation phase of the request.
10245:      -  returns the entire contents of the file or -1.
10246:      
10247: (b) files in /res
10248:    - returns the entire contents of a file or -1; 
10249:    it properly subscribes to and replicates the file if neccessary.
10250: 
10251: 
10252: =item *
10253: 
10254: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10255:                   reference
10256: 
10257: returns either a stat() list of data about the file or an empty list
10258: if the file doesn't exist or couldn't find out about it (connection
10259: problems or user unknown)
10260: 
10261: =item *
10262: 
10263: filelocation($dir,$file) : returns file system location of a file
10264: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10265: directory that relative $file lookups are to looked in ($dir of /a/dir
10266: and a file of ../bob will become /a/bob)
10267: 
10268: =item *
10269: 
10270: hreflocation($dir,$file) : returns file system location or a URL; same as
10271: filelocation except for hrefs
10272: 
10273: =item *
10274: 
10275: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10276: 
10277: =back
10278: 
10279: =head2 Usererfile file routines (/uploaded*)
10280: 
10281: =over 4
10282: 
10283: =item *
10284: 
10285: userfileupload(): main rotine for putting a file in a user or course's
10286:                   filespace, arguments are,
10287: 
10288:  formname - required - this is the name of the element in $env where the
10289:            filename, and the contents of the file to create/modifed exist
10290:            the filename is in $env{'form.'.$formname.'.filename'} and the
10291:            contents of the file is located in $env{'form.'.$formname}
10292:  coursedoc - if true, store the file in the course of the active role
10293:              of the current user
10294:  subdir - required - subdirectory to put the file in under ../userfiles/
10295:          if undefined, it will be placed in "unknown"
10296: 
10297:  (This routine calls clean_filename() to remove any dangerous
10298:  characters from the filename, and then calls finuserfileupload() to
10299:  complete the transaction)
10300: 
10301:  returns either the url of the uploaded file (/uploaded/....) if successful
10302:  and /adm/notfound.html if unsuccessful
10303: 
10304: =item *
10305: 
10306: clean_filename(): routine for cleaing a filename up for storage in
10307:                  userfile space, argument is:
10308: 
10309:  filename - proposed filename
10310: 
10311: returns: the new clean filename
10312: 
10313: =item *
10314: 
10315: finishuserfileupload(): routine that creaes and sends the file to
10316: userspace, probably shouldn't be called directly
10317: 
10318:   docuname: username or courseid of destination for the file
10319:   docudom: domain of user/course of destination for the file
10320:   formname: same as for userfileupload()
10321:   fname: filename (inculding subdirectories) for the file
10322: 
10323:  returns either the url of the uploaded file (/uploaded/....) if successful
10324:  and /adm/notfound.html if unsuccessful
10325: 
10326: =item *
10327: 
10328: renameuserfile(): renames an existing userfile to a new name
10329: 
10330:   Args:
10331:    docuname: username or courseid of destination for the file
10332:    docudom: domain of user/course of destination for the file
10333:    old: current file name (including any subdirs under userfiles)
10334:    new: desired file name (including any subdirs under userfiles)
10335: 
10336: =item *
10337: 
10338: mkdiruserfile(): creates a directory is a userfiles dir
10339: 
10340:   Args:
10341:    docuname: username or courseid of destination for the file
10342:    docudom: domain of user/course of destination for the file
10343:    dir: dir to create (including any subdirs under userfiles)
10344: 
10345: =item *
10346: 
10347: removeuserfile(): removes a file that exists in userfiles
10348: 
10349:   Args:
10350:    docuname: username or courseid of destination for the file
10351:    docudom: domain of user/course of destination for the file
10352:    fname: filname to delete (including any subdirs under userfiles)
10353: 
10354: =item *
10355: 
10356: removeuploadedurl(): convience function for removeuserfile()
10357: 
10358:   Args:
10359:    url:  a full /uploaded/... url to delete
10360: 
10361: =item * 
10362: 
10363: get_portfile_permissions():
10364:   Args:
10365:     domain: domain of user or course contain the portfolio files
10366:     user: name of user or num of course contain the portfolio files
10367:   Returns:
10368:     hashref of a dump of the proper file_permissions.db
10369:    
10370: 
10371: =item * 
10372: 
10373: get_access_controls():
10374: 
10375: Args:
10376:   current_permissions: the hash ref returned from get_portfile_permissions()
10377:   group: (optional) the group you want the files associated with
10378:   file: (optional) the file you want access info on
10379: 
10380: Returns:
10381:     a hash (keys are file names) of hashes containing
10382:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10383:         values are XML containing access control settings (see below) 
10384: 
10385: Internal notes:
10386: 
10387:  access controls are stored in file_permissions.db as key=value pairs.
10388:     key -> path to file/file_name\0uniqueID:scope_end_start
10389:         where scope -> public,guest,course,group,domains or users.
10390:               end -> UNIX time for end of access (0 -> no end date)
10391:               start -> UNIX time for start of access
10392: 
10393:     value -> XML description of access control
10394:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10395:             <start></start>
10396:             <end></end>
10397: 
10398:             <password></password>  for scope type = guest
10399: 
10400:             <domain></domain>     for scope type = course or group
10401:             <number></number>
10402:             <roles id="">
10403:              <role></role>
10404:              <access></access>
10405:              <section></section>
10406:              <group></group>
10407:             </roles>
10408: 
10409:             <dom></dom>         for scope type = domains
10410: 
10411:             <users>             for scope type = users
10412:              <user>
10413:               <uname></uname>
10414:               <udom></udom>
10415:              </user>
10416:             </users>
10417:            </scope> 
10418:               
10419:  Access data is also aggregated for each file in an additional key=value pair:
10420:  key -> path to file/file_name\0accesscontrol 
10421:  value -> reference to hash
10422:           hash contains key = value pairs
10423:           where key = uniqueID:scope_end_start
10424:                 value = UNIX time record was last updated
10425: 
10426:           Used to improve speed of look-ups of access controls for each file.  
10427:  
10428:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10429: 
10430: modify_access_controls():
10431: 
10432: Modifies access controls for a portfolio file
10433: Args
10434: 1. file name
10435: 2. reference to hash of required changes,
10436: 3. domain
10437: 4. username
10438:   where domain,username are the domain of the portfolio owner 
10439:   (either a user or a course) 
10440: 
10441: Returns:
10442: 1. result of additions or updates ('ok' or 'error', with error message). 
10443: 2. result of deletions ('ok' or 'error', with error message).
10444: 3. reference to hash of any new or updated access controls.
10445: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10446:    key = integer (inbound ID)
10447:    value = uniqueID  
10448: 
10449: =back
10450: 
10451: =head2 HTTP Helper Routines
10452: 
10453: =over 4
10454: 
10455: =item *
10456: 
10457: escape() : unpack non-word characters into CGI-compatible hex codes
10458: 
10459: =item *
10460: 
10461: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10462: 
10463: =back
10464: 
10465: =head1 PRIVATE SUBROUTINES
10466: 
10467: =head2 Underlying communication routines (Shouldn't call)
10468: 
10469: =over 4
10470: 
10471: =item *
10472: 
10473: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10474: 
10475: =item *
10476: 
10477: reply() : uses subreply to send a message to remote machine, logs all failures
10478: 
10479: =item *
10480: 
10481: critical() : passes a critical message to another server; if cannot
10482: get through then place message in connection buffer directory and
10483: returns con_delayed, if incapable of saving message, returns
10484: con_failed
10485: 
10486: =item *
10487: 
10488: reconlonc() : tries to reconnect lonc client processes.
10489: 
10490: =back
10491: 
10492: =head2 Resource Access Logging
10493: 
10494: =over 4
10495: 
10496: =item *
10497: 
10498: flushcourselogs() : flush (save) buffer logs and access logs
10499: 
10500: =item *
10501: 
10502: courselog($what) : save message for course in hash
10503: 
10504: =item *
10505: 
10506: courseacclog($what) : save message for course using &courselog().  Perform
10507: special processing for specific resource types (problems, exams, quizzes, etc).
10508: 
10509: =item *
10510: 
10511: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10512: as a PerlChildExitHandler
10513: 
10514: =back
10515: 
10516: =head2 Other
10517: 
10518: =over 4
10519: 
10520: =item *
10521: 
10522: symblist($mapname,%newhash) : update symbolic storage links
10523: 
10524: =back
10525: 
10526: =cut
10527: 

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