File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1007: download - view: text, annotated - select for diffs
Sat Jul 25 15:25:18 2009 UTC (14 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- &localenroll:possible_instcodes() takes an addition arg: $code_order which indicates the order in which components of the course code should be recombined.
  - e.g., At MSU, select boxes in the course request form are in the order:
          Year Semester Department
    but the order used to create the institutional code is:
          Semester Year Department

- &lonnet::auto_get_sections()
  - $cnum arg is undefined when checking for institutional sections during the course request process.  In the is case the homeserver used to retrieve the sections is the primary library server for the domain.

- &lonnet::auto_validate_instcode() - new routine used to validate an institutional course code during course requests.
  - Note: this differs from the institutional courseID (which in the institutional code with appended institutional section).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1007 2009/07/25 15:25:18 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','community') {
 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:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 1870:        $filelink .= 'inhibitmenu=yes';
 1871:        ($output,$response)=&ssi($filelink,%form);
 1872:     }
 1873:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1874:     $output=~s/^.*?\<body[^\>]*\>//si;
 1875:     $output=~s/\<\/body\s*\>.*?$//si;
 1876:     if (wantarray) {
 1877:         return ($output, $response);
 1878:     } else {
 1879:         return $output;
 1880:     }
 1881: }
 1882: 
 1883: # --------------------------------------------------------- Server Side Include
 1884: 
 1885: sub absolute_url {
 1886:     my ($host_name) = @_;
 1887:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1888:     if ($host_name eq '') {
 1889: 	$host_name = $ENV{'SERVER_NAME'};
 1890:     }
 1891:     return $protocol.$host_name;
 1892: }
 1893: 
 1894: #
 1895: #   Server side include.
 1896: # Parameters:
 1897: #  fn     Possibly encrypted resource name/id.
 1898: #  form   Hash that describes how the rendering should be done
 1899: #         and other things.
 1900: # Returns:
 1901: #   Scalar context: The content of the response.
 1902: #   Array context:  2 element list of the content and the full response object.
 1903: #     
 1904: sub ssi {
 1905: 
 1906:     my ($fn,%form)=@_;
 1907:     my $ua=new LWP::UserAgent;
 1908:     my $request;
 1909: 
 1910:     $form{'no_update_last_known'}=1;
 1911:     &Apache::lonenc::check_encrypt(\$fn);
 1912:     if (%form) {
 1913:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1914:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1915:     } else {
 1916:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1917:     }
 1918: 
 1919:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1920:     my $response=$ua->request($request);
 1921: 
 1922:     if (wantarray) {
 1923: 	return ($response->content, $response);
 1924:     } else {
 1925: 	return $response->content;
 1926:     }
 1927: }
 1928: 
 1929: sub externalssi {
 1930:     my ($url)=@_;
 1931:     my $ua=new LWP::UserAgent;
 1932:     my $request=new HTTP::Request('GET',$url);
 1933:     my $response=$ua->request($request);
 1934:     if (wantarray) {
 1935:         return ($response->content, $response);
 1936:     } else {
 1937:         return $response->content;
 1938:     }
 1939: }
 1940: 
 1941: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1942: 
 1943: sub allowuploaded {
 1944:     my ($srcurl,$url)=@_;
 1945:     $url=&clutter(&declutter($url));
 1946:     my $dir=$url;
 1947:     $dir=~s/\/[^\/]+$//;
 1948:     my %httpref=();
 1949:     my $httpurl=&hreflocation('',$url);
 1950:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1951:     &Apache::lonnet::appenv(\%httpref);
 1952: }
 1953: 
 1954: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1955: # input: action, courseID, current domain, intended
 1956: #        path to file, source of file, instruction to parse file for objects,
 1957: #        ref to hash for embedded objects,
 1958: #        ref to hash for codebase of java objects.
 1959: #
 1960: # output: url to file (if action was uploaddoc), 
 1961: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1962: #
 1963: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1964: # course.
 1965: #
 1966: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1967: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1968: #          course's home server.
 1969: #
 1970: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1971: #          be copied from $source (current location) to 
 1972: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1973: #         and will then be copied to
 1974: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1975: #         course's home server.
 1976: #
 1977: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1978: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1979: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1980: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1981: #         in course's home server.
 1982: #
 1983: 
 1984: sub process_coursefile {
 1985:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1986:     my $fetchresult;
 1987:     my $home=&homeserver($docuname,$docudom);
 1988:     if ($action eq 'propagate') {
 1989:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1990: 			     $home);
 1991:     } else {
 1992:         my $fpath = '';
 1993:         my $fname = $file;
 1994:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1995:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1996:         my $filepath = &build_filepath($fpath);
 1997:         if ($action eq 'copy') {
 1998:             if ($source eq '') {
 1999:                 $fetchresult = 'no source file';
 2000:                 return $fetchresult;
 2001:             } else {
 2002:                 my $destination = $filepath.'/'.$fname;
 2003:                 rename($source,$destination);
 2004:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2005:                                  $home);
 2006:             }
 2007:         } elsif ($action eq 'uploaddoc') {
 2008:             open(my $fh,'>'.$filepath.'/'.$fname);
 2009:             print $fh $env{'form.'.$source};
 2010:             close($fh);
 2011:             if ($parser eq 'parse') {
 2012:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2013:                 unless ($parse_result eq 'ok') {
 2014:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2015:                 }
 2016:             }
 2017:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2018:                                  $home);
 2019:             if ($fetchresult eq 'ok') {
 2020:                 return '/uploaded/'.$fpath.'/'.$fname;
 2021:             } else {
 2022:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2023:                         ' to host '.$home.': '.$fetchresult);
 2024:                 return '/adm/notfound.html';
 2025:             }
 2026:         }
 2027:     }
 2028:     unless ( $fetchresult eq 'ok') {
 2029:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2030:              ' to host '.$home.': '.$fetchresult);
 2031:     }
 2032:     return $fetchresult;
 2033: }
 2034: 
 2035: sub build_filepath {
 2036:     my ($fpath) = @_;
 2037:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2038:     unless ($fpath eq '') {
 2039:         my @parts=split('/',$fpath);
 2040:         foreach my $part (@parts) {
 2041:             $filepath.= '/'.$part;
 2042:             if ((-e $filepath)!=1) {
 2043:                 mkdir($filepath,0777);
 2044:             }
 2045:         }
 2046:     }
 2047:     return $filepath;
 2048: }
 2049: 
 2050: sub store_edited_file {
 2051:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2052:     my $file = $primary_url;
 2053:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2054:     my $fpath = '';
 2055:     my $fname = $file;
 2056:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2057:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2058:     my $filepath = &build_filepath($fpath);
 2059:     open(my $fh,'>'.$filepath.'/'.$fname);
 2060:     print $fh $content;
 2061:     close($fh);
 2062:     my $home=&homeserver($docuname,$docudom);
 2063:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2064: 			  $home);
 2065:     if ($$fetchresult eq 'ok') {
 2066:         return '/uploaded/'.$fpath.'/'.$fname;
 2067:     } else {
 2068:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2069: 		 ' to host '.$home.': '.$$fetchresult);
 2070:         return '/adm/notfound.html';
 2071:     }
 2072: }
 2073: 
 2074: sub clean_filename {
 2075:     my ($fname,$args)=@_;
 2076: # Replace Windows backslashes by forward slashes
 2077:     $fname=~s/\\/\//g;
 2078:     if (!$args->{'keep_path'}) {
 2079:         # Get rid of everything but the actual filename
 2080: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2081:     }
 2082: # Replace spaces by underscores
 2083:     $fname=~s/\s+/\_/g;
 2084: # Replace all other weird characters by nothing
 2085:     $fname=~s{[^/\w\.\-]}{}g;
 2086: # Replace all .\d. sequences with _\d. so they no longer look like version
 2087: # numbers
 2088:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2089:     return $fname;
 2090: }
 2091: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2092: sub resizeImage {
 2093: 	my($img_url) = @_;	
 2094: 	my $ima = Image::Magick->new;                       
 2095:         $ima->Read($img_url);
 2096: 	if($ima->Get('width') > 400)
 2097: 	{
 2098: 		my $factor = $ima->Get('width')/400;
 2099:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2100: 	}
 2101: 	if($ima->Get('height') > 500)
 2102:         {
 2103:         	my $factor = $ima->Get('height')/500;
 2104:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2105:         } 
 2106: 		
 2107: 	$ima->Write($img_url);
 2108: }
 2109: 
 2110: #Wrapper function for userphotoupload
 2111: sub userphotoupload
 2112: {
 2113: 	my($formname,$subdir) = @_;
 2114: 	$upload_photo_form = 1;
 2115: 	return &userfileupload($formname,undef,$subdir);
 2116: }
 2117: 
 2118: # --------------- Take an uploaded file and put it into the userfiles directory
 2119: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2120: #                    the desired filenam is in $env{"form.$formname.filename"}
 2121: #        $coursedoc - if true up to the current course
 2122: #                     if false
 2123: #        $subdir - directory in userfile to store the file into
 2124: #        $parser - instruction to parse file for objects ($parser = parse)    
 2125: #        $allfiles - reference to hash for embedded objects
 2126: #        $codebase - reference to hash for codebase of java objects
 2127: #        $desuname - username for permanent storage of uploaded file
 2128: #        $dsetudom - domain for permanaent storage of uploaded file
 2129: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2130: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2131: # 
 2132: # output: url of file in userspace, or error: <message> 
 2133: #             or /adm/notfound.html if failure to upload occurse
 2134: 
 2135: 
 2136: sub userfileupload {
 2137:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2138:         $destudom,$thumbwidth,$thumbheight)=@_;
 2139:     if (!defined($subdir)) { $subdir='unknown'; }
 2140:     my $fname=$env{'form.'.$formname.'.filename'};
 2141:     $fname=&clean_filename($fname);
 2142: # See if there is anything left
 2143:     unless ($fname) { return 'error: no uploaded file'; }
 2144:     chop($env{'form.'.$formname});
 2145:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2146:         my $now = time;
 2147:         my $filepath = 'tmp/helprequests/'.$now;
 2148:         my @parts=split(/\//,$filepath);
 2149:         my $fullpath = $perlvar{'lonDaemons'};
 2150:         for (my $i=0;$i<@parts;$i++) {
 2151:             $fullpath .= '/'.$parts[$i];
 2152:             if ((-e $fullpath)!=1) {
 2153:                 mkdir($fullpath,0777);
 2154:             }
 2155:         }
 2156:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2157:         print $fh $env{'form.'.$formname};
 2158:         close($fh);
 2159:         return $fullpath.'/'.$fname;
 2160:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2161:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2162:                        '_'.$env{'user.domain'}.'/pending';
 2163:         my @parts=split(/\//,$filepath);
 2164:         my $fullpath = $perlvar{'lonDaemons'};
 2165:         for (my $i=0;$i<@parts;$i++) {
 2166:             $fullpath .= '/'.$parts[$i];
 2167:             if ((-e $fullpath)!=1) {
 2168:                 mkdir($fullpath,0777);
 2169:             }
 2170:         }
 2171:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2172:         print $fh $env{'form.'.$formname};
 2173:         close($fh);
 2174:         return $fullpath.'/'.$fname;
 2175:     }
 2176:     if ($subdir eq 'scantron') {
 2177:         $fname = 'scantron_orig_'.$fname;
 2178:     } else {   
 2179: # Create the directory if not present
 2180:         $fname="$subdir/$fname";
 2181:     }
 2182:     if ($coursedoc) {
 2183: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2184: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2185:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2186:             return &finishuserfileupload($docuname,$docudom,
 2187: 					 $formname,$fname,$parser,$allfiles,
 2188: 					 $codebase,$thumbwidth,$thumbheight);
 2189:         } else {
 2190:             $fname=$env{'form.folder'}.'/'.$fname;
 2191:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2192: 				       $fname,$formname,$parser,
 2193: 				       $allfiles,$codebase);
 2194:         }
 2195:     } elsif (defined($destuname)) {
 2196:         my $docuname=$destuname;
 2197:         my $docudom=$destudom;
 2198: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2199: 				     $parser,$allfiles,$codebase,
 2200:                                      $thumbwidth,$thumbheight);
 2201:         
 2202:     } else {
 2203:         my $docuname=$env{'user.name'};
 2204:         my $docudom=$env{'user.domain'};
 2205:         if (exists($env{'form.group'})) {
 2206:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2207:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2208:         }
 2209: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2210: 				     $parser,$allfiles,$codebase,
 2211:                                      $thumbwidth,$thumbheight);
 2212:     }
 2213: }
 2214: 
 2215: sub finishuserfileupload {
 2216:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2217:         $thumbwidth,$thumbheight) = @_;
 2218:     my $path=$docudom.'/'.$docuname.'/';
 2219:     my $filepath=$perlvar{'lonDocRoot'};
 2220:   
 2221:     my ($fnamepath,$file,$fetchthumb);
 2222:     $file=$fname;
 2223:     if ($fname=~m|/|) {
 2224:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2225: 	$path.=$fnamepath.'/';
 2226:     }
 2227:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2228:     my $count;
 2229:     for ($count=4;$count<=$#parts;$count++) {
 2230:         $filepath.="/$parts[$count]";
 2231:         if ((-e $filepath)!=1) {
 2232: 	    mkdir($filepath,0777);
 2233:         }
 2234:     }
 2235: 
 2236: # Save the file
 2237:     {
 2238: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2239: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2240: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2241: 	    return '/adm/notfound.html';
 2242: 	}
 2243: 	if (!print FH ($env{'form.'.$formname})) {
 2244: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2245: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2246: 	    return '/adm/notfound.html';
 2247: 	}
 2248: 	close(FH);
 2249: 	if($upload_photo_form==1)
 2250: 	{
 2251: 		resizeImage($filepath.'/'.$file);		
 2252: 		$upload_photo_form = 0;
 2253: 	}
 2254:     }
 2255:     if ($parser eq 'parse') {
 2256:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2257: 						   $codebase);
 2258:         unless ($parse_result eq 'ok') {
 2259:             &logthis('Failed to parse '.$filepath.$file.
 2260: 		     ' for embedded media: '.$parse_result); 
 2261:         }
 2262:     }
 2263:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2264:         my $input = $filepath.'/'.$file;
 2265:         my $output = $filepath.'/'.'tn-'.$file;
 2266:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2267:         system("convert -sample $thumbsize $input $output");
 2268:         if (-e $filepath.'/'.'tn-'.$file) {
 2269:             $fetchthumb  = 1; 
 2270:         }
 2271:     }
 2272:  
 2273: # Notify homeserver to grep it
 2274: #
 2275:     my $docuhome=&homeserver($docuname,$docudom);	
 2276:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2277:     if ($fetchresult eq 'ok') {
 2278:         if ($fetchthumb) {
 2279:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2280:             if ($thumbresult ne 'ok') {
 2281:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2282:                          $docuhome.': '.$thumbresult);
 2283:             }
 2284:         }
 2285: #
 2286: # Return the URL to it
 2287:         return '/uploaded/'.$path.$file;
 2288:     } else {
 2289:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2290: 		 ': '.$fetchresult);
 2291:         return '/adm/notfound.html';
 2292:     }
 2293: }
 2294: 
 2295: sub extract_embedded_items {
 2296:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2297:     my @state = ();
 2298:     my %javafiles = (
 2299:                       codebase => '',
 2300:                       code => '',
 2301:                       archive => ''
 2302:                     );
 2303:     my %mediafiles = (
 2304:                       src => '',
 2305:                       movie => '',
 2306:                      );
 2307:     my $p;
 2308:     if ($content) {
 2309:         $p = HTML::LCParser->new($content);
 2310:     } else {
 2311:         $p = HTML::LCParser->new($fullpath);
 2312:     }
 2313:     while (my $t=$p->get_token()) {
 2314: 	if ($t->[0] eq 'S') {
 2315: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2316: 	    push(@state, $tagname);
 2317:             if (lc($tagname) eq 'allow') {
 2318:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2319:             }
 2320: 	    if (lc($tagname) eq 'img') {
 2321: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2322: 	    }
 2323: 	    if (lc($tagname) eq 'a') {
 2324: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2325: 	    }
 2326:             if (lc($tagname) eq 'script') {
 2327:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2328:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2329:                 } else {
 2330:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2331:                 }
 2332:             }
 2333:             if (lc($tagname) eq 'link') {
 2334:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2335:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2336:                 }
 2337:             }
 2338: 	    if (lc($tagname) eq 'object' ||
 2339: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2340: 		foreach my $item (keys(%javafiles)) {
 2341: 		    $javafiles{$item} = '';
 2342: 		}
 2343: 	    }
 2344: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2345: 		my $name = lc($attr->{'name'});
 2346: 		foreach my $item (keys(%javafiles)) {
 2347: 		    if ($name eq $item) {
 2348: 			$javafiles{$item} = $attr->{'value'};
 2349: 			last;
 2350: 		    }
 2351: 		}
 2352: 		foreach my $item (keys(%mediafiles)) {
 2353: 		    if ($name eq $item) {
 2354: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2355: 			last;
 2356: 		    }
 2357: 		}
 2358: 	    }
 2359: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2360: 		foreach my $item (keys(%javafiles)) {
 2361: 		    if ($attr->{$item}) {
 2362: 			$javafiles{$item} = $attr->{$item};
 2363: 			last;
 2364: 		    }
 2365: 		}
 2366: 		foreach my $item (keys(%mediafiles)) {
 2367: 		    if ($attr->{$item}) {
 2368: 			&add_filetype($allfiles,$attr->{$item},$item);
 2369: 			last;
 2370: 		    }
 2371: 		}
 2372: 	    }
 2373: 	} elsif ($t->[0] eq 'E') {
 2374: 	    my ($tagname) = ($t->[1]);
 2375: 	    if ($javafiles{'codebase'} ne '') {
 2376: 		$javafiles{'codebase'} .= '/';
 2377: 	    }  
 2378: 	    if (lc($tagname) eq 'applet' ||
 2379: 		lc($tagname) eq 'object' ||
 2380: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2381: 		) {
 2382: 		foreach my $item (keys(%javafiles)) {
 2383: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2384: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2385: 			&add_filetype($allfiles,$file,$item);
 2386: 		    }
 2387: 		}
 2388: 	    } 
 2389: 	    pop @state;
 2390: 	}
 2391:     }
 2392:     return 'ok';
 2393: }
 2394: 
 2395: sub add_filetype {
 2396:     my ($allfiles,$file,$type)=@_;
 2397:     if (exists($allfiles->{$file})) {
 2398: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2399: 	    push(@{$allfiles->{$file}}, &escape($type));
 2400: 	}
 2401:     } else {
 2402: 	@{$allfiles->{$file}} = (&escape($type));
 2403:     }
 2404: }
 2405: 
 2406: sub removeuploadedurl {
 2407:     my ($url)=@_;	
 2408:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2409:     return &removeuserfile($uname,$udom,$fname);
 2410: }
 2411: 
 2412: sub removeuserfile {
 2413:     my ($docuname,$docudom,$fname)=@_;
 2414:     my $home=&homeserver($docuname,$docudom);    
 2415:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2416:     if ($result eq 'ok') {	
 2417:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2418:             my $metafile = $fname.'.meta';
 2419:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2420: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2421:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2422:             my $sqlresult = 
 2423:                 &update_portfolio_table($docuname,$docudom,$file,
 2424:                                         'portfolio_metadata',$group,
 2425:                                         'delete');
 2426:         }
 2427:     }
 2428:     return $result;
 2429: }
 2430: 
 2431: sub mkdiruserfile {
 2432:     my ($docuname,$docudom,$dir)=@_;
 2433:     my $home=&homeserver($docuname,$docudom);
 2434:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2435: }
 2436: 
 2437: sub renameuserfile {
 2438:     my ($docuname,$docudom,$old,$new)=@_;
 2439:     my $home=&homeserver($docuname,$docudom);
 2440:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2441:                         &escape("$old").':'.&escape("$new"),$home);
 2442:     if ($result eq 'ok') {
 2443:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2444:             my $oldmeta = $old.'.meta';
 2445:             my $newmeta = $new.'.meta';
 2446:             my $metaresult = 
 2447:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2448: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2449:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2450:             my $sqlresult = 
 2451:                 &update_portfolio_table($docuname,$docudom,$file,
 2452:                                         'portfolio_metadata',$group,
 2453:                                         'delete');
 2454:         }
 2455:     }
 2456:     return $result;
 2457: }
 2458: 
 2459: # ------------------------------------------------------------------------- Log
 2460: 
 2461: sub log {
 2462:     my ($dom,$nam,$hom,$what)=@_;
 2463:     return critical("log:$dom:$nam:$what",$hom);
 2464: }
 2465: 
 2466: # ------------------------------------------------------------------ Course Log
 2467: #
 2468: # This routine flushes several buffers of non-mission-critical nature
 2469: #
 2470: 
 2471: sub flushcourselogs {
 2472:     &logthis('Flushing log buffers');
 2473: #
 2474: # course logs
 2475: # This is a log of all transactions in a course, which can be used
 2476: # for data mining purposes
 2477: #
 2478: # It also collects the courseid database, which lists last transaction
 2479: # times and course titles for all courseids
 2480: #
 2481:     my %courseidbuffer=();
 2482:     foreach my $crsid (keys(%courselogs)) {
 2483:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2484: 		          &escape($courselogs{$crsid}),
 2485: 		          $coursehombuf{$crsid}) eq 'ok') {
 2486: 	    delete $courselogs{$crsid};
 2487:         } else {
 2488:             &logthis('Failed to flush log buffer for '.$crsid);
 2489:             if (length($courselogs{$crsid})>40000) {
 2490:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2491:                         " exceeded maximum size, deleting.</font>");
 2492:                delete $courselogs{$crsid};
 2493:             }
 2494:         }
 2495:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2496:             'description' => $coursedescrbuf{$crsid},
 2497:             'inst_code'    => $courseinstcodebuf{$crsid},
 2498:             'type'        => $coursetypebuf{$crsid},
 2499:             'owner'       => $courseownerbuf{$crsid},
 2500:         };
 2501:     }
 2502: #
 2503: # Write course id database (reverse lookup) to homeserver of courses 
 2504: # Is used in pickcourse
 2505: #
 2506:     foreach my $crs_home (keys(%courseidbuffer)) {
 2507:         my $response = &courseidput(&host_domain($crs_home),
 2508:                                     $courseidbuffer{$crs_home},
 2509:                                     $crs_home,'timeonly');
 2510:     }
 2511: #
 2512: # File accesses
 2513: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2514: #
 2515:     foreach my $entry (keys(%accesshash)) {
 2516:         if ($entry =~ /___count$/) {
 2517:             my ($dom,$name);
 2518:             ($dom,$name,undef)=
 2519: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2520:             if (! defined($dom) || $dom eq '' || 
 2521:                 ! defined($name) || $name eq '') {
 2522:                 my $cid = $env{'request.course.id'};
 2523:                 $dom  = $env{'request.'.$cid.'.domain'};
 2524:                 $name = $env{'request.'.$cid.'.num'};
 2525:             }
 2526:             my $value = $accesshash{$entry};
 2527:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2528:             my %temphash=($url => $value);
 2529:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2530:             if ($result eq 'ok') {
 2531:                 delete $accesshash{$entry};
 2532:             } elsif ($result eq 'unknown_cmd') {
 2533:                 # Target server has old code running on it.
 2534:                 my %temphash=($entry => $value);
 2535:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2536:                     delete $accesshash{$entry};
 2537:                 }
 2538:             }
 2539:         } else {
 2540:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2541:             my %temphash=($entry => $accesshash{$entry});
 2542:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2543:                 delete $accesshash{$entry};
 2544:             }
 2545:         }
 2546:     }
 2547: #
 2548: # Roles
 2549: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2550: #
 2551:     foreach my $entry (keys(%userrolehash)) {
 2552:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2553: 	    split(/\:/,$entry);
 2554:         if (&Apache::lonnet::put('nohist_userroles',
 2555:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2556:                 $rudom,$runame) eq 'ok') {
 2557: 	    delete $userrolehash{$entry};
 2558:         }
 2559:     }
 2560: #
 2561: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2562: #
 2563:     my %domrolebuffer = ();
 2564:     foreach my $entry (keys(%domainrolehash)) {
 2565:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2566:         if ($domrolebuffer{$rudom}) {
 2567:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2568:                       '='.&escape($domainrolehash{$entry});
 2569:         } else {
 2570:             $domrolebuffer{$rudom}.=&escape($entry).
 2571:                       '='.&escape($domainrolehash{$entry});
 2572:         }
 2573:         delete $domainrolehash{$entry};
 2574:     }
 2575:     foreach my $dom (keys(%domrolebuffer)) {
 2576: 	my %servers = &get_servers($dom,'library');
 2577: 	foreach my $tryserver (keys(%servers)) {
 2578: 	    unless (&reply('domroleput:'.$dom.':'.
 2579: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2580: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2581: 	    }
 2582:         }
 2583:     }
 2584:     $dumpcount++;
 2585: }
 2586: 
 2587: sub courselog {
 2588:     my $what=shift;
 2589:     $what=time.':'.$what;
 2590:     unless ($env{'request.course.id'}) { return ''; }
 2591:     $coursedombuf{$env{'request.course.id'}}=
 2592:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2593:     $coursenumbuf{$env{'request.course.id'}}=
 2594:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2595:     $coursehombuf{$env{'request.course.id'}}=
 2596:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2597:     $coursedescrbuf{$env{'request.course.id'}}=
 2598:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2599:     $courseinstcodebuf{$env{'request.course.id'}}=
 2600:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2601:     $courseownerbuf{$env{'request.course.id'}}=
 2602:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2603:     $coursetypebuf{$env{'request.course.id'}}=
 2604:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2605:     if (defined $courselogs{$env{'request.course.id'}}) {
 2606: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2607:     } else {
 2608: 	$courselogs{$env{'request.course.id'}}.=$what;
 2609:     }
 2610:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2611: 	&flushcourselogs();
 2612:     }
 2613: }
 2614: 
 2615: sub courseacclog {
 2616:     my $fnsymb=shift;
 2617:     unless ($env{'request.course.id'}) { return ''; }
 2618:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2619:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2620:         $what.=':POST';
 2621:         # FIXME: Probably ought to escape things....
 2622: 	foreach my $key (keys(%env)) {
 2623:             if ($key=~/^form\.(.*)/) {
 2624:                 my $formitem = $1;
 2625:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2626:                     $what.=':'.$formitem.'='.$env{$key};
 2627:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2628:                     $what.=':'.$formitem.'='.$env{$key};
 2629:                 }
 2630:             }
 2631:         }
 2632:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2633:         # FIXME: We should not be depending on a form parameter that someone
 2634:         # editing lonsearchcat.pm might change in the future.
 2635:         if ($env{'form.phase'} eq 'course_search') {
 2636:             $what.= ':POST';
 2637:             # FIXME: Probably ought to escape things....
 2638:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2639:                                  'crsdiscuss') {
 2640:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2641:             }
 2642:         }
 2643:     }
 2644:     &courselog($what);
 2645: }
 2646: 
 2647: sub countacc {
 2648:     my $url=&declutter(shift);
 2649:     return if (! defined($url) || $url eq '');
 2650:     unless ($env{'request.course.id'}) { return ''; }
 2651:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2652:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2653:     $accesshash{$key}++;
 2654: }
 2655: 
 2656: sub linklog {
 2657:     my ($from,$to)=@_;
 2658:     $from=&declutter($from);
 2659:     $to=&declutter($to);
 2660:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2661:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2662: }
 2663:   
 2664: sub userrolelog {
 2665:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2666:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2667:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2668:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2669:         ($trole=~/^ta/)) {
 2670:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2671:        $userrolehash
 2672:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2673:                     =$tend.':'.$tstart;
 2674:     }
 2675:     if (($env{'request.role'} =~ /dc\./) &&
 2676: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2677: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2678: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2679:        $userrolehash
 2680:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2681:                     =$tend.':'.$tstart;
 2682:     }
 2683:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2684:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2685:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2686:         ($trole=~/^sc/)) {
 2687:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2688:        $domainrolehash
 2689:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2690:                     = $tend.':'.$tstart;
 2691:     }
 2692: }
 2693: 
 2694: sub courserolelog {
 2695:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2696:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2697:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2698:         ($trole eq 'ta') || ($trole eq 'st') ||
 2699:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2700:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2701:             my $cdom = $1;
 2702:             my $cnum = $2;
 2703:             my $sec = $3;
 2704:             my $namespace = 'rolelog';
 2705:             my %storehash = (
 2706:                                role    => $trole,
 2707:                                start   => $tstart,
 2708:                                end     => $tend,
 2709:                                selfenroll => $selfenroll,
 2710:                                context    => $context,
 2711:                             );
 2712:             if ($trole eq 'gr') {
 2713:                 $namespace = 'groupslog';
 2714:                 $storehash{'group'} = $sec;
 2715:             } else {
 2716:                 $storehash{'section'} = $sec;
 2717:             }
 2718:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2719:             if (($trole ne 'st') || ($sec ne '')) {
 2720:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2721:             }
 2722:         }
 2723:     }
 2724:     return;
 2725: }
 2726: 
 2727: sub get_course_adv_roles {
 2728:     my ($cid,$codes) = @_;
 2729:     $cid=$env{'request.course.id'} unless (defined($cid));
 2730:     my %coursehash=&coursedescription($cid);
 2731:     my $crstype = &Apache::loncommon::course_type($cid);
 2732:     my %nothide=();
 2733:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2734:         if ($user !~ /:/) {
 2735: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2736:         } else {
 2737:             $nothide{$user}=1;
 2738:         }
 2739:     }
 2740:     my %returnhash=();
 2741:     my %dumphash=
 2742:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2743:     my $now=time;
 2744:     my %privileged;
 2745:     foreach my $entry (keys(%dumphash)) {
 2746: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2747:         if (($tstart) && ($tstart<0)) { next; }
 2748:         if (($tend) && ($tend<$now)) { next; }
 2749:         if (($tstart) && ($now<$tstart)) { next; }
 2750:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2751: 	if ($username eq '' || $domain eq '') { next; }
 2752:         unless (ref($privileged{$domain}) eq 'HASH') {
 2753:             my %dompersonnel =
 2754:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2755:             $privileged{$domain} = {};
 2756:             foreach my $server (keys(%dompersonnel)) {
 2757:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2758:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2759:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2760:                         $privileged{$udom}{$uname} = 1;
 2761:                     }
 2762:                 }
 2763:             }
 2764:         }
 2765:         if ((exists($privileged{$domain}{$username})) && 
 2766:             (!$nothide{$username.':'.$domain})) { next; }
 2767: 	if ($role eq 'cr') { next; }
 2768:         if ($codes) {
 2769:             if ($section) { $role .= ':'.$section; }
 2770:             if ($returnhash{$role}) {
 2771:                 $returnhash{$role}.=','.$username.':'.$domain;
 2772:             } else {
 2773:                 $returnhash{$role}=$username.':'.$domain;
 2774:             }
 2775:         } else {
 2776:             my $key=&plaintext($role,$crstype);
 2777:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2778:             if ($returnhash{$key}) {
 2779: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2780:             } else {
 2781:                 $returnhash{$key}=$username.':'.$domain;
 2782:             }
 2783:         }
 2784:     }
 2785:     return %returnhash;
 2786: }
 2787: 
 2788: sub get_my_roles {
 2789:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2790:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2791:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2792:     my (%dumphash,%nothide);
 2793:     if ($context eq 'userroles') { 
 2794:         %dumphash = &dump('roles',$udom,$uname);
 2795:     } else {
 2796:         %dumphash=
 2797:             &dump('nohist_userroles',$udom,$uname);
 2798:         if ($hidepriv) {
 2799:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2800:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2801:                 if ($user !~ /:/) {
 2802:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2803:                 } else {
 2804:                     $nothide{$user} = 1;
 2805:                 }
 2806:             }
 2807:         }
 2808:     }
 2809:     my %returnhash=();
 2810:     my $now=time;
 2811:     my %privileged;
 2812:     foreach my $entry (keys(%dumphash)) {
 2813:         my ($role,$tend,$tstart);
 2814:         if ($context eq 'userroles') {
 2815: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2816:         } else {
 2817:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2818:         }
 2819:         if (($tstart) && ($tstart<0)) { next; }
 2820:         my $status = 'active';
 2821:         if (($tend) && ($tend<=$now)) {
 2822:             $status = 'previous';
 2823:         } 
 2824:         if (($tstart) && ($now<$tstart)) {
 2825:             $status = 'future';
 2826:         }
 2827:         if (ref($types) eq 'ARRAY') {
 2828:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2829:                 next;
 2830:             } 
 2831:         } else {
 2832:             if ($status ne 'active') {
 2833:                 next;
 2834:             }
 2835:         }
 2836:         my ($rolecode,$username,$domain,$section,$area);
 2837:         if ($context eq 'userroles') {
 2838:             ($area,$rolecode) = split(/_/,$entry);
 2839:             (undef,$domain,$username,$section) = split(/\//,$area);
 2840:         } else {
 2841:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2842:         }
 2843:         if (ref($roledoms) eq 'ARRAY') {
 2844:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2845:                 next;
 2846:             }
 2847:         }
 2848:         if (ref($roles) eq 'ARRAY') {
 2849:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2850:                 if ($role =~ /^cr\//) {
 2851:                     if (!grep(/^cr$/,@{$roles})) {
 2852:                         next;
 2853:                     }
 2854:                 } else {
 2855:                     next;
 2856:                 }
 2857:             }
 2858:         }
 2859:         if ($hidepriv) {
 2860:             if ($context eq 'userroles') {
 2861:                 if ((&privileged($username,$domain)) &&
 2862:                     (!$nothide{$username.':'.$domain})) {
 2863:                     next;
 2864:                 }
 2865:             } else {
 2866:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2867:                     my %dompersonnel =
 2868:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2869:                     $privileged{$domain} = {};
 2870:                     if (keys(%dompersonnel)) {
 2871:                         foreach my $server (keys(%dompersonnel)) {
 2872:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2873:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2874:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2875:                                     $privileged{$udom}{$uname} = $trole;
 2876:                                 }
 2877:                             }
 2878:                         }
 2879:                     }
 2880:                 }
 2881:                 if (exists($privileged{$domain}{$username})) {
 2882:                     if (!$nothide{$username.':'.$domain}) {
 2883:                         next;
 2884:                     }
 2885:                 }
 2886:             }
 2887:         }
 2888:         if ($withsec) {
 2889:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2890:                 $tstart.':'.$tend;
 2891:         } else {
 2892:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2893:         }
 2894:     }
 2895:     return %returnhash;
 2896: }
 2897: 
 2898: # ----------------------------------------------------- Frontpage Announcements
 2899: #
 2900: #
 2901: 
 2902: sub postannounce {
 2903:     my ($server,$text)=@_;
 2904:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2905:     unless ($text=~/\w/) { $text=''; }
 2906:     return &reply('setannounce:'.&escape($text),$server);
 2907: }
 2908: 
 2909: sub getannounce {
 2910: 
 2911:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2912: 	my $announcement='';
 2913: 	while (my $line = <$fh>) { $announcement .= $line; }
 2914: 	close($fh);
 2915: 	if ($announcement=~/\w/) { 
 2916: 	    return 
 2917:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2918:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2919: 	} else {
 2920: 	    return '';
 2921: 	}
 2922:     } else {
 2923: 	return '';
 2924:     }
 2925: }
 2926: 
 2927: # ---------------------------------------------------------- Course ID routines
 2928: # Deal with domain's nohist_courseid.db files
 2929: #
 2930: 
 2931: sub courseidput {
 2932:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2933:     my $outcome;
 2934:     if ($caller eq 'timeonly') {
 2935:         my $cids = '';
 2936:         foreach my $item (keys(%$storehash)) {
 2937:             $cids.=&escape($item).'&';
 2938:         }
 2939:         $cids=~s/\&$//;
 2940:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2941:                           $coursehome);       
 2942:     } else {
 2943:         my $items = '';
 2944:         foreach my $item (keys(%$storehash)) {
 2945:             $items.= &escape($item).'='.
 2946:                      &freeze_escape($$storehash{$item}).'&';
 2947:         }
 2948:         $items=~s/\&$//;
 2949:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2950:                           $coursehome);
 2951:     }
 2952:     if ($outcome eq 'unknown_cmd') {
 2953:         my $what;
 2954:         foreach my $cid (keys(%$storehash)) {
 2955:             $what .= &escape($cid).'=';
 2956:             foreach my $item ('description','inst_code','owner','type') {
 2957:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2958:             }
 2959:             $what =~ s/\:$/&/;
 2960:         }
 2961:         $what =~ s/\&$//;  
 2962:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2963:     } else {
 2964:         return $outcome;
 2965:     }
 2966: }
 2967: 
 2968: sub courseiddump {
 2969:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2970:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2971:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2972:     my $as_hash = 1;
 2973:     my %returnhash;
 2974:     if (!$domfilter) { $domfilter=''; }
 2975:     my %libserv = &all_library();
 2976:     foreach my $tryserver (keys(%libserv)) {
 2977:         if ( (  $hostidflag == 1 
 2978: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2979: 	     || (!defined($hostidflag)) ) {
 2980: 
 2981: 	    if (($domfilter eq '') ||
 2982: 		(&host_domain($tryserver) eq $domfilter)) {
 2983:                 my $rep = 
 2984:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2985:                          $sincefilter.':'.&escape($descfilter).':'.
 2986:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2987:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2988:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2989:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2990:                          $showhidden.':'.$caller,$tryserver);
 2991:                 my @pairs=split(/\&/,$rep);
 2992:                 foreach my $item (@pairs) {
 2993:                     my ($key,$value)=split(/\=/,$item,2);
 2994:                     $key = &unescape($key);
 2995:                     next if ($key =~ /^error: 2 /);
 2996:                     my $result = &thaw_unescape($value);
 2997:                     if (ref($result) eq 'HASH') {
 2998:                         $returnhash{$key}=$result;
 2999:                     } else {
 3000:                         my @responses = split(/:/,$value);
 3001:                         my @items = ('description','inst_code','owner','type');
 3002:                         for (my $i=0; $i<@responses; $i++) {
 3003:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3004:                         }
 3005:                     } 
 3006:                 }
 3007:             }
 3008:         }
 3009:     }
 3010:     return %returnhash;
 3011: }
 3012: 
 3013: # ---------------------------------------------------------- DC e-mail
 3014: 
 3015: sub dcmailput {
 3016:     my ($domain,$msgid,$message,$server)=@_;
 3017:     my $status = &Apache::lonnet::critical(
 3018:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3019:        &escape($message),$server);
 3020:     return $status;
 3021: }
 3022: 
 3023: sub dcmaildump {
 3024:     my ($dom,$startdate,$enddate,$senders) = @_;
 3025:     my %returnhash=();
 3026: 
 3027:     if (defined(&domain($dom,'primary'))) {
 3028:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3029:                                                          &escape($enddate).':';
 3030: 	my @esc_senders=map { &escape($_)} @$senders;
 3031: 	$cmd.=&escape(join('&',@esc_senders));
 3032: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3033:             my ($key,$value) = split(/\=/,$line,2);
 3034:             if (($key) && ($value)) {
 3035:                 $returnhash{&unescape($key)} = &unescape($value);
 3036:             }
 3037:         }
 3038:     }
 3039:     return %returnhash;
 3040: }
 3041: # ---------------------------------------------------------- Domain roles
 3042: 
 3043: sub get_domain_roles {
 3044:     my ($dom,$roles,$startdate,$enddate)=@_;
 3045:     if (undef($startdate) || $startdate eq '') {
 3046:         $startdate = '.';
 3047:     }
 3048:     if (undef($enddate) || $enddate eq '') {
 3049:         $enddate = '.';
 3050:     }
 3051:     my $rolelist;
 3052:     if (ref($roles) eq 'ARRAY') {
 3053:         $rolelist = join(':',@{$roles});
 3054:     }
 3055:     my %personnel = ();
 3056: 
 3057:     my %servers = &get_servers($dom,'library');
 3058:     foreach my $tryserver (keys(%servers)) {
 3059: 	%{$personnel{$tryserver}}=();
 3060: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3061: 					    &escape($startdate).':'.
 3062: 					    &escape($enddate).':'.
 3063: 					    &escape($rolelist), $tryserver))) {
 3064: 	    my ($key,$value) = split(/\=/,$line,2);
 3065: 	    if (($key) && ($value)) {
 3066: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3067: 	    }
 3068: 	}
 3069:     }
 3070:     return %personnel;
 3071: }
 3072: 
 3073: # ----------------------------------------------------------- Check out an item
 3074: 
 3075: sub get_first_access {
 3076:     my ($type,$argsymb)=@_;
 3077:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3078:     if ($argsymb) { $symb=$argsymb; }
 3079:     my ($map,$id,$res)=&decode_symb($symb);
 3080:     if ($type eq 'course') {
 3081: 	$res='course';
 3082:     } elsif ($type eq 'map') {
 3083: 	$res=&symbread($map);
 3084:     } else {
 3085: 	$res=$symb;
 3086:     }
 3087:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3088:     return $times{"$courseid\0$res"};
 3089: }
 3090: 
 3091: sub set_first_access {
 3092:     my ($type)=@_;
 3093:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3094:     my ($map,$id,$res)=&decode_symb($symb);
 3095:     if ($type eq 'course') {
 3096: 	$res='course';
 3097:     } elsif ($type eq 'map') {
 3098: 	$res=&symbread($map);
 3099:     } else {
 3100: 	$res=$symb;
 3101:     }
 3102:     my $firstaccess=&get_first_access($type,$symb);
 3103:     if (!$firstaccess) {
 3104: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3105:     }
 3106:     return 'already_set';
 3107: }
 3108: 
 3109: sub checkout {
 3110:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3111:     my $now=time;
 3112:     my $lonhost=$perlvar{'lonHostID'};
 3113:     my $infostr=&escape(
 3114:                  'CHECKOUTTOKEN&'.
 3115:                  $tuname.'&'.
 3116:                  $tudom.'&'.
 3117:                  $tcrsid.'&'.
 3118:                  $symb.'&'.
 3119: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3120:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3121:     if ($token=~/^error\:/) { 
 3122:         &logthis("<font color=\"blue\">WARNING: ".
 3123:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3124:                  "</font>");
 3125:         return ''; 
 3126:     }
 3127: 
 3128:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3129:     $token=~tr/a-z/A-Z/;
 3130: 
 3131:     my %infohash=('resource.0.outtoken' => $token,
 3132:                   'resource.0.checkouttime' => $now,
 3133:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3134: 
 3135:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3136:        return '';
 3137:     } else {
 3138:         &logthis("<font color=\"blue\">WARNING: ".
 3139:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3140:                  "</font>");
 3141:     }    
 3142: 
 3143:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3144:                          &escape('Checkout '.$infostr.' - '.
 3145:                                                  $token)) ne 'ok') {
 3146: 	return '';
 3147:     } else {
 3148:         &logthis("<font color=\"blue\">WARNING: ".
 3149:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3150:                  "</font>");
 3151:     }
 3152:     return $token;
 3153: }
 3154: 
 3155: # ------------------------------------------------------------ Check in an item
 3156: 
 3157: sub checkin {
 3158:     my $token=shift;
 3159:     my $now=time;
 3160:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3161:     $lonhost=~tr/A-Z/a-z/;
 3162:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3163:     $dtoken=~s/\W/\_/g;
 3164:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3165:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3166: 
 3167:     unless (($tuname) && ($tudom)) {
 3168:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3169:         return '';
 3170:     }
 3171:     
 3172:     unless (&allowed('mgr',$tcrsid)) {
 3173:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3174:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3175:         return '';
 3176:     }
 3177: 
 3178:     my %infohash=('resource.0.intoken' => $token,
 3179:                   'resource.0.checkintime' => $now,
 3180:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3181: 
 3182:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3183:        return '';
 3184:     }    
 3185: 
 3186:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3187:                          &escape('Checkin - '.$token)) ne 'ok') {
 3188: 	return '';
 3189:     }
 3190: 
 3191:     return ($symb,$tuname,$tudom,$tcrsid);    
 3192: }
 3193: 
 3194: # --------------------------------------------- Set Expire Date for Spreadsheet
 3195: 
 3196: sub expirespread {
 3197:     my ($uname,$udom,$stype,$usymb)=@_;
 3198:     my $cid=$env{'request.course.id'}; 
 3199:     if ($cid) {
 3200:        my $now=time;
 3201:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3202:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3203:                             $env{'course.'.$cid.'.num'}.
 3204: 	        	    ':nohist_expirationdates:'.
 3205:                             &escape($key).'='.$now,
 3206:                             $env{'course.'.$cid.'.home'})
 3207:     }
 3208:     return 'ok';
 3209: }
 3210: 
 3211: # ----------------------------------------------------- Devalidate Spreadsheets
 3212: 
 3213: sub devalidate {
 3214:     my ($symb,$uname,$udom)=@_;
 3215:     my $cid=$env{'request.course.id'}; 
 3216:     if ($cid) {
 3217:         # delete the stored spreadsheets for
 3218:         # - the student level sheet of this user in course's homespace
 3219:         # - the assessment level sheet for this resource 
 3220:         #   for this user in user's homespace
 3221: 	# - current conditional state info
 3222: 	my $key=$uname.':'.$udom.':';
 3223:         my $status=
 3224: 	    &del('nohist_calculatedsheets',
 3225: 		 [$key.'studentcalc:'],
 3226: 		 $env{'course.'.$cid.'.domain'},
 3227: 		 $env{'course.'.$cid.'.num'})
 3228: 		.' '.
 3229: 	    &del('nohist_calculatedsheets_'.$cid,
 3230: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3231:         unless ($status eq 'ok ok') {
 3232:            &logthis('Could not devalidate spreadsheet '.
 3233:                     $uname.' at '.$udom.' for '.
 3234: 		    $symb.': '.$status);
 3235:         }
 3236: 	&delenv('user.state.'.$cid);
 3237:     }
 3238: }
 3239: 
 3240: sub get_scalar {
 3241:     my ($string,$end) = @_;
 3242:     my $value;
 3243:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3244: 	$value = $1;
 3245:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3246: 	$value = $1;
 3247:     }
 3248:     return &unescape($value);
 3249: }
 3250: 
 3251: sub array2str {
 3252:   my (@array) = @_;
 3253:   my $result=&arrayref2str(\@array);
 3254:   $result=~s/^__ARRAY_REF__//;
 3255:   $result=~s/__END_ARRAY_REF__$//;
 3256:   return $result;
 3257: }
 3258: 
 3259: sub arrayref2str {
 3260:   my ($arrayref) = @_;
 3261:   my $result='__ARRAY_REF__';
 3262:   foreach my $elem (@$arrayref) {
 3263:     if(ref($elem) eq 'ARRAY') {
 3264:       $result.=&arrayref2str($elem).'&';
 3265:     } elsif(ref($elem) eq 'HASH') {
 3266:       $result.=&hashref2str($elem).'&';
 3267:     } elsif(ref($elem)) {
 3268:       #print("Got a ref of ".(ref($elem))." skipping.");
 3269:     } else {
 3270:       $result.=&escape($elem).'&';
 3271:     }
 3272:   }
 3273:   $result=~s/\&$//;
 3274:   $result .= '__END_ARRAY_REF__';
 3275:   return $result;
 3276: }
 3277: 
 3278: sub hash2str {
 3279:   my (%hash) = @_;
 3280:   my $result=&hashref2str(\%hash);
 3281:   $result=~s/^__HASH_REF__//;
 3282:   $result=~s/__END_HASH_REF__$//;
 3283:   return $result;
 3284: }
 3285: 
 3286: sub hashref2str {
 3287:   my ($hashref)=@_;
 3288:   my $result='__HASH_REF__';
 3289:   foreach my $key (sort(keys(%$hashref))) {
 3290:     if (ref($key) eq 'ARRAY') {
 3291:       $result.=&arrayref2str($key).'=';
 3292:     } elsif (ref($key) eq 'HASH') {
 3293:       $result.=&hashref2str($key).'=';
 3294:     } elsif (ref($key)) {
 3295:       $result.='=';
 3296:       #print("Got a ref of ".(ref($key))." skipping.");
 3297:     } else {
 3298: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3299:     }
 3300: 
 3301:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3302:       $result.=&arrayref2str($hashref->{$key}).'&';
 3303:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3304:       $result.=&hashref2str($hashref->{$key}).'&';
 3305:     } elsif(ref($hashref->{$key})) {
 3306:        $result.='&';
 3307:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3308:     } else {
 3309:       $result.=&escape($hashref->{$key}).'&';
 3310:     }
 3311:   }
 3312:   $result=~s/\&$//;
 3313:   $result .= '__END_HASH_REF__';
 3314:   return $result;
 3315: }
 3316: 
 3317: sub str2hash {
 3318:     my ($string)=@_;
 3319:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3320:     return %$hash;
 3321: }
 3322: 
 3323: sub str2hashref {
 3324:   my ($string) = @_;
 3325: 
 3326:   my %hash;
 3327: 
 3328:   if($string !~ /^__HASH_REF__/) {
 3329:       if (! ($string eq '' || !defined($string))) {
 3330: 	  $hash{'error'}='Not hash reference';
 3331:       }
 3332:       return (\%hash, $string);
 3333:   }
 3334: 
 3335:   $string =~ s/^__HASH_REF__//;
 3336: 
 3337:   while($string !~ /^__END_HASH_REF__/) {
 3338:       #key
 3339:       my $key='';
 3340:       if($string =~ /^__HASH_REF__/) {
 3341:           ($key, $string)=&str2hashref($string);
 3342:           if(defined($key->{'error'})) {
 3343:               $hash{'error'}='Bad data';
 3344:               return (\%hash, $string);
 3345:           }
 3346:       } elsif($string =~ /^__ARRAY_REF__/) {
 3347:           ($key, $string)=&str2arrayref($string);
 3348:           if($key->[0] eq 'Array reference error') {
 3349:               $hash{'error'}='Bad data';
 3350:               return (\%hash, $string);
 3351:           }
 3352:       } else {
 3353:           $string =~ s/^(.*?)=//;
 3354: 	  $key=&unescape($1);
 3355:       }
 3356:       $string =~ s/^=//;
 3357: 
 3358:       #value
 3359:       my $value='';
 3360:       if($string =~ /^__HASH_REF__/) {
 3361:           ($value, $string)=&str2hashref($string);
 3362:           if(defined($value->{'error'})) {
 3363:               $hash{'error'}='Bad data';
 3364:               return (\%hash, $string);
 3365:           }
 3366:       } elsif($string =~ /^__ARRAY_REF__/) {
 3367:           ($value, $string)=&str2arrayref($string);
 3368:           if($value->[0] eq 'Array reference error') {
 3369:               $hash{'error'}='Bad data';
 3370:               return (\%hash, $string);
 3371:           }
 3372:       } else {
 3373: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3374:       }
 3375:       $string =~ s/^&//;
 3376: 
 3377:       $hash{$key}=$value;
 3378:   }
 3379: 
 3380:   $string =~ s/^__END_HASH_REF__//;
 3381: 
 3382:   return (\%hash, $string);
 3383: }
 3384: 
 3385: sub str2array {
 3386:     my ($string)=@_;
 3387:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3388:     return @$array;
 3389: }
 3390: 
 3391: sub str2arrayref {
 3392:   my ($string) = @_;
 3393:   my @array;
 3394: 
 3395:   if($string !~ /^__ARRAY_REF__/) {
 3396:       if (! ($string eq '' || !defined($string))) {
 3397: 	  $array[0]='Array reference error';
 3398:       }
 3399:       return (\@array, $string);
 3400:   }
 3401: 
 3402:   $string =~ s/^__ARRAY_REF__//;
 3403: 
 3404:   while($string !~ /^__END_ARRAY_REF__/) {
 3405:       my $value='';
 3406:       if($string =~ /^__HASH_REF__/) {
 3407:           ($value, $string)=&str2hashref($string);
 3408:           if(defined($value->{'error'})) {
 3409:               $array[0] ='Array reference error';
 3410:               return (\@array, $string);
 3411:           }
 3412:       } elsif($string =~ /^__ARRAY_REF__/) {
 3413:           ($value, $string)=&str2arrayref($string);
 3414:           if($value->[0] eq 'Array reference error') {
 3415:               $array[0] ='Array reference error';
 3416:               return (\@array, $string);
 3417:           }
 3418:       } else {
 3419: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3420:       }
 3421:       $string =~ s/^&//;
 3422: 
 3423:       push(@array, $value);
 3424:   }
 3425: 
 3426:   $string =~ s/^__END_ARRAY_REF__//;
 3427: 
 3428:   return (\@array, $string);
 3429: }
 3430: 
 3431: # -------------------------------------------------------------------Temp Store
 3432: 
 3433: sub tmpreset {
 3434:   my ($symb,$namespace,$domain,$stuname) = @_;
 3435:   if (!$symb) {
 3436:     $symb=&symbread();
 3437:     if (!$symb) { $symb= $env{'request.url'}; }
 3438:   }
 3439:   $symb=escape($symb);
 3440: 
 3441:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3442:   $namespace=~s/\//\_/g;
 3443:   $namespace=~s/\W//g;
 3444: 
 3445:   if (!$domain) { $domain=$env{'user.domain'}; }
 3446:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3447:   if ($domain eq 'public' && $stuname eq 'public') {
 3448:       $stuname=$ENV{'REMOTE_ADDR'};
 3449:   }
 3450:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3451:   my %hash;
 3452:   if (tie(%hash,'GDBM_File',
 3453: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3454: 	  &GDBM_WRCREAT(),0640)) {
 3455:     foreach my $key (keys(%hash)) {
 3456:       if ($key=~ /:$symb/) {
 3457: 	delete($hash{$key});
 3458:       }
 3459:     }
 3460:   }
 3461: }
 3462: 
 3463: sub tmpstore {
 3464:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3465: 
 3466:   if (!$symb) {
 3467:     $symb=&symbread();
 3468:     if (!$symb) { $symb= $env{'request.url'}; }
 3469:   }
 3470:   $symb=escape($symb);
 3471: 
 3472:   if (!$namespace) {
 3473:     # I don't think we would ever want to store this for a course.
 3474:     # it seems this will only be used if we don't have a course.
 3475:     #$namespace=$env{'request.course.id'};
 3476:     #if (!$namespace) {
 3477:       $namespace=$env{'request.state'};
 3478:     #}
 3479:   }
 3480:   $namespace=~s/\//\_/g;
 3481:   $namespace=~s/\W//g;
 3482:   if (!$domain) { $domain=$env{'user.domain'}; }
 3483:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3484:   if ($domain eq 'public' && $stuname eq 'public') {
 3485:       $stuname=$ENV{'REMOTE_ADDR'};
 3486:   }
 3487:   my $now=time;
 3488:   my %hash;
 3489:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3490:   if (tie(%hash,'GDBM_File',
 3491: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3492: 	  &GDBM_WRCREAT(),0640)) {
 3493:     $hash{"version:$symb"}++;
 3494:     my $version=$hash{"version:$symb"};
 3495:     my $allkeys=''; 
 3496:     foreach my $key (keys(%$storehash)) {
 3497:       $allkeys.=$key.':';
 3498:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3499:     }
 3500:     $hash{"$version:$symb:timestamp"}=$now;
 3501:     $allkeys.='timestamp';
 3502:     $hash{"$version:keys:$symb"}=$allkeys;
 3503:     if (untie(%hash)) {
 3504:       return 'ok';
 3505:     } else {
 3506:       return "error:$!";
 3507:     }
 3508:   } else {
 3509:     return "error:$!";
 3510:   }
 3511: }
 3512: 
 3513: # -----------------------------------------------------------------Temp Restore
 3514: 
 3515: sub tmprestore {
 3516:   my ($symb,$namespace,$domain,$stuname) = @_;
 3517: 
 3518:   if (!$symb) {
 3519:     $symb=&symbread();
 3520:     if (!$symb) { $symb= $env{'request.url'}; }
 3521:   }
 3522:   $symb=escape($symb);
 3523: 
 3524:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3525: 
 3526:   if (!$domain) { $domain=$env{'user.domain'}; }
 3527:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3528:   if ($domain eq 'public' && $stuname eq 'public') {
 3529:       $stuname=$ENV{'REMOTE_ADDR'};
 3530:   }
 3531:   my %returnhash;
 3532:   $namespace=~s/\//\_/g;
 3533:   $namespace=~s/\W//g;
 3534:   my %hash;
 3535:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3536:   if (tie(%hash,'GDBM_File',
 3537: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3538: 	  &GDBM_READER(),0640)) {
 3539:     my $version=$hash{"version:$symb"};
 3540:     $returnhash{'version'}=$version;
 3541:     my $scope;
 3542:     for ($scope=1;$scope<=$version;$scope++) {
 3543:       my $vkeys=$hash{"$scope:keys:$symb"};
 3544:       my @keys=split(/:/,$vkeys);
 3545:       my $key;
 3546:       $returnhash{"$scope:keys"}=$vkeys;
 3547:       foreach $key (@keys) {
 3548: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3549: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3550:       }
 3551:     }
 3552:     if (!(untie(%hash))) {
 3553:       return "error:$!";
 3554:     }
 3555:   } else {
 3556:     return "error:$!";
 3557:   }
 3558:   return %returnhash;
 3559: }
 3560: 
 3561: # ----------------------------------------------------------------------- Store
 3562: 
 3563: sub store {
 3564:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3565:     my $home='';
 3566: 
 3567:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3568: 
 3569:     $symb=&symbclean($symb);
 3570:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3571: 
 3572:     if (!$domain) { $domain=$env{'user.domain'}; }
 3573:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3574: 
 3575:     &devalidate($symb,$stuname,$domain);
 3576: 
 3577:     $symb=escape($symb);
 3578:     if (!$namespace) { 
 3579:        unless ($namespace=$env{'request.course.id'}) { 
 3580:           return ''; 
 3581:        } 
 3582:     }
 3583:     if (!$home) { $home=$env{'user.home'}; }
 3584: 
 3585:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3586:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3587: 
 3588:     my $namevalue='';
 3589:     foreach my $key (keys(%$storehash)) {
 3590:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3591:     }
 3592:     $namevalue=~s/\&$//;
 3593:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3594:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3595: }
 3596: 
 3597: # -------------------------------------------------------------- Critical Store
 3598: 
 3599: sub cstore {
 3600:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3601:     my $home='';
 3602: 
 3603:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3604: 
 3605:     $symb=&symbclean($symb);
 3606:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3607: 
 3608:     if (!$domain) { $domain=$env{'user.domain'}; }
 3609:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3610: 
 3611:     &devalidate($symb,$stuname,$domain);
 3612: 
 3613:     $symb=escape($symb);
 3614:     if (!$namespace) { 
 3615:        unless ($namespace=$env{'request.course.id'}) { 
 3616:           return ''; 
 3617:        } 
 3618:     }
 3619:     if (!$home) { $home=$env{'user.home'}; }
 3620: 
 3621:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3622:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3623: 
 3624:     my $namevalue='';
 3625:     foreach my $key (keys(%$storehash)) {
 3626:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3627:     }
 3628:     $namevalue=~s/\&$//;
 3629:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3630:     return critical
 3631:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3632: }
 3633: 
 3634: # --------------------------------------------------------------------- Restore
 3635: 
 3636: sub restore {
 3637:     my ($symb,$namespace,$domain,$stuname) = @_;
 3638:     my $home='';
 3639: 
 3640:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3641: 
 3642:     if (!$symb) {
 3643:       unless ($symb=escape(&symbread())) { return ''; }
 3644:     } else {
 3645:       $symb=&escape(&symbclean($symb));
 3646:     }
 3647:     if (!$namespace) { 
 3648:        unless ($namespace=$env{'request.course.id'}) { 
 3649:           return ''; 
 3650:        } 
 3651:     }
 3652:     if (!$domain) { $domain=$env{'user.domain'}; }
 3653:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3654:     if (!$home) { $home=$env{'user.home'}; }
 3655:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3656: 
 3657:     my %returnhash=();
 3658:     foreach my $line (split(/\&/,$answer)) {
 3659: 	my ($name,$value)=split(/\=/,$line);
 3660:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3661:     }
 3662:     my $version;
 3663:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3664:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3665:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3666:        }
 3667:     }
 3668:     return %returnhash;
 3669: }
 3670: 
 3671: # ---------------------------------------------------------- Course Description
 3672: 
 3673: sub coursedescription {
 3674:     my ($courseid,$args)=@_;
 3675:     $courseid=~s/^\///;
 3676:     $courseid=~s/\_/\//g;
 3677:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3678:     my $chome=&homeserver($cnum,$cdomain);
 3679:     my $normalid=$cdomain.'_'.$cnum;
 3680:     # need to always cache even if we get errors otherwise we keep 
 3681:     # trying and trying and trying to get the course description.
 3682:     my %envhash=();
 3683:     my %returnhash=();
 3684:     
 3685:     my $expiretime=600;
 3686:     if ($env{'request.course.id'} eq $normalid) {
 3687: 	$expiretime=120;
 3688:     }
 3689: 
 3690:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3691:     if (!$args->{'freshen_cache'}
 3692: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3693: 	foreach my $key (keys(%env)) {
 3694: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3695: 	    my ($setting) = $1;
 3696: 	    $returnhash{$setting} = $env{$key};
 3697: 	}
 3698: 	return %returnhash;
 3699:     }
 3700: 
 3701:     # get the data agin
 3702:     if (!$args->{'one_time'}) {
 3703: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3704:     }
 3705: 
 3706:     if ($chome ne 'no_host') {
 3707:        %returnhash=&dump('environment',$cdomain,$cnum);
 3708:        if (!exists($returnhash{'con_lost'})) {
 3709:            $returnhash{'home'}= $chome;
 3710: 	   $returnhash{'domain'} = $cdomain;
 3711: 	   $returnhash{'num'} = $cnum;
 3712:            if (!defined($returnhash{'type'})) {
 3713:                $returnhash{'type'} = 'Course';
 3714:            }
 3715:            while (my ($name,$value) = each %returnhash) {
 3716:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3717:            }
 3718:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3719:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3720: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3721:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3722:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3723:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3724:        }
 3725:     }
 3726:     if (!$args->{'one_time'}) {
 3727: 	&appenv(\%envhash);
 3728:     }
 3729:     return %returnhash;
 3730: }
 3731: 
 3732: # -------------------------------------------------See if a user is privileged
 3733: 
 3734: sub privileged {
 3735:     my ($username,$domain)=@_;
 3736:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3737: 			&homeserver($username,$domain));
 3738:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3739:     my $now=time;
 3740:     if ($rolesdump ne '') {
 3741:         foreach my $entry (split(/&/,$rolesdump)) {
 3742: 	    if ($entry!~/^rolesdef_/) {
 3743: 		my ($area,$role)=split(/=/,$entry);
 3744: 		$area=~s/\_\w\w$//;
 3745: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3746: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3747: 		    my $active=1;
 3748: 		    if ($tend) {
 3749: 			if ($tend<$now) { $active=0; }
 3750: 		    }
 3751: 		    if ($tstart) {
 3752: 			if ($tstart>$now) { $active=0; }
 3753: 		    }
 3754: 		    if ($active) { return 1; }
 3755: 		}
 3756: 	    }
 3757: 	}
 3758:     }
 3759:     return 0;
 3760: }
 3761: 
 3762: # -------------------------------------------------------- Get user privileges
 3763: 
 3764: sub rolesinit {
 3765:     my ($domain,$username,$authhost)=@_;
 3766:     my %userroles;
 3767:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3768:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3769:     my %allroles=();
 3770:     my %allgroups=();   
 3771:     my $now=time;
 3772:     %userroles = ('user.login.time' => $now);
 3773:     my $group_privs;
 3774: 
 3775:     if ($rolesdump ne '') {
 3776:         foreach my $entry (split(/&/,$rolesdump)) {
 3777: 	  if ($entry!~/^rolesdef_/) {
 3778:             my ($area,$role)=split(/=/,$entry);
 3779: 	    $area=~s/\_\w\w$//;
 3780:             my ($trole,$tend,$tstart,$group_privs);
 3781: 	    if ($role=~/^cr/) { 
 3782: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3783: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3784: 		    ($tend,$tstart)=split('_',$trest);
 3785: 		} else {
 3786: 		    $trole=$role;
 3787: 		}
 3788:             } elsif ($role =~ m|^gr/|) {
 3789:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3790:                 ($trole,$group_privs) = split(/\//,$trole);
 3791:                 $group_privs = &unescape($group_privs);
 3792: 	    } else {
 3793: 		($trole,$tend,$tstart)=split(/_/,$role);
 3794: 	    }
 3795: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3796: 					 $username);
 3797: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3798:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3799:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3800:             if (($area ne '') && ($trole ne '')) {
 3801: 		my $spec=$trole.'.'.$area;
 3802: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3803: 		if ($trole =~ /^cr\//) {
 3804:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3805:                 } elsif ($trole eq 'gr') {
 3806:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3807: 		} else {
 3808:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3809: 		}
 3810:             }
 3811:           }
 3812:         }
 3813:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3814:         $userroles{'user.adv'}    = $adv;
 3815: 	$userroles{'user.author'} = $author;
 3816:         $env{'user.adv'}=$adv;
 3817:     }
 3818:     return \%userroles;  
 3819: }
 3820: 
 3821: sub set_arearole {
 3822:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3823: # log the associated role with the area
 3824:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3825:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3826: }
 3827: 
 3828: sub custom_roleprivs {
 3829:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3830:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3831:     my $homsvr=homeserver($rauthor,$rdomain);
 3832:     if (&hostname($homsvr) ne '') {
 3833:         my ($rdummy,$roledef)=
 3834:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3835:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3836:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3837:             if (defined($syspriv)) {
 3838:                 $$allroles{'cm./'}.=':'.$syspriv;
 3839:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3840:             }
 3841:             if ($tdomain ne '') {
 3842:                 if (defined($dompriv)) {
 3843:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3844:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3845:                 }
 3846:                 if (($trest ne '') && (defined($coursepriv))) {
 3847:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3848:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3849:                 }
 3850:             }
 3851:         }
 3852:     }
 3853: }
 3854: 
 3855: sub group_roleprivs {
 3856:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3857:     my $access = 1;
 3858:     my $now = time;
 3859:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3860:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3861:     if ($access) {
 3862:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3863:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3864:     }
 3865: }
 3866: 
 3867: sub standard_roleprivs {
 3868:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3869:     if (defined($pr{$trole.':s'})) {
 3870:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3871:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3872:     }
 3873:     if ($tdomain ne '') {
 3874:         if (defined($pr{$trole.':d'})) {
 3875:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3876:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3877:         }
 3878:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3879:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3880:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3881:         }
 3882:     }
 3883: }
 3884: 
 3885: sub set_userprivs {
 3886:     my ($userroles,$allroles,$allgroups) = @_; 
 3887:     my $author=0;
 3888:     my $adv=0;
 3889:     my %grouproles = ();
 3890:     if (keys(%{$allgroups}) > 0) {
 3891:         foreach my $role (keys(%{$allroles})) {
 3892:             my ($trole,$area,$sec,$extendedarea);
 3893:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3894:                 $trole = $1;
 3895:                 $area = $2;
 3896:                 $sec = $3;
 3897:                 $extendedarea = $area.$sec;
 3898:                 if (exists($$allgroups{$area})) {
 3899:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3900:                         my $spec = $trole.'.'.$extendedarea;
 3901:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3902:                                                 $$allgroups{$area}{$group};
 3903:                     }
 3904:                 }
 3905:             }
 3906:         }
 3907:     }
 3908:     foreach my $group (keys(%grouproles)) {
 3909:         $$allroles{$group} = $grouproles{$group};
 3910:     }
 3911:     foreach my $role (keys(%{$allroles})) {
 3912:         my %thesepriv;
 3913:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3914:         foreach my $item (split(/:/,$$allroles{$role})) {
 3915:             if ($item ne '') {
 3916:                 my ($privilege,$restrictions)=split(/&/,$item);
 3917:                 if ($restrictions eq '') {
 3918:                     $thesepriv{$privilege}='F';
 3919:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3920:                     $thesepriv{$privilege}.=$restrictions;
 3921:                 }
 3922:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3923:             }
 3924:         }
 3925:         my $thesestr='';
 3926:         foreach my $priv (keys(%thesepriv)) {
 3927: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3928: 	}
 3929:         $userroles->{'user.priv.'.$role} = $thesestr;
 3930:     }
 3931:     return ($author,$adv);
 3932: }
 3933: 
 3934: sub role_status {
 3935:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 3936:     my @pwhere = ();
 3937:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 3938:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 3939:         unless (!defined($$role) || $$role eq '') {
 3940:             $$where=join('.',@pwhere);
 3941:             $$trolecode=$$role.'.'.$$where;
 3942:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 3943:             $$tstatus='is';
 3944:             if ($$tstart && $$tstart>$then) {
 3945:                 $$tstatus='future';
 3946:                 if ($$tstart && $$tstart>$refresh) {
 3947:                     if ($$tstart<$now) {
 3948:                         if (($$where ne '') && ($$role ne '')) {
 3949:                             my (%allroles,%allgroups,$group_privs);
 3950:                             my %userroles = (
 3951:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 3952:                             );
 3953:                             my $spec=$$role.'.'.$$where;
 3954:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 3955:                             if ($$role eq 'gr') {
 3956:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 3957:                                                     $env{'user.name'})=@_;
 3958:                                 my ($trole) = split('_',$role,1);
 3959:                                 (undef,my $group_privs) = split(/\//,$trole);
 3960:                                 $group_privs = &unescape($group_privs);
 3961:                             }
 3962:                             if ($$role =~ /^cr\//) {
 3963:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 3964:                             } elsif ($$role eq 'gr') {
 3965:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 3966:                                                     $env{'user.name'});
 3967:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 3968:                                 (undef,my $group_privs) = split(/\//,$trole);
 3969:                                 $group_privs = &unescape($group_privs);
 3970:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 3971:                             } else {
 3972:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 3973:                             }
 3974:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3975:                             &appenv(\%userroles,[$$role,'cm']);
 3976:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 3977:                             $$tstatus = 'is';
 3978:                         }
 3979:                     }
 3980:                 }
 3981:             }
 3982:             if ($$tend) {
 3983:                 if ($$tend<$then) {
 3984:                     $$tstatus='expired';
 3985:                 } elsif ($$tend<$now) {
 3986:                     $$tstatus='will_not';
 3987:                 }
 3988:             }
 3989:         }
 3990:     }
 3991: }
 3992: 
 3993: sub check_adhoc_privs {
 3994:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 3995:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 3996:     if ($env{$cckey}) {
 3997:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 3998:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 3999:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4000:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4001:         }
 4002:     } else {
 4003:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4004:     }
 4005: }
 4006: 
 4007: sub set_adhoc_privileges {
 4008: # role can be cc or ca
 4009:     my ($dcdom,$pickedcourse,$role) = @_;
 4010:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4011:     my $spec = $role.'.'.$area;
 4012:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4013:                                   $env{'user.name'});
 4014:     my %ccrole = ();
 4015:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4016:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4017:     &appenv(\%userroles,[$role,'cm']);
 4018:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4019:     &appenv( {'request.role'        => $spec,
 4020:               'request.role.domain' => $dcdom,
 4021:               'request.course.sec'  => ''
 4022:              }
 4023:            );
 4024:     my $tadv=0;
 4025:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4026:     &appenv({'request.role.adv'    => $tadv});
 4027: }
 4028: 
 4029: # --------------------------------------------------------------- get interface
 4030: 
 4031: sub get {
 4032:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4033:    my $items='';
 4034:    foreach my $item (@$storearr) {
 4035:        $items.=&escape($item).'&';
 4036:    }
 4037:    $items=~s/\&$//;
 4038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4039:    if (!$uname) { $uname=$env{'user.name'}; }
 4040:    my $uhome=&homeserver($uname,$udomain);
 4041: 
 4042:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4043:    my @pairs=split(/\&/,$rep);
 4044:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4045:      return @pairs;
 4046:    }
 4047:    my %returnhash=();
 4048:    my $i=0;
 4049:    foreach my $item (@$storearr) {
 4050:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4051:       $i++;
 4052:    }
 4053:    return %returnhash;
 4054: }
 4055: 
 4056: # --------------------------------------------------------------- del interface
 4057: 
 4058: sub del {
 4059:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4060:    my $items='';
 4061:    foreach my $item (@$storearr) {
 4062:        $items.=&escape($item).'&';
 4063:    }
 4064: 
 4065:    $items=~s/\&$//;
 4066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4067:    if (!$uname) { $uname=$env{'user.name'}; }
 4068:    my $uhome=&homeserver($uname,$udomain);
 4069:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4070: }
 4071: 
 4072: # -------------------------------------------------------------- dump interface
 4073: 
 4074: sub dump {
 4075:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4076:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4077:     if (!$uname) { $uname=$env{'user.name'}; }
 4078:     my $uhome=&homeserver($uname,$udomain);
 4079:     if ($regexp) {
 4080: 	$regexp=&escape($regexp);
 4081:     } else {
 4082: 	$regexp='.';
 4083:     }
 4084:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4085:     my @pairs=split(/\&/,$rep);
 4086:     my %returnhash=();
 4087:     foreach my $item (@pairs) {
 4088: 	my ($key,$value)=split(/=/,$item,2);
 4089: 	$key = &unescape($key);
 4090: 	next if ($key =~ /^error: 2 /);
 4091: 	$returnhash{$key}=&thaw_unescape($value);
 4092:     }
 4093:     return %returnhash;
 4094: }
 4095: 
 4096: # --------------------------------------------------------- dumpstore interface
 4097: 
 4098: sub dumpstore {
 4099:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4100:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4101:    if (!$uname) { $uname=$env{'user.name'}; }
 4102:    my $uhome=&homeserver($uname,$udomain);
 4103:    if ($regexp) {
 4104:        $regexp=&escape($regexp);
 4105:    } else {
 4106:        $regexp='.';
 4107:    }
 4108:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4109:    my @pairs=split(/\&/,$rep);
 4110:    my %returnhash=();
 4111:    foreach my $item (@pairs) {
 4112:        my ($key,$value)=split(/=/,$item,2);
 4113:        next if ($key =~ /^error: 2 /);
 4114:        $returnhash{$key}=&thaw_unescape($value);
 4115:    }
 4116:    return %returnhash;
 4117: }
 4118: 
 4119: # -------------------------------------------------------------- keys interface
 4120: 
 4121: sub getkeys {
 4122:    my ($namespace,$udomain,$uname)=@_;
 4123:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4124:    if (!$uname) { $uname=$env{'user.name'}; }
 4125:    my $uhome=&homeserver($uname,$udomain);
 4126:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4127:    my @keyarray=();
 4128:    foreach my $key (split(/\&/,$rep)) {
 4129:       next if ($key =~ /^error: 2 /);
 4130:       push(@keyarray,&unescape($key));
 4131:    }
 4132:    return @keyarray;
 4133: }
 4134: 
 4135: # --------------------------------------------------------------- currentdump
 4136: sub currentdump {
 4137:    my ($courseid,$sdom,$sname)=@_;
 4138:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4139:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4140:    $sname    = $env{'user.name'}         if (! defined($sname));
 4141:    my $uhome = &homeserver($sname,$sdom);
 4142:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4143:    return if ($rep =~ /^(error:|no_such_host)/);
 4144:    #
 4145:    my %returnhash=();
 4146:    #
 4147:    if ($rep eq "unknown_cmd") { 
 4148:        # an old lond will not know currentdump
 4149:        # Do a dump and make it look like a currentdump
 4150:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4151:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4152:        my %hash = @tmp;
 4153:        @tmp=();
 4154:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4155:    } else {
 4156:        my @pairs=split(/\&/,$rep);
 4157:        foreach my $pair (@pairs) {
 4158:            my ($key,$value)=split(/=/,$pair,2);
 4159:            my ($symb,$param) = split(/:/,$key);
 4160:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4161:                                                         &thaw_unescape($value);
 4162:        }
 4163:    }
 4164:    return %returnhash;
 4165: }
 4166: 
 4167: sub convert_dump_to_currentdump{
 4168:     my %hash = %{shift()};
 4169:     my %returnhash;
 4170:     # Code ripped from lond, essentially.  The only difference
 4171:     # here is the unescaping done by lonnet::dump().  Conceivably
 4172:     # we might run in to problems with parameter names =~ /^v\./
 4173:     while (my ($key,$value) = each(%hash)) {
 4174:         my ($v,$symb,$param) = split(/:/,$key);
 4175: 	$symb  = &unescape($symb);
 4176: 	$param = &unescape($param);
 4177:         next if ($v eq 'version' || $symb eq 'keys');
 4178:         next if (exists($returnhash{$symb}) &&
 4179:                  exists($returnhash{$symb}->{$param}) &&
 4180:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4181:         $returnhash{$symb}->{$param}=$value;
 4182:         $returnhash{$symb}->{'v.'.$param}=$v;
 4183:     }
 4184:     #
 4185:     # Remove all of the keys in the hashes which keep track of
 4186:     # the version of the parameter.
 4187:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4188:         # use a foreach because we are going to delete from the hash.
 4189:         foreach my $key (keys(%$param_hash)) {
 4190:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4191:         }
 4192:     }
 4193:     return \%returnhash;
 4194: }
 4195: 
 4196: # ------------------------------------------------------ critical inc interface
 4197: 
 4198: sub cinc {
 4199:     return &inc(@_,'critical');
 4200: }
 4201: 
 4202: # --------------------------------------------------------------- inc interface
 4203: 
 4204: sub inc {
 4205:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4206:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4207:     if (!$uname) { $uname=$env{'user.name'}; }
 4208:     my $uhome=&homeserver($uname,$udomain);
 4209:     my $items='';
 4210:     if (! ref($store)) {
 4211:         # got a single value, so use that instead
 4212:         $items = &escape($store).'=&';
 4213:     } elsif (ref($store) eq 'SCALAR') {
 4214:         $items = &escape($$store).'=&';        
 4215:     } elsif (ref($store) eq 'ARRAY') {
 4216:         $items = join('=&',map {&escape($_);} @{$store});
 4217:     } elsif (ref($store) eq 'HASH') {
 4218:         while (my($key,$value) = each(%{$store})) {
 4219:             $items.= &escape($key).'='.&escape($value).'&';
 4220:         }
 4221:     }
 4222:     $items=~s/\&$//;
 4223:     if ($critical) {
 4224: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4225:     } else {
 4226: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4227:     }
 4228: }
 4229: 
 4230: # --------------------------------------------------------------- put interface
 4231: 
 4232: sub put {
 4233:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4234:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4235:    if (!$uname) { $uname=$env{'user.name'}; }
 4236:    my $uhome=&homeserver($uname,$udomain);
 4237:    my $items='';
 4238:    foreach my $item (keys(%$storehash)) {
 4239:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4240:    }
 4241:    $items=~s/\&$//;
 4242:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4243: }
 4244: 
 4245: # ------------------------------------------------------------ newput interface
 4246: 
 4247: sub newput {
 4248:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4249:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4250:    if (!$uname) { $uname=$env{'user.name'}; }
 4251:    my $uhome=&homeserver($uname,$udomain);
 4252:    my $items='';
 4253:    foreach my $key (keys(%$storehash)) {
 4254:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4255:    }
 4256:    $items=~s/\&$//;
 4257:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4258: }
 4259: 
 4260: # ---------------------------------------------------------  putstore interface
 4261: 
 4262: sub putstore {
 4263:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4264:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4265:    if (!$uname) { $uname=$env{'user.name'}; }
 4266:    my $uhome=&homeserver($uname,$udomain);
 4267:    my $items='';
 4268:    foreach my $key (keys(%$storehash)) {
 4269:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4270:    }
 4271:    $items=~s/\&$//;
 4272:    my $esc_symb=&escape($symb);
 4273:    my $esc_v=&escape($version);
 4274:    my $reply =
 4275:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4276: 	      $uhome);
 4277:    if ($reply eq 'unknown_cmd') {
 4278:        # gfall back to way things use to be done
 4279:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4280: 			    $uname);
 4281:    }
 4282:    return $reply;
 4283: }
 4284: 
 4285: sub old_putstore {
 4286:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4287:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4288:     if (!$uname) { $uname=$env{'user.name'}; }
 4289:     my $uhome=&homeserver($uname,$udomain);
 4290:     my %newstorehash;
 4291:     foreach my $item (keys(%$storehash)) {
 4292: 	my $key = $version.':'.&escape($symb).':'.$item;
 4293: 	$newstorehash{$key} = $storehash->{$item};
 4294:     }
 4295:     my $items='';
 4296:     my %allitems = ();
 4297:     foreach my $item (keys(%newstorehash)) {
 4298: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4299: 	    my $key = $1.':keys:'.$2;
 4300: 	    $allitems{$key} .= $3.':';
 4301: 	}
 4302: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4303:     }
 4304:     foreach my $item (keys(%allitems)) {
 4305: 	$allitems{$item} =~ s/\:$//;
 4306: 	$items.= $item.'='.$allitems{$item}.'&';
 4307:     }
 4308:     $items=~s/\&$//;
 4309:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4310: }
 4311: 
 4312: # ------------------------------------------------------ critical put interface
 4313: 
 4314: sub cput {
 4315:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4316:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4317:    if (!$uname) { $uname=$env{'user.name'}; }
 4318:    my $uhome=&homeserver($uname,$udomain);
 4319:    my $items='';
 4320:    foreach my $item (keys(%$storehash)) {
 4321:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4322:    }
 4323:    $items=~s/\&$//;
 4324:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4325: }
 4326: 
 4327: # -------------------------------------------------------------- eget interface
 4328: 
 4329: sub eget {
 4330:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4331:    my $items='';
 4332:    foreach my $item (@$storearr) {
 4333:        $items.=&escape($item).'&';
 4334:    }
 4335:    $items=~s/\&$//;
 4336:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4337:    if (!$uname) { $uname=$env{'user.name'}; }
 4338:    my $uhome=&homeserver($uname,$udomain);
 4339:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4340:    my @pairs=split(/\&/,$rep);
 4341:    my %returnhash=();
 4342:    my $i=0;
 4343:    foreach my $item (@$storearr) {
 4344:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4345:       $i++;
 4346:    }
 4347:    return %returnhash;
 4348: }
 4349: 
 4350: # ------------------------------------------------------------ tmpput interface
 4351: sub tmpput {
 4352:     my ($storehash,$server,$context)=@_;
 4353:     my $items='';
 4354:     foreach my $item (keys(%$storehash)) {
 4355: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4356:     }
 4357:     $items=~s/\&$//;
 4358:     if (defined($context)) {
 4359:         $items .= ':'.&escape($context);
 4360:     }
 4361:     return &reply("tmpput:$items",$server);
 4362: }
 4363: 
 4364: # ------------------------------------------------------------ tmpget interface
 4365: sub tmpget {
 4366:     my ($token,$server)=@_;
 4367:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4368:     my $rep=&reply("tmpget:$token",$server);
 4369:     my %returnhash;
 4370:     foreach my $item (split(/\&/,$rep)) {
 4371: 	my ($key,$value)=split(/=/,$item);
 4372:         next if ($key =~ /^error: 2 /);
 4373: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4374:     }
 4375:     return %returnhash;
 4376: }
 4377: 
 4378: # ------------------------------------------------------------ tmpget interface
 4379: sub tmpdel {
 4380:     my ($token,$server)=@_;
 4381:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4382:     return &reply("tmpdel:$token",$server);
 4383: }
 4384: 
 4385: # -------------------------------------------------- portfolio access checking
 4386: 
 4387: sub portfolio_access {
 4388:     my ($requrl) = @_;
 4389:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4390:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4391:     if ($result) {
 4392:         my %setters;
 4393:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4394:             my ($startblock,$endblock) =
 4395:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4396:             if ($startblock && $endblock) {
 4397:                 return 'B';
 4398:             }
 4399:         } else {
 4400:             my ($startblock,$endblock) =
 4401:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4402:             if ($startblock && $endblock) {
 4403:                 return 'B';
 4404:             }
 4405:         }
 4406:     }
 4407:     if ($result eq 'ok') {
 4408:        return 'F';
 4409:     } elsif ($result =~ /^[^:]+:guest_/) {
 4410:        return 'A';
 4411:     }
 4412:     return '';
 4413: }
 4414: 
 4415: sub get_portfolio_access {
 4416:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4417: 
 4418:     if (!ref($access_hash)) {
 4419: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4420: 	my %access_controls = &get_access_controls($current_perms,$group,
 4421: 						   $file_name);
 4422: 	$access_hash = $access_controls{$file_name};
 4423:     }
 4424: 
 4425:     my ($public,$guest,@domains,@users,@courses,@groups);
 4426:     my $now = time;
 4427:     if (ref($access_hash) eq 'HASH') {
 4428:         foreach my $key (keys(%{$access_hash})) {
 4429:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4430:             if ($start > $now) {
 4431:                 next;
 4432:             }
 4433:             if ($end && $end<$now) {
 4434:                 next;
 4435:             }
 4436:             if ($scope eq 'public') {
 4437:                 $public = $key;
 4438:                 last;
 4439:             } elsif ($scope eq 'guest') {
 4440:                 $guest = $key;
 4441:             } elsif ($scope eq 'domains') {
 4442:                 push(@domains,$key);
 4443:             } elsif ($scope eq 'users') {
 4444:                 push(@users,$key);
 4445:             } elsif ($scope eq 'course') {
 4446:                 push(@courses,$key);
 4447:             } elsif ($scope eq 'group') {
 4448:                 push(@groups,$key);
 4449:             }
 4450:         }
 4451:         if ($public) {
 4452:             return 'ok';
 4453:         }
 4454:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4455:             if ($guest) {
 4456:                 return $guest;
 4457:             }
 4458:         } else {
 4459:             if (@domains > 0) {
 4460:                 foreach my $domkey (@domains) {
 4461:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4462:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4463:                             return 'ok';
 4464:                         }
 4465:                     }
 4466:                 }
 4467:             }
 4468:             if (@users > 0) {
 4469:                 foreach my $userkey (@users) {
 4470:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4471:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4472:                             if (ref($item) eq 'HASH') {
 4473:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4474:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4475:                                     return 'ok';
 4476:                                 }
 4477:                             }
 4478:                         }
 4479:                     } 
 4480:                 }
 4481:             }
 4482:             my %roleshash;
 4483:             my @courses_and_groups = @courses;
 4484:             push(@courses_and_groups,@groups); 
 4485:             if (@courses_and_groups > 0) {
 4486:                 my (%allgroups,%allroles); 
 4487:                 my ($start,$end,$role,$sec,$group);
 4488:                 foreach my $envkey (%env) {
 4489:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4490:                         my $cid = $2.'_'.$3; 
 4491:                         if ($1 eq 'gr') {
 4492:                             $group = $4;
 4493:                             $allgroups{$cid}{$group} = $env{$envkey};
 4494:                         } else {
 4495:                             if ($4 eq '') {
 4496:                                 $sec = 'none';
 4497:                             } else {
 4498:                                 $sec = $4;
 4499:                             }
 4500:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4501:                         }
 4502:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4503:                         my $cid = $2.'_'.$3;
 4504:                         if ($4 eq '') {
 4505:                             $sec = 'none';
 4506:                         } else {
 4507:                             $sec = $4;
 4508:                         }
 4509:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4510:                     }
 4511:                 }
 4512:                 if (keys(%allroles) == 0) {
 4513:                     return;
 4514:                 }
 4515:                 foreach my $key (@courses_and_groups) {
 4516:                     my %content = %{$$access_hash{$key}};
 4517:                     my $cnum = $content{'number'};
 4518:                     my $cdom = $content{'domain'};
 4519:                     my $cid = $cdom.'_'.$cnum;
 4520:                     if (!exists($allroles{$cid})) {
 4521:                         next;
 4522:                     }    
 4523:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4524:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4525:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4526:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4527:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4528:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4529:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4530:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4531:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4532:                                         if (grep/^all$/,@sections) {
 4533:                                             return 'ok';
 4534:                                         } else {
 4535:                                             if (grep/^$sec$/,@sections) {
 4536:                                                 return 'ok';
 4537:                                             }
 4538:                                         }
 4539:                                     }
 4540:                                 }
 4541:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4542:                                     if (grep/^none$/,@groups) {
 4543:                                         return 'ok';
 4544:                                     }
 4545:                                 } else {
 4546:                                     if (grep/^all$/,@groups) {
 4547:                                         return 'ok';
 4548:                                     } 
 4549:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4550:                                         if (grep/^$group$/,@groups) {
 4551:                                             return 'ok';
 4552:                                         }
 4553:                                     }
 4554:                                 } 
 4555:                             }
 4556:                         }
 4557:                     }
 4558:                 }
 4559:             }
 4560:             if ($guest) {
 4561:                 return $guest;
 4562:             }
 4563:         }
 4564:     }
 4565:     return;
 4566: }
 4567: 
 4568: sub course_group_datechecker {
 4569:     my ($dates,$now,$status) = @_;
 4570:     my ($start,$end) = split(/\./,$dates);
 4571:     if (!$start && !$end) {
 4572:         return 'ok';
 4573:     }
 4574:     if (grep/^active$/,@{$status}) {
 4575:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4576:             return 'ok';
 4577:         }
 4578:     }
 4579:     if (grep/^previous$/,@{$status}) {
 4580:         if ($end > $now ) {
 4581:             return 'ok';
 4582:         }
 4583:     }
 4584:     if (grep/^future$/,@{$status}) {
 4585:         if ($start > $now) {
 4586:             return 'ok';
 4587:         }
 4588:     }
 4589:     return; 
 4590: }
 4591: 
 4592: sub parse_portfolio_url {
 4593:     my ($url) = @_;
 4594: 
 4595:     my ($type,$udom,$unum,$group,$file_name);
 4596:     
 4597:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4598: 	$type = 1;
 4599:         $udom = $1;
 4600:         $unum = $2;
 4601:         $file_name = $3;
 4602:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4603: 	$type = 2;
 4604:         $udom = $1;
 4605:         $unum = $2;
 4606:         $group = $3;
 4607:         $file_name = $3.'/'.$4;
 4608:     }
 4609:     if (wantarray) {
 4610: 	return ($type,$udom,$unum,$file_name,$group);
 4611:     }
 4612:     return $type;
 4613: }
 4614: 
 4615: sub is_portfolio_url {
 4616:     my ($url) = @_;
 4617:     return scalar(&parse_portfolio_url($url));
 4618: }
 4619: 
 4620: sub is_portfolio_file {
 4621:     my ($file) = @_;
 4622:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4623:         return 1;
 4624:     }
 4625:     return;
 4626: }
 4627: 
 4628: sub usertools_access {
 4629:     my ($uname,$udom,$tool,$action,$context) = @_;
 4630:     my ($access,%tools);
 4631:     if ($context eq '') {
 4632:         $context = 'tools';
 4633:     }
 4634:     if ($context eq 'requestcourses') {
 4635:         %tools = (
 4636:                       official   => 1,
 4637:                       unofficial => 1,
 4638:                       community  => 1,
 4639:                  );
 4640:     } else {
 4641:         %tools = (
 4642:                       aboutme   => 1,
 4643:                       blog      => 1,
 4644:                       portfolio => 1,
 4645:                  );
 4646:     }
 4647:     return if (!defined($tools{$tool}));
 4648: 
 4649:     if ((!defined($udom)) || (!defined($uname))) {
 4650:         $udom = $env{'user.domain'};
 4651:         $uname = $env{'user.name'};
 4652:     }
 4653: 
 4654:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4655:         if ($action ne 'reload') {
 4656:             if ($context eq 'requestcourses') {
 4657:                 return $env{'environment.canrequest.'.$tool};
 4658:             } else {
 4659:                 return $env{'environment.availabletools.'.$tool};
 4660:             }
 4661:         }
 4662:     }
 4663: 
 4664:     my ($toolstatus,$inststatus);
 4665: 
 4666:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4667:          ($action ne 'reload')) {
 4668:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4669:         $inststatus = $env{'environment.inststatus'};
 4670:     } else {
 4671:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4672:         $toolstatus = $userenv{$context.'.'.$tool};
 4673:         $inststatus = $userenv{'inststatus'};
 4674:     }
 4675: 
 4676:     if ($toolstatus ne '') {
 4677:         if ($toolstatus) {
 4678:             $access = 1;
 4679:         } else {
 4680:             $access = 0;
 4681:         }
 4682:         return $access;
 4683:     }
 4684: 
 4685:     my $is_adv = &is_advanced_user($udom,$uname);
 4686:     my %domdef = &get_domain_defaults($udom);
 4687:     if (ref($domdef{$tool}) eq 'HASH') {
 4688:         if ($is_adv) {
 4689:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4690:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4691:                     $access = 1;
 4692:                 } else {
 4693:                     $access = 0;
 4694:                 }
 4695:                 return $access;
 4696:             }
 4697:         }
 4698:         if ($inststatus ne '') {
 4699:             my ($hasaccess,$hasnoaccess);
 4700:             foreach my $affiliation (split(/:/,$inststatus)) {
 4701:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4702:                     if ($domdef{$tool}{$affiliation}) {
 4703:                         $hasaccess = 1;
 4704:                     } else {
 4705:                         $hasnoaccess = 1;
 4706:                     }
 4707:                 }
 4708:             }
 4709:             if ($hasaccess || $hasnoaccess) {
 4710:                 if ($hasaccess) {
 4711:                     $access = 1;
 4712:                 } elsif ($hasnoaccess) {
 4713:                     $access = 0; 
 4714:                 }
 4715:                 return $access;
 4716:             }
 4717:         } else {
 4718:             if ($domdef{$tool}{'default'} ne '') {
 4719:                 if ($domdef{$tool}{'default'}) {
 4720:                     $access = 1;
 4721:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4722:                     $access = 0;
 4723:                 }
 4724:                 return $access;
 4725:             }
 4726:         }
 4727:     } else {
 4728:         if ($context eq 'tools') {
 4729:             $access = 1;
 4730:         } else {
 4731:             $access = 0;
 4732:         }
 4733:         return $access;
 4734:     }
 4735: }
 4736: 
 4737: sub is_advanced_user {
 4738:     my ($udom,$uname) = @_;
 4739:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4740:     my %allroles;
 4741:     my $is_adv;
 4742:     foreach my $role (keys(%roleshash)) {
 4743:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4744:         my $area = '/'.$tdomain.'/'.$trest;
 4745:         if ($sec ne '') {
 4746:             $area .= '/'.$sec;
 4747:         }
 4748:         if (($area ne '') && ($trole ne '')) {
 4749:             my $spec=$trole.'.'.$area;
 4750:             if ($trole =~ /^cr\//) {
 4751:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4752:             } elsif ($trole ne 'gr') {
 4753:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4754:             }
 4755:         }
 4756:     }
 4757:     foreach my $role (keys(%allroles)) {
 4758:         last if ($is_adv);
 4759:         foreach my $item (split(/:/,$allroles{$role})) {
 4760:             if ($item ne '') {
 4761:                 my ($privilege,$restrictions)=split(/&/,$item);
 4762:                 if ($privilege eq 'adv') {
 4763:                     $is_adv = 1;
 4764:                     last;
 4765:                 }
 4766:             }
 4767:         }
 4768:     }
 4769:     return $is_adv;
 4770: }
 4771: 
 4772: # ---------------------------------------------- Custom access rule evaluation
 4773: 
 4774: sub customaccess {
 4775:     my ($priv,$uri)=@_;
 4776:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4777:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4778:     $udom = &LONCAPA::clean_domain($udom);
 4779:     $ucrs = &LONCAPA::clean_username($ucrs);
 4780:     my $access=0;
 4781:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4782: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4783: 	if ($type eq 'user') {
 4784: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4785: 		my ($tdom,$tuname)=split(m{/},$scope);
 4786: 		if ($tdom) {
 4787: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4788: 		}
 4789: 		if ($tuname) {
 4790: 		    if ($tuname ne $env{'user.name'}) { next; }
 4791: 		}
 4792: 		$access=($effect eq 'allow');
 4793: 		last;
 4794: 	    }
 4795: 	} else {
 4796: 	    if ($role) {
 4797: 		if ($role ne $urole) { next; }
 4798: 	    }
 4799: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4800: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4801: 		if ($tdom) {
 4802: 		    if ($tdom ne $udom) { next; }
 4803: 		}
 4804: 		if ($tcrs) {
 4805: 		    if ($tcrs ne $ucrs) { next; }
 4806: 		}
 4807: 		if ($tsec) {
 4808: 		    if ($tsec ne $usec) { next; }
 4809: 		}
 4810: 		$access=($effect eq 'allow');
 4811: 		last;
 4812: 	    }
 4813: 	    if ($realm eq '' && $role eq '') {
 4814: 		$access=($effect eq 'allow');
 4815: 	    }
 4816: 	}
 4817:     }
 4818:     return $access;
 4819: }
 4820: 
 4821: # ------------------------------------------------- Check for a user privilege
 4822: 
 4823: sub allowed {
 4824:     my ($priv,$uri,$symb,$role)=@_;
 4825:     my $ver_orguri=$uri;
 4826:     $uri=&deversion($uri);
 4827:     my $orguri=$uri;
 4828:     $uri=&declutter($uri);
 4829: 
 4830:     if ($priv eq 'evb') {
 4831: # Evade communication block restrictions for specified role in a course
 4832:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4833:             return $1;
 4834:         } else {
 4835:             return;
 4836:         }
 4837:     }
 4838: 
 4839:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4840: # Free bre access to adm and meta resources
 4841:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4842: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4843: 	&& ($priv eq 'bre')) {
 4844: 	return 'F';
 4845:     }
 4846: 
 4847: # Free bre access to user's own portfolio contents
 4848:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4849:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4850: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4851:         my %setters;
 4852:         my ($startblock,$endblock) = 
 4853:             &Apache::loncommon::blockcheck(\%setters,'port');
 4854:         if ($startblock && $endblock) {
 4855:             return 'B';
 4856:         } else {
 4857:             return 'F';
 4858:         }
 4859:     }
 4860: 
 4861: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4862:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4863:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4864:         if (exists($env{'request.course.id'})) {
 4865:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4866:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4867:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4868:                 my $courseprivid=$env{'request.course.id'};
 4869:                 $courseprivid=~s/\_/\//;
 4870:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4871:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4872:                     return $1; 
 4873:                 } else {
 4874:                     if ($env{'request.course.sec'}) {
 4875:                         $courseprivid.='/'.$env{'request.course.sec'};
 4876:                     }
 4877:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4878:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4879:                         return $2;
 4880:                     }
 4881:                 }
 4882:             }
 4883:         }
 4884:     }
 4885: 
 4886: # Free bre to public access
 4887: 
 4888:     if ($priv eq 'bre') {
 4889:         my $copyright=&metadata($uri,'copyright');
 4890: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4891:            return 'F'; 
 4892:         }
 4893:         if ($copyright eq 'priv') {
 4894:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4895: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4896: 		return '';
 4897:             }
 4898:         }
 4899:         if ($copyright eq 'domain') {
 4900:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4901: 	    unless (($env{'user.domain'} eq $1) ||
 4902:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4903: 		return '';
 4904:             }
 4905:         }
 4906:         if ($env{'request.role'}=~ /li\.\//) {
 4907:             # Library role, so allow browsing of resources in this domain.
 4908:             return 'F';
 4909:         }
 4910:         if ($copyright eq 'custom') {
 4911: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4912:         }
 4913:     }
 4914:     # Domain coordinator is trying to create a course
 4915:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4916:         # uri is the requested domain in this case.
 4917:         # comparison to 'request.role.domain' shows if the user has selected
 4918:         # a role of dc for the domain in question.
 4919:         return 'F' if ($uri eq $env{'request.role.domain'});
 4920:     }
 4921: 
 4922:     my $thisallowed='';
 4923:     my $statecond=0;
 4924:     my $courseprivid='';
 4925: 
 4926: # Course
 4927: 
 4928:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4929:        $thisallowed.=$1;
 4930:     }
 4931: 
 4932: # Domain
 4933: 
 4934:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4935:        =~/\Q$priv\E\&([^\:]*)/) {
 4936:        $thisallowed.=$1;
 4937:     }
 4938: 
 4939: # Course: uri itself is a course
 4940:     my $courseuri=$uri;
 4941:     $courseuri=~s/\_(\d)/\/$1/;
 4942:     $courseuri=~s/^([^\/])/\/$1/;
 4943: 
 4944:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4945:        =~/\Q$priv\E\&([^\:]*)/) {
 4946:        $thisallowed.=$1;
 4947:     }
 4948: 
 4949: # URI is an uploaded document for this course, default permissions don't matter
 4950: # not allowing 'edit' access (editupload) to uploaded course docs
 4951:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4952: 	$thisallowed='';
 4953:         my ($match)=&is_on_map($uri);
 4954:         if ($match) {
 4955:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4956:                   =~/\Q$priv\E\&([^\:]*)/) {
 4957:                 $thisallowed.=$1;
 4958:             }
 4959:         } else {
 4960:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4961:             if ($refuri) {
 4962:                 if ($refuri =~ m|^/adm/|) {
 4963:                     $thisallowed='F';
 4964:                 } else {
 4965:                     $refuri=&declutter($refuri);
 4966:                     my ($match) = &is_on_map($refuri);
 4967:                     if ($match) {
 4968:                         $thisallowed='F';
 4969:                     }
 4970:                 }
 4971:             }
 4972:         }
 4973:     }
 4974: 
 4975:     if ($priv eq 'bre'
 4976: 	&& $thisallowed ne 'F' 
 4977: 	&& $thisallowed ne '2'
 4978: 	&& &is_portfolio_url($uri)) {
 4979: 	$thisallowed = &portfolio_access($uri);
 4980:     }
 4981:     
 4982: # Full access at system, domain or course-wide level? Exit.
 4983:     if ($thisallowed=~/F/) {
 4984: 	return 'F';
 4985:     }
 4986: 
 4987: # If this is generating or modifying users, exit with special codes
 4988: 
 4989:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4990: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4991: 	    my ($audom,$auname)=split('/',$uri);
 4992: # no author name given, so this just checks on the general right to make a co-author in this domain
 4993: 	    unless ($auname) { return $thisallowed; }
 4994: # an author name is given, so we are about to actually make a co-author for a certain account
 4995: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4996: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4997: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4998: 	}
 4999: 	return $thisallowed;
 5000:     }
 5001: #
 5002: # Gathered so far: system, domain and course wide privileges
 5003: #
 5004: # Course: See if uri or referer is an individual resource that is part of 
 5005: # the course
 5006: 
 5007:     if ($env{'request.course.id'}) {
 5008: 
 5009:        $courseprivid=$env{'request.course.id'};
 5010:        if ($env{'request.course.sec'}) {
 5011:           $courseprivid.='/'.$env{'request.course.sec'};
 5012:        }
 5013:        $courseprivid=~s/\_/\//;
 5014:        my $checkreferer=1;
 5015:        my ($match,$cond)=&is_on_map($uri);
 5016:        if ($match) {
 5017:            $statecond=$cond;
 5018:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5019:                =~/\Q$priv\E\&([^\:]*)/) {
 5020:                $thisallowed.=$1;
 5021:                $checkreferer=0;
 5022:            }
 5023:        }
 5024:        
 5025:        if ($checkreferer) {
 5026: 	  my $refuri=$env{'httpref.'.$orguri};
 5027:             unless ($refuri) {
 5028:                 foreach my $key (keys(%env)) {
 5029: 		    if ($key=~/^httpref\..*\*/) {
 5030: 			my $pattern=$key;
 5031:                         $pattern=~s/^httpref\.\/res\///;
 5032:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5033:                         $pattern=~s/\//\\\//g;
 5034:                         if ($orguri=~/$pattern/) {
 5035: 			    $refuri=$env{$key};
 5036:                         }
 5037:                     }
 5038:                 }
 5039:             }
 5040: 
 5041:          if ($refuri) { 
 5042: 	  $refuri=&declutter($refuri);
 5043:           my ($match,$cond)=&is_on_map($refuri);
 5044:             if ($match) {
 5045:               my $refstatecond=$cond;
 5046:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5047:                   =~/\Q$priv\E\&([^\:]*)/) {
 5048:                   $thisallowed.=$1;
 5049:                   $uri=$refuri;
 5050:                   $statecond=$refstatecond;
 5051:               }
 5052:           }
 5053:         }
 5054:        }
 5055:    }
 5056: 
 5057: #
 5058: # Gathered now: all privileges that could apply, and condition number
 5059: # 
 5060: #
 5061: # Full or no access?
 5062: #
 5063: 
 5064:     if ($thisallowed=~/F/) {
 5065: 	return 'F';
 5066:     }
 5067: 
 5068:     unless ($thisallowed) {
 5069:         return '';
 5070:     }
 5071: 
 5072: # Restrictions exist, deal with them
 5073: #
 5074: #   C:according to course preferences
 5075: #   R:according to resource settings
 5076: #   L:unless locked
 5077: #   X:according to user session state
 5078: #
 5079: 
 5080: # Possibly locked functionality, check all courses
 5081: # Locks might take effect only after 10 minutes cache expiration for other
 5082: # courses, and 2 minutes for current course
 5083: 
 5084:     my $envkey;
 5085:     if ($thisallowed=~/L/) {
 5086:         foreach $envkey (keys(%env)) {
 5087:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5088:                my $courseid=$2;
 5089:                my $roleid=$1.'.'.$2;
 5090:                $courseid=~s/^\///;
 5091:                my $expiretime=600;
 5092:                if ($env{'request.role'} eq $roleid) {
 5093: 		  $expiretime=120;
 5094:                }
 5095: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5096:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5097:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5098: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5099:                }
 5100:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5101:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5102: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5103:                        &log($env{'user.domain'},$env{'user.name'},
 5104:                             $env{'user.home'},
 5105:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5106:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5107:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5108: 		       return '';
 5109:                    }
 5110:                }
 5111:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5112:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5113: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5114:                        &log($env{'user.domain'},$env{'user.name'},
 5115:                             $env{'user.home'},
 5116:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5117:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5118:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5119: 		       return '';
 5120:                    }
 5121:                }
 5122: 	   }
 5123:        }
 5124:     }
 5125:    
 5126: #
 5127: # Rest of the restrictions depend on selected course
 5128: #
 5129: 
 5130:     unless ($env{'request.course.id'}) {
 5131: 	if ($thisallowed eq 'A') {
 5132: 	    return 'A';
 5133:         } elsif ($thisallowed eq 'B') {
 5134:             return 'B';
 5135: 	} else {
 5136: 	    return '1';
 5137: 	}
 5138:     }
 5139: 
 5140: #
 5141: # Now user is definitely in a course
 5142: #
 5143: 
 5144: 
 5145: # Course preferences
 5146: 
 5147:    if ($thisallowed=~/C/) {
 5148:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5149:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5150:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5151: 	   =~/\Q$rolecode\E/) {
 5152: 	   if ($priv ne 'pch') { 
 5153: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5154: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5155: 			$env{'request.course.id'});
 5156: 	   }
 5157:            return '';
 5158:        }
 5159: 
 5160:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5161: 	   =~/\Q$unamedom\E/) {
 5162: 	   if ($priv ne 'pch') { 
 5163: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5164: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5165: 			$env{'request.course.id'});
 5166: 	   }
 5167:            return '';
 5168:        }
 5169:    }
 5170: 
 5171: # Resource preferences
 5172: 
 5173:    if ($thisallowed=~/R/) {
 5174:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5175:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5176: 	   if ($priv ne 'pch') { 
 5177: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5178: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5179: 	   }
 5180: 	   return '';
 5181:        }
 5182:    }
 5183: 
 5184: # Restricted by state or randomout?
 5185: 
 5186:    if ($thisallowed=~/X/) {
 5187:       if ($env{'acc.randomout'}) {
 5188: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5189:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5190:             return ''; 
 5191:          }
 5192:       }
 5193:       if (&condval($statecond)) {
 5194: 	 return '2';
 5195:       } else {
 5196:          return '';
 5197:       }
 5198:    }
 5199: 
 5200:     if ($thisallowed eq 'A') {
 5201: 	return 'A';
 5202:     } elsif ($thisallowed eq 'B') {
 5203:         return 'B';
 5204:     }
 5205:    return 'F';
 5206: }
 5207: 
 5208: sub split_uri_for_cond {
 5209:     my $uri=&deversion(&declutter(shift));
 5210:     my @uriparts=split(/\//,$uri);
 5211:     my $filename=pop(@uriparts);
 5212:     my $pathname=join('/',@uriparts);
 5213:     return ($pathname,$filename);
 5214: }
 5215: # --------------------------------------------------- Is a resource on the map?
 5216: 
 5217: sub is_on_map {
 5218:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5219:     #Trying to find the conditional for the file
 5220:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5221: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5222:     if ($match) {
 5223: 	return (1,$1);
 5224:     } else {
 5225: 	return (0,0);
 5226:     }
 5227: }
 5228: 
 5229: # --------------------------------------------------------- Get symb from alias
 5230: 
 5231: sub get_symb_from_alias {
 5232:     my $symb=shift;
 5233:     my ($map,$resid,$url)=&decode_symb($symb);
 5234: # Already is a symb
 5235:     if ($url) { return $symb; }
 5236: # Must be an alias
 5237:     my $aliassymb='';
 5238:     my %bighash;
 5239:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5240:                             &GDBM_READER(),0640)) {
 5241:         my $rid=$bighash{'mapalias_'.$symb};
 5242: 	if ($rid) {
 5243: 	    my ($mapid,$resid)=split(/\./,$rid);
 5244: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5245: 				    $resid,$bighash{'src_'.$rid});
 5246: 	}
 5247:         untie %bighash;
 5248:     }
 5249:     return $aliassymb;
 5250: }
 5251: 
 5252: # ----------------------------------------------------------------- Define Role
 5253: 
 5254: sub definerole {
 5255:   if (allowed('mcr','/')) {
 5256:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5257:     foreach my $role (split(':',$sysrole)) {
 5258: 	my ($crole,$cqual)=split(/\&/,$role);
 5259:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5260:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5261: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5262:                return "refused:s:$crole&$cqual"; 
 5263:             }
 5264:         }
 5265:     }
 5266:     foreach my $role (split(':',$domrole)) {
 5267: 	my ($crole,$cqual)=split(/\&/,$role);
 5268:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5269:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5270: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5271:                return "refused:d:$crole&$cqual"; 
 5272:             }
 5273:         }
 5274:     }
 5275:     foreach my $role (split(':',$courole)) {
 5276: 	my ($crole,$cqual)=split(/\&/,$role);
 5277:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5278:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5279: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5280:                return "refused:c:$crole&$cqual"; 
 5281:             }
 5282:         }
 5283:     }
 5284:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5285:                 "$env{'user.domain'}:$env{'user.name'}:".
 5286: 	        "rolesdef_$rolename=".
 5287:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5288:     return reply($command,$env{'user.home'});
 5289:   } else {
 5290:     return 'refused';
 5291:   }
 5292: }
 5293: 
 5294: # ---------------- Make a metadata query against the network of library servers
 5295: 
 5296: sub metadata_query {
 5297:     my ($query,$custom,$customshow,$server_array)=@_;
 5298:     my %rhash;
 5299:     my %libserv = &all_library();
 5300:     my @server_list = (defined($server_array) ? @$server_array
 5301:                                               : keys(%libserv) );
 5302:     for my $server (@server_list) {
 5303: 	unless ($custom or $customshow) {
 5304: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5305: 	    $rhash{$server}=$reply;
 5306: 	}
 5307: 	else {
 5308: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5309: 			     &escape($custom).':'.&escape($customshow),
 5310: 			     $server);
 5311: 	    $rhash{$server}=$reply;
 5312: 	}
 5313:     }
 5314:     return \%rhash;
 5315: }
 5316: 
 5317: # ----------------------------------------- Send log queries and wait for reply
 5318: 
 5319: sub log_query {
 5320:     my ($uname,$udom,$query,%filters)=@_;
 5321:     my $uhome=&homeserver($uname,$udom);
 5322:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5323:     my $uhost=&hostname($uhome);
 5324:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5325:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5326:                        $uhome);
 5327:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5328:     return get_query_reply($queryid);
 5329: }
 5330: 
 5331: # -------------------------- Update MySQL table for portfolio file
 5332: 
 5333: sub update_portfolio_table {
 5334:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5335:     if ($group ne '') {
 5336:         $file_name =~s /^\Q$group\E//;
 5337:     }
 5338:     my $homeserver = &homeserver($uname,$udom);
 5339:     my $queryid=
 5340:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5341:                ':'.&escape($file_name).':'.$action,$homeserver);
 5342:     my $reply = &get_query_reply($queryid);
 5343:     return $reply;
 5344: }
 5345: 
 5346: # -------------------------- Update MySQL allusers table
 5347: 
 5348: sub update_allusers_table {
 5349:     my ($uname,$udom,$names) = @_;
 5350:     my $homeserver = &homeserver($uname,$udom);
 5351:     my $queryid=
 5352:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5353:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5354:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5355:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5356:                'generation='.&escape($names->{'generation'}).'%%'.
 5357:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5358:                'id='.&escape($names->{'id'}),$homeserver);
 5359:     my $reply = &get_query_reply($queryid);
 5360:     return $reply;
 5361: }
 5362: 
 5363: # ------- Request retrieval of institutional classlists for course(s)
 5364: 
 5365: sub fetch_enrollment_query {
 5366:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5367:     my $homeserver;
 5368:     my $maxtries = 1;
 5369:     if ($context eq 'automated') {
 5370:         $homeserver = $perlvar{'lonHostID'};
 5371:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5372:     } else {
 5373:         $homeserver = &homeserver($cnum,$dom);
 5374:     }
 5375:     my $host=&hostname($homeserver);
 5376:     my $cmd = '';
 5377:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5378:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5379:     }
 5380:     $cmd =~ s/%%$//;
 5381:     $cmd = &escape($cmd);
 5382:     my $query = 'fetchenrollment';
 5383:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5384:     unless ($queryid=~/^\Q$host\E\_/) { 
 5385:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5386:         return 'error: '.$queryid;
 5387:     }
 5388:     my $reply = &get_query_reply($queryid);
 5389:     my $tries = 1;
 5390:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5391:         $reply = &get_query_reply($queryid);
 5392:         $tries ++;
 5393:     }
 5394:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5395:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5396:     } else {
 5397:         my @responses = split(/:/,$reply);
 5398:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5399:             foreach my $line (@responses) {
 5400:                 my ($key,$value) = split(/=/,$line,2);
 5401:                 $$replyref{$key} = $value;
 5402:             }
 5403:         } else {
 5404:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5405:             foreach my $line (@responses) {
 5406:                 my ($key,$value) = split(/=/,$line);
 5407:                 $$replyref{$key} = $value;
 5408:                 if ($value > 0) {
 5409:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5410:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5411:                         my $destname = $pathname.'/'.$filename;
 5412:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5413:                         if ($xml_classlist =~ /^error/) {
 5414:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5415:                         } else {
 5416:                             if ( open(FILE,">$destname") ) {
 5417:                                 print FILE &unescape($xml_classlist);
 5418:                                 close(FILE);
 5419:                             } else {
 5420:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5421:                             }
 5422:                         }
 5423:                     }
 5424:                 }
 5425:             }
 5426:         }
 5427:         return 'ok';
 5428:     }
 5429:     return 'error';
 5430: }
 5431: 
 5432: sub get_query_reply {
 5433:     my $queryid=shift;
 5434:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5435:     my $reply='';
 5436:     for (1..100) {
 5437: 	sleep 2;
 5438:         if (-e $replyfile.'.end') {
 5439: 	    if (open(my $fh,$replyfile)) {
 5440: 		$reply = join('',<$fh>);
 5441: 		close($fh);
 5442: 	   } else { return 'error: reply_file_error'; }
 5443:            return &unescape($reply);
 5444: 	}
 5445:     }
 5446:     return 'timeout:'.$queryid;
 5447: }
 5448: 
 5449: sub courselog_query {
 5450: #
 5451: # possible filters:
 5452: # url: url or symb
 5453: # username
 5454: # domain
 5455: # action: view, submit, grade
 5456: # start: timestamp
 5457: # end: timestamp
 5458: #
 5459:     my (%filters)=@_;
 5460:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5461:     if ($filters{'url'}) {
 5462: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5463:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5464:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5465:     }
 5466:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5467:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5468:     return &log_query($cname,$cdom,'courselog',%filters);
 5469: }
 5470: 
 5471: sub userlog_query {
 5472: #
 5473: # possible filters:
 5474: # action: log check role
 5475: # start: timestamp
 5476: # end: timestamp
 5477: #
 5478:     my ($uname,$udom,%filters)=@_;
 5479:     return &log_query($uname,$udom,'userlog',%filters);
 5480: }
 5481: 
 5482: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5483: 
 5484: sub auto_run {
 5485:     my ($cnum,$cdom) = @_;
 5486:     my $response = 0;
 5487:     my $settings;
 5488:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5489:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5490:         $settings = $domconfig{'autoenroll'};
 5491:         if ($settings->{'run'} eq '1') {
 5492:             $response = 1;
 5493:         }
 5494:     } else {
 5495:         my $homeserver;
 5496:         if (&is_course($cdom,$cnum)) {
 5497:             $homeserver = &homeserver($cnum,$cdom);
 5498:         } else {
 5499:             $homeserver = &domain($cdom,'primary');
 5500:         }
 5501:         if ($homeserver ne 'no_host') {
 5502:             $response = &reply('autorun:'.$cdom,$homeserver);
 5503:         }
 5504:     }
 5505:     return $response;
 5506: }
 5507: 
 5508: sub auto_get_sections {
 5509:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5510:     my $homeserver;
 5511:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5512:         $homeserver = &homeserver($cnum,$cdom);
 5513:     }
 5514:     if (!defined($homeserver)) { 
 5515:         if ($cdom =~ /^$match_domain$/) {
 5516:             $homeserver = &domain($cdom,'primary');
 5517:         }
 5518:     }
 5519:     my @secs;
 5520:     if (defined($homeserver)) {
 5521:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5522:         unless ($response eq 'refused') {
 5523:             @secs = split(/:/,$response);
 5524:         }
 5525:     }
 5526:     return @secs;
 5527: }
 5528: 
 5529: sub auto_new_course {
 5530:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5531:     my $homeserver = &homeserver($cnum,$cdom);
 5532:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5533:     return $response;
 5534: }
 5535: 
 5536: sub auto_validate_courseID {
 5537:     my ($cnum,$cdom,$inst_course_id) = @_;
 5538:     my $homeserver = &homeserver($cnum,$cdom);
 5539:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5540:     return $response;
 5541: }
 5542: 
 5543: sub auto_validate_instcode {
 5544:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5545:     my ($homeserver,$response);
 5546:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5547:         $homeserver = &homeserver($cnum,$cdom);
 5548:     }
 5549:     if (!defined($homeserver)) {
 5550:         if ($cdom =~ /^$match_domain$/) {
 5551:             $homeserver = &domain($cdom,'primary');
 5552:         }
 5553:     }
 5554:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5555:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5556:     return $response;
 5557: }
 5558: 
 5559: sub auto_create_password {
 5560:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5561:     my ($homeserver,$response);
 5562:     my $create_passwd = 0;
 5563:     my $authchk = '';
 5564:     if ($udom =~ /^$match_domain$/) {
 5565:         $homeserver = &domain($udom,'primary');
 5566:     }
 5567:     if ($homeserver eq '') {
 5568:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5569:             $homeserver = &homeserver($cnum,$cdom);
 5570:         }
 5571:     }
 5572:     if ($homeserver eq '') {
 5573:         $authchk = 'nodomain';
 5574:     } else {
 5575:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5576:         if ($response eq 'refused') {
 5577:             $authchk = 'refused';
 5578:         } else {
 5579:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5580:         }
 5581:     }
 5582:     return ($authparam,$create_passwd,$authchk);
 5583: }
 5584: 
 5585: sub auto_photo_permission {
 5586:     my ($cnum,$cdom,$students) = @_;
 5587:     my $homeserver = &homeserver($cnum,$cdom);
 5588:     my ($outcome,$perm_reqd,$conditions) = 
 5589: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5590:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5591: 	return (undef,undef);
 5592:     }
 5593:     return ($outcome,$perm_reqd,$conditions);
 5594: }
 5595: 
 5596: sub auto_checkphotos {
 5597:     my ($uname,$udom,$pid) = @_;
 5598:     my $homeserver = &homeserver($uname,$udom);
 5599:     my ($result,$resulttype);
 5600:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5601: 				   &escape($uname).':'.&escape($pid),
 5602: 				   $homeserver));
 5603:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5604: 	return (undef,undef);
 5605:     }
 5606:     if ($outcome) {
 5607:         ($result,$resulttype) = split(/:/,$outcome);
 5608:     } 
 5609:     return ($result,$resulttype);
 5610: }
 5611: 
 5612: sub auto_photochoice {
 5613:     my ($cnum,$cdom) = @_;
 5614:     my $homeserver = &homeserver($cnum,$cdom);
 5615:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5616: 						       &escape($cdom),
 5617: 						       $homeserver)));
 5618:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5619: 	return (undef,undef);
 5620:     }
 5621:     return ($update,$comment);
 5622: }
 5623: 
 5624: sub auto_photoupdate {
 5625:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5626:     my $homeserver = &homeserver($cnum,$dom);
 5627:     my $host=&hostname($homeserver);
 5628:     my $cmd = '';
 5629:     my $maxtries = 1;
 5630:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5631:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5632:     }
 5633:     $cmd =~ s/%%$//;
 5634:     $cmd = &escape($cmd);
 5635:     my $query = 'institutionalphotos';
 5636:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5637:     unless ($queryid=~/^\Q$host\E\_/) {
 5638:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5639:         return 'error: '.$queryid;
 5640:     }
 5641:     my $reply = &get_query_reply($queryid);
 5642:     my $tries = 1;
 5643:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5644:         $reply = &get_query_reply($queryid);
 5645:         $tries ++;
 5646:     }
 5647:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5648:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5649:     } else {
 5650:         my @responses = split(/:/,$reply);
 5651:         my $outcome = shift(@responses); 
 5652:         foreach my $item (@responses) {
 5653:             my ($key,$value) = split(/=/,$item);
 5654:             $$photo{$key} = $value;
 5655:         }
 5656:         return $outcome;
 5657:     }
 5658:     return 'error';
 5659: }
 5660: 
 5661: sub auto_instcode_format {
 5662:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5663: 	$cat_order) = @_;
 5664:     my $courses = '';
 5665:     my @homeservers;
 5666:     if ($caller eq 'global') {
 5667: 	my %servers = &get_servers($codedom,'library');
 5668: 	foreach my $tryserver (keys(%servers)) {
 5669: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5670: 		push(@homeservers,$tryserver);
 5671: 	    }
 5672:         }
 5673:     } else {
 5674:         push(@homeservers,&homeserver($caller,$codedom));
 5675:     }
 5676:     foreach my $code (keys(%{$instcodes})) {
 5677:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5678:     }
 5679:     chop($courses);
 5680:     my $ok_response = 0;
 5681:     my $response;
 5682:     while (@homeservers > 0 && $ok_response == 0) {
 5683:         my $server = shift(@homeservers); 
 5684:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5685:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5686:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5687: 		split(/:/,$response);
 5688:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5689:             push(@{$codetitles},&str2array($codetitles_str));
 5690:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5691:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5692:             $ok_response = 1;
 5693:         }
 5694:     }
 5695:     if ($ok_response) {
 5696:         return 'ok';
 5697:     } else {
 5698:         return $response;
 5699:     }
 5700: }
 5701: 
 5702: sub auto_instcode_defaults {
 5703:     my ($domain,$returnhash,$code_order) = @_;
 5704:     my @homeservers;
 5705: 
 5706:     my %servers = &get_servers($domain,'library');
 5707:     foreach my $tryserver (keys(%servers)) {
 5708: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5709: 	    push(@homeservers,$tryserver);
 5710: 	}
 5711:     }
 5712: 
 5713:     my $response;
 5714:     foreach my $server (@homeservers) {
 5715:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5716:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5717: 	
 5718: 	foreach my $pair (split(/\&/,$response)) {
 5719: 	    my ($name,$value)=split(/\=/,$pair);
 5720: 	    if ($name eq 'code_order') {
 5721: 		@{$code_order} = split(/\&/,&unescape($value));
 5722: 	    } else {
 5723: 		$returnhash->{&unescape($name)}=&unescape($value);
 5724: 	    }
 5725: 	}
 5726: 	return 'ok';
 5727:     }
 5728: 
 5729:     return $response;
 5730: }
 5731: 
 5732: sub auto_possible_instcodes {
 5733:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 5734:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 5735:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 5736:         return;
 5737:     }
 5738:     my (@homeservers,$uhome);
 5739:     if (defined(&domain($domain,'primary'))) {
 5740:         $uhome=&domain($domain,'primary');
 5741:         push(@homeservers,&domain($domain,'primary'));
 5742:     } else {
 5743:         my %servers = &get_servers($domain,'library');
 5744:         foreach my $tryserver (keys(%servers)) {
 5745:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5746:                 push(@homeservers,$tryserver);
 5747:             }
 5748:         }
 5749:     }
 5750:     my $response;
 5751:     foreach my $server (@homeservers) {
 5752:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 5753:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5754:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 5755:             split(':',$response);
 5756:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 5757:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 5758:         foreach my $item (split('&',$cat_title)) {   
 5759:             my ($name,$value)=split('=',$item);
 5760:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 5761:         }
 5762:         foreach my $item (split('&',$cat_order)) {
 5763:             my ($name,$value)=split('=',$item);
 5764:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 5765:         }
 5766:         return 'ok';
 5767:     }
 5768:     return $response;
 5769: }
 5770: 
 5771: sub auto_validate_class_sec {
 5772:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5773:     my $homeserver = &homeserver($cnum,$cdom);
 5774:     my $ownerlist;
 5775:     if (ref($owners) eq 'ARRAY') {
 5776:         $ownerlist = join(',',@{$owners});
 5777:     } else {
 5778:         $ownerlist = $owners;
 5779:     }
 5780:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5781:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5782:     return $response;
 5783: }
 5784: 
 5785: # ------------------------------------------------------- Course Group routines
 5786: 
 5787: sub get_coursegroups {
 5788:     my ($cdom,$cnum,$group,$namespace) = @_;
 5789:     return(&dump($namespace,$cdom,$cnum,$group));
 5790: }
 5791: 
 5792: sub modify_coursegroup {
 5793:     my ($cdom,$cnum,$groupsettings) = @_;
 5794:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5795: }
 5796: 
 5797: sub toggle_coursegroup_status {
 5798:     my ($cdom,$cnum,$group,$action) = @_;
 5799:     my ($from_namespace,$to_namespace);
 5800:     if ($action eq 'delete') {
 5801:         $from_namespace = 'coursegroups';
 5802:         $to_namespace = 'deleted_groups';
 5803:     } else {
 5804:         $from_namespace = 'deleted_groups';
 5805:         $to_namespace = 'coursegroups';
 5806:     }
 5807:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5808:     if (my $tmp = &error(%curr_group)) {
 5809:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5810:         return ('read error',$tmp);
 5811:     } else {
 5812:         my %savedsettings = %curr_group; 
 5813:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5814:         my $deloutcome;
 5815:         if ($result eq 'ok') {
 5816:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5817:         } else {
 5818:             return ('write error',$result);
 5819:         }
 5820:         if ($deloutcome eq 'ok') {
 5821:             return 'ok';
 5822:         } else {
 5823:             return ('delete error',$deloutcome);
 5824:         }
 5825:     }
 5826: }
 5827: 
 5828: sub modify_group_roles {
 5829:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5830:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5831:     my $role = 'gr/'.&escape($userprivs);
 5832:     my ($uname,$udom) = split(/:/,$user);
 5833:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5834:     if ($result eq 'ok') {
 5835:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5836:     }
 5837:     return $result;
 5838: }
 5839: 
 5840: sub modify_coursegroup_membership {
 5841:     my ($cdom,$cnum,$membership) = @_;
 5842:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5843:     return $result;
 5844: }
 5845: 
 5846: sub get_active_groups {
 5847:     my ($udom,$uname,$cdom,$cnum) = @_;
 5848:     my $now = time;
 5849:     my %groups = ();
 5850:     foreach my $key (keys(%env)) {
 5851:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5852:             my ($start,$end) = split(/\./,$env{$key});
 5853:             if (($end!=0) && ($end<$now)) { next; }
 5854:             if (($start!=0) && ($start>$now)) { next; }
 5855:             if ($1 eq $cdom && $2 eq $cnum) {
 5856:                 $groups{$3} = $env{$key} ;
 5857:             }
 5858:         }
 5859:     }
 5860:     return %groups;
 5861: }
 5862: 
 5863: sub get_group_membership {
 5864:     my ($cdom,$cnum,$group) = @_;
 5865:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5866: }
 5867: 
 5868: sub get_users_groups {
 5869:     my ($udom,$uname,$courseid) = @_;
 5870:     my @usersgroups;
 5871:     my $cachetime=1800;
 5872: 
 5873:     my $hashid="$udom:$uname:$courseid";
 5874:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5875:     if (defined($cached)) {
 5876:         @usersgroups = split(/:/,$grouplist);
 5877:     } else {  
 5878:         $grouplist = '';
 5879:         my $courseurl = &courseid_to_courseurl($courseid);
 5880:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5881:         my $access_end = $env{'course.'.$courseid.
 5882:                               '.default_enrollment_end_date'};
 5883:         my $now = time;
 5884:         foreach my $key (keys(%roleshash)) {
 5885:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5886:                 my $group = $1;
 5887:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5888:                     my $start = $2;
 5889:                     my $end = $1;
 5890:                     if ($start == -1) { next; } # deleted from group
 5891:                     if (($start!=0) && ($start>$now)) { next; }
 5892:                     if (($end!=0) && ($end<$now)) {
 5893:                         if ($access_end && $access_end < $now) {
 5894:                             if ($access_end - $end < 86400) {
 5895:                                 push(@usersgroups,$group);
 5896:                             }
 5897:                         }
 5898:                         next;
 5899:                     }
 5900:                     push(@usersgroups,$group);
 5901:                 }
 5902:             }
 5903:         }
 5904:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5905:         $grouplist = join(':',@usersgroups);
 5906:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5907:     }
 5908:     return @usersgroups;
 5909: }
 5910: 
 5911: sub devalidate_getgroups_cache {
 5912:     my ($udom,$uname,$cdom,$cnum)=@_;
 5913:     my $courseid = $cdom.'_'.$cnum;
 5914: 
 5915:     my $hashid="$udom:$uname:$courseid";
 5916:     &devalidate_cache_new('getgroups',$hashid);
 5917: }
 5918: 
 5919: # ------------------------------------------------------------------ Plain Text
 5920: 
 5921: sub plaintext {
 5922:     my ($short,$type,$cid,$forcedefault) = @_;
 5923:     if ($short =~ /^cr/) {
 5924: 	return (split('/',$short))[-1];
 5925:     }
 5926:     if (!defined($cid)) {
 5927:         $cid = $env{'request.course.id'};
 5928:     }
 5929:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 5930:         unless ($forcedefault) {
 5931:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 5932:             &Apache::lonlocal::mt_escape(\$roletext);
 5933:             return &Apache::lonlocal::mt($roletext);
 5934:         }
 5935:     }
 5936:     my %rolenames = (
 5937:                       Course => 'std',
 5938:                       Group => 'alt1',
 5939:                     );
 5940:     if (defined($type) && 
 5941:          defined($rolenames{$type}) && 
 5942:          defined($prp{$short}{$rolenames{$type}})) {
 5943:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5944:     } else {
 5945:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5946:     }
 5947: }
 5948: 
 5949: # ----------------------------------------------------------------- Assign Role
 5950: 
 5951: sub assignrole {
 5952:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5953:         $context)=@_;
 5954:     my $mrole;
 5955:     if ($role =~ /^cr\//) {
 5956:         my $cwosec=$url;
 5957:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5958: 	unless (&allowed('ccr',$cwosec)) {
 5959:            &logthis('Refused custom assignrole: '.
 5960:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5961: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5962:            return 'refused'; 
 5963:         }
 5964:         $mrole='cr';
 5965:     } elsif ($role =~ /^gr\//) {
 5966:         my $cwogrp=$url;
 5967:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5968:         unless (&allowed('mdg',$cwogrp)) {
 5969:             &logthis('Refused group assignrole: '.
 5970:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5971:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5972:             return 'refused';
 5973:         }
 5974:         $mrole='gr';
 5975:     } else {
 5976:         my $cwosec=$url;
 5977:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5978:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5979:             my $refused;
 5980:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5981:                 if (!(&allowed('c'.$role,$url))) {
 5982:                     $refused = 1;
 5983:                 }
 5984:             } else {
 5985:                 $refused = 1;
 5986:             }
 5987:             if ($refused) {
 5988:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5989:                     $refused = '';
 5990:                 } else {
 5991:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5992:                              ' '.$role.' '.$end.' '.$start.' by '.
 5993: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5994:                     return 'refused';
 5995:                 }
 5996:             }
 5997:         }
 5998:         $mrole=$role;
 5999:     }
 6000:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6001:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6002:     if ($end) { $command.='_'.$end; }
 6003:     if ($start) {
 6004: 	if ($end) { 
 6005:            $command.='_'.$start; 
 6006:         } else {
 6007:            $command.='_0_'.$start;
 6008:         }
 6009:     }
 6010:     my $origstart = $start;
 6011:     my $origend = $end;
 6012:     my $delflag;
 6013: # actually delete
 6014:     if ($deleteflag) {
 6015: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6016: # modify command to delete the role
 6017:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6018:                 "$udom:$uname:$url".'_'."$mrole";
 6019: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6020: # set start and finish to negative values for userrolelog
 6021:            $start=-1;
 6022:            $end=-1;
 6023:            $delflag = 1;
 6024:         }
 6025:     }
 6026: # send command
 6027:     my $answer=&reply($command,&homeserver($uname,$udom));
 6028: # log new user role if status is ok
 6029:     if ($answer eq 'ok') {
 6030: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6031: # for course roles, perform group memberships changes triggered by role change.
 6032:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6033:         unless ($role =~ /^gr/) {
 6034:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6035:                                              $origstart,$selfenroll,$context);
 6036:         }
 6037:     }
 6038:     return $answer;
 6039: }
 6040: 
 6041: # -------------------------------------------------- Modify user authentication
 6042: # Overrides without validation
 6043: 
 6044: sub modifyuserauth {
 6045:     my ($udom,$uname,$umode,$upass)=@_;
 6046:     my $uhome=&homeserver($uname,$udom);
 6047:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6048:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6049:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6050:              ' in domain '.$env{'request.role.domain'});  
 6051:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6052: 		     &escape($upass),$uhome);
 6053:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6054:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6055:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6056:     &log($udom,,$uname,$uhome,
 6057:         'Authentication changed by '.$env{'user.domain'}.', '.
 6058:                                      $env{'user.name'}.', '.$umode.
 6059:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6060:     unless ($reply eq 'ok') {
 6061:         &logthis('Authentication mode error: '.$reply);
 6062: 	return 'error: '.$reply;
 6063:     }   
 6064:     return 'ok';
 6065: }
 6066: 
 6067: # --------------------------------------------------------------- Modify a user
 6068: 
 6069: sub modifyuser {
 6070:     my ($udom,    $uname, $uid,
 6071:         $umode,   $upass, $first,
 6072:         $middle,  $last,  $gene,
 6073:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6074:     $udom= &LONCAPA::clean_domain($udom);
 6075:     $uname=&LONCAPA::clean_username($uname);
 6076:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6077:              $umode.', '.$first.', '.$middle.', '.
 6078: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6079:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6080:                                      ' desiredhome not specified'). 
 6081:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6082:              ' in domain '.$env{'request.role.domain'});
 6083:     my $uhome=&homeserver($uname,$udom,'true');
 6084: # ----------------------------------------------------------------- Create User
 6085:     if (($uhome eq 'no_host') && 
 6086: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6087:         my $unhome='';
 6088:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6089:             $unhome = $desiredhome;
 6090: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6091: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6092:         } else { # load balancing routine for determining $unhome
 6093:             my $loadm=10000000;
 6094: 	    my %servers = &get_servers($udom,'library');
 6095: 	    foreach my $tryserver (keys(%servers)) {
 6096: 		my $answer=reply('load',$tryserver);
 6097: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6098: 		    $loadm=$answer;
 6099: 		    $unhome=$tryserver;
 6100: 		}
 6101: 	    }
 6102:         }
 6103:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6104: 	    return 'error: unable to find a home server for '.$uname.
 6105:                    ' in domain '.$udom;
 6106:         }
 6107:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6108:                          &escape($upass),$unhome);
 6109: 	unless ($reply eq 'ok') {
 6110:             return 'error: '.$reply;
 6111:         }   
 6112:         $uhome=&homeserver($uname,$udom,'true');
 6113:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6114: 	    return 'error: unable verify users home machine.';
 6115:         }
 6116:     }   # End of creation of new user
 6117: # ---------------------------------------------------------------------- Add ID
 6118:     if ($uid) {
 6119:        $uid=~tr/A-Z/a-z/;
 6120:        my %uidhash=&idrget($udom,$uname);
 6121:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6122:          && (!$forceid)) {
 6123: 	  unless ($uid eq $uidhash{$uname}) {
 6124: 	      return 'error: user id "'.$uid.'" does not match '.
 6125:                   'current user id "'.$uidhash{$uname}.'".';
 6126:           }
 6127:        } else {
 6128: 	  &idput($udom,($uname => $uid));
 6129:        }
 6130:     }
 6131: # -------------------------------------------------------------- Add names, etc
 6132:     my @tmp=&get('environment',
 6133: 		   ['firstname','middlename','lastname','generation','id',
 6134:                     'permanentemail','inststatus'],
 6135: 		   $udom,$uname);
 6136:     my %names;
 6137:     if ($tmp[0] =~ m/^error:.*/) { 
 6138:         %names=(); 
 6139:     } else {
 6140:         %names = @tmp;
 6141:     }
 6142: #
 6143: # Make sure to not trash student environment if instructor does not bother
 6144: # to supply name and email information
 6145: #
 6146:     if ($first)  { $names{'firstname'}  = $first; }
 6147:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6148:     if ($last)   { $names{'lastname'}   = $last; }
 6149:     if (defined($gene))   { $names{'generation'} = $gene; }
 6150:     if ($email) {
 6151:        $email=~s/[^\w\@\.\-\,]//gs;
 6152:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6153:     }
 6154:     if ($uid) { $names{'id'}  = $uid; }
 6155:     if (defined($inststatus)) {
 6156:         $names{'inststatus'} = '';
 6157:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6158:         if (ref($usertypes) eq 'HASH') {
 6159:             my @okstatuses; 
 6160:             foreach my $item (split(/:/,$inststatus)) {
 6161:                 if (defined($usertypes->{$item})) {
 6162:                     push(@okstatuses,$item);  
 6163:                 }
 6164:             }
 6165:             if (@okstatuses) {
 6166:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6167:             }
 6168:         }
 6169:     }
 6170:     my $reply = &put('environment', \%names, $udom,$uname);
 6171:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6172:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6173:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6174:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6175:                  $umode.', '.$first.', '.$middle.', '.
 6176: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6177:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6178:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6179:     } else {
 6180:         $logmsg .= ' during self creation';
 6181:     }
 6182:     &logthis($logmsg);
 6183:     return 'ok';
 6184: }
 6185: 
 6186: # -------------------------------------------------------------- Modify student
 6187: 
 6188: sub modifystudent {
 6189:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6190:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6191:         $selfenroll,$context,$inststatus)=@_;
 6192:     if (!$cid) {
 6193: 	unless ($cid=$env{'request.course.id'}) {
 6194: 	    return 'not_in_class';
 6195: 	}
 6196:     }
 6197: # --------------------------------------------------------------- Make the user
 6198:     my $reply=&modifyuser
 6199: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6200:          $desiredhome,$email,$inststatus);
 6201:     unless ($reply eq 'ok') { return $reply; }
 6202:     # This will cause &modify_student_enrollment to get the uid from the
 6203:     # students environment
 6204:     $uid = undef if (!$forceid);
 6205:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6206: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6207:     return $reply;
 6208: }
 6209: 
 6210: sub modify_student_enrollment {
 6211:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6212:     my ($cdom,$cnum,$chome);
 6213:     if (!$cid) {
 6214: 	unless ($cid=$env{'request.course.id'}) {
 6215: 	    return 'not_in_class';
 6216: 	}
 6217: 	$cdom=$env{'course.'.$cid.'.domain'};
 6218: 	$cnum=$env{'course.'.$cid.'.num'};
 6219:     } else {
 6220: 	($cdom,$cnum)=split(/_/,$cid);
 6221:     }
 6222:     $chome=$env{'course.'.$cid.'.home'};
 6223:     if (!$chome) {
 6224: 	$chome=&homeserver($cnum,$cdom);
 6225:     }
 6226:     if (!$chome) { return 'unknown_course'; }
 6227:     # Make sure the user exists
 6228:     my $uhome=&homeserver($uname,$udom);
 6229:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6230: 	return 'error: no such user';
 6231:     }
 6232:     # Get student data if we were not given enough information
 6233:     if (!defined($first)  || $first  eq '' || 
 6234:         !defined($last)   || $last   eq '' || 
 6235:         !defined($uid)    || $uid    eq '' || 
 6236:         !defined($middle) || $middle eq '' || 
 6237:         !defined($gene)   || $gene   eq '') {
 6238:         # They did not supply us with enough data to enroll the student, so
 6239:         # we need to pick up more information.
 6240:         my %tmp = &get('environment',
 6241:                        ['firstname','middlename','lastname', 'generation','id']
 6242:                        ,$udom,$uname);
 6243: 
 6244:         #foreach my $key (keys(%tmp)) {
 6245:         #    &logthis("key $key = ".$tmp{$key});
 6246:         #}
 6247:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6248:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6249:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6250:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6251:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6252:     }
 6253:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6254:     my $reply=cput('classlist',
 6255: 		   {"$uname:$udom" => 
 6256: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6257: 		   $cdom,$cnum);
 6258:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6259: 	return 'error: '.$reply;
 6260:     } else {
 6261: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6262:     }
 6263:     # Add student role to user
 6264:     my $uurl='/'.$cid;
 6265:     $uurl=~s/\_/\//g;
 6266:     if ($usec) {
 6267: 	$uurl.='/'.$usec;
 6268:     }
 6269:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6270: }
 6271: 
 6272: sub format_name {
 6273:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6274:     my $name;
 6275:     if ($first ne 'lastname') {
 6276: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6277:     } else {
 6278: 	if ($lastname=~/\S/) {
 6279: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6280: 	    $name=~s/\s+,/,/;
 6281: 	} else {
 6282: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6283: 	}
 6284:     }
 6285:     $name=~s/^\s+//;
 6286:     $name=~s/\s+$//;
 6287:     $name=~s/\s+/ /g;
 6288:     return $name;
 6289: }
 6290: 
 6291: # ------------------------------------------------- Write to course preferences
 6292: 
 6293: sub writecoursepref {
 6294:     my ($courseid,%prefs)=@_;
 6295:     $courseid=~s/^\///;
 6296:     $courseid=~s/\_/\//g;
 6297:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6298:     my $chome=homeserver($cnum,$cdomain);
 6299:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6300: 	return 'error: no such course';
 6301:     }
 6302:     my $cstring='';
 6303:     foreach my $pref (keys(%prefs)) {
 6304: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6305:     }
 6306:     $cstring=~s/\&$//;
 6307:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6308: }
 6309: 
 6310: # ---------------------------------------------------------- Make/modify course
 6311: 
 6312: sub createcourse {
 6313:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6314:         $course_owner,$crstype)=@_;
 6315:     $url=&declutter($url);
 6316:     my $cid='';
 6317:     unless (&allowed('ccc',$udom)) {
 6318:         return 'refused';
 6319:     }
 6320: # ------------------------------------------------------------------- Create ID
 6321:    my $uname=int(1+rand(9)).
 6322:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6323:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6324:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6325: # ----------------------------------------------- Make sure that does not exist
 6326:    my $uhome=&homeserver($uname,$udom,'true');
 6327:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6328:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6329:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6330:        $uhome=&homeserver($uname,$udom,'true');       
 6331:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6332:            return 'error: unable to generate unique course-ID';
 6333:        } 
 6334:    }
 6335: # ------------------------------------------------ Check supplied server name
 6336:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6337:     if (! &is_library($course_server)) {
 6338:         return 'error:bad server name '.$course_server;
 6339:     }
 6340: # ------------------------------------------------------------- Make the course
 6341:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6342:                       $course_server);
 6343:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6344:     $uhome=&homeserver($uname,$udom,'true');
 6345:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6346: 	return 'error: no such course';
 6347:     }
 6348: # ----------------------------------------------------------------- Course made
 6349: # log existence
 6350:     my $newcourse = {
 6351:                     $udom.'_'.$uname => {
 6352:                                      description => $description,
 6353:                                      inst_code   => $inst_code,
 6354:                                      owner       => $course_owner,
 6355:                                      type        => $crstype,
 6356:                                                 },
 6357:                     };
 6358:     &courseidput($udom,$newcourse,$uhome,'notime');
 6359: # set toplevel url
 6360:     my $topurl=$url;
 6361:     unless ($nonstandard) {
 6362: # ------------------------------------------ For standard courses, make top url
 6363:         my $mapurl=&clutter($url);
 6364:         if ($mapurl eq '/res/') { $mapurl=''; }
 6365:         $env{'form.initmap'}=(<<ENDINITMAP);
 6366: <map>
 6367: <resource id="1" type="start"></resource>
 6368: <resource id="2" src="$mapurl"></resource>
 6369: <resource id="3" type="finish"></resource>
 6370: <link index="1" from="1" to="2"></link>
 6371: <link index="2" from="2" to="3"></link>
 6372: </map>
 6373: ENDINITMAP
 6374:         $topurl=&declutter(
 6375:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6376:                           );
 6377:     }
 6378: # ----------------------------------------------------------- Write preferences
 6379:     &writecoursepref($udom.'_'.$uname,
 6380:                      ('description' => $description,
 6381:                       'url'         => $topurl));
 6382:     return '/'.$udom.'/'.$uname;
 6383: }
 6384: 
 6385: sub is_course {
 6386:     my ($cdom,$cnum) = @_;
 6387:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6388: 				undef,'.');
 6389:     if (exists($courses{$cdom.'_'.$cnum})) {
 6390:         return 1;
 6391:     }
 6392:     return 0;
 6393: }
 6394: 
 6395: # ---------------------------------------------------------- Assign Custom Role
 6396: 
 6397: sub assigncustomrole {
 6398:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6399:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6400:                        $end,$start,$deleteflag,$selfenroll,$context);
 6401: }
 6402: 
 6403: # ----------------------------------------------------------------- Revoke Role
 6404: 
 6405: sub revokerole {
 6406:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6407:     my $now=time;
 6408:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6409: }
 6410: 
 6411: # ---------------------------------------------------------- Revoke Custom Role
 6412: 
 6413: sub revokecustomrole {
 6414:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6415:     my $now=time;
 6416:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6417:            $deleteflag,$selfenroll,$context);
 6418: }
 6419: 
 6420: # ------------------------------------------------------------ Disk usage
 6421: sub diskusage {
 6422:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6423:     $directorypath =~ s/\/$//;
 6424:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6425:                        .&escape($getpropath).':'.&escape($uname).':'
 6426:                        .&escape($udom),homeserver($uname,$udom));
 6427:     if ($listing eq 'unknown_cmd') {
 6428:         if ($getpropath) {
 6429:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6430:         }
 6431:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6432:     }
 6433:     return $listing;
 6434: }
 6435: 
 6436: sub is_locked {
 6437:     my ($file_name, $domain, $user) = @_;
 6438:     my @check;
 6439:     my $is_locked;
 6440:     push @check, $file_name;
 6441:     my %locked = &get('file_permissions',\@check,
 6442: 		      $env{'user.domain'},$env{'user.name'});
 6443:     my ($tmp)=keys(%locked);
 6444:     if ($tmp=~/^error:/) { undef(%locked); }
 6445:     
 6446:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6447:         $is_locked = 'false';
 6448:         foreach my $entry (@{$locked{$file_name}}) {
 6449:            if (ref($entry) eq 'ARRAY') { 
 6450:                $is_locked = 'true';
 6451:                last;
 6452:            }
 6453:        }
 6454:     } else {
 6455:         $is_locked = 'false';
 6456:     }
 6457: }
 6458: 
 6459: sub declutter_portfile {
 6460:     my ($file) = @_;
 6461:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6462:     return $file;
 6463: }
 6464: 
 6465: # ------------------------------------------------------------- Mark as Read Only
 6466: 
 6467: sub mark_as_readonly {
 6468:     my ($domain,$user,$files,$what) = @_;
 6469:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6470:     my ($tmp)=keys(%current_permissions);
 6471:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6472:     foreach my $file (@{$files}) {
 6473: 	$file = &declutter_portfile($file);
 6474:         push(@{$current_permissions{$file}},$what);
 6475:     }
 6476:     &put('file_permissions',\%current_permissions,$domain,$user);
 6477:     return;
 6478: }
 6479: 
 6480: # ------------------------------------------------------------Save Selected Files
 6481: 
 6482: sub save_selected_files {
 6483:     my ($user, $path, @files) = @_;
 6484:     my $filename = $user."savedfiles";
 6485:     my @other_files = &files_not_in_path($user, $path);
 6486:     open (OUT, '>'.$tmpdir.$filename);
 6487:     foreach my $file (@files) {
 6488:         print (OUT $env{'form.currentpath'}.$file."\n");
 6489:     }
 6490:     foreach my $file (@other_files) {
 6491:         print (OUT $file."\n");
 6492:     }
 6493:     close (OUT);
 6494:     return 'ok';
 6495: }
 6496: 
 6497: sub clear_selected_files {
 6498:     my ($user) = @_;
 6499:     my $filename = $user."savedfiles";
 6500:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6501:     print (OUT undef);
 6502:     close (OUT);
 6503:     return ("ok");    
 6504: }
 6505: 
 6506: sub files_in_path {
 6507:     my ($user, $path) = @_;
 6508:     my $filename = $user."savedfiles";
 6509:     my %return_files;
 6510:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6511:     while (my $line_in = <IN>) {
 6512:         chomp ($line_in);
 6513:         my @paths_and_file = split (m!/!, $line_in);
 6514:         my $file_part = pop (@paths_and_file);
 6515:         my $path_part = join ('/', @paths_and_file);
 6516:         $path_part.='/';
 6517:         my $path_and_file = $path_part.$file_part;
 6518:         if ($path_part eq $path) {
 6519:             $return_files{$file_part}= 'selected';
 6520:         }
 6521:     }
 6522:     close (IN);
 6523:     return (\%return_files);
 6524: }
 6525: 
 6526: # called in portfolio select mode, to show files selected NOT in current directory
 6527: sub files_not_in_path {
 6528:     my ($user, $path) = @_;
 6529:     my $filename = $user."savedfiles";
 6530:     my @return_files;
 6531:     my $path_part;
 6532:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6533:     while (my $line = <IN>) {
 6534:         #ok, I know it's clunky, but I want it to work
 6535:         my @paths_and_file = split(m|/|, $line);
 6536:         my $file_part = pop(@paths_and_file);
 6537:         chomp($file_part);
 6538:         my $path_part = join('/', @paths_and_file);
 6539:         $path_part .= '/';
 6540:         my $path_and_file = $path_part.$file_part;
 6541:         if ($path_part ne $path) {
 6542:             push(@return_files, ($path_and_file));
 6543:         }
 6544:     }
 6545:     close(OUT);
 6546:     return (@return_files);
 6547: }
 6548: 
 6549: #----------------------------------------------Get portfolio file permissions
 6550: 
 6551: sub get_portfile_permissions {
 6552:     my ($domain,$user) = @_;
 6553:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6554:     my ($tmp)=keys(%current_permissions);
 6555:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6556:     return \%current_permissions;
 6557: }
 6558: 
 6559: #---------------------------------------------Get portfolio file access controls
 6560: 
 6561: sub get_access_controls {
 6562:     my ($current_permissions,$group,$file) = @_;
 6563:     my %access;
 6564:     my $real_file = $file;
 6565:     $file =~ s/\.meta$//;
 6566:     if (defined($file)) {
 6567:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6568:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6569:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6570:             }
 6571:         }
 6572:     } else {
 6573:         foreach my $key (keys(%{$current_permissions})) {
 6574:             if ($key =~ /\0accesscontrol$/) {
 6575:                 if (defined($group)) {
 6576:                     if ($key !~ m-^\Q$group\E/-) {
 6577:                         next;
 6578:                     }
 6579:                 }
 6580:                 my ($fullpath) = split(/\0/,$key);
 6581:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6582:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6583:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6584:                     }
 6585:                 }
 6586:             }
 6587:         }
 6588:     }
 6589:     return %access;
 6590: }
 6591: 
 6592: sub modify_access_controls {
 6593:     my ($file_name,$changes,$domain,$user)=@_;
 6594:     my ($outcome,$deloutcome);
 6595:     my %store_permissions;
 6596:     my %new_values;
 6597:     my %new_control;
 6598:     my %translation;
 6599:     my @deletions = ();
 6600:     my $now = time;
 6601:     if (exists($$changes{'activate'})) {
 6602:         if (ref($$changes{'activate'}) eq 'HASH') {
 6603:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6604:             my $numnew = scalar(@newitems);
 6605:             for (my $i=0; $i<$numnew; $i++) {
 6606:                 my $newkey = $newitems[$i];
 6607:                 my $newid = &Apache::loncommon::get_cgi_id();
 6608:                 if ($newkey =~ /^\d+:/) { 
 6609:                     $newkey =~ s/^(\d+)/$newid/;
 6610:                     $translation{$1} = $newid;
 6611:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6612:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6613:                     $translation{$1} = $newid;
 6614:                 }
 6615:                 $new_values{$file_name."\0".$newkey} = 
 6616:                                           $$changes{'activate'}{$newitems[$i]};
 6617:                 $new_control{$newkey} = $now;
 6618:             }
 6619:         }
 6620:     }
 6621:     my %todelete;
 6622:     my %changed_items;
 6623:     foreach my $action ('delete','update') {
 6624:         if (exists($$changes{$action})) {
 6625:             if (ref($$changes{$action}) eq 'HASH') {
 6626:                 foreach my $key (keys(%{$$changes{$action}})) {
 6627:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6628:                     if ($action eq 'delete') { 
 6629:                         $todelete{$itemnum} = 1;
 6630:                     } else {
 6631:                         $changed_items{$itemnum} = $key;
 6632:                     }
 6633:                 }
 6634:             }
 6635:         }
 6636:     }
 6637:     # get lock on access controls for file.
 6638:     my $lockhash = {
 6639:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6640:                                                        ':'.$env{'user.domain'},
 6641:                    }; 
 6642:     my $tries = 0;
 6643:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6644:    
 6645:     while (($gotlock ne 'ok') && $tries <3) {
 6646:         $tries ++;
 6647:         sleep 1;
 6648:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6649:     }
 6650:     if ($gotlock eq 'ok') {
 6651:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6652:         my ($tmp)=keys(%curr_permissions);
 6653:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6654:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6655:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6656:             if (ref($curr_controls) eq 'HASH') {
 6657:                 foreach my $control_item (keys(%{$curr_controls})) {
 6658:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6659:                     if (defined($todelete{$itemnum})) {
 6660:                         push(@deletions,$file_name."\0".$control_item);
 6661:                     } else {
 6662:                         if (defined($changed_items{$itemnum})) {
 6663:                             $new_control{$changed_items{$itemnum}} = $now;
 6664:                             push(@deletions,$file_name."\0".$control_item);
 6665:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6666:                         } else {
 6667:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6668:                         }
 6669:                     }
 6670:                 }
 6671:             }
 6672:         }
 6673:         my ($group);
 6674:         if (&is_course($domain,$user)) {
 6675:             ($group,my $file) = split(/\//,$file_name,2);
 6676:         }
 6677:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6678:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6679:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6680:         #  remove lock
 6681:         my @del_lock = ($file_name."\0".'locked_access_records');
 6682:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6683:         my $sqlresult =
 6684:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6685:                                     $group);
 6686:     } else {
 6687:         $outcome = "error: could not obtain lockfile\n";  
 6688:     }
 6689:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6690: }
 6691: 
 6692: sub make_public_indefinitely {
 6693:     my ($requrl) = @_;
 6694:     my $now = time;
 6695:     my $action = 'activate';
 6696:     my $aclnum = 0;
 6697:     if (&is_portfolio_url($requrl)) {
 6698:         my (undef,$udom,$unum,$file_name,$group) =
 6699:             &parse_portfolio_url($requrl);
 6700:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6701:         my %access_controls = &get_access_controls($current_perms,
 6702:                                                    $group,$file_name);
 6703:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6704:             my ($num,$scope,$end,$start) = 
 6705:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6706:             if ($scope eq 'public') {
 6707:                 if ($start <= $now && $end == 0) {
 6708:                     $action = 'none';
 6709:                 } else {
 6710:                     $action = 'update';
 6711:                     $aclnum = $num;
 6712:                 }
 6713:                 last;
 6714:             }
 6715:         }
 6716:         if ($action eq 'none') {
 6717:              return 'ok';
 6718:         } else {
 6719:             my %changes;
 6720:             my $newend = 0;
 6721:             my $newstart = $now;
 6722:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6723:             $changes{$action}{$newkey} = {
 6724:                 type => 'public',
 6725:                 time => {
 6726:                     start => $newstart,
 6727:                     end   => $newend,
 6728:                 },
 6729:             };
 6730:             my ($outcome,$deloutcome,$new_values,$translation) =
 6731:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6732:             return $outcome;
 6733:         }
 6734:     } else {
 6735:         return 'invalid';
 6736:     }
 6737: }
 6738: 
 6739: #------------------------------------------------------Get Marked as Read Only
 6740: 
 6741: sub get_marked_as_readonly {
 6742:     my ($domain,$user,$what,$group) = @_;
 6743:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6744:     my @readonly_files;
 6745:     my $cmp1=$what;
 6746:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6747:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6748:         if (defined($group)) {
 6749:             if ($file_name !~ m-^\Q$group\E/-) {
 6750:                 next;
 6751:             }
 6752:         }
 6753:         if (ref($value) eq "ARRAY"){
 6754:             foreach my $stored_what (@{$value}) {
 6755:                 my $cmp2=$stored_what;
 6756:                 if (ref($stored_what) eq 'ARRAY') {
 6757:                     $cmp2=join('',@{$stored_what});
 6758:                 }
 6759:                 if ($cmp1 eq $cmp2) {
 6760:                     push(@readonly_files, $file_name);
 6761:                     last;
 6762:                 } elsif (!defined($what)) {
 6763:                     push(@readonly_files, $file_name);
 6764:                     last;
 6765:                 }
 6766:             }
 6767:         }
 6768:     }
 6769:     return @readonly_files;
 6770: }
 6771: #-----------------------------------------------------------Get Marked as Read Only Hash
 6772: 
 6773: sub get_marked_as_readonly_hash {
 6774:     my ($current_permissions,$group,$what) = @_;
 6775:     my %readonly_files;
 6776:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6777:         if (defined($group)) {
 6778:             if ($file_name !~ m-^\Q$group\E/-) {
 6779:                 next;
 6780:             }
 6781:         }
 6782:         if (ref($value) eq "ARRAY"){
 6783:             foreach my $stored_what (@{$value}) {
 6784:                 if (ref($stored_what) eq 'ARRAY') {
 6785:                     foreach my $lock_descriptor(@{$stored_what}) {
 6786:                         if ($lock_descriptor eq 'graded') {
 6787:                             $readonly_files{$file_name} = 'graded';
 6788:                         } elsif ($lock_descriptor eq 'handback') {
 6789:                             $readonly_files{$file_name} = 'handback';
 6790:                         } else {
 6791:                             if (!exists($readonly_files{$file_name})) {
 6792:                                 $readonly_files{$file_name} = 'locked';
 6793:                             }
 6794:                         }
 6795:                     }
 6796:                 } 
 6797:             }
 6798:         } 
 6799:     }
 6800:     return %readonly_files;
 6801: }
 6802: # ------------------------------------------------------------ Unmark as Read Only
 6803: 
 6804: sub unmark_as_readonly {
 6805:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6806:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6807:     my ($domain,$user,$what,$file_name,$group) = @_;
 6808:     $file_name = &declutter_portfile($file_name);
 6809:     my $symb_crs = $what;
 6810:     if (ref($what)) { $symb_crs=join('',@$what); }
 6811:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6812:     my ($tmp)=keys(%current_permissions);
 6813:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6814:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6815:     foreach my $file (@readonly_files) {
 6816: 	my $clean_file = &declutter_portfile($file);
 6817: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6818: 	my $current_locks = $current_permissions{$file};
 6819:         my @new_locks;
 6820:         my @del_keys;
 6821:         if (ref($current_locks) eq "ARRAY"){
 6822:             foreach my $locker (@{$current_locks}) {
 6823:                 my $compare=$locker;
 6824:                 if (ref($locker) eq 'ARRAY') {
 6825:                     $compare=join('',@{$locker});
 6826:                     if ($compare ne $symb_crs) {
 6827:                         push(@new_locks, $locker);
 6828:                     }
 6829:                 }
 6830:             }
 6831:             if (scalar(@new_locks) > 0) {
 6832:                 $current_permissions{$file} = \@new_locks;
 6833:             } else {
 6834:                 push(@del_keys, $file);
 6835:                 &del('file_permissions',\@del_keys, $domain, $user);
 6836:                 delete($current_permissions{$file});
 6837:             }
 6838:         }
 6839:     }
 6840:     &put('file_permissions',\%current_permissions,$domain,$user);
 6841:     return;
 6842: }
 6843: 
 6844: # ------------------------------------------------------------ Directory lister
 6845: 
 6846: sub dirlist {
 6847:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6848:     $uri=~s/^\///;
 6849:     $uri=~s/\/$//;
 6850:     my ($udom, $uname);
 6851:     if ($getuserdir) {
 6852:         $udom = $userdomain;
 6853:         $uname = $username;
 6854:     } else {
 6855:         (undef,$udom,$uname)=split(/\//,$uri);
 6856:         if(defined($userdomain)) {
 6857:             $udom = $userdomain;
 6858:         }
 6859:         if(defined($username)) {
 6860:             $uname = $username;
 6861:         }
 6862:     }
 6863:     my ($dirRoot,$listing,@listing_results);
 6864: 
 6865:     $dirRoot = $perlvar{'lonDocRoot'};
 6866:     if (defined($getpropath)) {
 6867:         $dirRoot = &propath($udom,$uname);
 6868:         $dirRoot =~ s/\/$//;
 6869:     } elsif (defined($getuserdir)) {
 6870:         my $subdir=$uname.'__';
 6871:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6872:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6873:                    ."/$udom/$subdir/$uname";
 6874:     } elsif (defined($alternateRoot)) {
 6875:         $dirRoot = $alternateRoot;
 6876:     }
 6877: 
 6878:     if($udom) {
 6879:         if($uname) {
 6880:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6881:                               .$getuserdir.':'.&escape($dirRoot)
 6882:                               .':'.&escape($uname).':'.&escape($udom),
 6883:                               &homeserver($uname,$udom));
 6884:             if ($listing eq 'unknown_cmd') {
 6885:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6886:                                   &homeserver($uname,$udom));
 6887:             } else {
 6888:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6889:             }
 6890:             if ($listing eq 'unknown_cmd') {
 6891:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6892: 				  &homeserver($uname,$udom));
 6893:                 @listing_results = split(/:/,$listing);
 6894:             } else {
 6895:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6896:             }
 6897:             return @listing_results;
 6898:         } elsif(!$alternateRoot) {
 6899:             my %allusers;
 6900: 	    my %servers = &get_servers($udom,'library');
 6901:  	    foreach my $tryserver (keys(%servers)) {
 6902:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6903:                                   &escape($udom),$tryserver);
 6904:                 if ($listing eq 'unknown_cmd') {
 6905: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6906: 				      $udom, $tryserver);
 6907:                 } else {
 6908:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6909:                 }
 6910: 		if ($listing eq 'unknown_cmd') {
 6911: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6912: 				      $udom, $tryserver);
 6913: 		    @listing_results = split(/:/,$listing);
 6914: 		} else {
 6915: 		    @listing_results =
 6916: 			map { &unescape($_); } split(/:/,$listing);
 6917: 		}
 6918: 		if ($listing_results[0] ne 'no_such_dir' && 
 6919: 		    $listing_results[0] ne 'empty'       &&
 6920: 		    $listing_results[0] ne 'con_lost') {
 6921: 		    foreach my $line (@listing_results) {
 6922: 			my ($entry) = split(/&/,$line,2);
 6923: 			$allusers{$entry} = 1;
 6924: 		    }
 6925: 		}
 6926:             }
 6927:             my $alluserstr='';
 6928:             foreach my $user (sort(keys(%allusers))) {
 6929:                 $alluserstr.=$user.'&user:';
 6930:             }
 6931:             $alluserstr=~s/:$//;
 6932:             return split(/:/,$alluserstr);
 6933:         } else {
 6934:             return ('missing user name');
 6935:         }
 6936:     } elsif(!defined($getpropath)) {
 6937:         my @all_domains = sort(&all_domains());
 6938:         foreach my $domain (@all_domains) {
 6939:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6940:         }
 6941:         return @all_domains;
 6942:     } else {
 6943:         return ('missing domain');
 6944:     }
 6945: }
 6946: 
 6947: # --------------------------------------------- GetFileTimestamp
 6948: # This function utilizes dirlist and returns the date stamp for
 6949: # when it was last modified.  It will also return an error of -1
 6950: # if an error occurs
 6951: 
 6952: sub GetFileTimestamp {
 6953:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6954:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6955:     $studentName   = &LONCAPA::clean_username($studentName);
 6956:     my ($fileStat) = 
 6957:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6958:                                  undef,$getuserdir);
 6959:     my @stats = split('&', $fileStat);
 6960:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6961:         # @stats contains first the filename, then the stat output
 6962:         return $stats[10]; # so this is 10 instead of 9.
 6963:     } else {
 6964:         return -1;
 6965:     }
 6966: }
 6967: 
 6968: sub stat_file {
 6969:     my ($uri) = @_;
 6970:     $uri = &clutter_with_no_wrapper($uri);
 6971: 
 6972:     my ($udom,$uname,$file);
 6973:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6974: 	($udom,$uname,$file) =
 6975: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6976: 	$file = 'userfiles/'.$file;
 6977:     }
 6978:     if ($uri =~ m-^/res/-) {
 6979: 	($udom,$uname) = 
 6980: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6981: 	$file = $uri;
 6982:     }
 6983: 
 6984:     if (!$udom || !$uname || !$file) {
 6985: 	# unable to handle the uri
 6986: 	return ();
 6987:     }
 6988:     my $getpropath;
 6989:     if ($file =~ /^userfiles\//) {
 6990:         $getpropath = 1;
 6991:     }
 6992:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6993:     my @stats = split('&', $result);
 6994:     
 6995:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6996: 	shift(@stats); #filename is first
 6997: 	return @stats;
 6998:     }
 6999:     return ();
 7000: }
 7001: 
 7002: # -------------------------------------------------------- Value of a Condition
 7003: 
 7004: # gets the value of a specific preevaluated condition
 7005: #    stored in the string  $env{user.state.<cid>}
 7006: # or looks up a condition reference in the bighash and if if hasn't
 7007: # already been evaluated recurses into docondval to get the value of
 7008: # the condition, then memoizing it to 
 7009: #   $env{user.state.<cid>.<condition>}
 7010: sub directcondval {
 7011:     my $number=shift;
 7012:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7013: 	&Apache::lonuserstate::evalstate();
 7014:     }
 7015:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7016: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7017:     } elsif ($number =~ /^_/) {
 7018: 	my $sub_condition;
 7019: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7020: 		&GDBM_READER(),0640)) {
 7021: 	    $sub_condition=$bighash{'conditions'.$number};
 7022: 	    untie(%bighash);
 7023: 	}
 7024: 	my $value = &docondval($sub_condition);
 7025: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7026: 	return $value;
 7027:     }
 7028:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7029:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7030:     } else {
 7031:        return 2;
 7032:     }
 7033: }
 7034: 
 7035: # get the collection of conditions for this resource
 7036: sub condval {
 7037:     my $condidx=shift;
 7038:     my $allpathcond='';
 7039:     foreach my $cond (split(/\|/,$condidx)) {
 7040: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7041: 	    $allpathcond.=
 7042: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7043: 	}
 7044:     }
 7045:     $allpathcond=~s/\|$//;
 7046:     return &docondval($allpathcond);
 7047: }
 7048: 
 7049: #evaluates an expression of conditions
 7050: sub docondval {
 7051:     my ($allpathcond) = @_;
 7052:     my $result=0;
 7053:     if ($env{'request.course.id'}
 7054: 	&& defined($allpathcond)) {
 7055: 	my $operand='|';
 7056: 	my @stack;
 7057: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7058: 	    if ($chunk eq '(') {
 7059: 		push @stack,($operand,$result);
 7060: 	    } elsif ($chunk eq ')') {
 7061: 		my $before=pop @stack;
 7062: 		if (pop @stack eq '&') {
 7063: 		    $result=$result>$before?$before:$result;
 7064: 		} else {
 7065: 		    $result=$result>$before?$result:$before;
 7066: 		}
 7067: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7068: 		$operand=$chunk;
 7069: 	    } else {
 7070: 		my $new=directcondval($chunk);
 7071: 		if ($operand eq '&') {
 7072: 		    $result=$result>$new?$new:$result;
 7073: 		} else {
 7074: 		    $result=$result>$new?$result:$new;
 7075: 		}
 7076: 	    }
 7077: 	}
 7078:     }
 7079:     return $result;
 7080: }
 7081: 
 7082: # ---------------------------------------------------- Devalidate courseresdata
 7083: 
 7084: sub devalidatecourseresdata {
 7085:     my ($coursenum,$coursedomain)=@_;
 7086:     my $hashid=$coursenum.':'.$coursedomain;
 7087:     &devalidate_cache_new('courseres',$hashid);
 7088: }
 7089: 
 7090: 
 7091: # --------------------------------------------------- Course Resourcedata Query
 7092: #
 7093: #  Parameters:
 7094: #      $coursenum    - Number of the course.
 7095: #      $coursedomain - Domain at which the course was created.
 7096: #  Returns:
 7097: #     A hash of the course parameters along (I think) with timestamps
 7098: #     and version info.
 7099: 
 7100: sub get_courseresdata {
 7101:     my ($coursenum,$coursedomain)=@_;
 7102:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7103:     my $hashid=$coursenum.':'.$coursedomain;
 7104:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7105:     my %dumpreply;
 7106:     unless (defined($cached)) {
 7107: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7108: 	$result=\%dumpreply;
 7109: 	my ($tmp) = keys(%dumpreply);
 7110: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7111: 	    &do_cache_new('courseres',$hashid,$result,600);
 7112: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7113: 	    return $tmp;
 7114: 	} elsif ($tmp =~ /^(error)/) {
 7115: 	    $result=undef;
 7116: 	    &do_cache_new('courseres',$hashid,$result,600);
 7117: 	}
 7118:     }
 7119:     return $result;
 7120: }
 7121: 
 7122: sub devalidateuserresdata {
 7123:     my ($uname,$udom)=@_;
 7124:     my $hashid="$udom:$uname";
 7125:     &devalidate_cache_new('userres',$hashid);
 7126: }
 7127: 
 7128: sub get_userresdata {
 7129:     my ($uname,$udom)=@_;
 7130:     #most student don\'t have any data set, check if there is some data
 7131:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7132: 
 7133:     my $hashid="$udom:$uname";
 7134:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7135:     if (!defined($cached)) {
 7136: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7137: 	$result=\%resourcedata;
 7138: 	&do_cache_new('userres',$hashid,$result,600);
 7139:     }
 7140:     my ($tmp)=keys(%$result);
 7141:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7142: 	return $result;
 7143:     }
 7144:     #error 2 occurs when the .db doesn't exist
 7145:     if ($tmp!~/error: 2 /) {
 7146: 	&logthis("<font color=\"blue\">WARNING:".
 7147: 		 " Trying to get resource data for ".
 7148: 		 $uname." at ".$udom.": ".
 7149: 		 $tmp."</font>");
 7150:     } elsif ($tmp=~/error: 2 /) {
 7151: 	#&EXT_cache_set($udom,$uname);
 7152: 	&do_cache_new('userres',$hashid,undef,600);
 7153: 	undef($tmp); # not really an error so don't send it back
 7154:     }
 7155:     return $tmp;
 7156: }
 7157: #----------------------------------------------- resdata - return resource data
 7158: #  Purpose:
 7159: #    Return resource data for either users or for a course.
 7160: #  Parameters:
 7161: #     $name      - Course/user name.
 7162: #     $domain    - Name of the domain the user/course is registered on.
 7163: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7164: #     @which     - Array of names of resources desired.
 7165: #  Returns:
 7166: #     The value of the first reasource in @which that is found in the
 7167: #     resource hash.
 7168: #  Exceptional Conditions:
 7169: #     If the $type passed in is not valid (not the string 'course' or 
 7170: #     'user', an undefined  reference is returned.
 7171: #     If none of the resources are found, an undef is returned
 7172: sub resdata {
 7173:     my ($name,$domain,$type,@which)=@_;
 7174:     my $result;
 7175:     if ($type eq 'course') {
 7176: 	$result=&get_courseresdata($name,$domain);
 7177:     } elsif ($type eq 'user') {
 7178: 	$result=&get_userresdata($name,$domain);
 7179:     }
 7180:     if (!ref($result)) { return $result; }    
 7181:     foreach my $item (@which) {
 7182: 	if (defined($result->{$item->[0]})) {
 7183: 	    return [$result->{$item->[0]},$item->[1]];
 7184: 	}
 7185:     }
 7186:     return undef;
 7187: }
 7188: 
 7189: #
 7190: # EXT resource caching routines
 7191: #
 7192: 
 7193: sub clear_EXT_cache_status {
 7194:     &delenv('cache.EXT.');
 7195: }
 7196: 
 7197: sub EXT_cache_status {
 7198:     my ($target_domain,$target_user) = @_;
 7199:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7200:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7201:         # We know already the user has no data
 7202:         return 1;
 7203:     } else {
 7204:         return 0;
 7205:     }
 7206: }
 7207: 
 7208: sub EXT_cache_set {
 7209:     my ($target_domain,$target_user) = @_;
 7210:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7211:     #&appenv({$cachename => time});
 7212: }
 7213: 
 7214: # --------------------------------------------------------- Value of a Variable
 7215: sub EXT {
 7216: 
 7217:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7218:     unless ($varname) { return ''; }
 7219:     #get real user name/domain, courseid and symb
 7220:     my $courseid;
 7221:     my $publicuser;
 7222:     if ($symbparm) {
 7223: 	$symbparm=&get_symb_from_alias($symbparm);
 7224:     }
 7225:     if (!($uname && $udom)) {
 7226:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7227:       if (!$symbparm) {	$symbparm=$cursymb; }
 7228:     } else {
 7229: 	$courseid=$env{'request.course.id'};
 7230:     }
 7231:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7232:     my $rest;
 7233:     if (defined($therest[0])) {
 7234:        $rest=join('.',@therest);
 7235:     } else {
 7236:        $rest='';
 7237:     }
 7238: 
 7239:     my $qualifierrest=$qualifier;
 7240:     if ($rest) { $qualifierrest.='.'.$rest; }
 7241:     my $spacequalifierrest=$space;
 7242:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7243:     if ($realm eq 'user') {
 7244: # --------------------------------------------------------------- user.resource
 7245: 	if ($space eq 'resource') {
 7246: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7247: 		  || defined($Apache::lonhomework::parsing_a_task))
 7248: 		 &&
 7249: 		 ($symbparm eq &symbread()) ) {	
 7250: 		# if we are in the middle of processing the resource the
 7251: 		# get the value we are planning on committing
 7252:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7253:                     return $Apache::lonhomework::results{$qualifierrest};
 7254:                 } else {
 7255:                     return $Apache::lonhomework::history{$qualifierrest};
 7256:                 }
 7257: 	    } else {
 7258: 		my %restored;
 7259: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7260: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7261: 		} else {
 7262: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7263: 		}
 7264: 		return $restored{$qualifierrest};
 7265: 	    }
 7266: # ----------------------------------------------------------------- user.access
 7267:         } elsif ($space eq 'access') {
 7268: 	    # FIXME - not supporting calls for a specific user
 7269:             return &allowed($qualifier,$rest);
 7270: # ------------------------------------------ user.preferences, user.environment
 7271:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7272: 	    if (($uname eq $env{'user.name'}) &&
 7273: 		($udom eq $env{'user.domain'})) {
 7274: 		return $env{join('.',('environment',$qualifierrest))};
 7275: 	    } else {
 7276: 		my %returnhash;
 7277: 		if (!$publicuser) {
 7278: 		    %returnhash=&userenvironment($udom,$uname,
 7279: 						 $qualifierrest);
 7280: 		}
 7281: 		return $returnhash{$qualifierrest};
 7282: 	    }
 7283: # ----------------------------------------------------------------- user.course
 7284:         } elsif ($space eq 'course') {
 7285: 	    # FIXME - not supporting calls for a specific user
 7286:             return $env{join('.',('request.course',$qualifier))};
 7287: # ------------------------------------------------------------------- user.role
 7288:         } elsif ($space eq 'role') {
 7289: 	    # FIXME - not supporting calls for a specific user
 7290:             my ($role,$where)=split(/\./,$env{'request.role'});
 7291:             if ($qualifier eq 'value') {
 7292: 		return $role;
 7293:             } elsif ($qualifier eq 'extent') {
 7294:                 return $where;
 7295:             }
 7296: # ----------------------------------------------------------------- user.domain
 7297:         } elsif ($space eq 'domain') {
 7298:             return $udom;
 7299: # ------------------------------------------------------------------- user.name
 7300:         } elsif ($space eq 'name') {
 7301:             return $uname;
 7302: # ---------------------------------------------------- Any other user namespace
 7303:         } else {
 7304: 	    my %reply;
 7305: 	    if (!$publicuser) {
 7306: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7307: 	    }
 7308: 	    return $reply{$qualifierrest};
 7309:         }
 7310:     } elsif ($realm eq 'query') {
 7311: # ---------------------------------------------- pull stuff out of query string
 7312:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7313: 						[$spacequalifierrest]);
 7314: 	return $env{'form.'.$spacequalifierrest}; 
 7315:    } elsif ($realm eq 'request') {
 7316: # ------------------------------------------------------------- request.browser
 7317:         if ($space eq 'browser') {
 7318: 	    if ($qualifier eq 'textremote') {
 7319: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7320: 		    return 1;
 7321: 		} else {
 7322: 		    return 0;
 7323: 		}
 7324: 	    } else {
 7325: 		return $env{'browser.'.$qualifier};
 7326: 	    }
 7327: # ------------------------------------------------------------ request.filename
 7328:         } else {
 7329:             return $env{'request.'.$spacequalifierrest};
 7330:         }
 7331:     } elsif ($realm eq 'course') {
 7332: # ---------------------------------------------------------- course.description
 7333:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7334:     } elsif ($realm eq 'resource') {
 7335: 
 7336: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7337: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7338: 	}
 7339: 
 7340: 	if ($space eq 'title') {
 7341: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7342: 	    return &gettitle($symbparm);
 7343: 	}
 7344: 	
 7345: 	if ($space eq 'map') {
 7346: 	    my ($map) = &decode_symb($symbparm);
 7347: 	    return &symbread($map);
 7348: 	}
 7349: 	if ($space eq 'filename') {
 7350: 	    if ($symbparm) {
 7351: 		return &clutter((&decode_symb($symbparm))[2]);
 7352: 	    }
 7353: 	    return &hreflocation('',$env{'request.filename'});
 7354: 	}
 7355: 
 7356: 	my ($section, $group, @groups);
 7357: 	my ($courselevelm,$courselevel);
 7358: 	if ($symbparm && defined($courseid) && 
 7359: 	    $courseid eq $env{'request.course.id'}) {
 7360: 
 7361: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7362: 
 7363: # ----------------------------------------------------- Cascading lookup scheme
 7364: 	    my $symbp=$symbparm;
 7365: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7366: 
 7367: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7368: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7369: 
 7370: 	    if (($env{'user.name'} eq $uname) &&
 7371: 		($env{'user.domain'} eq $udom)) {
 7372: 		$section=$env{'request.course.sec'};
 7373:                 @groups = split(/:/,$env{'request.course.groups'});  
 7374:                 @groups=&sort_course_groups($courseid,@groups); 
 7375: 	    } else {
 7376: 		if (! defined($usection)) {
 7377: 		    $section=&getsection($udom,$uname,$courseid);
 7378: 		} else {
 7379: 		    $section = $usection;
 7380: 		}
 7381:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7382: 	    }
 7383: 
 7384: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7385: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7386: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7387: 
 7388: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7389: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7390: 	    $courselevelm=$courseid.'.'.$mapparm;
 7391: 
 7392: # ----------------------------------------------------------- first, check user
 7393: 
 7394: 	    my $userreply=&resdata($uname,$udom,'user',
 7395: 				       ([$courselevelr,'resource'],
 7396: 					[$courselevelm,'map'     ],
 7397: 					[$courselevel, 'course'  ]));
 7398: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7399: 
 7400: # ------------------------------------------------ second, check some of course
 7401:             my $coursereply;
 7402:             if (@groups > 0) {
 7403:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7404:                                        $mapparm,$spacequalifierrest);
 7405:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7406:             }
 7407: 
 7408: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7409: 				  $env{'course.'.$courseid.'.domain'},
 7410: 				  'course',
 7411: 				  ([$seclevelr,   'resource'],
 7412: 				   [$seclevelm,   'map'     ],
 7413: 				   [$seclevel,    'course'  ],
 7414: 				   [$courselevelr,'resource']));
 7415: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7416: 
 7417: # ------------------------------------------------------ third, check map parms
 7418: 	    my %parmhash=();
 7419: 	    my $thisparm='';
 7420: 	    if (tie(%parmhash,'GDBM_File',
 7421: 		    $env{'request.course.fn'}.'_parms.db',
 7422: 		    &GDBM_READER(),0640)) {
 7423: 		$thisparm=$parmhash{$symbparm};
 7424: 		untie(%parmhash);
 7425: 	    }
 7426: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7427: 	}
 7428: # ------------------------------------------ fourth, look in resource metadata
 7429: 
 7430: 	$spacequalifierrest=~s/\./\_/;
 7431: 	my $filename;
 7432: 	if (!$symbparm) { $symbparm=&symbread(); }
 7433: 	if ($symbparm) {
 7434: 	    $filename=(&decode_symb($symbparm))[2];
 7435: 	} else {
 7436: 	    $filename=$env{'request.filename'};
 7437: 	}
 7438: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7439: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7440: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7441: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7442: 
 7443: # ---------------------------------------------- fourth, look in rest of course
 7444: 	if ($symbparm && defined($courseid) && 
 7445: 	    $courseid eq $env{'request.course.id'}) {
 7446: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7447: 				     $env{'course.'.$courseid.'.domain'},
 7448: 				     'course',
 7449: 				     ([$courselevelm,'map'   ],
 7450: 				      [$courselevel, 'course']));
 7451: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7452: 	}
 7453: # ------------------------------------------------------------------ Cascade up
 7454: 	unless ($space eq '0') {
 7455: 	    my @parts=split(/_/,$space);
 7456: 	    my $id=pop(@parts);
 7457: 	    my $part=join('_',@parts);
 7458: 	    if ($part eq '') { $part='0'; }
 7459: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7460: 				 $symbparm,$udom,$uname,$section,1);
 7461: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7462: 	}
 7463: 	if ($recurse) { return undef; }
 7464: 	my $pack_def=&packages_tab_default($filename,$varname);
 7465: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7466: # ---------------------------------------------------- Any other user namespace
 7467:     } elsif ($realm eq 'environment') {
 7468: # ----------------------------------------------------------------- environment
 7469: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7470: 	    return $env{'environment.'.$spacequalifierrest};
 7471: 	} else {
 7472: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7473: 		return '';
 7474: 	    }
 7475: 	    my %returnhash=&userenvironment($udom,$uname,
 7476: 					    $spacequalifierrest);
 7477: 	    return $returnhash{$spacequalifierrest};
 7478: 	}
 7479:     } elsif ($realm eq 'system') {
 7480: # ----------------------------------------------------------------- system.time
 7481: 	if ($space eq 'time') {
 7482: 	    return time;
 7483:         }
 7484:     } elsif ($realm eq 'server') {
 7485: # ----------------------------------------------------------------- system.time
 7486: 	if ($space eq 'name') {
 7487: 	    return $ENV{'SERVER_NAME'};
 7488:         }
 7489:     }
 7490:     return '';
 7491: }
 7492: 
 7493: sub get_reply {
 7494:     my ($reply_value) = @_;
 7495:     if (ref($reply_value) eq 'ARRAY') {
 7496:         if (wantarray) {
 7497: 	    return @$reply_value;
 7498:         }
 7499:         return $reply_value->[0];
 7500:     } else {
 7501:         return $reply_value;
 7502:     }
 7503: }
 7504: 
 7505: sub check_group_parms {
 7506:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7507:     my @groupitems = ();
 7508:     my $resultitem;
 7509:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7510:     foreach my $group (@{$groups}) {
 7511:         foreach my $level (@levels) {
 7512:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7513:              push(@groupitems,[$item,$level->[1]]);
 7514:         }
 7515:     }
 7516:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7517:                             $env{'course.'.$courseid.'.domain'},
 7518:                                      'course',@groupitems);
 7519:     return $coursereply;
 7520: }
 7521: 
 7522: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7523:     my ($courseid,@groups) = @_;
 7524:     @groups = sort(@groups);
 7525:     return @groups;
 7526: }
 7527: 
 7528: sub packages_tab_default {
 7529:     my ($uri,$varname)=@_;
 7530:     my (undef,$part,$name)=split(/\./,$varname);
 7531: 
 7532:     my (@extension,@specifics,$do_default);
 7533:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7534: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7535: 	if ($pack_type eq 'default') {
 7536: 	    $do_default=1;
 7537: 	} elsif ($pack_type eq 'extension') {
 7538: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7539: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7540: 	    # only look at packages defaults for packages that this id is
 7541: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7542: 	}
 7543:     }
 7544:     # first look for a package that matches the requested part id
 7545:     foreach my $package (@specifics) {
 7546: 	my (undef,$pack_type,$pack_part)=@{$package};
 7547: 	next if ($pack_part ne $part);
 7548: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7549: 	    return $packagetab{"$pack_type&$name&default"};
 7550: 	}
 7551:     }
 7552:     # look for any possible matching non extension_ package
 7553:     foreach my $package (@specifics) {
 7554: 	my (undef,$pack_type,$pack_part)=@{$package};
 7555: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7556: 	    return $packagetab{"$pack_type&$name&default"};
 7557: 	}
 7558: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7559: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7560: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7561: 	}
 7562:     }
 7563:     # look for any posible extension_ match
 7564:     foreach my $package (@extension) {
 7565: 	my ($package,$pack_type)=@{$package};
 7566: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7567: 	    return $packagetab{"$pack_type&$name&default"};
 7568: 	}
 7569: 	if (defined($packagetab{$package."&$name&default"})) {
 7570: 	    return $packagetab{$package."&$name&default"};
 7571: 	}
 7572:     }
 7573:     # look for a global default setting
 7574:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7575: 	return $packagetab{"default&$name&default"};
 7576:     }
 7577:     return undef;
 7578: }
 7579: 
 7580: sub add_prefix_and_part {
 7581:     my ($prefix,$part)=@_;
 7582:     my $keyroot;
 7583:     if (defined($prefix) && $prefix !~ /^__/) {
 7584: 	# prefix that has a part already
 7585: 	$keyroot=$prefix;
 7586:     } elsif (defined($prefix)) {
 7587: 	# prefix that is missing a part
 7588: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7589:     } else {
 7590: 	# no prefix at all
 7591: 	if (defined($part)) { $keyroot='_'.$part; }
 7592:     }
 7593:     return $keyroot;
 7594: }
 7595: 
 7596: # ---------------------------------------------------------------- Get metadata
 7597: 
 7598: my %metaentry;
 7599: sub metadata {
 7600:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7601:     $uri=&declutter($uri);
 7602:     # if it is a non metadata possible uri return quickly
 7603:     if (($uri eq '') || 
 7604: 	(($uri =~ m|^/*adm/|) && 
 7605: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7606:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7607: 	return undef;
 7608:     }
 7609:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7610: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7611: 	return undef;
 7612:     }
 7613:     my $filename=$uri;
 7614:     $uri=~s/\.meta$//;
 7615: #
 7616: # Is the metadata already cached?
 7617: # Look at timestamp of caching
 7618: # Everything is cached by the main uri, libraries are never directly cached
 7619: #
 7620:     if (!defined($liburi)) {
 7621: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7622: 	if (defined($cached)) { return $result->{':'.$what}; }
 7623:     }
 7624:     {
 7625: #
 7626: # Is this a recursive call for a library?
 7627: #
 7628: #	if (! exists($metacache{$uri})) {
 7629: #	    $metacache{$uri}={};
 7630: #	}
 7631: 	my $cachetime = 60*60;
 7632:         if ($liburi) {
 7633: 	    $liburi=&declutter($liburi);
 7634:             $filename=$liburi;
 7635:         } else {
 7636: 	    &devalidate_cache_new('meta',$uri);
 7637: 	    undef(%metaentry);
 7638: 	}
 7639:         my %metathesekeys=();
 7640:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7641: 	my $metastring;
 7642: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7643: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7644: 	    $metastring = 
 7645: 		&Apache::lonnet::ssi_body($which,
 7646: 					  ('grade_target' => 'meta'));
 7647: 	    $cachetime = 1; # only want this cached in the child not long term
 7648: 	} elsif ($uri !~ m -^(editupload)/-) {
 7649: 	    my $file=&filelocation('',&clutter($filename));
 7650: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7651: 	    $metastring=&getfile($file);
 7652: 	}
 7653:         my $parser=HTML::LCParser->new(\$metastring);
 7654:         my $token;
 7655:         undef %metathesekeys;
 7656:         while ($token=$parser->get_token) {
 7657: 	    if ($token->[0] eq 'S') {
 7658: 		if (defined($token->[2]->{'package'})) {
 7659: #
 7660: # This is a package - get package info
 7661: #
 7662: 		    my $package=$token->[2]->{'package'};
 7663: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7664: 		    if (defined($token->[2]->{'id'})) { 
 7665: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7666: 		    }
 7667: 		    if ($metaentry{':packages'}) {
 7668: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7669: 		    } else {
 7670: 			$metaentry{':packages'}=$package.$keyroot;
 7671: 		    }
 7672: 		    foreach my $pack_entry (keys(%packagetab)) {
 7673: 			my $part=$keyroot;
 7674: 			$part=~s/^\_//;
 7675: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7676: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7677: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7678: 			    # ignore package.tab specified default values
 7679:                             # here &package_tab_default() will fetch those
 7680: 			    if ($subp eq 'default') { next; }
 7681: 			    my $value=$packagetab{$pack_entry};
 7682: 			    my $unikey;
 7683: 			    if ($pack =~ /_0$/) {
 7684: 				$unikey='parameter_0_'.$name;
 7685: 				$part=0;
 7686: 			    } else {
 7687: 				$unikey='parameter'.$keyroot.'_'.$name;
 7688: 			    }
 7689: 			    if ($subp eq 'display') {
 7690: 				$value.=' [Part: '.$part.']';
 7691: 			    }
 7692: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7693: 			    $metathesekeys{$unikey}=1;
 7694: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7695: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7696: 			    }
 7697: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7698: 				$metaentry{':'.$unikey}=
 7699: 				    $metaentry{':'.$unikey.'.default'};
 7700: 			    }
 7701: 			}
 7702: 		    }
 7703: 		} else {
 7704: #
 7705: # This is not a package - some other kind of start tag
 7706: #
 7707: 		    my $entry=$token->[1];
 7708: 		    my $unikey;
 7709: 		    if ($entry eq 'import') {
 7710: 			$unikey='';
 7711: 		    } else {
 7712: 			$unikey=$entry;
 7713: 		    }
 7714: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7715: 
 7716: 		    if (defined($token->[2]->{'id'})) { 
 7717: 			$unikey.='_'.$token->[2]->{'id'}; 
 7718: 		    }
 7719: 
 7720: 		    if ($entry eq 'import') {
 7721: #
 7722: # Importing a library here
 7723: #
 7724: 			if ($depthcount<20) {
 7725: 			    my $location=$parser->get_text('/import');
 7726: 			    my $dir=$filename;
 7727: 			    $dir=~s|[^/]*$||;
 7728: 			    $location=&filelocation($dir,$location);
 7729: 			    my $metadata = 
 7730: 				&metadata($uri,'keys', $location,$unikey,
 7731: 					  $depthcount+1);
 7732: 			    foreach my $meta (split(',',$metadata)) {
 7733: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7734: 				$metathesekeys{$meta}=1;
 7735: 			    }
 7736: 			}
 7737: 		    } else { 
 7738: 			
 7739: 			if (defined($token->[2]->{'name'})) { 
 7740: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7741: 			}
 7742: 			$metathesekeys{$unikey}=1;
 7743: 			foreach my $param (@{$token->[3]}) {
 7744: 			    $metaentry{':'.$unikey.'.'.$param} =
 7745: 				$token->[2]->{$param};
 7746: 			}
 7747: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7748: 			my $default=$metaentry{':'.$unikey.'.default'};
 7749: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7750: 		 # only ws inside the tag, and not in default, so use default
 7751: 		 # as value
 7752: 			    $metaentry{':'.$unikey}=$default;
 7753: 			} elsif ( $internaltext =~ /\S/ ) {
 7754: 		  # something interesting inside the tag
 7755: 			    $metaentry{':'.$unikey}=$internaltext;
 7756: 			} else {
 7757: 		  # no interesting values, don't set a default
 7758: 			}
 7759: # end of not-a-package not-a-library import
 7760: 		    }
 7761: # end of not-a-package start tag
 7762: 		}
 7763: # the next is the end of "start tag"
 7764: 	    }
 7765: 	}
 7766: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7767: 	$extension = lc($extension);
 7768: 	if ($extension eq 'htm') { $extension='html'; }
 7769: 
 7770: 	foreach my $key (keys(%packagetab)) {
 7771: 	    #no specific packages #how's our extension
 7772: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7773: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7774: 					 \%metathesekeys);
 7775: 	}
 7776: 
 7777: 	if (!exists($metaentry{':packages'})
 7778: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7779: 	    foreach my $key (keys(%packagetab)) {
 7780: 		#no specific packages well let's get default then
 7781: 		if ($key!~/^default&/) { next; }
 7782: 		&metadata_create_package_def($uri,$key,'default',
 7783: 					     \%metathesekeys);
 7784: 	    }
 7785: 	}
 7786: # are there custom rights to evaluate
 7787: 	if ($metaentry{':copyright'} eq 'custom') {
 7788: 
 7789:     #
 7790:     # Importing a rights file here
 7791:     #
 7792: 	    unless ($depthcount) {
 7793: 		my $location=$metaentry{':customdistributionfile'};
 7794: 		my $dir=$filename;
 7795: 		$dir=~s|[^/]*$||;
 7796: 		$location=&filelocation($dir,$location);
 7797: 		my $rights_metadata =
 7798: 		    &metadata($uri,'keys',$location,'_rights',
 7799: 			      $depthcount+1);
 7800: 		foreach my $rights (split(',',$rights_metadata)) {
 7801: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7802: 		    $metathesekeys{$rights}=1;
 7803: 		}
 7804: 	    }
 7805: 	}
 7806: 	# uniqifiy package listing
 7807: 	my %seen;
 7808: 	my @uniq_packages =
 7809: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7810: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7811: 
 7812: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7813: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7814: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7815: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7816: # this is the end of "was not already recently cached
 7817:     }
 7818:     return $metaentry{':'.$what};
 7819: }
 7820: 
 7821: sub metadata_create_package_def {
 7822:     my ($uri,$key,$package,$metathesekeys)=@_;
 7823:     my ($pack,$name,$subp)=split(/\&/,$key);
 7824:     if ($subp eq 'default') { next; }
 7825:     
 7826:     if (defined($metaentry{':packages'})) {
 7827: 	$metaentry{':packages'}.=','.$package;
 7828:     } else {
 7829: 	$metaentry{':packages'}=$package;
 7830:     }
 7831:     my $value=$packagetab{$key};
 7832:     my $unikey;
 7833:     $unikey='parameter_0_'.$name;
 7834:     $metaentry{':'.$unikey.'.part'}=0;
 7835:     $$metathesekeys{$unikey}=1;
 7836:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7837: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7838:     }
 7839:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7840: 	$metaentry{':'.$unikey}=
 7841: 	    $metaentry{':'.$unikey.'.default'};
 7842:     }
 7843: }
 7844: 
 7845: sub metadata_generate_part0 {
 7846:     my ($metadata,$metacache,$uri) = @_;
 7847:     my %allnames;
 7848:     foreach my $metakey (keys(%$metadata)) {
 7849: 	if ($metakey=~/^parameter\_(.*)/) {
 7850: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7851: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7852: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7853: 	    $allnames{$name}=$part;
 7854: 	  }
 7855: 	}
 7856:     }
 7857:     foreach my $name (keys(%allnames)) {
 7858:       $$metadata{"parameter_0_$name"}=1;
 7859:       my $key=":parameter_0_$name";
 7860:       $$metacache{"$key.part"}='0';
 7861:       $$metacache{"$key.name"}=$name;
 7862:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7863: 					   $allnames{$name}.'_'.$name.
 7864: 					   '.type'};
 7865:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7866: 			     '.display'};
 7867:       my $expr='[Part: '.$allnames{$name}.']';
 7868:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7869:       $$metacache{"$key.display"}=$olddis;
 7870:     }
 7871: }
 7872: 
 7873: # ------------------------------------------------------ Devalidate title cache
 7874: 
 7875: sub devalidate_title_cache {
 7876:     my ($url)=@_;
 7877:     if (!$env{'request.course.id'}) { return; }
 7878:     my $symb=&symbread($url);
 7879:     if (!$symb) { return; }
 7880:     my $key=$env{'request.course.id'}."\0".$symb;
 7881:     &devalidate_cache_new('title',$key);
 7882: }
 7883: 
 7884: # ------------------------------------------------- Get the title of a resource
 7885: 
 7886: sub gettitle {
 7887:     my $urlsymb=shift;
 7888:     my $symb=&symbread($urlsymb);
 7889:     if ($symb) {
 7890: 	my $key=$env{'request.course.id'}."\0".$symb;
 7891: 	my ($result,$cached)=&is_cached_new('title',$key);
 7892: 	if (defined($cached)) { 
 7893: 	    return $result;
 7894: 	}
 7895: 	my ($map,$resid,$url)=&decode_symb($symb);
 7896: 	my $title='';
 7897: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7898: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7899: 	} else {
 7900: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7901: 		    &GDBM_READER(),0640)) {
 7902: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7903: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7904: 		untie(%bighash);
 7905: 	    }
 7906: 	}
 7907: 	$title=~s/\&colon\;/\:/gs;
 7908: 	if ($title) {
 7909: 	    return &do_cache_new('title',$key,$title,600);
 7910: 	}
 7911: 	$urlsymb=$url;
 7912:     }
 7913:     my $title=&metadata($urlsymb,'title');
 7914:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7915:     return $title;
 7916: }
 7917: 
 7918: sub get_slot {
 7919:     my ($which,$cnum,$cdom)=@_;
 7920:     if (!$cnum || !$cdom) {
 7921: 	(undef,my $courseid)=&whichuser();
 7922: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7923: 	$cnum=$env{'course.'.$courseid.'.num'};
 7924:     }
 7925:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7926:     my %slotinfo;
 7927:     if (exists($remembered{$key})) {
 7928: 	$slotinfo{$which} = $remembered{$key};
 7929:     } else {
 7930: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7931: 	&Apache::lonhomework::showhash(%slotinfo);
 7932: 	my ($tmp)=keys(%slotinfo);
 7933: 	if ($tmp=~/^error:/) { return (); }
 7934: 	$remembered{$key} = $slotinfo{$which};
 7935:     }
 7936:     if (ref($slotinfo{$which}) eq 'HASH') {
 7937: 	return %{$slotinfo{$which}};
 7938:     }
 7939:     return $slotinfo{$which};
 7940: }
 7941: # ------------------------------------------------- Update symbolic store links
 7942: 
 7943: sub symblist {
 7944:     my ($mapname,%newhash)=@_;
 7945:     $mapname=&deversion(&declutter($mapname));
 7946:     my %hash;
 7947:     if (($env{'request.course.fn'}) && (%newhash)) {
 7948:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7949:                       &GDBM_WRCREAT(),0640)) {
 7950: 	    foreach my $url (keys(%newhash)) {
 7951: 		next if ($url eq 'last_known'
 7952: 			 && $env{'form.no_update_last_known'});
 7953: 		$hash{declutter($url)}=&encode_symb($mapname,
 7954: 						    $newhash{$url}->[1],
 7955: 						    $newhash{$url}->[0]);
 7956:             }
 7957:             if (untie(%hash)) {
 7958: 		return 'ok';
 7959:             }
 7960:         }
 7961:     }
 7962:     return 'error';
 7963: }
 7964: 
 7965: # --------------------------------------------------------------- Verify a symb
 7966: 
 7967: sub symbverify {
 7968:     my ($symb,$thisurl)=@_;
 7969:     my $thisfn=$thisurl;
 7970:     $thisfn=&declutter($thisfn);
 7971: # direct jump to resource in page or to a sequence - will construct own symbs
 7972:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7973: # check URL part
 7974:     my ($map,$resid,$url)=&decode_symb($symb);
 7975: 
 7976:     unless ($url eq $thisfn) { return 0; }
 7977: 
 7978:     $symb=&symbclean($symb);
 7979:     $thisurl=&deversion($thisurl);
 7980:     $thisfn=&deversion($thisfn);
 7981: 
 7982:     my %bighash;
 7983:     my $okay=0;
 7984: 
 7985:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7986:                             &GDBM_READER(),0640)) {
 7987:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7988:         unless ($ids) { 
 7989:            $ids=$bighash{'ids_/'.$thisurl};
 7990:         }
 7991:         if ($ids) {
 7992: # ------------------------------------------------------------------- Has ID(s)
 7993: 	    foreach my $id (split(/\,/,$ids)) {
 7994: 	       my ($mapid,$resid)=split(/\./,$id);
 7995:                if (
 7996:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7997:    eq $symb) { 
 7998: 		   if (($env{'request.role.adv'}) ||
 7999: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8000: 		       $okay=1; 
 8001: 		   }
 8002: 	       }
 8003: 	   }
 8004:         }
 8005: 	untie(%bighash);
 8006:     }
 8007:     return $okay;
 8008: }
 8009: 
 8010: # --------------------------------------------------------------- Clean-up symb
 8011: 
 8012: sub symbclean {
 8013:     my $symb=shift;
 8014:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8015: # remove version from map
 8016:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8017: 
 8018: # remove version from URL
 8019:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8020: 
 8021: # remove wrapper
 8022: 
 8023:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8024:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8025:     return $symb;
 8026: }
 8027: 
 8028: # ---------------------------------------------- Split symb to find map and url
 8029: 
 8030: sub encode_symb {
 8031:     my ($map,$resid,$url)=@_;
 8032:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8033: }
 8034: 
 8035: sub decode_symb {
 8036:     my $symb=shift;
 8037:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8038:     my ($map,$resid,$url)=split(/___/,$symb);
 8039:     return (&fixversion($map),$resid,&fixversion($url));
 8040: }
 8041: 
 8042: sub fixversion {
 8043:     my $fn=shift;
 8044:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8045:     my %bighash;
 8046:     my $uri=&clutter($fn);
 8047:     my $key=$env{'request.course.id'}.'_'.$uri;
 8048: # is this cached?
 8049:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8050:     if (defined($cached)) { return $result; }
 8051: # unfortunately not cached, or expired
 8052:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8053: 	    &GDBM_READER(),0640)) {
 8054:  	if ($bighash{'version_'.$uri}) {
 8055:  	    my $version=$bighash{'version_'.$uri};
 8056:  	    unless (($version eq 'mostrecent') || 
 8057: 		    ($version==&getversion($uri))) {
 8058:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8059:  	    }
 8060:  	}
 8061:  	untie %bighash;
 8062:     }
 8063:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8064: }
 8065: 
 8066: sub deversion {
 8067:     my $url=shift;
 8068:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8069:     return $url;
 8070: }
 8071: 
 8072: # ------------------------------------------------------ Return symb list entry
 8073: 
 8074: sub symbread {
 8075:     my ($thisfn,$donotrecurse)=@_;
 8076:     my $cache_str='request.symbread.cached.'.$thisfn;
 8077:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8078: # no filename provided? try from environment
 8079:     unless ($thisfn) {
 8080:         if ($env{'request.symb'}) {
 8081: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8082: 	}
 8083: 	$thisfn=$env{'request.filename'};
 8084:     }
 8085:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8086: # is that filename actually a symb? Verify, clean, and return
 8087:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8088: 	if (&symbverify($thisfn,$1)) {
 8089: 	    return $env{$cache_str}=&symbclean($thisfn);
 8090: 	}
 8091:     }
 8092:     $thisfn=declutter($thisfn);
 8093:     my %hash;
 8094:     my %bighash;
 8095:     my $syval='';
 8096:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8097:         my $targetfn = $thisfn;
 8098:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8099:             $targetfn = 'adm/wrapper/'.$thisfn;
 8100:         }
 8101: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8102: 	    $targetfn=$1;
 8103: 	}
 8104:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8105:                       &GDBM_READER(),0640)) {
 8106: 	    $syval=$hash{$targetfn};
 8107:             untie(%hash);
 8108:         }
 8109: # ---------------------------------------------------------- There was an entry
 8110:         if ($syval) {
 8111: 	    #unless ($syval=~/\_\d+$/) {
 8112: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8113: 		    #&appenv({'request.ambiguous' => $thisfn});
 8114: 		    #return $env{$cache_str}='';
 8115: 		#}    
 8116: 		#$syval.=$1;
 8117: 	    #}
 8118:         } else {
 8119: # ------------------------------------------------------- Was not in symb table
 8120:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8121:                             &GDBM_READER(),0640)) {
 8122: # ---------------------------------------------- Get ID(s) for current resource
 8123:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8124:               unless ($ids) { 
 8125:                  $ids=$bighash{'ids_/'.$thisfn};
 8126:               }
 8127:               unless ($ids) {
 8128: # alias?
 8129: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8130:               }
 8131:               if ($ids) {
 8132: # ------------------------------------------------------------------- Has ID(s)
 8133:                  my @possibilities=split(/\,/,$ids);
 8134:                  if ($#possibilities==0) {
 8135: # ----------------------------------------------- There is only one possibility
 8136: 		     my ($mapid,$resid)=split(/\./,$ids);
 8137: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8138: 						    $resid,$thisfn);
 8139:                  } elsif (!$donotrecurse) {
 8140: # ------------------------------------------ There is more than one possibility
 8141:                      my $realpossible=0;
 8142:                      foreach my $id (@possibilities) {
 8143: 			 my $file=$bighash{'src_'.$id};
 8144:                          if (&allowed('bre',$file)) {
 8145:          		    my ($mapid,$resid)=split(/\./,$id);
 8146:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8147: 				$realpossible++;
 8148:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8149: 						    $resid,$thisfn);
 8150:                             }
 8151: 			 }
 8152:                      }
 8153: 		     if ($realpossible!=1) { $syval=''; }
 8154:                  } else {
 8155:                      $syval='';
 8156:                  }
 8157: 	      }
 8158:               untie(%bighash)
 8159:            }
 8160:         }
 8161:         if ($syval) {
 8162: 	    return $env{$cache_str}=$syval;
 8163:         }
 8164:     }
 8165:     &appenv({'request.ambiguous' => $thisfn});
 8166:     return $env{$cache_str}='';
 8167: }
 8168: 
 8169: # ---------------------------------------------------------- Return random seed
 8170: 
 8171: sub numval {
 8172:     my $txt=shift;
 8173:     $txt=~tr/A-J/0-9/;
 8174:     $txt=~tr/a-j/0-9/;
 8175:     $txt=~tr/K-T/0-9/;
 8176:     $txt=~tr/k-t/0-9/;
 8177:     $txt=~tr/U-Z/0-5/;
 8178:     $txt=~tr/u-z/0-5/;
 8179:     $txt=~s/\D//g;
 8180:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8181:     return int($txt);
 8182: }
 8183: 
 8184: sub numval2 {
 8185:     my $txt=shift;
 8186:     $txt=~tr/A-J/0-9/;
 8187:     $txt=~tr/a-j/0-9/;
 8188:     $txt=~tr/K-T/0-9/;
 8189:     $txt=~tr/k-t/0-9/;
 8190:     $txt=~tr/U-Z/0-5/;
 8191:     $txt=~tr/u-z/0-5/;
 8192:     $txt=~s/\D//g;
 8193:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8194:     my $total;
 8195:     foreach my $val (@txts) { $total+=$val; }
 8196:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8197:     return int($total);
 8198: }
 8199: 
 8200: sub numval3 {
 8201:     use integer;
 8202:     my $txt=shift;
 8203:     $txt=~tr/A-J/0-9/;
 8204:     $txt=~tr/a-j/0-9/;
 8205:     $txt=~tr/K-T/0-9/;
 8206:     $txt=~tr/k-t/0-9/;
 8207:     $txt=~tr/U-Z/0-5/;
 8208:     $txt=~tr/u-z/0-5/;
 8209:     $txt=~s/\D//g;
 8210:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8211:     my $total;
 8212:     foreach my $val (@txts) { $total+=$val; }
 8213:     if ($_64bit) { $total=(($total<<32)>>32); }
 8214:     return $total;
 8215: }
 8216: 
 8217: sub digest {
 8218:     my ($data)=@_;
 8219:     my $digest=&Digest::MD5::md5($data);
 8220:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8221:     my ($e,$f);
 8222:     {
 8223:         use integer;
 8224:         $e=($a+$b);
 8225:         $f=($c+$d);
 8226:         if ($_64bit) {
 8227:             $e=(($e<<32)>>32);
 8228:             $f=(($f<<32)>>32);
 8229:         }
 8230:     }
 8231:     if (wantarray) {
 8232: 	return ($e,$f);
 8233:     } else {
 8234: 	my $g;
 8235: 	{
 8236: 	    use integer;
 8237: 	    $g=($e+$f);
 8238: 	    if ($_64bit) {
 8239: 		$g=(($g<<32)>>32);
 8240: 	    }
 8241: 	}
 8242: 	return $g;
 8243:     }
 8244: }
 8245: 
 8246: sub latest_rnd_algorithm_id {
 8247:     return '64bit5';
 8248: }
 8249: 
 8250: sub get_rand_alg {
 8251:     my ($courseid)=@_;
 8252:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8253:     if ($courseid) {
 8254: 	return $env{"course.$courseid.rndseed"};
 8255:     }
 8256:     return &latest_rnd_algorithm_id();
 8257: }
 8258: 
 8259: sub validCODE {
 8260:     my ($CODE)=@_;
 8261:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8262:     return 0;
 8263: }
 8264: 
 8265: sub getCODE {
 8266:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8267:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8268: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8269: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8270: 	return $Apache::lonhomework::history{'resource.CODE'};
 8271:     }
 8272:     return undef;
 8273: }
 8274: 
 8275: sub rndseed {
 8276:     my ($symb,$courseid,$domain,$username)=@_;
 8277:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8278:     if (!defined($symb)) {
 8279: 	unless ($symb=$wsymb) { return time; }
 8280:     }
 8281:     if (!$courseid) { $courseid=$wcourseid; }
 8282:     if (!$domain) { $domain=$wdomain; }
 8283:     if (!$username) { $username=$wusername }
 8284:     my $which=&get_rand_alg();
 8285: 
 8286:     if (defined(&getCODE())) {
 8287: 	if ($which eq '64bit5') {
 8288: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8289: 	} elsif ($which eq '64bit4') {
 8290: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8291: 	} else {
 8292: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8293: 	}
 8294:     } elsif ($which eq '64bit5') {
 8295: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8296:     } elsif ($which eq '64bit4') {
 8297: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8298:     } elsif ($which eq '64bit3') {
 8299: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8300:     } elsif ($which eq '64bit2') {
 8301: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8302:     } elsif ($which eq '64bit') {
 8303: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8304:     }
 8305:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8306: }
 8307: 
 8308: sub rndseed_32bit {
 8309:     my ($symb,$courseid,$domain,$username)=@_;
 8310:     {
 8311: 	use integer;
 8312: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8313: 	my $symbseed=numval($symb) << 22;
 8314: 	my $namechck=unpack("%32C*",$username) << 17;
 8315: 	my $nameseed=numval($username) << 12;
 8316: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8317: 	my $courseseed=unpack("%32C*",$courseid);
 8318: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8319: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8320: 	#&logthis("rndseed :$num:$symb");
 8321: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8322: 	return $num;
 8323:     }
 8324: }
 8325: 
 8326: sub rndseed_64bit {
 8327:     my ($symb,$courseid,$domain,$username)=@_;
 8328:     {
 8329: 	use integer;
 8330: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8331: 	my $symbseed=numval($symb) << 10;
 8332: 	my $namechck=unpack("%32S*",$username);
 8333: 	
 8334: 	my $nameseed=numval($username) << 21;
 8335: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8336: 	my $courseseed=unpack("%32S*",$courseid);
 8337: 	
 8338: 	my $num1=$symbchck+$symbseed+$namechck;
 8339: 	my $num2=$nameseed+$domainseed+$courseseed;
 8340: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8341: 	#&logthis("rndseed :$num:$symb");
 8342: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8343: 	return "$num1,$num2";
 8344:     }
 8345: }
 8346: 
 8347: sub rndseed_64bit2 {
 8348:     my ($symb,$courseid,$domain,$username)=@_;
 8349:     {
 8350: 	use integer;
 8351: 	# strings need to be an even # of cahracters long, it it is odd the
 8352:         # last characters gets thrown away
 8353: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8354: 	my $symbseed=numval($symb) << 10;
 8355: 	my $namechck=unpack("%32S*",$username.' ');
 8356: 	
 8357: 	my $nameseed=numval($username) << 21;
 8358: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8359: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8360: 	
 8361: 	my $num1=$symbchck+$symbseed+$namechck;
 8362: 	my $num2=$nameseed+$domainseed+$courseseed;
 8363: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8364: 	#&logthis("rndseed :$num:$symb");
 8365: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8366: 	return "$num1,$num2";
 8367:     }
 8368: }
 8369: 
 8370: sub rndseed_64bit3 {
 8371:     my ($symb,$courseid,$domain,$username)=@_;
 8372:     {
 8373: 	use integer;
 8374: 	# strings need to be an even # of cahracters long, it it is odd the
 8375:         # last characters gets thrown away
 8376: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8377: 	my $symbseed=numval2($symb) << 10;
 8378: 	my $namechck=unpack("%32S*",$username.' ');
 8379: 	
 8380: 	my $nameseed=numval2($username) << 21;
 8381: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8382: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8383: 	
 8384: 	my $num1=$symbchck+$symbseed+$namechck;
 8385: 	my $num2=$nameseed+$domainseed+$courseseed;
 8386: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8387: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8388: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8389: 	
 8390: 	return "$num1:$num2";
 8391:     }
 8392: }
 8393: 
 8394: sub rndseed_64bit4 {
 8395:     my ($symb,$courseid,$domain,$username)=@_;
 8396:     {
 8397: 	use integer;
 8398: 	# strings need to be an even # of cahracters long, it it is odd the
 8399:         # last characters gets thrown away
 8400: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8401: 	my $symbseed=numval3($symb) << 10;
 8402: 	my $namechck=unpack("%32S*",$username.' ');
 8403: 	
 8404: 	my $nameseed=numval3($username) << 21;
 8405: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8406: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8407: 	
 8408: 	my $num1=$symbchck+$symbseed+$namechck;
 8409: 	my $num2=$nameseed+$domainseed+$courseseed;
 8410: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8411: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8412: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8413: 	
 8414: 	return "$num1:$num2";
 8415:     }
 8416: }
 8417: 
 8418: sub rndseed_64bit5 {
 8419:     my ($symb,$courseid,$domain,$username)=@_;
 8420:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8421:     return "$num1:$num2";
 8422: }
 8423: 
 8424: sub rndseed_CODE_64bit {
 8425:     my ($symb,$courseid,$domain,$username)=@_;
 8426:     {
 8427: 	use integer;
 8428: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8429: 	my $symbseed=numval2($symb);
 8430: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8431: 	my $CODEseed=numval(&getCODE());
 8432: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8433: 	my $num1=$symbseed+$CODEchck;
 8434: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8435: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8436: 	#&logthis("rndseed :$num1:$num2:$symb");
 8437: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8438: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8439: 	return "$num1:$num2";
 8440:     }
 8441: }
 8442: 
 8443: sub rndseed_CODE_64bit4 {
 8444:     my ($symb,$courseid,$domain,$username)=@_;
 8445:     {
 8446: 	use integer;
 8447: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8448: 	my $symbseed=numval3($symb);
 8449: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8450: 	my $CODEseed=numval3(&getCODE());
 8451: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8452: 	my $num1=$symbseed+$CODEchck;
 8453: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8454: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8455: 	#&logthis("rndseed :$num1:$num2:$symb");
 8456: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8457: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8458: 	return "$num1:$num2";
 8459:     }
 8460: }
 8461: 
 8462: sub rndseed_CODE_64bit5 {
 8463:     my ($symb,$courseid,$domain,$username)=@_;
 8464:     my $code = &getCODE();
 8465:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8466:     return "$num1:$num2";
 8467: }
 8468: 
 8469: sub setup_random_from_rndseed {
 8470:     my ($rndseed)=@_;
 8471:     if ($rndseed =~/([,:])/) {
 8472: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8473: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8474:     } else {
 8475: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8476:     }
 8477: }
 8478: 
 8479: sub latest_receipt_algorithm_id {
 8480:     return 'receipt3';
 8481: }
 8482: 
 8483: sub recunique {
 8484:     my $fucourseid=shift;
 8485:     my $unique;
 8486:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8487: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8488: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8489:     } else {
 8490: 	$unique=$perlvar{'lonReceipt'};
 8491:     }
 8492:     return unpack("%32C*",$unique);
 8493: }
 8494: 
 8495: sub recprefix {
 8496:     my $fucourseid=shift;
 8497:     my $prefix;
 8498:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8499: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8500: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8501:     } else {
 8502: 	$prefix=$perlvar{'lonHostID'};
 8503:     }
 8504:     return unpack("%32C*",$prefix);
 8505: }
 8506: 
 8507: sub ireceipt {
 8508:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8509: 
 8510:     my $return =&recprefix($fucourseid).'-';
 8511: 
 8512:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8513: 	$env{'request.state'} eq 'construct') {
 8514: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8515: 	return $return;
 8516:     }
 8517: 
 8518:     my $cuname=unpack("%32C*",$funame);
 8519:     my $cudom=unpack("%32C*",$fudom);
 8520:     my $cucourseid=unpack("%32C*",$fucourseid);
 8521:     my $cusymb=unpack("%32C*",$fusymb);
 8522:     my $cunique=&recunique($fucourseid);
 8523:     my $cpart=unpack("%32S*",$part);
 8524:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8525: 
 8526: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8527: 			       
 8528: 	$return.= ($cunique%$cuname+
 8529: 		   $cunique%$cudom+
 8530: 		   $cusymb%$cuname+
 8531: 		   $cusymb%$cudom+
 8532: 		   $cucourseid%$cuname+
 8533: 		   $cucourseid%$cudom+
 8534: 		   $cpart%$cuname+
 8535: 		   $cpart%$cudom);
 8536:     } else {
 8537: 	$return.= ($cunique%$cuname+
 8538: 		   $cunique%$cudom+
 8539: 		   $cusymb%$cuname+
 8540: 		   $cusymb%$cudom+
 8541: 		   $cucourseid%$cuname+
 8542: 		   $cucourseid%$cudom);
 8543:     }
 8544:     return $return;
 8545: }
 8546: 
 8547: sub receipt {
 8548:     my ($part)=@_;
 8549:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8550:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8551: }
 8552: 
 8553: sub whichuser {
 8554:     my ($passedsymb)=@_;
 8555:     my ($symb,$courseid,$domain,$name,$publicuser);
 8556:     if (defined($env{'form.grade_symb'})) {
 8557: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8558: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8559: 	if (!$allowed &&
 8560: 	    exists($env{'request.course.sec'}) &&
 8561: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8562: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8563: 			      '/'.$env{'request.course.sec'});
 8564: 	}
 8565: 	if ($allowed) {
 8566: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8567: 	    $courseid=$tmp_courseid;
 8568: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8569: 	    ($name)=&get_env_multiple('form.grade_username');
 8570: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8571: 	}
 8572:     }
 8573:     if (!$passedsymb) {
 8574: 	$symb=&symbread();
 8575:     } else {
 8576: 	$symb=$passedsymb;
 8577:     }
 8578:     $courseid=$env{'request.course.id'};
 8579:     $domain=$env{'user.domain'};
 8580:     $name=$env{'user.name'};
 8581:     if ($name eq 'public' && $domain eq 'public') {
 8582: 	if (!defined($env{'form.username'})) {
 8583: 	    $env{'form.username'}.=time.rand(10000000);
 8584: 	}
 8585: 	$name.=$env{'form.username'};
 8586:     }
 8587:     return ($symb,$courseid,$domain,$name,$publicuser);
 8588: 
 8589: }
 8590: 
 8591: # ------------------------------------------------------------ Serves up a file
 8592: # returns either the contents of the file or 
 8593: # -1 if the file doesn't exist
 8594: #
 8595: # if the target is a file that was uploaded via DOCS, 
 8596: # a check will be made to see if a current copy exists on the local server,
 8597: # if it does this will be served, otherwise a copy will be retrieved from
 8598: # the home server for the course and stored in /home/httpd/html/userfiles on
 8599: # the local server.   
 8600: 
 8601: sub getfile {
 8602:     my ($file) = @_;
 8603:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8604:     &repcopy($file);
 8605:     return &readfile($file);
 8606: }
 8607: 
 8608: sub repcopy_userfile {
 8609:     my ($file)=@_;
 8610:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8611:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8612:     my ($cdom,$cnum,$filename) = 
 8613: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8614:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8615:     if (-e "$file") {
 8616: # we already have a local copy, check it out
 8617: 	my @fileinfo = stat($file);
 8618: 	my $rtncode;
 8619: 	my $info;
 8620: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8621: 	if ($lwpresp ne 'ok') {
 8622: # there is no such file anymore, even though we had a local copy
 8623: 	    if ($rtncode eq '404') {
 8624: 		unlink($file);
 8625: 	    }
 8626: 	    return -1;
 8627: 	}
 8628: 	if ($info < $fileinfo[9]) {
 8629: # nice, the file we have is up-to-date, just say okay
 8630: 	    return 'ok';
 8631: 	} else {
 8632: # the file is outdated, get rid of it
 8633: 	    unlink($file);
 8634: 	}
 8635:     }
 8636: # one way or the other, at this point, we don't have the file
 8637: # construct the correct path for the file
 8638:     my @parts = ($cdom,$cnum); 
 8639:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8640: 	push @parts, split(/\//,$1);
 8641:     }
 8642:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8643:     foreach my $part (@parts) {
 8644: 	$path .= '/'.$part;
 8645: 	if (!-e $path) {
 8646: 	    mkdir($path,0770);
 8647: 	}
 8648:     }
 8649: # now the path exists for sure
 8650: # get a user agent
 8651:     my $ua=new LWP::UserAgent;
 8652:     my $transferfile=$file.'.in.transfer';
 8653: # FIXME: this should flock
 8654:     if (-e $transferfile) { return 'ok'; }
 8655:     my $request;
 8656:     $uri=~s/^\///;
 8657:     my $homeserver = &homeserver($cnum,$cdom);
 8658:     my $protocol = $protocol{$homeserver};
 8659:     $protocol = 'http' if ($protocol ne 'https');
 8660:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8661:     my $response=$ua->request($request,$transferfile);
 8662: # did it work?
 8663:     if ($response->is_error()) {
 8664: 	unlink($transferfile);
 8665: 	&logthis("Userfile repcopy failed for $uri");
 8666: 	return -1;
 8667:     }
 8668: # worked, rename the transfer file
 8669:     rename($transferfile,$file);
 8670:     return 'ok';
 8671: }
 8672: 
 8673: sub tokenwrapper {
 8674:     my $uri=shift;
 8675:     $uri=~s|^https?\://([^/]+)||;
 8676:     $uri=~s|^/||;
 8677:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8678:     my $token=$1;
 8679:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8680:     if ($udom && $uname && $file) {
 8681: 	$file=~s|(\?\.*)*$||;
 8682:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8683:         my $homeserver = &homeserver($uname,$udom);
 8684:         my $protocol = $protocol{$homeserver};
 8685:         $protocol = 'http' if ($protocol ne 'https');
 8686:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8687:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8688:                                '&tokenissued='.$perlvar{'lonHostID'};
 8689:     } else {
 8690:         return '/adm/notfound.html';
 8691:     }
 8692: }
 8693: 
 8694: # call with reqtype HEAD: get last modification time
 8695: # call with reqtype GET: get the file contents
 8696: # Do not call this with reqtype GET for large files! It loads everything into memory
 8697: #
 8698: sub getuploaded {
 8699:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8700:     $uri=~s/^\///;
 8701:     my $homeserver = &homeserver($cnum,$cdom);
 8702:     my $protocol = $protocol{$homeserver};
 8703:     $protocol = 'http' if ($protocol ne 'https');
 8704:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8705:     my $ua=new LWP::UserAgent;
 8706:     my $request=new HTTP::Request($reqtype,$uri);
 8707:     my $response=$ua->request($request);
 8708:     $$rtncode = $response->code;
 8709:     if (! $response->is_success()) {
 8710: 	return 'failed';
 8711:     }      
 8712:     if ($reqtype eq 'HEAD') {
 8713: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8714:     } elsif ($reqtype eq 'GET') {
 8715: 	$$info = $response->content;
 8716:     }
 8717:     return 'ok';
 8718: }
 8719: 
 8720: sub readfile {
 8721:     my $file = shift;
 8722:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8723:     my $fh;
 8724:     open($fh,"<$file");
 8725:     my $a='';
 8726:     while (my $line = <$fh>) { $a .= $line; }
 8727:     return $a;
 8728: }
 8729: 
 8730: sub filelocation {
 8731:     my ($dir,$file) = @_;
 8732:     my $location;
 8733:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8734: 
 8735:     if ($file =~ m-^/adm/-) {
 8736: 	$file=~s-^/adm/wrapper/-/-;
 8737: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8738:     }
 8739: 
 8740:     if ($file=~m:^/~:) { # is a contruction space reference
 8741:         $location = $file;
 8742:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8743:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8744: 	# is a correct contruction space reference
 8745:         $location = $file;
 8746:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8747:         $location = $file;
 8748:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8749:         my ($udom,$uname,$filename)=
 8750:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8751:         my $home=&homeserver($uname,$udom);
 8752:         my $is_me=0;
 8753:         my @ids=&current_machine_ids();
 8754:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8755:         if ($is_me) {
 8756:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8757:         } else {
 8758:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8759:   	      $udom.'/'.$uname.'/'.$filename;
 8760:         }
 8761:     } elsif ($file =~ m-^/adm/-) {
 8762: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8763:     } else {
 8764:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8765:         $file=~s:^/res/:/:;
 8766:         if ( !( $file =~ m:^/:) ) {
 8767:             $location = $dir. '/'.$file;
 8768:         } else {
 8769:             $location = '/home/httpd/html/res'.$file;
 8770:         }
 8771:     }
 8772:     $location=~s://+:/:g; # remove duplicate /
 8773:     while ($location=~m{/\.\./}) {
 8774: 	if ($location =~ m{/[^/]+/\.\./}) {
 8775: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8776: 	} else {
 8777: 	    $location=~ s{/\.\./}{/}g;
 8778: 	}
 8779:     } #remove dir/..
 8780:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8781:     return $location;
 8782: }
 8783: 
 8784: sub hreflocation {
 8785:     my ($dir,$file)=@_;
 8786:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8787: 	$file=filelocation($dir,$file);
 8788:     } elsif ($file=~m-^/adm/-) {
 8789: 	$file=~s-^/adm/wrapper/-/-;
 8790: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8791:     }
 8792:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8793: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8794:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8795: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8796:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8797: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8798: 	    -/uploaded/$1/$2/-x;
 8799:     }
 8800:     if ($file=~ m{^/userfiles/}) {
 8801: 	$file =~ s{^/userfiles/}{/uploaded/};
 8802:     }
 8803:     return $file;
 8804: }
 8805: 
 8806: sub current_machine_domains {
 8807:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8808: }
 8809: 
 8810: sub machine_domains {
 8811:     my ($hostname) = @_;
 8812:     my @domains;
 8813:     my %hostname = &all_hostnames();
 8814:     while( my($id, $name) = each(%hostname)) {
 8815: #	&logthis("-$id-$name-$hostname-");
 8816: 	if ($hostname eq $name) {
 8817: 	    push(@domains,&host_domain($id));
 8818: 	}
 8819:     }
 8820:     return @domains;
 8821: }
 8822: 
 8823: sub current_machine_ids {
 8824:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8825: }
 8826: 
 8827: sub machine_ids {
 8828:     my ($hostname) = @_;
 8829:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8830:     my @ids;
 8831:     my %name_to_host = &all_names();
 8832:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8833: 	return @{ $name_to_host{$hostname} };
 8834:     }
 8835:     return;
 8836: }
 8837: 
 8838: sub additional_machine_domains {
 8839:     my @domains;
 8840:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8841:     while( my $line = <$fh>) {
 8842:         $line =~ s/\s//g;
 8843:         push(@domains,$line);
 8844:     }
 8845:     return @domains;
 8846: }
 8847: 
 8848: sub default_login_domain {
 8849:     my $domain = $perlvar{'lonDefDomain'};
 8850:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8851:     foreach my $posdom (&current_machine_domains(),
 8852:                         &additional_machine_domains()) {
 8853:         if (lc($posdom) eq lc($testdomain)) {
 8854:             $domain=$posdom;
 8855:             last;
 8856:         }
 8857:     }
 8858:     return $domain;
 8859: }
 8860: 
 8861: # ------------------------------------------------------------- Declutters URLs
 8862: 
 8863: sub declutter {
 8864:     my $thisfn=shift;
 8865:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8866:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8867:     $thisfn=~s/^\///;
 8868:     $thisfn=~s|^adm/wrapper/||;
 8869:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8870:     $thisfn=~s/^res\///;
 8871:     $thisfn=~s/\?.+$//;
 8872:     return $thisfn;
 8873: }
 8874: 
 8875: # ------------------------------------------------------------- Clutter up URLs
 8876: 
 8877: sub clutter {
 8878:     my $thisfn='/'.&declutter(shift);
 8879:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8880: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8881:        $thisfn='/res'.$thisfn; 
 8882:     }
 8883:     if ($thisfn !~m|/adm|) {
 8884: 	if ($thisfn =~ m|/ext/|) {
 8885: 	    $thisfn='/adm/wrapper'.$thisfn;
 8886: 	} else {
 8887: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8888: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8889: 	    if ($embstyle eq 'ssi'
 8890: 		|| ($embstyle eq 'hdn')
 8891: 		|| ($embstyle eq 'rat')
 8892: 		|| ($embstyle eq 'prv')
 8893: 		|| ($embstyle eq 'ign')) {
 8894: 		#do nothing with these
 8895: 	    } elsif (($embstyle eq 'img') 
 8896: 		|| ($embstyle eq 'emb')
 8897: 		|| ($embstyle eq 'wrp')) {
 8898: 		$thisfn='/adm/wrapper'.$thisfn;
 8899: 	    } elsif ($embstyle eq 'unk'
 8900: 		     && $thisfn!~/\.(sequence|page)$/) {
 8901: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8902: 	    } else {
 8903: #		&logthis("Got a blank emb style");
 8904: 	    }
 8905: 	}
 8906:     }
 8907:     return $thisfn;
 8908: }
 8909: 
 8910: sub clutter_with_no_wrapper {
 8911:     my $uri = &clutter(shift);
 8912:     if ($uri =~ m-^/adm/-) {
 8913: 	$uri =~ s-^/adm/wrapper/-/-;
 8914: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8915:     }
 8916:     return $uri;
 8917: }
 8918: 
 8919: sub freeze_escape {
 8920:     my ($value)=@_;
 8921:     if (ref($value)) {
 8922: 	$value=&nfreeze($value);
 8923: 	return '__FROZEN__'.&escape($value);
 8924:     }
 8925:     return &escape($value);
 8926: }
 8927: 
 8928: 
 8929: sub thaw_unescape {
 8930:     my ($value)=@_;
 8931:     if ($value =~ /^__FROZEN__/) {
 8932: 	substr($value,0,10,undef);
 8933: 	$value=&unescape($value);
 8934: 	return &thaw($value);
 8935:     }
 8936:     return &unescape($value);
 8937: }
 8938: 
 8939: sub correct_line_ends {
 8940:     my ($result)=@_;
 8941:     $$result =~s/\r\n/\n/mg;
 8942:     $$result =~s/\r/\n/mg;
 8943: }
 8944: # ================================================================ Main Program
 8945: 
 8946: sub goodbye {
 8947:    &logthis("Starting Shut down");
 8948: #not converted to using infrastruture and probably shouldn't be
 8949:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8950: #converted
 8951: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8952:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8953: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8954: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8955: #1.1 only
 8956: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8957: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8958: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8959: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8960:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8961:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8962:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8963:    &flushcourselogs();
 8964:    &logthis("Shutting down");
 8965: }
 8966: 
 8967: sub get_dns {
 8968:     my ($url,$func,$ignore_cache) = @_;
 8969:     if (!$ignore_cache) {
 8970: 	my ($content,$cached)=
 8971: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8972: 	if ($cached) {
 8973: 	    &$func($content);
 8974: 	    return;
 8975: 	}
 8976:     }
 8977: 
 8978:     my %alldns;
 8979:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8980:     foreach my $dns (<$config>) {
 8981: 	next if ($dns !~ /^\^(\S*)/x);
 8982:         my $line = $1;
 8983:         my ($host,$protocol) = split(/:/,$line);
 8984:         if ($protocol ne 'https') {
 8985:             $protocol = 'http';
 8986:         }
 8987: 	$alldns{$host} = $protocol;
 8988:     }
 8989:     while (%alldns) {
 8990: 	my ($dns) = keys(%alldns);
 8991: 	my $ua=new LWP::UserAgent;
 8992: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8993: 	my $response=$ua->request($request);
 8994:         delete($alldns{$dns});
 8995: 	next if ($response->is_error());
 8996: 	my @content = split("\n",$response->content);
 8997: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8998: 	&$func(\@content);
 8999: 	return;
 9000:     }
 9001:     close($config);
 9002:     my $which = (split('/',$url))[3];
 9003:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9004:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9005:     my @content = <$config>;
 9006:     &$func(\@content);
 9007:     return;
 9008: }
 9009: # ------------------------------------------------------------ Read domain file
 9010: {
 9011:     my $loaded;
 9012:     my %domain;
 9013: 
 9014:     sub parse_domain_tab {
 9015: 	my ($lines) = @_;
 9016: 	foreach my $line (@$lines) {
 9017: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9018: 
 9019: 	    chomp($line);
 9020: 	    my ($name,@elements) = split(/:/,$line,9);
 9021: 	    my %this_domain;
 9022: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9023: 			       'lang_def', 'city', 'longi', 'lati',
 9024: 			       'primary') {
 9025: 		$this_domain{$field} = shift(@elements);
 9026: 	    }
 9027: 	    $domain{$name} = \%this_domain;
 9028: 	}
 9029:     }
 9030: 
 9031:     sub reset_domain_info {
 9032: 	undef($loaded);
 9033: 	undef(%domain);
 9034:     }
 9035: 
 9036:     sub load_domain_tab {
 9037: 	my ($ignore_cache) = @_;
 9038: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9039: 	my $fh;
 9040: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9041: 	    my @lines = <$fh>;
 9042: 	    &parse_domain_tab(\@lines);
 9043: 	}
 9044: 	close($fh);
 9045: 	$loaded = 1;
 9046:     }
 9047: 
 9048:     sub domain {
 9049: 	&load_domain_tab() if (!$loaded);
 9050: 
 9051: 	my ($name,$what) = @_;
 9052: 	return if ( !exists($domain{$name}) );
 9053: 
 9054: 	if (!$what) {
 9055: 	    return $domain{$name}{'description'};
 9056: 	}
 9057: 	return $domain{$name}{$what};
 9058:     }
 9059: 
 9060:     sub domain_info {
 9061:         &load_domain_tab() if (!$loaded);
 9062:         return %domain;
 9063:     }
 9064: 
 9065: }
 9066: 
 9067: 
 9068: # ------------------------------------------------------------- Read hosts file
 9069: {
 9070:     my %hostname;
 9071:     my %hostdom;
 9072:     my %libserv;
 9073:     my $loaded;
 9074:     my %name_to_host;
 9075: 
 9076:     sub parse_hosts_tab {
 9077: 	my ($file) = @_;
 9078: 	foreach my $configline (@$file) {
 9079: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9080: 	    next if ($configline =~ /^\^/);
 9081: 	    chomp($configline);
 9082: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9083: 	    $name=~s/\s//g;
 9084: 	    if ($id && $domain && $role && $name) {
 9085: 		$hostname{$id}=$name;
 9086: 		push(@{$name_to_host{$name}}, $id);
 9087: 		$hostdom{$id}=$domain;
 9088: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9089:                 if (defined($protocol)) {
 9090:                     if ($protocol eq 'https') {
 9091:                         $protocol{$id} = $protocol;
 9092:                     } else {
 9093:                         $protocol{$id} = 'http'; 
 9094:                     }
 9095:                 } else {
 9096:                     $protocol{$id} = 'http';
 9097:                 }
 9098: 	    }
 9099: 	}
 9100:     }
 9101:     
 9102:     sub reset_hosts_info {
 9103: 	&purge_remembered();
 9104: 	&reset_domain_info();
 9105: 	&reset_hosts_ip_info();
 9106: 	undef(%name_to_host);
 9107: 	undef(%hostname);
 9108: 	undef(%hostdom);
 9109: 	undef(%libserv);
 9110: 	undef($loaded);
 9111:     }
 9112: 
 9113:     sub load_hosts_tab {
 9114: 	my ($ignore_cache) = @_;
 9115: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9116: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9117: 	my @config = <$config>;
 9118: 	&parse_hosts_tab(\@config);
 9119: 	close($config);
 9120: 	$loaded=1;
 9121:     }
 9122: 
 9123:     sub hostname {
 9124: 	&load_hosts_tab() if (!$loaded);
 9125: 
 9126: 	my ($lonid) = @_;
 9127: 	return $hostname{$lonid};
 9128:     }
 9129: 
 9130:     sub all_hostnames {
 9131: 	&load_hosts_tab() if (!$loaded);
 9132: 
 9133: 	return %hostname;
 9134:     }
 9135: 
 9136:     sub all_names {
 9137: 	&load_hosts_tab() if (!$loaded);
 9138: 
 9139: 	return %name_to_host;
 9140:     }
 9141: 
 9142:     sub all_host_domain {
 9143:         &load_hosts_tab() if (!$loaded);
 9144:         return %hostdom;
 9145:     }
 9146: 
 9147:     sub is_library {
 9148: 	&load_hosts_tab() if (!$loaded);
 9149: 
 9150: 	return exists($libserv{$_[0]});
 9151:     }
 9152: 
 9153:     sub all_library {
 9154: 	&load_hosts_tab() if (!$loaded);
 9155: 
 9156: 	return %libserv;
 9157:     }
 9158: 
 9159:     sub get_servers {
 9160: 	&load_hosts_tab() if (!$loaded);
 9161: 
 9162: 	my ($domain,$type) = @_;
 9163: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9164: 	                                          : %hostname;
 9165: 	my %result;
 9166: 	if (ref($domain) eq 'ARRAY') {
 9167: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9168: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9169: 		    $result{$host} = $hostname;
 9170: 		}
 9171: 	    }
 9172: 	} else {
 9173: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9174: 		if ($hostdom{$host} eq $domain) {
 9175: 		    $result{$host} = $hostname;
 9176: 		}
 9177: 	    }
 9178: 	}
 9179: 	return %result;
 9180:     }
 9181: 
 9182:     sub host_domain {
 9183: 	&load_hosts_tab() if (!$loaded);
 9184: 
 9185: 	my ($lonid) = @_;
 9186: 	return $hostdom{$lonid};
 9187:     }
 9188: 
 9189:     sub all_domains {
 9190: 	&load_hosts_tab() if (!$loaded);
 9191: 
 9192: 	my %seen;
 9193: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9194: 	return @uniq;
 9195:     }
 9196: }
 9197: 
 9198: { 
 9199:     my %iphost;
 9200:     my %name_to_ip;
 9201:     my %lonid_to_ip;
 9202: 
 9203:     sub get_hosts_from_ip {
 9204: 	my ($ip) = @_;
 9205: 	my %iphosts = &get_iphost();
 9206: 	if (ref($iphosts{$ip})) {
 9207: 	    return @{$iphosts{$ip}};
 9208: 	}
 9209: 	return;
 9210:     }
 9211:     
 9212:     sub reset_hosts_ip_info {
 9213: 	undef(%iphost);
 9214: 	undef(%name_to_ip);
 9215: 	undef(%lonid_to_ip);
 9216:     }
 9217: 
 9218:     sub get_host_ip {
 9219: 	my ($lonid) = @_;
 9220: 	if (exists($lonid_to_ip{$lonid})) {
 9221: 	    return $lonid_to_ip{$lonid};
 9222: 	}
 9223: 	my $name=&hostname($lonid);
 9224:    	my $ip = gethostbyname($name);
 9225: 	return if (!$ip || length($ip) ne 4);
 9226: 	$ip=inet_ntoa($ip);
 9227: 	$name_to_ip{$name}   = $ip;
 9228: 	$lonid_to_ip{$lonid} = $ip;
 9229: 	return $ip;
 9230:     }
 9231:     
 9232:     sub get_iphost {
 9233: 	my ($ignore_cache) = @_;
 9234: 
 9235: 	if (!$ignore_cache) {
 9236: 	    if (%iphost) {
 9237: 		return %iphost;
 9238: 	    }
 9239: 	    my ($ip_info,$cached)=
 9240: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9241: 	    if ($cached) {
 9242: 		%iphost      = %{$ip_info->[0]};
 9243: 		%name_to_ip  = %{$ip_info->[1]};
 9244: 		%lonid_to_ip = %{$ip_info->[2]};
 9245: 		return %iphost;
 9246: 	    }
 9247: 	}
 9248: 
 9249: 	# get yesterday's info for fallback
 9250: 	my %old_name_to_ip;
 9251: 	my ($ip_info,$cached)=
 9252: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9253: 	if ($cached) {
 9254: 	    %old_name_to_ip = %{$ip_info->[1]};
 9255: 	}
 9256: 
 9257: 	my %name_to_host = &all_names();
 9258: 	foreach my $name (keys(%name_to_host)) {
 9259: 	    my $ip;
 9260: 	    if (!exists($name_to_ip{$name})) {
 9261: 		$ip = gethostbyname($name);
 9262: 		if (!$ip || length($ip) ne 4) {
 9263: 		    if (defined($old_name_to_ip{$name})) {
 9264: 			$ip = $old_name_to_ip{$name};
 9265: 			&logthis("Can't find $name defaulting to old $ip");
 9266: 		    } else {
 9267: 			&logthis("Name $name no IP found");
 9268: 			next;
 9269: 		    }
 9270: 		} else {
 9271: 		    $ip=inet_ntoa($ip);
 9272: 		}
 9273: 		$name_to_ip{$name} = $ip;
 9274: 	    } else {
 9275: 		$ip = $name_to_ip{$name};
 9276: 	    }
 9277: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9278: 		$lonid_to_ip{$id} = $ip;
 9279: 	    }
 9280: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9281: 	}
 9282: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9283: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9284: 				      48*60*60);
 9285: 
 9286: 	return %iphost;
 9287:     }
 9288: 
 9289:     #
 9290:     #  Given a DNS returns the loncapa host name for that DNS 
 9291:     # 
 9292:     sub host_from_dns {
 9293:         my ($dns) = @_;
 9294:         my @hosts;
 9295:         my $ip;
 9296: 
 9297:         if (exists($name_to_ip{$dns})) {
 9298:             $ip = $name_to_ip{$dns};
 9299:         }
 9300:         if (!$ip) {
 9301:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9302:             if (length($ip) == 4) { 
 9303: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9304:             }
 9305:         }
 9306:         if ($ip) {
 9307: 	    @hosts = get_hosts_from_ip($ip);
 9308: 	    return $hosts[0];
 9309:         }
 9310:         return undef;
 9311:     }
 9312: 
 9313: }
 9314: 
 9315: BEGIN {
 9316: 
 9317: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9318:     unless ($readit) {
 9319: {
 9320:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9321:     %perlvar = (%perlvar,%{$configvars});
 9322: }
 9323: 
 9324: 
 9325: # ------------------------------------------------------ Read spare server file
 9326: {
 9327:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9328: 
 9329:     while (my $configline=<$config>) {
 9330:        chomp($configline);
 9331:        if ($configline) {
 9332: 	   my ($host,$type) = split(':',$configline,2);
 9333: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9334: 	   push(@{ $spareid{$type} }, $host);
 9335:        }
 9336:     }
 9337:     close($config);
 9338: }
 9339: # ------------------------------------------------------------ Read permissions
 9340: {
 9341:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9342: 
 9343:     while (my $configline=<$config>) {
 9344: 	chomp($configline);
 9345: 	if ($configline) {
 9346: 	    my ($role,$perm)=split(/ /,$configline);
 9347: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9348: 	}
 9349:     }
 9350:     close($config);
 9351: }
 9352: 
 9353: # -------------------------------------------- Read plain texts for permissions
 9354: {
 9355:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9356: 
 9357:     while (my $configline=<$config>) {
 9358: 	chomp($configline);
 9359: 	if ($configline) {
 9360: 	    my ($short,@plain)=split(/:/,$configline);
 9361:             %{$prp{$short}} = ();
 9362: 	    if (@plain > 0) {
 9363:                 $prp{$short}{'std'} = $plain[0];
 9364:                 for (my $i=1; $i<@plain; $i++) {
 9365:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9366:                 }
 9367:             }
 9368: 	}
 9369:     }
 9370:     close($config);
 9371: }
 9372: 
 9373: # ---------------------------------------------------------- Read package table
 9374: {
 9375:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9376: 
 9377:     while (my $configline=<$config>) {
 9378: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9379: 	chomp($configline);
 9380: 	my ($short,$plain)=split(/:/,$configline);
 9381: 	my ($pack,$name)=split(/\&/,$short);
 9382: 	if ($plain ne '') {
 9383: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9384: 	    $packagetab{$short}=$plain; 
 9385: 	}
 9386:     }
 9387:     close($config);
 9388: }
 9389: 
 9390: # ------------- set up temporary directory
 9391: {
 9392:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9393: 
 9394: }
 9395: 
 9396: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9397: 				'compress_threshold'=> 20_000,
 9398:  			        });
 9399: 
 9400: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9401: $dumpcount=0;
 9402: $locknum=0;
 9403: 
 9404: &logtouch();
 9405: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9406: $readit=1;
 9407:     {
 9408: 	use integer;
 9409: 	my $test=(2**32)+1;
 9410: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9411: 	&logthis(" Detected 64bit platform ($_64bit)");
 9412:     }
 9413: }
 9414: }
 9415: 
 9416: 1;
 9417: __END__
 9418: 
 9419: =pod
 9420: 
 9421: =head1 NAME
 9422: 
 9423: Apache::lonnet - Subroutines to ask questions about things in the network.
 9424: 
 9425: =head1 SYNOPSIS
 9426: 
 9427: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9428: 
 9429:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9430: 
 9431: Common parameters:
 9432: 
 9433: =over 4
 9434: 
 9435: =item *
 9436: 
 9437: $uname : an internal username (if $cname expecting a course Id specifically)
 9438: 
 9439: =item *
 9440: 
 9441: $udom : a domain (if $cdom expecting a course's domain specifically)
 9442: 
 9443: =item *
 9444: 
 9445: $symb : a resource instance identifier
 9446: 
 9447: =item *
 9448: 
 9449: $namespace : the name of a .db file that contains the data needed or
 9450: being set.
 9451: 
 9452: =back
 9453: 
 9454: =head1 OVERVIEW
 9455: 
 9456: lonnet provides subroutines which interact with the
 9457: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9458: about classes, users, and resources.
 9459: 
 9460: For many of these objects you can also use this to store data about
 9461: them or modify them in various ways.
 9462: 
 9463: =head2 Symbs
 9464: 
 9465: To identify a specific instance of a resource, LON-CAPA uses symbols
 9466: or "symbs"X<symb>. These identifiers are built from the URL of the
 9467: map, the resource number of the resource in the map, and the URL of
 9468: the resource itself. The latter is somewhat redundant, but might help
 9469: if maps change.
 9470: 
 9471: An example is
 9472: 
 9473:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9474: 
 9475: The respective map entry is
 9476: 
 9477:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9478:   title="Problem 2">
 9479:  </resource>
 9480: 
 9481: Symbs are used by the random number generator, as well as to store and
 9482: restore data specific to a certain instance of for example a problem.
 9483: 
 9484: =head2 Storing And Retrieving Data
 9485: 
 9486: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9487: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9488: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9489: is is the non-critical message twin of cstore. These functions are for
 9490: handlers to store a perl hash to a user's permanent data space in an
 9491: easy manner, and to retrieve it again on another call. It is expected
 9492: that a handler would use this once at the beginning to retrieve data,
 9493: and then again once at the end to send only the new data back.
 9494: 
 9495: The data is stored in the user's data directory on the user's
 9496: homeserver under the ID of the course.
 9497: 
 9498: The hash that is returned by restore will have all of the previous
 9499: value for all of the elements of the hash.
 9500: 
 9501: Example:
 9502: 
 9503:  #creating a hash
 9504:  my %hash;
 9505:  $hash{'foo'}='bar';
 9506: 
 9507:  #storing it
 9508:  &Apache::lonnet::cstore(\%hash);
 9509: 
 9510:  #changing a value
 9511:  $hash{'foo'}='notbar';
 9512: 
 9513:  #adding a new value
 9514:  $hash{'bar'}='foo';
 9515:  &Apache::lonnet::cstore(\%hash);
 9516: 
 9517:  #retrieving the hash
 9518:  my %history=&Apache::lonnet::restore();
 9519: 
 9520:  #print the hash
 9521:  foreach my $key (sort(keys(%history))) {
 9522:    print("\%history{$key} = $history{$key}");
 9523:  }
 9524: 
 9525: Will print out:
 9526: 
 9527:  %history{1:foo} = bar
 9528:  %history{1:keys} = foo:timestamp
 9529:  %history{1:timestamp} = 990455579
 9530:  %history{2:bar} = foo
 9531:  %history{2:foo} = notbar
 9532:  %history{2:keys} = foo:bar:timestamp
 9533:  %history{2:timestamp} = 990455580
 9534:  %history{bar} = foo
 9535:  %history{foo} = notbar
 9536:  %history{timestamp} = 990455580
 9537:  %history{version} = 2
 9538: 
 9539: Note that the special hash entries C<keys>, C<version> and
 9540: C<timestamp> were added to the hash. C<version> will be equal to the
 9541: total number of versions of the data that have been stored. The
 9542: C<timestamp> attribute will be the UNIX time the hash was
 9543: stored. C<keys> is available in every historical section to list which
 9544: keys were added or changed at a specific historical revision of a
 9545: hash.
 9546: 
 9547: B<Warning>: do not store the hash that restore returns directly. This
 9548: will cause a mess since it will restore the historical keys as if the
 9549: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9550: 
 9551: Calling convention:
 9552: 
 9553:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9554:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9555: 
 9556: For more detailed information, see lonnet specific documentation.
 9557: 
 9558: =head1 RETURN MESSAGES
 9559: 
 9560: =over 4
 9561: 
 9562: =item * B<con_lost>: unable to contact remote host
 9563: 
 9564: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9565: when the connection is brought back up
 9566: 
 9567: =item * B<con_failed>: unable to contact remote host and unable to save message
 9568: for later delivery
 9569: 
 9570: =item * B<error:>: an error a occurred, a description of the error follows the :
 9571: 
 9572: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9573: that was requested
 9574: 
 9575: =back
 9576: 
 9577: =head1 PUBLIC SUBROUTINES
 9578: 
 9579: =head2 Session Environment Functions
 9580: 
 9581: =over 4
 9582: 
 9583: =item * 
 9584: X<appenv()>
 9585: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9586: the user envirnoment file, and will be restored for each access this
 9587: user makes during this session, also modifies the %env for the current
 9588: process. Optional rolesarrayref - if defined contains a reference to an array
 9589: of roles which are exempt from the restriction on modifying user.role entries 
 9590: in the user's environment.db and in %env.    
 9591: 
 9592: =item *
 9593: X<delenv()>
 9594: B<delenv($delthis,$regexp)>: removes all items from the session
 9595: environment file that begin with $delthis. If the 
 9596: optional second arg - $regexp - is true, $delthis is treated as a 
 9597: regular expression, otherwise \Q$delthis\E is used. 
 9598: The values are also deleted from the current processes %env.
 9599: 
 9600: =item * get_env_multiple($name) 
 9601: 
 9602: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9603: values may be defined and end up as an array ref.
 9604: 
 9605: returns an array of values
 9606: 
 9607: =back
 9608: 
 9609: =head2 User Information
 9610: 
 9611: =over 4
 9612: 
 9613: =item *
 9614: X<queryauthenticate()>
 9615: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9616: authentication scheme
 9617: 
 9618: =item *
 9619: X<authenticate()>
 9620: B<authenticate($uname,$upass,$udom)>: try to
 9621: authenticate user from domain's lib servers (first use the current
 9622: one). C<$upass> should be the users password.
 9623: 
 9624: =item *
 9625: X<homeserver()>
 9626: B<homeserver($uname,$udom)>: find the server which has
 9627: the user's directory and files (there must be only one), this caches
 9628: the answer, and also caches if there is a borken connection.
 9629: 
 9630: =item *
 9631: X<idget()>
 9632: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9633: (IDs are a unique resource in a domain, there must be only 1 ID per
 9634: username, and only 1 username per ID in a specific domain) (returns
 9635: hash: id=>name,id=>name)
 9636: 
 9637: =item *
 9638: X<idrget()>
 9639: B<idrget($udom,@unames)>: find the IDs behind a list of
 9640: usernames (returns hash: name=>id,name=>id)
 9641: 
 9642: =item *
 9643: X<idput()>
 9644: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9645: 
 9646: =item *
 9647: X<rolesinit()>
 9648: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9649: 
 9650: =item *
 9651: X<getsection()>
 9652: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9653: course $cname, return section name/number or '' for "not in course"
 9654: and '-1' for "no section"
 9655: 
 9656: =item *
 9657: X<userenvironment()>
 9658: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9659: passed in @what from the requested user's environment, returns a hash
 9660: 
 9661: =item * 
 9662: X<userlog_query()>
 9663: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9664: activity.log file. %filters defines filters applied when parsing the
 9665: log file. These can be start or end timestamps, or the type of action
 9666: - log to look for Login or Logout events, check for Checkin or
 9667: Checkout, role for role selection. The response is in the form
 9668: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9669: escaped strings of the action recorded in the activity.log file.
 9670: 
 9671: =back
 9672: 
 9673: =head2 User Roles
 9674: 
 9675: =over 4
 9676: 
 9677: =item *
 9678: 
 9679: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9680:  F: full access
 9681:  U,I,K: authentication modes (cxx only)
 9682:  '': forbidden
 9683:  1: user needs to choose course
 9684:  2: browse allowed
 9685:  A: passphrase authentication needed
 9686: 
 9687: =item *
 9688: 
 9689: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9690: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9691: and course level
 9692: 
 9693: =item *
 9694: 
 9695: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9696: (rolesplain.tab); plain text explanation of a user role term.
 9697: $type is Course (default) or Group.
 9698: If $forcedefault evaluates to true, text returned will be default 
 9699: text for $type. Otherwise, if this is a course, the text returned 
 9700: will be a custom name for the role (if defined in the course's 
 9701: environment).  If no custom name is defined the default is returned.
 9702:    
 9703: =item *
 9704: 
 9705: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9706: All arguments are optional. Returns a hash of a roles, either for
 9707: co-author/assistant author roles for a user's Construction Space
 9708: (default), or if $context is 'userroles', roles for the user himself,
 9709: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9710: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9711: For each key, value is set to colon-separated start and end times for
 9712: the role.  If no username and domain are specified, will default to
 9713: current user/domain. Types, roles, and roledoms are references to arrays
 9714: of role statuses (active, future or previous), roles 
 9715: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9716: to restrict the list of roles reported. If no array ref is 
 9717: provided for types, will default to return only active roles.
 9718: 
 9719: =back
 9720: 
 9721: =head2 User Modification
 9722: 
 9723: =over 4
 9724: 
 9725: =item *
 9726: 
 9727: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9728: user for the level given by URL.  Optional start and end dates (leave empty
 9729: string or zero for "no date")
 9730: 
 9731: =item *
 9732: 
 9733: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9734: change a users, password, possible return values are: ok,
 9735: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9736: refused
 9737: 
 9738: =item *
 9739: 
 9740: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9741: 
 9742: =item *
 9743: 
 9744: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9745:            $forceid,$desiredhome,$email,$inststatus) : 
 9746: modify user
 9747: 
 9748: =item *
 9749: 
 9750: modifystudent
 9751: 
 9752: modify a student's enrollment and identification information.
 9753: The course id is resolved based on the current users environment.  
 9754: This means the envoking user must be a course coordinator or otherwise
 9755: associated with a course.
 9756: 
 9757: This call is essentially a wrapper for lonnet::modifyuser and
 9758: lonnet::modify_student_enrollment
 9759: 
 9760: Inputs: 
 9761: 
 9762: =over 4
 9763: 
 9764: =item B<$udom> Student's loncapa domain
 9765: 
 9766: =item B<$uname> Student's loncapa login name
 9767: 
 9768: =item B<$uid> Student/Employee ID
 9769: 
 9770: =item B<$umode> Student's authentication mode
 9771: 
 9772: =item B<$upass> Student's password
 9773: 
 9774: =item B<$first> Student's first name
 9775: 
 9776: =item B<$middle> Student's middle name
 9777: 
 9778: =item B<$last> Student's last name
 9779: 
 9780: =item B<$gene> Student's generation
 9781: 
 9782: =item B<$usec> Student's section in course
 9783: 
 9784: =item B<$end> Unix time of the roles expiration
 9785: 
 9786: =item B<$start> Unix time of the roles start date
 9787: 
 9788: =item B<$forceid> If defined, allow $uid to be changed
 9789: 
 9790: =item B<$desiredhome> server to use as home server for student
 9791: 
 9792: =item B<$email> Student's permanent e-mail address
 9793: 
 9794: =item B<$type> Type of enrollment (auto or manual)
 9795: 
 9796: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9797: 
 9798: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9799: 
 9800: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9801: 
 9802: =item B<$context> role change context (shown in User Management Logs display in a course)
 9803: 
 9804: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9805: 
 9806: =back
 9807: 
 9808: =item *
 9809: 
 9810: modify_student_enrollment
 9811: 
 9812: Change a students enrollment status in a class.  The environment variable
 9813: 'role.request.course' must be defined for this function to proceed.
 9814: 
 9815: Inputs:
 9816: 
 9817: =over 4
 9818: 
 9819: =item $udom, students domain
 9820: 
 9821: =item $uname, students name
 9822: 
 9823: =item $uid, students user id
 9824: 
 9825: =item $first, students first name
 9826: 
 9827: =item $middle
 9828: 
 9829: =item $last
 9830: 
 9831: =item $gene
 9832: 
 9833: =item $usec
 9834: 
 9835: =item $end
 9836: 
 9837: =item $start
 9838: 
 9839: =item $type
 9840: 
 9841: =item $locktype
 9842: 
 9843: =item $cid
 9844: 
 9845: =item $selfenroll
 9846: 
 9847: =item $context
 9848: 
 9849: =back
 9850: 
 9851: 
 9852: =item *
 9853: 
 9854: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9855: custom role; give a custom role to a user for the level given by URL.  Specify
 9856: name and domain of role author, and role name
 9857: 
 9858: =item *
 9859: 
 9860: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9861: 
 9862: =item *
 9863: 
 9864: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9865: 
 9866: =back
 9867: 
 9868: =head2 Course Infomation
 9869: 
 9870: =over 4
 9871: 
 9872: =item *
 9873: 
 9874: coursedescription($courseid) : returns a hash of information about the
 9875: specified course id, including all environment settings for the
 9876: course, the description of the course will be in the hash under the
 9877: key 'description'
 9878: 
 9879: =item *
 9880: 
 9881: resdata($name,$domain,$type,@which) : request for current parameter
 9882: setting for a specific $type, where $type is either 'course' or 'user',
 9883: @what should be a list of parameters to ask about. This routine caches
 9884: answers for 5 minutes.
 9885: 
 9886: =item *
 9887: 
 9888: get_courseresdata($courseid, $domain) : dump the entire course resource
 9889: data base, returning a hash that is keyed by the resource name and has
 9890: values that are the resource value.  I believe that the timestamps and
 9891: versions are also returned.
 9892: 
 9893: 
 9894: =back
 9895: 
 9896: =head2 Course Modification
 9897: 
 9898: =over 4
 9899: 
 9900: =item *
 9901: 
 9902: writecoursepref($courseid,%prefs) : write preferences (environment
 9903: database) for a course
 9904: 
 9905: =item *
 9906: 
 9907: createcourse($udom,$description,$url) : make/modify course
 9908: 
 9909: =back
 9910: 
 9911: =head2 Resource Subroutines
 9912: 
 9913: =over 4
 9914: 
 9915: =item *
 9916: 
 9917: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9918: 
 9919: =item *
 9920: 
 9921: repcopy($filename) : subscribes to the requested file, and attempts to
 9922: replicate from the owning library server, Might return
 9923: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9924: 'bad_request', also attempts to grab the metadata for the
 9925: resource. Expects the local filesystem pathname
 9926: (/home/httpd/html/res/....)
 9927: 
 9928: =back
 9929: 
 9930: =head2 Resource Information
 9931: 
 9932: =over 4
 9933: 
 9934: =item *
 9935: 
 9936: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9937: a vairety of different possible values, $varname should be a request
 9938: string, and the other parameters can be used to specify who and what
 9939: one is asking about.
 9940: 
 9941: Possible values for $varname are environment.lastname (or other item
 9942: from the envirnment hash), user.name (or someother aspect about the
 9943: user), resource.0.maxtries (or some other part and parameter of a
 9944: resource)
 9945: 
 9946: =item *
 9947: 
 9948: directcondval($number) : get current value of a condition; reads from a state
 9949: string
 9950: 
 9951: =item *
 9952: 
 9953: condval($condidx) : value of condition index based on state
 9954: 
 9955: =item *
 9956: 
 9957: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9958: resource's metadata, $what should be either a specific key, or either
 9959: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9960: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9961: 
 9962: this function automatically caches all requests
 9963: 
 9964: =item *
 9965: 
 9966: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9967: network of library servers; returns file handle of where SQL and regex results
 9968: will be stored for query
 9969: 
 9970: =item *
 9971: 
 9972: symbread($filename) : return symbolic list entry (filename argument optional);
 9973: returns the data handle
 9974: 
 9975: =item *
 9976: 
 9977: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9978: a possible symb for the URL in $thisfn, and if is an encryypted
 9979: resource that the user accessed using /enc/ returns a 1 on success, 0
 9980: on failure, user must be in a course, as it assumes the existance of
 9981: the course initial hash, and uses $env('request.course.id'}
 9982: 
 9983: 
 9984: =item *
 9985: 
 9986: symbclean($symb) : removes versions numbers from a symb, returns the
 9987: cleaned symb
 9988: 
 9989: =item *
 9990: 
 9991: is_on_map($uri) : checks if the $uri is somewhere on the current
 9992: course map, user must be in a course for it to work.
 9993: 
 9994: =item *
 9995: 
 9996: numval($salt) : return random seed value (addend for rndseed)
 9997: 
 9998: =item *
 9999: 
10000: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10001: a random seed, all arguments are optional, if they aren't sent it uses the
10002: environment to derive them. Note: if symb isn't sent and it can't get one
10003: from &symbread it will use the current time as its return value
10004: 
10005: =item *
10006: 
10007: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10008: unfakeable, receipt
10009: 
10010: =item *
10011: 
10012: receipt() : API to ireceipt working off of env values; given out to users
10013: 
10014: =item *
10015: 
10016: countacc($url) : count the number of accesses to a given URL
10017: 
10018: =item *
10019: 
10020: 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
10021: 
10022: =item *
10023: 
10024: 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)
10025: 
10026: =item *
10027: 
10028: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10029: 
10030: =item *
10031: 
10032: devalidate($symb) : devalidate temporary spreadsheet calculations,
10033: forcing spreadsheet to reevaluate the resource scores next time.
10034: 
10035: =back
10036: 
10037: =head2 Storing/Retreiving Data
10038: 
10039: =over 4
10040: 
10041: =item *
10042: 
10043: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10044: for this url; hashref needs to be given and should be a \%hashname; the
10045: remaining args aren't required and if they aren't passed or are '' they will
10046: be derived from the env
10047: 
10048: =item *
10049: 
10050: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10051: uses critical subroutine
10052: 
10053: =item *
10054: 
10055: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10056: all args are optional
10057: 
10058: =item *
10059: 
10060: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10061: dumps the complete (or key matching regexp) namespace into a hash
10062: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10063: normally &store()ed into
10064: 
10065: $range should be either an integer '100' (give me the first 100
10066:                                            matching records)
10067:               or be  two integers sperated by a - with no spaces
10068:                  '30-50' (give me the 30th through the 50th matching
10069:                           records)
10070: 
10071: 
10072: =item *
10073: 
10074: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10075: replaces a &store() version of data with a replacement set of data
10076: for a particular resource in a namespace passed in the $storehash hash 
10077: reference
10078: 
10079: =item *
10080: 
10081: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10082: works very similar to store/cstore, but all data is stored in a
10083: temporary location and can be reset using tmpreset, $storehash should
10084: be a hash reference, returns nothing on success
10085: 
10086: =item *
10087: 
10088: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10089: similar to restore, but all data is stored in a temporary location and
10090: can be reset using tmpreset. Returns a hash of values on success,
10091: error string otherwise.
10092: 
10093: =item *
10094: 
10095: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10096: deltes all keys for $symb form the temporary storage hash.
10097: 
10098: =item *
10099: 
10100: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10101: reference filled in from namesp ($udom and $uname are optional)
10102: 
10103: =item *
10104: 
10105: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10106: namesp ($udom and $uname are optional)
10107: 
10108: =item *
10109: 
10110: dump($namespace,$udom,$uname,$regexp,$range) : 
10111: dumps the complete (or key matching regexp) namespace into a hash
10112: ($udom, $uname, $regexp, $range are optional)
10113: 
10114: $range should be either an integer '100' (give me the first 100
10115:                                            matching records)
10116:               or be  two integers sperated by a - with no spaces
10117:                  '30-50' (give me the 30th through the 50th matching
10118:                           records)
10119: =item *
10120: 
10121: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10122: $store can be a scalar, an array reference, or if the amount to be 
10123: incremented is > 1, a hash reference.
10124: 
10125: ($udom and $uname are optional)
10126: 
10127: =item *
10128: 
10129: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10130: ($udom and $uname are optional)
10131: 
10132: =item *
10133: 
10134: cput($namespace,$storehash,$udom,$uname) : critical put
10135: ($udom and $uname are optional)
10136: 
10137: =item *
10138: 
10139: newput($namespace,$storehash,$udom,$uname) :
10140: 
10141: Attempts to store the items in the $storehash, but only if they don't
10142: currently exist, if this succeeds you can be certain that you have 
10143: successfully created a new key value pair in the $namespace db.
10144: 
10145: 
10146: Args:
10147:  $namespace: name of database to store values to
10148:  $storehash: hashref to store to the db
10149:  $udom: (optional) domain of user containing the db
10150:  $uname: (optional) name of user caontaining the db
10151: 
10152: Returns:
10153:  'ok' -> succeeded in storing all keys of $storehash
10154:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10155:                         least <key> already existed in the db (other
10156:                         requested keys may also already exist)
10157:  'error: <msg>' -> unable to tie the DB or other error occurred
10158:  'con_lost' -> unable to contact request server
10159:  'refused' -> action was not allowed by remote machine
10160: 
10161: 
10162: =item *
10163: 
10164: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10165: reference filled in from namesp (encrypts the return communication)
10166: ($udom and $uname are optional)
10167: 
10168: =item *
10169: 
10170: log($udom,$name,$home,$message) : write to permanent log for user; use
10171: critical subroutine
10172: 
10173: =item *
10174: 
10175: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10176: array reference filled in from namespace found in domain level on either
10177: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10178: 
10179: =item *
10180: 
10181: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10182: domain level either on specified domain server ($uhome) or primary domain 
10183: server ($udom and $uhome are optional)
10184: 
10185: =item * 
10186: 
10187: get_domain_defaults($target_domain) : returns hash with defaults for
10188: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10189: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10190: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10191: Values are retrieved from cache (if current), or from domain's configuration.db
10192: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10193: or lonTabs/domain.tab. 
10194: 
10195: %domdefaults = &get_auth_defaults($target_domain);
10196: 
10197: =back
10198: 
10199: =head2 Network Status Functions
10200: 
10201: =over 4
10202: 
10203: =item *
10204: 
10205: dirlist($uri) : return directory list based on URI
10206: 
10207: =item *
10208: 
10209: spareserver() : find server with least workload from spare.tab
10210: 
10211: 
10212: =item *
10213: 
10214: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10215: if there is no corresponding loncapa host.
10216: 
10217: =back
10218: 
10219: 
10220: =head2 Apache Request
10221: 
10222: =over 4
10223: 
10224: =item *
10225: 
10226: ssi($url,%hash) : server side include, does a complete request cycle on url to
10227: localhost, posts hash
10228: 
10229: =back
10230: 
10231: =head2 Data to String to Data
10232: 
10233: =over 4
10234: 
10235: =item *
10236: 
10237: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10238: and '&' separators, supports elements that are arrayrefs and hashrefs
10239: 
10240: =item *
10241: 
10242: hashref2str($hashref) : convert a hashref into a string complete with
10243: escaping and '=' and '&' separators, supports elements that are
10244: arrayrefs and hashrefs
10245: 
10246: =item *
10247: 
10248: arrayref2str($arrayref) : convert an arrayref into a string complete
10249: with escaping and '&' separators, supports elements that are arrayrefs
10250: and hashrefs
10251: 
10252: =item *
10253: 
10254: str2hash($string) : convert string to hash using unescaping and
10255: splitting on '=' and '&', supports elements that are arrayrefs and
10256: hashrefs
10257: 
10258: =item *
10259: 
10260: str2array($string) : convert string to hash using unescaping and
10261: splitting on '&', supports elements that are arrayrefs and hashrefs
10262: 
10263: =back
10264: 
10265: =head2 Logging Routines
10266: 
10267: =over 4
10268: 
10269: These routines allow one to make log messages in the lonnet.log and
10270: lonnet.perm logfiles.
10271: 
10272: =item *
10273: 
10274: logtouch() : make sure the logfile, lonnet.log, exists
10275: 
10276: =item *
10277: 
10278: logthis() : append message to the normal lonnet.log file, it gets
10279: preiodically rolled over and deleted.
10280: 
10281: =item *
10282: 
10283: logperm() : append a permanent message to lonnet.perm.log, this log
10284: file never gets deleted by any automated portion of the system, only
10285: messages of critical importance should go in here.
10286: 
10287: =back
10288: 
10289: =head2 General File Helper Routines
10290: 
10291: =over 4
10292: 
10293: =item *
10294: 
10295: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10296: (a) files in /uploaded
10297:   (i) If a local copy of the file exists - 
10298:       compares modification date of local copy with last-modified date for 
10299:       definitive version stored on home server for course. If local copy is 
10300:       stale, requests a new version from the home server and stores it. 
10301:       If the original has been removed from the home server, then local copy 
10302:       is unlinked.
10303:   (ii) If local copy does not exist -
10304:       requests the file from the home server and stores it. 
10305:   
10306:   If $caller is 'uploadrep':  
10307:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10308:     for request for files originally uploaded via DOCS. 
10309:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10310:   
10311:   Otherwise:
10312:      This indicates a call from the content generation phase of the request.
10313:      -  returns the entire contents of the file or -1.
10314:      
10315: (b) files in /res
10316:    - returns the entire contents of a file or -1; 
10317:    it properly subscribes to and replicates the file if neccessary.
10318: 
10319: 
10320: =item *
10321: 
10322: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10323:                   reference
10324: 
10325: returns either a stat() list of data about the file or an empty list
10326: if the file doesn't exist or couldn't find out about it (connection
10327: problems or user unknown)
10328: 
10329: =item *
10330: 
10331: filelocation($dir,$file) : returns file system location of a file
10332: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10333: directory that relative $file lookups are to looked in ($dir of /a/dir
10334: and a file of ../bob will become /a/bob)
10335: 
10336: =item *
10337: 
10338: hreflocation($dir,$file) : returns file system location or a URL; same as
10339: filelocation except for hrefs
10340: 
10341: =item *
10342: 
10343: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10344: 
10345: =back
10346: 
10347: =head2 Usererfile file routines (/uploaded*)
10348: 
10349: =over 4
10350: 
10351: =item *
10352: 
10353: userfileupload(): main rotine for putting a file in a user or course's
10354:                   filespace, arguments are,
10355: 
10356:  formname - required - this is the name of the element in $env where the
10357:            filename, and the contents of the file to create/modifed exist
10358:            the filename is in $env{'form.'.$formname.'.filename'} and the
10359:            contents of the file is located in $env{'form.'.$formname}
10360:  coursedoc - if true, store the file in the course of the active role
10361:              of the current user
10362:  subdir - required - subdirectory to put the file in under ../userfiles/
10363:          if undefined, it will be placed in "unknown"
10364: 
10365:  (This routine calls clean_filename() to remove any dangerous
10366:  characters from the filename, and then calls finuserfileupload() to
10367:  complete the transaction)
10368: 
10369:  returns either the url of the uploaded file (/uploaded/....) if successful
10370:  and /adm/notfound.html if unsuccessful
10371: 
10372: =item *
10373: 
10374: clean_filename(): routine for cleaing a filename up for storage in
10375:                  userfile space, argument is:
10376: 
10377:  filename - proposed filename
10378: 
10379: returns: the new clean filename
10380: 
10381: =item *
10382: 
10383: finishuserfileupload(): routine that creaes and sends the file to
10384: userspace, probably shouldn't be called directly
10385: 
10386:   docuname: username or courseid of destination for the file
10387:   docudom: domain of user/course of destination for the file
10388:   formname: same as for userfileupload()
10389:   fname: filename (inculding subdirectories) for the file
10390: 
10391:  returns either the url of the uploaded file (/uploaded/....) if successful
10392:  and /adm/notfound.html if unsuccessful
10393: 
10394: =item *
10395: 
10396: renameuserfile(): renames an existing userfile to a new name
10397: 
10398:   Args:
10399:    docuname: username or courseid of destination for the file
10400:    docudom: domain of user/course of destination for the file
10401:    old: current file name (including any subdirs under userfiles)
10402:    new: desired file name (including any subdirs under userfiles)
10403: 
10404: =item *
10405: 
10406: mkdiruserfile(): creates a directory is a userfiles dir
10407: 
10408:   Args:
10409:    docuname: username or courseid of destination for the file
10410:    docudom: domain of user/course of destination for the file
10411:    dir: dir to create (including any subdirs under userfiles)
10412: 
10413: =item *
10414: 
10415: removeuserfile(): removes a file that exists in userfiles
10416: 
10417:   Args:
10418:    docuname: username or courseid of destination for the file
10419:    docudom: domain of user/course of destination for the file
10420:    fname: filname to delete (including any subdirs under userfiles)
10421: 
10422: =item *
10423: 
10424: removeuploadedurl(): convience function for removeuserfile()
10425: 
10426:   Args:
10427:    url:  a full /uploaded/... url to delete
10428: 
10429: =item * 
10430: 
10431: get_portfile_permissions():
10432:   Args:
10433:     domain: domain of user or course contain the portfolio files
10434:     user: name of user or num of course contain the portfolio files
10435:   Returns:
10436:     hashref of a dump of the proper file_permissions.db
10437:    
10438: 
10439: =item * 
10440: 
10441: get_access_controls():
10442: 
10443: Args:
10444:   current_permissions: the hash ref returned from get_portfile_permissions()
10445:   group: (optional) the group you want the files associated with
10446:   file: (optional) the file you want access info on
10447: 
10448: Returns:
10449:     a hash (keys are file names) of hashes containing
10450:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10451:         values are XML containing access control settings (see below) 
10452: 
10453: Internal notes:
10454: 
10455:  access controls are stored in file_permissions.db as key=value pairs.
10456:     key -> path to file/file_name\0uniqueID:scope_end_start
10457:         where scope -> public,guest,course,group,domains or users.
10458:               end -> UNIX time for end of access (0 -> no end date)
10459:               start -> UNIX time for start of access
10460: 
10461:     value -> XML description of access control
10462:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10463:             <start></start>
10464:             <end></end>
10465: 
10466:             <password></password>  for scope type = guest
10467: 
10468:             <domain></domain>     for scope type = course or group
10469:             <number></number>
10470:             <roles id="">
10471:              <role></role>
10472:              <access></access>
10473:              <section></section>
10474:              <group></group>
10475:             </roles>
10476: 
10477:             <dom></dom>         for scope type = domains
10478: 
10479:             <users>             for scope type = users
10480:              <user>
10481:               <uname></uname>
10482:               <udom></udom>
10483:              </user>
10484:             </users>
10485:            </scope> 
10486:               
10487:  Access data is also aggregated for each file in an additional key=value pair:
10488:  key -> path to file/file_name\0accesscontrol 
10489:  value -> reference to hash
10490:           hash contains key = value pairs
10491:           where key = uniqueID:scope_end_start
10492:                 value = UNIX time record was last updated
10493: 
10494:           Used to improve speed of look-ups of access controls for each file.  
10495:  
10496:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10497: 
10498: modify_access_controls():
10499: 
10500: Modifies access controls for a portfolio file
10501: Args
10502: 1. file name
10503: 2. reference to hash of required changes,
10504: 3. domain
10505: 4. username
10506:   where domain,username are the domain of the portfolio owner 
10507:   (either a user or a course) 
10508: 
10509: Returns:
10510: 1. result of additions or updates ('ok' or 'error', with error message). 
10511: 2. result of deletions ('ok' or 'error', with error message).
10512: 3. reference to hash of any new or updated access controls.
10513: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10514:    key = integer (inbound ID)
10515:    value = uniqueID  
10516: 
10517: =back
10518: 
10519: =head2 HTTP Helper Routines
10520: 
10521: =over 4
10522: 
10523: =item *
10524: 
10525: escape() : unpack non-word characters into CGI-compatible hex codes
10526: 
10527: =item *
10528: 
10529: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10530: 
10531: =back
10532: 
10533: =head1 PRIVATE SUBROUTINES
10534: 
10535: =head2 Underlying communication routines (Shouldn't call)
10536: 
10537: =over 4
10538: 
10539: =item *
10540: 
10541: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10542: 
10543: =item *
10544: 
10545: reply() : uses subreply to send a message to remote machine, logs all failures
10546: 
10547: =item *
10548: 
10549: critical() : passes a critical message to another server; if cannot
10550: get through then place message in connection buffer directory and
10551: returns con_delayed, if incapable of saving message, returns
10552: con_failed
10553: 
10554: =item *
10555: 
10556: reconlonc() : tries to reconnect lonc client processes.
10557: 
10558: =back
10559: 
10560: =head2 Resource Access Logging
10561: 
10562: =over 4
10563: 
10564: =item *
10565: 
10566: flushcourselogs() : flush (save) buffer logs and access logs
10567: 
10568: =item *
10569: 
10570: courselog($what) : save message for course in hash
10571: 
10572: =item *
10573: 
10574: courseacclog($what) : save message for course using &courselog().  Perform
10575: special processing for specific resource types (problems, exams, quizzes, etc).
10576: 
10577: =item *
10578: 
10579: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10580: as a PerlChildExitHandler
10581: 
10582: =back
10583: 
10584: =head2 Other
10585: 
10586: =over 4
10587: 
10588: =item *
10589: 
10590: symblist($mapname,%newhash) : update symbolic storage links
10591: 
10592: =back
10593: 
10594: =cut
10595: 

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