File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1050: download - view: text, annotated - select for diffs
Sun Feb 21 02:38:31 2010 UTC (14 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6176. Owners of courses can clone them even if they no longer have an
  active Course Coordinator role.
- New subroutine in lonnet.pm - &is_course_owner() returns 1 if user is
  the owner of the specified course.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1050 2010/02/21 02:38:31 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 File::MMagic;
   96: use LONCAPA qw(:DEFAULT :match);
   97: use LONCAPA::Configuration;
   98: 
   99: my $readit;
  100: my $max_connection_retries = 10;     # Or some such value.
  101: 
  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  103: 
  104: require Exporter;
  105: 
  106: our @ISA = qw (Exporter);
  107: our @EXPORT = qw(%env);
  108: 
  109: 
  110: # --------------------------------------------------------------------- Logging
  111: {
  112:     my $logid;
  113:     sub instructor_log {
  114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  115:         if (($cnum eq '') || ($cdom eq '')) {
  116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  118:         }
  119: 	$logid++;
  120:         my $now = time();
  121: 	my $id=$now.'00000'.$$.'00000'.$logid;
  122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  123: 				    { $id => {
  124: 					'exe_uname' => $env{'user.name'},
  125: 					'exe_udom'  => $env{'user.domain'},
  126: 					'exe_time'  => $now,
  127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  128: 					'delflag'   => $delflag,
  129: 					'logentry'  => $storehash,
  130: 					'uname'     => $uname,
  131: 					'udom'      => $udom,
  132: 				    }
  133: 				  },$cdom,$cnum);
  134:     }
  135: }
  136: 
  137: sub logtouch {
  138:     my $execdir=$perlvar{'lonDaemons'};
  139:     unless (-e "$execdir/logs/lonnet.log") {	
  140: 	open(my $fh,">>$execdir/logs/lonnet.log");
  141: 	close $fh;
  142:     }
  143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  145: }
  146: 
  147: sub logthis {
  148:     my $message=shift;
  149:     my $execdir=$perlvar{'lonDaemons'};
  150:     my $now=time;
  151:     my $local=localtime($now);
  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  154: 	print $fh $logstring;
  155: 	close($fh);
  156:     }
  157:     return 1;
  158: }
  159: 
  160: sub logperm {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  166: 	print $fh "$now:$message:$local\n";
  167: 	close($fh);
  168:     }
  169:     return 1;
  170: }
  171: 
  172: sub create_connection {
  173:     my ($hostname,$lonid) = @_;
  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  175: 				     Type    => SOCK_STREAM,
  176: 				     Timeout => 10);
  177:     return 0 if (!$client);
  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  179:     my $result = <$client>;
  180:     chomp($result);
  181:     return 1 if ($result eq 'done');
  182:     return 0;
  183: }
  184: 
  185: sub get_server_timezone {
  186:     my ($cnum,$cdom) = @_;
  187:     my $home=&homeserver($cnum,$cdom);
  188:     if ($home ne 'no_host') {
  189:         my $cachetime = 24*3600;
  190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  191:         if (defined($cached)) {
  192:             return $timezone;
  193:         } else {
  194:             my $timezone = &reply('servertimezone',$home);
  195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  196:         }
  197:     }
  198: }
  199: 
  200: sub get_server_loncaparev {
  201:     my ($dom,$lonhost) = @_;
  202:     if (defined($lonhost)) {
  203:         if (!defined(&hostname($lonhost))) {
  204:             undef($lonhost);
  205:         }
  206:     }
  207:     if (!defined($lonhost)) {
  208:         if (defined(&domain($dom,'primary'))) {
  209:             $lonhost=&domain($dom,'primary');
  210:             if ($lonhost eq 'no_host') {
  211:                 undef($lonhost);
  212:             }
  213:         }
  214:     }
  215:     if (defined($lonhost)) {
  216:         my $cachetime = 24*3600;
  217:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  218:         if (defined($cached)) {
  219:             return $loncaparev;
  220:         } else {
  221:             my $loncaparev = &reply('serverloncaparev',$lonhost);
  222:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  223:         }
  224:     }
  225: }
  226: 
  227: # -------------------------------------------------- Non-critical communication
  228: sub subreply {
  229:     my ($cmd,$server)=@_;
  230:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  231:     #
  232:     #  With loncnew process trimming, there's a timing hole between lonc server
  233:     #  process exit and the master server picking up the listen on the AF_UNIX
  234:     #  socket.  In that time interval, a lock file will exist:
  235: 
  236:     my $lockfile=$peerfile.".lock";
  237:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  238: 	sleep(1);
  239:     }
  240:     # At this point, either a loncnew parent is listening or an old lonc
  241:     # or loncnew child is listening so we can connect or everything's dead.
  242:     #
  243:     #   We'll give the connection a few tries before abandoning it.  If
  244:     #   connection is not possible, we'll con_lost back to the client.
  245:     #   
  246:     my $client;
  247:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  248: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  249: 				      Type    => SOCK_STREAM,
  250: 				      Timeout => 10);
  251: 	if ($client) {
  252: 	    last;		# Connected!
  253: 	} else {
  254: 	    &create_connection(&hostname($server),$server);
  255: 	}
  256:         sleep(1);		# Try again later if failed connection.
  257:     }
  258:     my $answer;
  259:     if ($client) {
  260: 	print $client "sethost:$server:$cmd\n";
  261: 	$answer=<$client>;
  262: 	if (!$answer) { $answer="con_lost"; }
  263: 	chomp($answer);
  264:     } else {
  265: 	$answer = 'con_lost';	# Failed connection.
  266:     }
  267:     return $answer;
  268: }
  269: 
  270: sub reply {
  271:     my ($cmd,$server)=@_;
  272:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  273:     my $answer=subreply($cmd,$server);
  274:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  275:        &logthis("<font color=\"blue\">WARNING:".
  276:                 " $cmd to $server returned $answer</font>");
  277:     }
  278:     return $answer;
  279: }
  280: 
  281: # ----------------------------------------------------------- Send USR1 to lonc
  282: 
  283: sub reconlonc {
  284:     my ($lonid) = @_;
  285:     my $hostname = &hostname($lonid);
  286:     if ($lonid) {
  287: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  288: 	if ($hostname && -e $peerfile) {
  289: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  290: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  291: 					     Type    => SOCK_STREAM,
  292: 					     Timeout => 10);
  293: 	    if ($client) {
  294: 		print $client ("reset_retries\n");
  295: 		my $answer=<$client>;
  296: 		#reset just this one.
  297: 	    }
  298: 	}
  299: 	return;
  300:     }
  301: 
  302:     &logthis("Trying to reconnect lonc");
  303:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  304:     if (open(my $fh,"<$loncfile")) {
  305: 	my $loncpid=<$fh>;
  306:         chomp($loncpid);
  307:         if (kill 0 => $loncpid) {
  308: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  309:             kill USR1 => $loncpid;
  310:             sleep 1;
  311:          } else {
  312: 	    &logthis(
  313:                "<font color=\"blue\">WARNING:".
  314:                " lonc at pid $loncpid not responding, giving up</font>");
  315:         }
  316:     } else {
  317: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  318:     }
  319: }
  320: 
  321: # ------------------------------------------------------ Critical communication
  322: 
  323: sub critical {
  324:     my ($cmd,$server)=@_;
  325:     unless (&hostname($server)) {
  326:         &logthis("<font color=\"blue\">WARNING:".
  327:                " Critical message to unknown server ($server)</font>");
  328:         return 'no_such_host';
  329:     }
  330:     my $answer=reply($cmd,$server);
  331:     if ($answer eq 'con_lost') {
  332: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  333: 	my $answer=reply($cmd,$server);
  334:         if ($answer eq 'con_lost') {
  335:             my $now=time;
  336:             my $middlename=$cmd;
  337:             $middlename=substr($middlename,0,16);
  338:             $middlename=~s/\W//g;
  339:             my $dfilename=
  340:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  341:             $dumpcount++;
  342:             {
  343: 		my $dfh;
  344: 		if (open($dfh,">$dfilename")) {
  345: 		    print $dfh "$cmd\n"; 
  346: 		    close($dfh);
  347: 		}
  348:             }
  349:             sleep 2;
  350:             my $wcmd='';
  351:             {
  352: 		my $dfh;
  353: 		if (open($dfh,"<$dfilename")) {
  354: 		    $wcmd=<$dfh>; 
  355: 		    close($dfh);
  356: 		}
  357:             }
  358:             chomp($wcmd);
  359:             if ($wcmd eq $cmd) {
  360: 		&logthis("<font color=\"blue\">WARNING: ".
  361:                          "Connection buffer $dfilename: $cmd</font>");
  362:                 &logperm("D:$server:$cmd");
  363: 	        return 'con_delayed';
  364:             } else {
  365:                 &logthis("<font color=\"red\">CRITICAL:"
  366:                         ." Critical connection failed: $server $cmd</font>");
  367:                 &logperm("F:$server:$cmd");
  368:                 return 'con_failed';
  369:             }
  370:         }
  371:     }
  372:     return $answer;
  373: }
  374: 
  375: # ------------------------------------------- check if return value is an error
  376: 
  377: sub error {
  378:     my ($result) = @_;
  379:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  380: 	if ($2 == 2) { return undef; }
  381: 	return $1;
  382:     }
  383:     return undef;
  384: }
  385: 
  386: sub convert_and_load_session_env {
  387:     my ($lonidsdir,$handle)=@_;
  388:     my @profile;
  389:     {
  390: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  391: 	if (!$opened) {
  392: 	    return 0;
  393: 	}
  394: 	flock($idf,LOCK_SH);
  395: 	@profile=<$idf>;
  396: 	close($idf);
  397:     }
  398:     my %temp_env;
  399:     foreach my $line (@profile) {
  400: 	if ($line !~ m/=/) {
  401: 	    return 0;
  402: 	}
  403: 	chomp($line);
  404: 	my ($envname,$envvalue)=split(/=/,$line,2);
  405: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  406:     }
  407:     unlink("$lonidsdir/$handle.id");
  408:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  409: 	    0640)) {
  410: 	%disk_env = %temp_env;
  411: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  412: 	untie(%disk_env);
  413:     }
  414:     return 1;
  415: }
  416: 
  417: # ------------------------------------------- Transfer profile into environment
  418: my $env_loaded;
  419: sub transfer_profile_to_env {
  420:     my ($lonidsdir,$handle,$force_transfer) = @_;
  421:     if (!$force_transfer && $env_loaded) { return; } 
  422: 
  423:     if (!defined($lonidsdir)) {
  424: 	$lonidsdir = $perlvar{'lonIDsDir'};
  425:     }
  426:     if (!defined($handle)) {
  427:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  428:     }
  429: 
  430:     my $convert;
  431:     {
  432:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  433: 	if (!$opened) {
  434: 	    return;
  435: 	}
  436: 	flock($idf,LOCK_SH);
  437: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  438: 		&GDBM_READER(),0640)) {
  439: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  440: 	    untie(%disk_env);
  441: 	} else {
  442: 	    $convert = 1;
  443: 	}
  444:     }
  445:     if ($convert) {
  446: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  447: 	    &logthis("Failed to load session, or convert session.");
  448: 	}
  449:     }
  450: 
  451:     my %remove;
  452:     while ( my $envname = each(%env) ) {
  453:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  454:             if ($time < time-300) {
  455:                 $remove{$key}++;
  456:             }
  457:         }
  458:     }
  459: 
  460:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  461:     $env_loaded=1;
  462:     foreach my $expired_key (keys(%remove)) {
  463:         &delenv($expired_key);
  464:     }
  465: }
  466: 
  467: # ---------------------------------------------------- Check for valid session 
  468: sub check_for_valid_session {
  469:     my ($r) = @_;
  470:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  471:     my $lonid=$cookies{'lonID'};
  472:     return undef if (!$lonid);
  473: 
  474:     my $handle=&LONCAPA::clean_handle($lonid->value);
  475:     my $lonidsdir=$r->dir_config('lonIDsDir');
  476:     return undef if (!-e "$lonidsdir/$handle.id");
  477: 
  478:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  479:     return undef if (!$opened);
  480: 
  481:     flock($idf,LOCK_SH);
  482:     my %disk_env;
  483:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  484: 	    &GDBM_READER(),0640)) {
  485: 	return undef;	
  486:     }
  487: 
  488:     if (!defined($disk_env{'user.name'})
  489: 	|| !defined($disk_env{'user.domain'})) {
  490: 	return undef;
  491:     }
  492:     return $handle;
  493: }
  494: 
  495: sub timed_flock {
  496:     my ($file,$lock_type) = @_;
  497:     my $failed=0;
  498:     eval {
  499: 	local $SIG{__DIE__}='DEFAULT';
  500: 	local $SIG{ALRM}=sub {
  501: 	    $failed=1;
  502: 	    die("failed lock");
  503: 	};
  504: 	alarm(13);
  505: 	flock($file,$lock_type);
  506: 	alarm(0);
  507:     };
  508:     if ($failed) {
  509: 	return undef;
  510:     } else {
  511: 	return 1;
  512:     }
  513: }
  514: 
  515: # ---------------------------------------------------------- Append Environment
  516: 
  517: sub appenv {
  518:     my ($newenv,$roles) = @_;
  519:     if (ref($newenv) eq 'HASH') {
  520:         foreach my $key (keys(%{$newenv})) {
  521:             my $refused = 0;
  522: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  523:                 $refused = 1;
  524:                 if (ref($roles) eq 'ARRAY') {
  525:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  526:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  527:                         $refused = 0;
  528:                     }
  529:                 }
  530:             }
  531:             if ($refused) {
  532:                 &logthis("<font color=\"blue\">WARNING: ".
  533:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  534:                          .'</font>');
  535: 	        delete($newenv->{$key});
  536:             } else {
  537:                 $env{$key}=$newenv->{$key};
  538:             }
  539:         }
  540:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  541:         if ($opened
  542: 	    && &timed_flock($env_file,LOCK_EX)
  543: 	    &&
  544: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  545: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  546: 	    while (my ($key,$value) = each(%{$newenv})) {
  547: 	        $disk_env{$key} = $value;
  548: 	    }
  549: 	    untie(%disk_env);
  550:         }
  551:     }
  552:     return 'ok';
  553: }
  554: # ----------------------------------------------------- Delete from Environment
  555: 
  556: sub delenv {
  557:     my ($delthis,$regexp) = @_;
  558:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  559:         &logthis("<font color=\"blue\">WARNING: ".
  560:                 "Attempt to delete from environment ".$delthis);
  561:         return 'error';
  562:     }
  563:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  564:     if ($opened
  565: 	&& &timed_flock($env_file,LOCK_EX)
  566: 	&&
  567: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  568: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  569: 	foreach my $key (keys(%disk_env)) {
  570: 	    if ($regexp) {
  571:                 if ($key=~/^$delthis/) {
  572:                     delete($env{$key});
  573:                     delete($disk_env{$key});
  574:                 } 
  575:             } else {
  576:                 if ($key=~/^\Q$delthis\E/) {
  577: 		    delete($env{$key});
  578: 		    delete($disk_env{$key});
  579: 	        }
  580:             }
  581: 	}
  582: 	untie(%disk_env);
  583:     }
  584:     return 'ok';
  585: }
  586: 
  587: sub get_env_multiple {
  588:     my ($name) = @_;
  589:     my @values;
  590:     if (defined($env{$name})) {
  591:         # exists is it an array
  592:         if (ref($env{$name})) {
  593:             @values=@{ $env{$name} };
  594:         } else {
  595:             $values[0]=$env{$name};
  596:         }
  597:     }
  598:     return(@values);
  599: }
  600: 
  601: # ------------------------------------------------------------------- Locking
  602: 
  603: sub set_lock {
  604:     my ($text)=@_;
  605:     $locknum++;
  606:     my $id=$$.'-'.$locknum;
  607:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  608:              'session.lock.'.$id => $text});
  609:     return $id;
  610: }
  611: 
  612: sub get_locks {
  613:     my $num=0;
  614:     my %texts=();
  615:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  616:        if ($lock=~/\w/) {
  617:           $num++;
  618:           $texts{$lock}=$env{'session.lock.'.$lock};
  619:        }
  620:    }
  621:    return ($num,%texts);
  622: }
  623: 
  624: sub remove_lock {
  625:     my ($id)=@_;
  626:     my $newlocks='';
  627:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  628:        if (($lock=~/\w/) && ($lock ne $id)) {
  629:           $newlocks.=','.$lock;
  630:        }
  631:     }
  632:     &appenv({'session.locks' => $newlocks});
  633:     &delenv('session.lock.'.$id);
  634: }
  635: 
  636: sub remove_all_locks {
  637:     my $activelocks=$env{'session.locks'};
  638:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  639:        if ($lock=~/\w/) {
  640:           &remove_lock($lock);
  641:        }
  642:     }
  643: }
  644: 
  645: 
  646: # ------------------------------------------ Find out current server userload
  647: sub userload {
  648:     my $numusers=0;
  649:     {
  650: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  651: 	my $filename;
  652: 	my $curtime=time;
  653: 	while ($filename=readdir(LONIDS)) {
  654: 	    next if ($filename eq '.' || $filename eq '..');
  655: 	    next if ($filename =~ /publicuser_\d+\.id/);
  656: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  657: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  658: 	}
  659: 	closedir(LONIDS);
  660:     }
  661:     my $userloadpercent=0;
  662:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  663:     if ($maxuserload) {
  664: 	$userloadpercent=100*$numusers/$maxuserload;
  665:     }
  666:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  667:     return $userloadpercent;
  668: }
  669: 
  670: # ------------------------------------------ Fight off request when overloaded
  671: 
  672: sub overloaderror {
  673:     my ($r,$checkserver)=@_;
  674:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  675:     my $loadavg;
  676:     if ($checkserver eq $perlvar{'lonHostID'}) {
  677:        open(my $loadfile,'/proc/loadavg');
  678:        $loadavg=<$loadfile>;
  679:        $loadavg =~ s/\s.*//g;
  680:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  681:        close($loadfile);
  682:     } else {
  683:        $loadavg=&reply('load',$checkserver);
  684:     }
  685:     my $overload=$loadavg-100;
  686:     if ($overload>0) {
  687: 	$r->err_headers_out->{'Retry-After'}=$overload;
  688:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  689:         return 413;
  690:     }    
  691:     return '';
  692: }
  693: 
  694: # ------------------------------ Find server with least workload from spare.tab
  695: 
  696: sub spareserver {
  697:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  698:     my $spare_server;
  699:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  700:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  701:                                                      :  $userloadpercent;
  702:     
  703:     foreach my $try_server (@{ $spareid{'primary'} }) {
  704: 	($spare_server, $lowest_load) =
  705: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  706:     }
  707: 
  708:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  709: 
  710:     if (!$found_server) {
  711: 	foreach my $try_server (@{ $spareid{'default'} }) {
  712: 	    ($spare_server, $lowest_load) =
  713: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  714: 	}
  715:     }
  716: 
  717:     if (!$want_server_name) {
  718:         my $protocol = 'http';
  719:         if ($protocol{$spare_server} eq 'https') {
  720:             $protocol = $protocol{$spare_server};
  721:         }
  722:         if (defined($spare_server)) {
  723:             my $hostname = &hostname($spare_server);
  724:             if (defined($hostname)) {  
  725: 	        $spare_server = $protocol.'://'.$hostname;
  726:             }
  727:         }
  728:     }
  729:     return $spare_server;
  730: }
  731: 
  732: sub compare_server_load {
  733:     my ($try_server, $spare_server, $lowest_load) = @_;
  734: 
  735:     my $loadans     = &reply('load',    $try_server);
  736:     my $userloadans = &reply('userload',$try_server);
  737: 
  738:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  739: 	next; #didn't get a number from the server
  740:     }
  741: 
  742:     my $load;
  743:     if ($loadans =~ /\d/) {
  744: 	if ($userloadans =~ /\d/) {
  745: 	    #both are numbers, pick the bigger one
  746: 	    $load = ($loadans > $userloadans) ? $loadans 
  747: 		                              : $userloadans;
  748: 	} else {
  749: 	    $load = $loadans;
  750: 	}
  751:     } else {
  752: 	$load = $userloadans;
  753:     }
  754: 
  755:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  756: 	$spare_server = $try_server;
  757: 	$lowest_load  = $load;
  758:     }
  759:     return ($spare_server,$lowest_load);
  760: }
  761: 
  762: # --------------------------- ask offload servers if user already has a session
  763: sub find_existing_session {
  764:     my ($udom,$uname) = @_;
  765:     foreach my $try_server (@{ $spareid{'primary'} },
  766: 			    @{ $spareid{'default'} }) {
  767: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  768:     }
  769:     return;
  770: }
  771: 
  772: # -------------------------------- ask if server already has a session for user
  773: sub has_user_session {
  774:     my ($lonid,$udom,$uname) = @_;
  775:     my $result = &reply(join(':','userhassession',
  776: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  777:     return 1 if ($result eq 'ok');
  778: 
  779:     return 0;
  780: }
  781: 
  782: # --------------------------------------------- Try to change a user's password
  783: 
  784: sub changepass {
  785:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  786:     $currentpass = &escape($currentpass);
  787:     $newpass     = &escape($newpass);
  788:     my $lonhost = $perlvar{'lonHostID'};
  789:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  790: 		       $server);
  791:     if (! $answer) {
  792: 	&logthis("No reply on password change request to $server ".
  793: 		 "by $uname in domain $udom.");
  794:     } elsif ($answer =~ "^ok") {
  795:         &logthis("$uname in $udom successfully changed their password ".
  796: 		 "on $server.");
  797:     } elsif ($answer =~ "^pwchange_failure") {
  798: 	&logthis("$uname in $udom was unable to change their password ".
  799: 		 "on $server.  The action was blocked by either lcpasswd ".
  800: 		 "or pwchange");
  801:     } elsif ($answer =~ "^non_authorized") {
  802:         &logthis("$uname in $udom did not get their password correct when ".
  803: 		 "attempting to change it on $server.");
  804:     } elsif ($answer =~ "^auth_mode_error") {
  805:         &logthis("$uname in $udom attempted to change their password despite ".
  806: 		 "not being locally or internally authenticated on $server.");
  807:     } elsif ($answer =~ "^unknown_user") {
  808:         &logthis("$uname in $udom attempted to change their password ".
  809: 		 "on $server but were unable to because $server is not ".
  810: 		 "their home server.");
  811:     } elsif ($answer =~ "^refused") {
  812: 	&logthis("$server refused to change $uname in $udom password because ".
  813: 		 "it was sent an unencrypted request to change the password.");
  814:     } elsif ($answer =~ "invalid_client") {
  815:         &logthis("$server refused to change $uname in $udom password because ".
  816:                  "it was a reset by e-mail originating from an invalid server.");
  817:     }
  818:     return $answer;
  819: }
  820: 
  821: # ----------------------- Try to determine user's current authentication scheme
  822: 
  823: sub queryauthenticate {
  824:     my ($uname,$udom)=@_;
  825:     my $uhome=&homeserver($uname,$udom);
  826:     if (!$uhome) {
  827: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  828: 	return 'no_host';
  829:     }
  830:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  831:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  832: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  833:     }
  834:     return $answer;
  835: }
  836: 
  837: # --------- Try to authenticate user from domain's lib servers (first this one)
  838: 
  839: sub authenticate {
  840:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  841:     $upass=&escape($upass);
  842:     $uname= &LONCAPA::clean_username($uname);
  843:     my $uhome=&homeserver($uname,$udom,1);
  844:     my $newhome;
  845:     if ((!$uhome) || ($uhome eq 'no_host')) {
  846: # Maybe the machine was offline and only re-appeared again recently?
  847:         &reconlonc();
  848: # One more
  849: 	$uhome=&homeserver($uname,$udom,1);
  850:         if (($uhome eq 'no_host') && $checkdefauth) {
  851:             if (defined(&domain($udom,'primary'))) {
  852:                 $newhome=&domain($udom,'primary');
  853:             }
  854:             if ($newhome ne '') {
  855:                 $uhome = $newhome;
  856:             }
  857:         }
  858: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  859: 	    &logthis("User $uname at $udom is unknown in authenticate");
  860: 	    return 'no_host';
  861:         }
  862:     }
  863:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  864:     if ($answer eq 'authorized') {
  865:         if ($newhome) {
  866:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  867:             return 'no_account_on_host'; 
  868:         } else {
  869:             &logthis("User $uname at $udom authorized by $uhome");
  870:             return $uhome;
  871:         }
  872:     }
  873:     if ($answer eq 'non_authorized') {
  874: 	&logthis("User $uname at $udom rejected by $uhome");
  875: 	return 'no_host'; 
  876:     }
  877:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  878:     return 'no_host';
  879: }
  880: 
  881: # ---------------------- Find the homebase for a user from domain's lib servers
  882: 
  883: my %homecache;
  884: sub homeserver {
  885:     my ($uname,$udom,$ignoreBadCache)=@_;
  886:     my $index="$uname:$udom";
  887: 
  888:     if (exists($homecache{$index})) { return $homecache{$index}; }
  889: 
  890:     my %servers = &get_servers($udom,'library');
  891:     foreach my $tryserver (keys(%servers)) {
  892:         next if ($ignoreBadCache ne 'true' && 
  893: 		 exists($badServerCache{$tryserver}));
  894: 
  895: 	my $answer=reply("home:$udom:$uname",$tryserver);
  896: 	if ($answer eq 'found') {
  897: 	    delete($badServerCache{$tryserver}); 
  898: 	    return $homecache{$index}=$tryserver;
  899: 	} elsif ($answer eq 'no_host') {
  900: 	    $badServerCache{$tryserver}=1;
  901: 	}
  902:     }    
  903:     return 'no_host';
  904: }
  905: 
  906: # ------------------------------------- Find the usernames behind a list of IDs
  907: 
  908: sub idget {
  909:     my ($udom,@ids)=@_;
  910:     my %returnhash=();
  911:     
  912:     my %servers = &get_servers($udom,'library');
  913:     foreach my $tryserver (keys(%servers)) {
  914: 	my $idlist=join('&',@ids);
  915: 	$idlist=~tr/A-Z/a-z/; 
  916: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  917: 	my @answer=();
  918: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  919: 	    @answer=split(/\&/,$reply);
  920: 	}                    ;
  921: 	my $i;
  922: 	for ($i=0;$i<=$#ids;$i++) {
  923: 	    if ($answer[$i]) {
  924: 		$returnhash{$ids[$i]}=$answer[$i];
  925: 	    } 
  926: 	}
  927:     } 
  928:     return %returnhash;
  929: }
  930: 
  931: # ------------------------------------- Find the IDs behind a list of usernames
  932: 
  933: sub idrget {
  934:     my ($udom,@unames)=@_;
  935:     my %returnhash=();
  936:     foreach my $uname (@unames) {
  937:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  938:     }
  939:     return %returnhash;
  940: }
  941: 
  942: # ------------------------------- Store away a list of names and associated IDs
  943: 
  944: sub idput {
  945:     my ($udom,%ids)=@_;
  946:     my %servers=();
  947:     foreach my $uname (keys(%ids)) {
  948: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  949:         my $uhom=&homeserver($uname,$udom);
  950:         if ($uhom ne 'no_host') {
  951:             my $id=&escape($ids{$uname});
  952:             $id=~tr/A-Z/a-z/;
  953:             my $esc_unam=&escape($uname);
  954: 	    if ($servers{$uhom}) {
  955: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  956:             } else {
  957:                 $servers{$uhom}=$id.'='.$esc_unam;
  958:             }
  959:         }
  960:     }
  961:     foreach my $server (keys(%servers)) {
  962:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  963:     }
  964: }
  965: 
  966: # ------------------------------dump from db file owned by domainconfig user
  967: sub dump_dom {
  968:     my ($namespace,$udom,$regexp,$range)=@_;
  969:     if (!$udom) {
  970:         $udom=$env{'user.domain'};
  971:     }
  972:     my %returnhash;
  973:     if ($udom) {
  974:         my $uname = &get_domainconfiguser($udom);
  975:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
  976:     }
  977:     return %returnhash;
  978: }
  979: 
  980: # ------------------------------------------ get items from domain db files   
  981: 
  982: sub get_dom {
  983:     my ($namespace,$storearr,$udom,$uhome)=@_;
  984:     my $items='';
  985:     foreach my $item (@$storearr) {
  986:         $items.=&escape($item).'&';
  987:     }
  988:     $items=~s/\&$//;
  989:     if (!$udom) {
  990:         $udom=$env{'user.domain'};
  991:         if (defined(&domain($udom,'primary'))) {
  992:             $uhome=&domain($udom,'primary');
  993:         } else {
  994:             undef($uhome);
  995:         }
  996:     } else {
  997:         if (!$uhome) {
  998:             if (defined(&domain($udom,'primary'))) {
  999:                 $uhome=&domain($udom,'primary');
 1000:             }
 1001:         }
 1002:     }
 1003:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1004:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1005:         my %returnhash;
 1006:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1007:             return %returnhash;
 1008:         }
 1009:         my @pairs=split(/\&/,$rep);
 1010:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1011:             return @pairs;
 1012:         }
 1013:         my $i=0;
 1014:         foreach my $item (@$storearr) {
 1015:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1016:             $i++;
 1017:         }
 1018:         return %returnhash;
 1019:     } else {
 1020:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1021:     }
 1022: }
 1023: 
 1024: # -------------------------------------------- put items in domain db files 
 1025: 
 1026: sub put_dom {
 1027:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1028:     if (!$udom) {
 1029:         $udom=$env{'user.domain'};
 1030:         if (defined(&domain($udom,'primary'))) {
 1031:             $uhome=&domain($udom,'primary');
 1032:         } else {
 1033:             undef($uhome);
 1034:         }
 1035:     } else {
 1036:         if (!$uhome) {
 1037:             if (defined(&domain($udom,'primary'))) {
 1038:                 $uhome=&domain($udom,'primary');
 1039:             }
 1040:         }
 1041:     } 
 1042:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1043:         my $items='';
 1044:         foreach my $item (keys(%$storehash)) {
 1045:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1046:         }
 1047:         $items=~s/\&$//;
 1048:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1049:     } else {
 1050:         &logthis("put_dom failed - no homeserver and/or domain");
 1051:     }
 1052: }
 1053: 
 1054: # --------------------- newput for items in db file owned by domainconfig user
 1055: sub newput_dom {
 1056:     my ($namespace,$storehash,$udom) = @_;
 1057:     my $result;
 1058:     if (!$udom) {
 1059:         $udom=$env{'user.domain'};
 1060:     }
 1061:     if ($udom) {
 1062:         my $uname = &get_domainconfiguser($udom);
 1063:         $result = &newput($namespace,$storehash,$udom,$uname);
 1064:     }
 1065:     return $result;
 1066: }
 1067: 
 1068: # --------------------- delete for items in db file owned by domainconfig user
 1069: sub del_dom {
 1070:     my ($namespace,$storearr,$udom)=@_;
 1071:     if (ref($storearr) eq 'ARRAY') {
 1072:         if (!$udom) {
 1073:             $udom=$env{'user.domain'};
 1074:         }
 1075:         if ($udom) {
 1076:             my $uname = &get_domainconfiguser($udom); 
 1077:             return &del($namespace,$storearr,$udom,$uname);
 1078:         }
 1079:     }
 1080: }
 1081: 
 1082: # ----------------------------------construct domainconfig user for a domain 
 1083: sub get_domainconfiguser {
 1084:     my ($udom) = @_;
 1085:     return $udom.'-domainconfig';
 1086: }
 1087: 
 1088: sub retrieve_inst_usertypes {
 1089:     my ($udom) = @_;
 1090:     my (%returnhash,@order);
 1091:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1092:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1093:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1094:         %returnhash = %{$domdefs{'inststatustypes'}};
 1095:         @order = @{$domdefs{'inststatusorder'}};
 1096:     } else {
 1097:         if (defined(&domain($udom,'primary'))) {
 1098:             my $uhome=&domain($udom,'primary');
 1099:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1100:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1101:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1102:                 return (\%returnhash,\@order);
 1103:             }
 1104:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1105:             my @pairs=split(/\&/,$hashitems);
 1106:             foreach my $item (@pairs) {
 1107:                 my ($key,$value)=split(/=/,$item,2);
 1108:                 $key = &unescape($key);
 1109:                 next if ($key =~ /^error: 2 /);
 1110:                 $returnhash{$key}=&thaw_unescape($value);
 1111:             }
 1112:             my @esc_order = split(/\&/,$orderitems);
 1113:             foreach my $item (@esc_order) {
 1114:                 push(@order,&unescape($item));
 1115:             }
 1116:         } else {
 1117:             &logthis("get_dom failed - no primary domain server for $udom");
 1118:         }
 1119:     }
 1120:     return (\%returnhash,\@order);
 1121: }
 1122: 
 1123: sub is_domainimage {
 1124:     my ($url) = @_;
 1125:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1126:         if (&domain($1) ne '') {
 1127:             return '1';
 1128:         }
 1129:     }
 1130:     return;
 1131: }
 1132: 
 1133: sub inst_directory_query {
 1134:     my ($srch) = @_;
 1135:     my $udom = $srch->{'srchdomain'};
 1136:     my %results;
 1137:     my $homeserver = &domain($udom,'primary');
 1138:     my $outcome;
 1139:     if ($homeserver ne '') {
 1140: 	my $queryid=&reply("querysend:instdirsearch:".
 1141: 			   &escape($srch->{'srchby'}).':'.
 1142: 			   &escape($srch->{'srchterm'}).':'.
 1143: 			   &escape($srch->{'srchtype'}),$homeserver);
 1144: 	my $host=&hostname($homeserver);
 1145: 	if ($queryid !~/^\Q$host\E\_/) {
 1146: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1147: 	    return;
 1148: 	}
 1149: 	my $response = &get_query_reply($queryid);
 1150: 	my $maxtries = 5;
 1151: 	my $tries = 1;
 1152: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1153: 	    $response = &get_query_reply($queryid);
 1154: 	    $tries ++;
 1155: 	}
 1156: 
 1157:         if (!&error($response) && $response ne 'refused') {
 1158:             if ($response eq 'unavailable') {
 1159:                 $outcome = $response;
 1160:             } else {
 1161:                 $outcome = 'ok';
 1162:                 my @matches = split(/\n/,$response);
 1163:                 foreach my $match (@matches) {
 1164:                     my ($key,$value) = split(/=/,$match);
 1165:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1166:                 }
 1167:             }
 1168:         }
 1169:     }
 1170:     return ($outcome,%results);
 1171: }
 1172: 
 1173: sub usersearch {
 1174:     my ($srch) = @_;
 1175:     my $dom = $srch->{'srchdomain'};
 1176:     my %results;
 1177:     my %libserv = &all_library();
 1178:     my $query = 'usersearch';
 1179:     foreach my $tryserver (keys(%libserv)) {
 1180:         if (&host_domain($tryserver) eq $dom) {
 1181:             my $host=&hostname($tryserver);
 1182:             my $queryid=
 1183:                 &reply("querysend:".&escape($query).':'.
 1184:                        &escape($srch->{'srchby'}).':'.
 1185:                        &escape($srch->{'srchtype'}).':'.
 1186:                        &escape($srch->{'srchterm'}),$tryserver);
 1187:             if ($queryid !~/^\Q$host\E\_/) {
 1188:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1189:                 next;
 1190:             }
 1191:             my $reply = &get_query_reply($queryid);
 1192:             my $maxtries = 1;
 1193:             my $tries = 1;
 1194:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1195:                 $reply = &get_query_reply($queryid);
 1196:                 $tries ++;
 1197:             }
 1198:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1199:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1200:             } else {
 1201:                 my @matches;
 1202:                 if ($reply =~ /\n/) {
 1203:                     @matches = split(/\n/,$reply);
 1204:                 } else {
 1205:                     @matches = split(/\&/,$reply);
 1206:                 }
 1207:                 foreach my $match (@matches) {
 1208:                     my ($uname,$udom,%userhash);
 1209:                     foreach my $entry (split(/:/,$match)) {
 1210:                         my ($key,$value) =
 1211:                             map {&unescape($_);} split(/=/,$entry);
 1212:                         $userhash{$key} = $value;
 1213:                         if ($key eq 'username') {
 1214:                             $uname = $value;
 1215:                         } elsif ($key eq 'domain') {
 1216:                             $udom = $value;
 1217:                         }
 1218:                     }
 1219:                     $results{$uname.':'.$udom} = \%userhash;
 1220:                 }
 1221:             }
 1222:         }
 1223:     }
 1224:     return %results;
 1225: }
 1226: 
 1227: sub get_instuser {
 1228:     my ($udom,$uname,$id) = @_;
 1229:     my $homeserver = &domain($udom,'primary');
 1230:     my ($outcome,%results);
 1231:     if ($homeserver ne '') {
 1232:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1233:                            &escape($id).':'.&escape($udom),$homeserver);
 1234:         my $host=&hostname($homeserver);
 1235:         if ($queryid !~/^\Q$host\E\_/) {
 1236:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1237:             return;
 1238:         }
 1239:         my $response = &get_query_reply($queryid);
 1240:         my $maxtries = 5;
 1241:         my $tries = 1;
 1242:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1243:             $response = &get_query_reply($queryid);
 1244:             $tries ++;
 1245:         }
 1246:         if (!&error($response) && $response ne 'refused') {
 1247:             if ($response eq 'unavailable') {
 1248:                 $outcome = $response;
 1249:             } else {
 1250:                 $outcome = 'ok';
 1251:                 my @matches = split(/\n/,$response);
 1252:                 foreach my $match (@matches) {
 1253:                     my ($key,$value) = split(/=/,$match);
 1254:                     $results{&unescape($key)} = &thaw_unescape($value);
 1255:                 }
 1256:             }
 1257:         }
 1258:     }
 1259:     my %userinfo;
 1260:     if (ref($results{$uname}) eq 'HASH') {
 1261:         %userinfo = %{$results{$uname}};
 1262:     } 
 1263:     return ($outcome,%userinfo);
 1264: }
 1265: 
 1266: sub inst_rulecheck {
 1267:     my ($udom,$uname,$id,$item,$rules) = @_;
 1268:     my %returnhash;
 1269:     if ($udom ne '') {
 1270:         if (ref($rules) eq 'ARRAY') {
 1271:             @{$rules} = map {&escape($_);} (@{$rules});
 1272:             my $rulestr = join(':',@{$rules});
 1273:             my $homeserver=&domain($udom,'primary');
 1274:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1275:                 my $response;
 1276:                 if ($item eq 'username') {                
 1277:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1278:                                               ':'.&escape($uname).':'.$rulestr,
 1279:                                               $homeserver));
 1280:                 } elsif ($item eq 'id') {
 1281:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1282:                                               ':'.&escape($id).':'.$rulestr,
 1283:                                               $homeserver));
 1284:                 } elsif ($item eq 'selfcreate') {
 1285:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1286:                                                &escape($udom).':'.&escape($uname).
 1287:                                               ':'.$rulestr,$homeserver));
 1288:                 }
 1289:                 if ($response ne 'refused') {
 1290:                     my @pairs=split(/\&/,$response);
 1291:                     foreach my $item (@pairs) {
 1292:                         my ($key,$value)=split(/=/,$item,2);
 1293:                         $key = &unescape($key);
 1294:                         next if ($key =~ /^error: 2 /);
 1295:                         $returnhash{$key}=&thaw_unescape($value);
 1296:                     }
 1297:                 }
 1298:             }
 1299:         }
 1300:     }
 1301:     return %returnhash;
 1302: }
 1303: 
 1304: sub inst_userrules {
 1305:     my ($udom,$check) = @_;
 1306:     my (%ruleshash,@ruleorder);
 1307:     if ($udom ne '') {
 1308:         my $homeserver=&domain($udom,'primary');
 1309:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1310:             my $response;
 1311:             if ($check eq 'id') {
 1312:                 $response=&reply('instidrules:'.&escape($udom),
 1313:                                  $homeserver);
 1314:             } elsif ($check eq 'email') {
 1315:                 $response=&reply('instemailrules:'.&escape($udom),
 1316:                                  $homeserver);
 1317:             } else {
 1318:                 $response=&reply('instuserrules:'.&escape($udom),
 1319:                                  $homeserver);
 1320:             }
 1321:             if (($response ne 'refused') && ($response ne 'error') && 
 1322:                 ($response ne 'unknown_cmd') && 
 1323:                 ($response ne 'no_such_host')) {
 1324:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1325:                 my @pairs=split(/\&/,$hashitems);
 1326:                 foreach my $item (@pairs) {
 1327:                     my ($key,$value)=split(/=/,$item,2);
 1328:                     $key = &unescape($key);
 1329:                     next if ($key =~ /^error: 2 /);
 1330:                     $ruleshash{$key}=&thaw_unescape($value);
 1331:                 }
 1332:                 my @esc_order = split(/\&/,$orderitems);
 1333:                 foreach my $item (@esc_order) {
 1334:                     push(@ruleorder,&unescape($item));
 1335:                 }
 1336:             }
 1337:         }
 1338:     }
 1339:     return (\%ruleshash,\@ruleorder);
 1340: }
 1341: 
 1342: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1343: 
 1344: sub get_domain_defaults {
 1345:     my ($domain) = @_;
 1346:     my $cachetime = 60*60*24;
 1347:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1348:     if (defined($cached)) {
 1349:         if (ref($result) eq 'HASH') {
 1350:             return %{$result};
 1351:         }
 1352:     }
 1353:     my %domdefaults;
 1354:     my %domconfig =
 1355:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1356:                                   'requestcourses','inststatus',
 1357:                                   'coursedefaults'],$domain);
 1358:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1359:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1360:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1361:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1362:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1363:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1364:     } else {
 1365:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1366:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1367:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1368:     }
 1369:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1370:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1371:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1372:         } else {
 1373:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1374:         } 
 1375:         my @usertools = ('aboutme','blog','portfolio');
 1376:         foreach my $item (@usertools) {
 1377:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1378:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1379:             }
 1380:         }
 1381:     }
 1382:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1383:         foreach my $item ('official','unofficial','community') {
 1384:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1385:         }
 1386:     }
 1387:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1388:         foreach my $item ('inststatustypes','inststatusorder') {
 1389:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1390:         }
 1391:     }
 1392:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1393:         foreach my $item ('canuse_pdfforms') {
 1394:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1395:         }
 1396:     }
 1397:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1398:                                   $cachetime);
 1399:     return %domdefaults;
 1400: }
 1401: 
 1402: # --------------------------------------------------- Assign a key to a student
 1403: 
 1404: sub assign_access_key {
 1405: #
 1406: # a valid key looks like uname:udom#comments
 1407: # comments are being appended
 1408: #
 1409:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1410:     $kdom=
 1411:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1412:     $knum=
 1413:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1414:     $cdom=
 1415:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1416:     $cnum=
 1417:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1418:     $udom=$env{'user.name'} unless (defined($udom));
 1419:     $uname=$env{'user.domain'} unless (defined($uname));
 1420:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1421:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1422:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1423:                                                   # assigned to this person
 1424:                                                   # - this should not happen,
 1425:                                                   # unless something went wrong
 1426:                                                   # the first time around
 1427: # ready to assign
 1428:         $logentry=$1.'; '.$logentry;
 1429:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1430:                                                  $kdom,$knum) eq 'ok') {
 1431: # key now belongs to user
 1432: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1433:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1434:                 &appenv({'environment.'.$envkey => $ckey});
 1435:                 return 'ok';
 1436:             } else {
 1437:                 return 
 1438:   'error: Count not permanently assign key, will need to be re-entered later.';
 1439: 	    }
 1440:         } else {
 1441:             return 'error: Could not assign key, try again later.';
 1442:         }
 1443:     } elsif (!$existing{$ckey}) {
 1444: # the key does not exist
 1445: 	return 'error: The key does not exist';
 1446:     } else {
 1447: # the key is somebody else's
 1448: 	return 'error: The key is already in use';
 1449:     }
 1450: }
 1451: 
 1452: # ------------------------------------------ put an additional comment on a key
 1453: 
 1454: sub comment_access_key {
 1455: #
 1456: # a valid key looks like uname:udom#comments
 1457: # comments are being appended
 1458: #
 1459:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1460:     $cdom=
 1461:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1462:     $cnum=
 1463:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1464:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1465:     if ($existing{$ckey}) {
 1466:         $existing{$ckey}.='; '.$logentry;
 1467: # ready to assign
 1468:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1469:                                                  $cdom,$cnum) eq 'ok') {
 1470: 	    return 'ok';
 1471:         } else {
 1472: 	    return 'error: Count not store comment.';
 1473:         }
 1474:     } else {
 1475: # the key does not exist
 1476: 	return 'error: The key does not exist';
 1477:     }
 1478: }
 1479: 
 1480: # ------------------------------------------------------ Generate a set of keys
 1481: 
 1482: sub generate_access_keys {
 1483:     my ($number,$cdom,$cnum,$logentry)=@_;
 1484:     $cdom=
 1485:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1486:     $cnum=
 1487:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1488:     unless (&allowed('mky',$cdom)) { return 0; }
 1489:     unless (($cdom) && ($cnum)) { return 0; }
 1490:     if ($number>10000) { return 0; }
 1491:     sleep(2); # make sure don't get same seed twice
 1492:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1493:     my $total=0;
 1494:     for (my $i=1;$i<=$number;$i++) {
 1495:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1496:                   sprintf("%lx",int(100000*rand)).'-'.
 1497:                   sprintf("%lx",int(100000*rand));
 1498:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1499:        $newkey=~s/0/h/g; # and also 0 and O
 1500:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1501:        if ($existing{$newkey}) {
 1502:            $i--;
 1503:        } else {
 1504: 	  if (&put('accesskeys',
 1505:               { $newkey => '# generated '.localtime().
 1506:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1507:                            '; '.$logentry },
 1508: 		   $cdom,$cnum) eq 'ok') {
 1509:               $total++;
 1510: 	  }
 1511:        }
 1512:     }
 1513:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1514:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1515:     return $total;
 1516: }
 1517: 
 1518: # ------------------------------------------------------- Validate an accesskey
 1519: 
 1520: sub validate_access_key {
 1521:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1522:     $cdom=
 1523:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1524:     $cnum=
 1525:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1526:     $udom=$env{'user.domain'} unless (defined($udom));
 1527:     $uname=$env{'user.name'} unless (defined($uname));
 1528:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1529:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1530: }
 1531: 
 1532: # ------------------------------------- Find the section of student in a course
 1533: sub devalidate_getsection_cache {
 1534:     my ($udom,$unam,$courseid)=@_;
 1535:     my $hashid="$udom:$unam:$courseid";
 1536:     &devalidate_cache_new('getsection',$hashid);
 1537: }
 1538: 
 1539: sub courseid_to_courseurl {
 1540:     my ($courseid) = @_;
 1541:     #already url style courseid
 1542:     return $courseid if ($courseid =~ m{^/});
 1543: 
 1544:     if (exists($env{'course.'.$courseid.'.num'})) {
 1545: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1546: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1547: 	return "/$cdom/$cnum";
 1548:     }
 1549: 
 1550:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1551:     if (exists($courseinfo{'num'})) {
 1552: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1553:     }
 1554: 
 1555:     return undef;
 1556: }
 1557: 
 1558: sub getsection {
 1559:     my ($udom,$unam,$courseid)=@_;
 1560:     my $cachetime=1800;
 1561: 
 1562:     my $hashid="$udom:$unam:$courseid";
 1563:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1564:     if (defined($cached)) { return $result; }
 1565: 
 1566:     my %Pending; 
 1567:     my %Expired;
 1568:     #
 1569:     # Each role can either have not started yet (pending), be active, 
 1570:     #    or have expired.
 1571:     #
 1572:     # If there is an active role, we are done.
 1573:     #
 1574:     # If there is more than one role which has not started yet, 
 1575:     #     choose the one which will start sooner
 1576:     # If there is one role which has not started yet, return it.
 1577:     #
 1578:     # If there is more than one expired role, choose the one which ended last.
 1579:     # If there is a role which has expired, return it.
 1580:     #
 1581:     $courseid = &courseid_to_courseurl($courseid);
 1582:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1583:     foreach my $key (keys(%roleshash)) {
 1584:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1585:         my $section=$1;
 1586:         if ($key eq $courseid.'_st') { $section=''; }
 1587:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1588:         my $now=time;
 1589:         if (defined($end) && $end && ($now > $end)) {
 1590:             $Expired{$end}=$section;
 1591:             next;
 1592:         }
 1593:         if (defined($start) && $start && ($now < $start)) {
 1594:             $Pending{$start}=$section;
 1595:             next;
 1596:         }
 1597:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1598:     }
 1599:     #
 1600:     # Presumedly there will be few matching roles from the above
 1601:     # loop and the sorting time will be negligible.
 1602:     if (scalar(keys(%Pending))) {
 1603:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1604:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1605:     } 
 1606:     if (scalar(keys(%Expired))) {
 1607:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1608:         my $time = pop(@sorted);
 1609:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1610:     }
 1611:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1612: }
 1613: 
 1614: sub save_cache {
 1615:     &purge_remembered();
 1616:     #&Apache::loncommon::validate_page();
 1617:     undef(%env);
 1618:     undef($env_loaded);
 1619: }
 1620: 
 1621: my $to_remember=-1;
 1622: my %remembered;
 1623: my %accessed;
 1624: my $kicks=0;
 1625: my $hits=0;
 1626: sub make_key {
 1627:     my ($name,$id) = @_;
 1628:     if (length($id) > 65 
 1629: 	&& length(&escape($id)) > 200) {
 1630: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1631:     }
 1632:     return &escape($name.':'.$id);
 1633: }
 1634: 
 1635: sub devalidate_cache_new {
 1636:     my ($name,$id,$debug) = @_;
 1637:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1638:     $id=&make_key($name,$id);
 1639:     $memcache->delete($id);
 1640:     delete($remembered{$id});
 1641:     delete($accessed{$id});
 1642: }
 1643: 
 1644: sub is_cached_new {
 1645:     my ($name,$id,$debug) = @_;
 1646:     $id=&make_key($name,$id);
 1647:     if (exists($remembered{$id})) {
 1648: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1649: 	$accessed{$id}=[&gettimeofday()];
 1650: 	$hits++;
 1651: 	return ($remembered{$id},1);
 1652:     }
 1653:     my $value = $memcache->get($id);
 1654:     if (!(defined($value))) {
 1655: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1656: 	return (undef,undef);
 1657:     }
 1658:     if ($value eq '__undef__') {
 1659: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1660: 	$value=undef;
 1661:     }
 1662:     &make_room($id,$value,$debug);
 1663:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1664:     return ($value,1);
 1665: }
 1666: 
 1667: sub do_cache_new {
 1668:     my ($name,$id,$value,$time,$debug) = @_;
 1669:     $id=&make_key($name,$id);
 1670:     my $setvalue=$value;
 1671:     if (!defined($setvalue)) {
 1672: 	$setvalue='__undef__';
 1673:     }
 1674:     if (!defined($time) ) {
 1675: 	$time=600;
 1676:     }
 1677:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1678:     my $result = $memcache->set($id,$setvalue,$time);
 1679:     if (! $result) {
 1680: 	&logthis("caching of id -> $id  failed");
 1681: 	$memcache->disconnect_all();
 1682:     }
 1683:     # need to make a copy of $value
 1684:     &make_room($id,$value,$debug);
 1685:     return $value;
 1686: }
 1687: 
 1688: sub make_room {
 1689:     my ($id,$value,$debug)=@_;
 1690: 
 1691:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1692:                                     : $value;
 1693:     if ($to_remember<0) { return; }
 1694:     $accessed{$id}=[&gettimeofday()];
 1695:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1696:     my $to_kick;
 1697:     my $max_time=0;
 1698:     foreach my $other (keys(%accessed)) {
 1699: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1700: 	    $to_kick=$other;
 1701: 	    $max_time=&tv_interval($accessed{$other});
 1702: 	}
 1703:     }
 1704:     delete($remembered{$to_kick});
 1705:     delete($accessed{$to_kick});
 1706:     $kicks++;
 1707:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1708:     return;
 1709: }
 1710: 
 1711: sub purge_remembered {
 1712:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1713:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1714:     undef(%remembered);
 1715:     undef(%accessed);
 1716: }
 1717: # ------------------------------------- Read an entry from a user's environment
 1718: 
 1719: sub userenvironment {
 1720:     my ($udom,$unam,@what)=@_;
 1721:     my $items;
 1722:     foreach my $item (@what) {
 1723:         $items.=&escape($item).'&';
 1724:     }
 1725:     $items=~s/\&$//;
 1726:     my %returnhash=();
 1727:     my $uhome = &homeserver($unam,$udom);
 1728:     unless ($uhome eq 'no_host') {
 1729:         my @answer=split(/\&/, 
 1730:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 1731:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 1732:             return %returnhash;
 1733:         }
 1734:         my $i;
 1735:         for ($i=0;$i<=$#what;$i++) {
 1736: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 1737:         }
 1738:     }
 1739:     return %returnhash;
 1740: }
 1741: 
 1742: # ---------------------------------------------------------- Get a studentphoto
 1743: sub studentphoto {
 1744:     my ($udom,$unam,$ext) = @_;
 1745:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1746:     if (defined($env{'request.course.id'})) {
 1747:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1748:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1749:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1750:             } else {
 1751:                 my ($result,$perm_reqd)=
 1752: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1753:                 if ($result eq 'ok') {
 1754:                     if (!($perm_reqd eq 'yes')) {
 1755:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1756:                     }
 1757:                 }
 1758:             }
 1759:         }
 1760:     } else {
 1761:         my ($result,$perm_reqd) = 
 1762: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1763:         if ($result eq 'ok') {
 1764:             if (!($perm_reqd eq 'yes')) {
 1765:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1766:             }
 1767:         }
 1768:     }
 1769:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1770: }
 1771: 
 1772: sub retrievestudentphoto {
 1773:     my ($udom,$unam,$ext,$type) = @_;
 1774:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1775:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1776:     if ($ret eq 'ok') {
 1777:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1778:         if ($type eq 'thumbnail') {
 1779:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1780:         }
 1781:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1782:         return $tokenurl;
 1783:     } else {
 1784:         if ($type eq 'thumbnail') {
 1785:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1786:         } else { 
 1787:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1788:         }
 1789:     }
 1790: }
 1791: 
 1792: # -------------------------------------------------------------------- New chat
 1793: 
 1794: sub chatsend {
 1795:     my ($newentry,$anon,$group)=@_;
 1796:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1797:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1798:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1799:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1800: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1801: 		   &escape($newentry)).':'.$group,$chome);
 1802: }
 1803: 
 1804: # ------------------------------------------ Find current version of a resource
 1805: 
 1806: sub getversion {
 1807:     my $fname=&clutter(shift);
 1808:     unless ($fname=~/^\/res\//) { return -1; }
 1809:     return &currentversion(&filelocation('',$fname));
 1810: }
 1811: 
 1812: sub currentversion {
 1813:     my $fname=shift;
 1814:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1815:     if (defined($cached)) { return $result; }
 1816:     my $author=$fname;
 1817:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1818:     my ($udom,$uname)=split(/\//,$author);
 1819:     my $home=homeserver($uname,$udom);
 1820:     if ($home eq 'no_host') { 
 1821:         return -1; 
 1822:     }
 1823:     my $answer=reply("currentversion:$fname",$home);
 1824:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1825: 	return -1;
 1826:     }
 1827:     return &do_cache_new('resversion',$fname,$answer,600);
 1828: }
 1829: 
 1830: # ----------------------------- Subscribe to a resource, return URL if possible
 1831: 
 1832: sub subscribe {
 1833:     my $fname=shift;
 1834:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1835:     $fname=~s/[\n\r]//g;
 1836:     my $author=$fname;
 1837:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1838:     my ($udom,$uname)=split(/\//,$author);
 1839:     my $home=homeserver($uname,$udom);
 1840:     if ($home eq 'no_host') {
 1841:         return 'not_found';
 1842:     }
 1843:     my $answer=reply("sub:$fname",$home);
 1844:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1845: 	$answer.=' by '.$home;
 1846:     }
 1847:     return $answer;
 1848: }
 1849:     
 1850: # -------------------------------------------------------------- Replicate file
 1851: 
 1852: sub repcopy {
 1853:     my $filename=shift;
 1854:     $filename=~s/\/+/\//g;
 1855:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1856:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1857:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1858: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1859: 	return &repcopy_userfile($filename);
 1860:     }
 1861:     $filename=~s/[\n\r]//g;
 1862:     my $transname="$filename.in.transfer";
 1863: # FIXME: this should flock
 1864:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1865:     my $remoteurl=subscribe($filename);
 1866:     if ($remoteurl =~ /^con_lost by/) {
 1867: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1868:            return 'unavailable';
 1869:     } elsif ($remoteurl eq 'not_found') {
 1870: 	   #&logthis("Subscribe returned not_found: $filename");
 1871: 	   return 'not_found';
 1872:     } elsif ($remoteurl =~ /^rejected by/) {
 1873: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1874:            return 'forbidden';
 1875:     } elsif ($remoteurl eq 'directory') {
 1876:            return 'ok';
 1877:     } else {
 1878:         my $author=$filename;
 1879:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1880:         my ($udom,$uname)=split(/\//,$author);
 1881:         my $home=homeserver($uname,$udom);
 1882:         unless ($home eq $perlvar{'lonHostID'}) {
 1883:            my @parts=split(/\//,$filename);
 1884:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1885:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1886:                &logthis("Malconfiguration for replication: $filename");
 1887: 	       return 'bad_request';
 1888:            }
 1889:            my $count;
 1890:            for ($count=5;$count<$#parts;$count++) {
 1891:                $path.="/$parts[$count]";
 1892:                if ((-e $path)!=1) {
 1893: 		   mkdir($path,0777);
 1894:                }
 1895:            }
 1896:            my $ua=new LWP::UserAgent;
 1897:            my $request=new HTTP::Request('GET',"$remoteurl");
 1898:            my $response=$ua->request($request,$transname);
 1899:            if ($response->is_error()) {
 1900: 	       unlink($transname);
 1901:                my $message=$response->status_line;
 1902:                &logthis("<font color=\"blue\">WARNING:"
 1903:                        ." LWP get: $message: $filename</font>");
 1904:                return 'unavailable';
 1905:            } else {
 1906: 	       if ($remoteurl!~/\.meta$/) {
 1907:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1908:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1909:                   if ($mresponse->is_error()) {
 1910: 		      unlink($filename.'.meta');
 1911:                       &logthis(
 1912:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1913:                   }
 1914: 	       }
 1915:                rename($transname,$filename);
 1916:                return 'ok';
 1917:            }
 1918:        }
 1919:     }
 1920: }
 1921: 
 1922: # ------------------------------------------------ Get server side include body
 1923: sub ssi_body {
 1924:     my ($filelink,%form)=@_;
 1925:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1926:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1927:     }
 1928:     my $output='';
 1929:     my $response;
 1930:     if ($filelink=~/^https?\:/) {
 1931:        ($output,$response)=&externalssi($filelink);
 1932:     } else {
 1933:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 1934:        $filelink .= 'inhibitmenu=yes';
 1935:        ($output,$response)=&ssi($filelink,%form);
 1936:     }
 1937:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1938:     $output=~s/^.*?\<body[^\>]*\>//si;
 1939:     $output=~s/\<\/body\s*\>.*?$//si;
 1940:     if (wantarray) {
 1941:         return ($output, $response);
 1942:     } else {
 1943:         return $output;
 1944:     }
 1945: }
 1946: 
 1947: # --------------------------------------------------------- Server Side Include
 1948: 
 1949: sub absolute_url {
 1950:     my ($host_name) = @_;
 1951:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1952:     if ($host_name eq '') {
 1953: 	$host_name = $ENV{'SERVER_NAME'};
 1954:     }
 1955:     return $protocol.$host_name;
 1956: }
 1957: 
 1958: #
 1959: #   Server side include.
 1960: # Parameters:
 1961: #  fn     Possibly encrypted resource name/id.
 1962: #  form   Hash that describes how the rendering should be done
 1963: #         and other things.
 1964: # Returns:
 1965: #   Scalar context: The content of the response.
 1966: #   Array context:  2 element list of the content and the full response object.
 1967: #     
 1968: sub ssi {
 1969: 
 1970:     my ($fn,%form)=@_;
 1971:     my $ua=new LWP::UserAgent;
 1972:     my $request;
 1973: 
 1974:     $form{'no_update_last_known'}=1;
 1975:     &Apache::lonenc::check_encrypt(\$fn);
 1976:     if (%form) {
 1977:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1978:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1979:     } else {
 1980:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1981:     }
 1982: 
 1983:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1984:     my $response=$ua->request($request);
 1985: 
 1986:     if (wantarray) {
 1987: 	return ($response->content, $response);
 1988:     } else {
 1989: 	return $response->content;
 1990:     }
 1991: }
 1992: 
 1993: sub externalssi {
 1994:     my ($url)=@_;
 1995:     my $ua=new LWP::UserAgent;
 1996:     my $request=new HTTP::Request('GET',$url);
 1997:     my $response=$ua->request($request);
 1998:     if (wantarray) {
 1999:         return ($response->content, $response);
 2000:     } else {
 2001:         return $response->content;
 2002:     }
 2003: }
 2004: 
 2005: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2006: 
 2007: sub allowuploaded {
 2008:     my ($srcurl,$url)=@_;
 2009:     $url=&clutter(&declutter($url));
 2010:     my $dir=$url;
 2011:     $dir=~s/\/[^\/]+$//;
 2012:     my %httpref=();
 2013:     my $httpurl=&hreflocation('',$url);
 2014:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2015:     &Apache::lonnet::appenv(\%httpref);
 2016: }
 2017: 
 2018: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2019: # input: action, courseID, current domain, intended
 2020: #        path to file, source of file, instruction to parse file for objects,
 2021: #        ref to hash for embedded objects,
 2022: #        ref to hash for codebase of java objects.
 2023: #
 2024: # output: url to file (if action was uploaddoc), 
 2025: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2026: #
 2027: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2028: # course.
 2029: #
 2030: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2031: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2032: #          course's home server.
 2033: #
 2034: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2035: #          be copied from $source (current location) to 
 2036: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2037: #         and will then be copied to
 2038: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2039: #         course's home server.
 2040: #
 2041: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2042: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2043: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2044: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2045: #         in course's home server.
 2046: #
 2047: 
 2048: sub process_coursefile {
 2049:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 2050:     my $fetchresult;
 2051:     my $home=&homeserver($docuname,$docudom);
 2052:     if ($action eq 'propagate') {
 2053:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2054: 			     $home);
 2055:     } else {
 2056:         my $fpath = '';
 2057:         my $fname = $file;
 2058:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2059:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2060:         my $filepath = &build_filepath($fpath);
 2061:         if ($action eq 'copy') {
 2062:             if ($source eq '') {
 2063:                 $fetchresult = 'no source file';
 2064:                 return $fetchresult;
 2065:             } else {
 2066:                 my $destination = $filepath.'/'.$fname;
 2067:                 rename($source,$destination);
 2068:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2069:                                  $home);
 2070:             }
 2071:         } elsif ($action eq 'uploaddoc') {
 2072:             open(my $fh,'>'.$filepath.'/'.$fname);
 2073:             print $fh $env{'form.'.$source};
 2074:             close($fh);
 2075:             if ($parser eq 'parse') {
 2076:                 my $mm = new File::MMagic;
 2077:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
 2078:                 if ($mime_type eq 'text/html') {
 2079:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2080:                     unless ($parse_result eq 'ok') {
 2081:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2082:                     }
 2083:                 }
 2084:             }
 2085:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2086:                                  $home);
 2087:             if ($fetchresult eq 'ok') {
 2088:                 return '/uploaded/'.$fpath.'/'.$fname;
 2089:             } else {
 2090:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2091:                         ' to host '.$home.': '.$fetchresult);
 2092:                 return '/adm/notfound.html';
 2093:             }
 2094:         }
 2095:     }
 2096:     unless ( $fetchresult eq 'ok') {
 2097:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2098:              ' to host '.$home.': '.$fetchresult);
 2099:     }
 2100:     return $fetchresult;
 2101: }
 2102: 
 2103: sub build_filepath {
 2104:     my ($fpath) = @_;
 2105:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2106:     unless ($fpath eq '') {
 2107:         my @parts=split('/',$fpath);
 2108:         foreach my $part (@parts) {
 2109:             $filepath.= '/'.$part;
 2110:             if ((-e $filepath)!=1) {
 2111:                 mkdir($filepath,0777);
 2112:             }
 2113:         }
 2114:     }
 2115:     return $filepath;
 2116: }
 2117: 
 2118: sub store_edited_file {
 2119:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2120:     my $file = $primary_url;
 2121:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2122:     my $fpath = '';
 2123:     my $fname = $file;
 2124:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2125:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2126:     my $filepath = &build_filepath($fpath);
 2127:     open(my $fh,'>'.$filepath.'/'.$fname);
 2128:     print $fh $content;
 2129:     close($fh);
 2130:     my $home=&homeserver($docuname,$docudom);
 2131:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2132: 			  $home);
 2133:     if ($$fetchresult eq 'ok') {
 2134:         return '/uploaded/'.$fpath.'/'.$fname;
 2135:     } else {
 2136:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2137: 		 ' to host '.$home.': '.$$fetchresult);
 2138:         return '/adm/notfound.html';
 2139:     }
 2140: }
 2141: 
 2142: sub clean_filename {
 2143:     my ($fname,$args)=@_;
 2144: # Replace Windows backslashes by forward slashes
 2145:     $fname=~s/\\/\//g;
 2146:     if (!$args->{'keep_path'}) {
 2147:         # Get rid of everything but the actual filename
 2148: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2149:     }
 2150: # Replace spaces by underscores
 2151:     $fname=~s/\s+/\_/g;
 2152: # Replace all other weird characters by nothing
 2153:     $fname=~s{[^/\w\.\-]}{}g;
 2154: # Replace all .\d. sequences with _\d. so they no longer look like version
 2155: # numbers
 2156:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2157:     return $fname;
 2158: }
 2159: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2160: sub resizeImage {
 2161: 	my($img_url) = @_;	
 2162: 	my $ima = Image::Magick->new;                       
 2163:         $ima->Read($img_url);
 2164: 	if($ima->Get('width') > 400)
 2165: 	{
 2166: 		my $factor = $ima->Get('width')/400;
 2167:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2168: 	}
 2169: 	if($ima->Get('height') > 500)
 2170:         {
 2171:         	my $factor = $ima->Get('height')/500;
 2172:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2173:         } 
 2174: 		
 2175: 	$ima->Write($img_url);
 2176: }
 2177: 
 2178: #Wrapper function for userphotoupload
 2179: sub userphotoupload
 2180: {
 2181: 	my($formname,$subdir) = @_;
 2182: 	$upload_photo_form = 1;
 2183: 	return &userfileupload($formname,undef,$subdir);
 2184: }
 2185: 
 2186: # --------------- Take an uploaded file and put it into the userfiles directory
 2187: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2188: #                    the desired filenam is in $env{"form.$formname.filename"}
 2189: #        $coursedoc - if true up to the current course
 2190: #                     if false
 2191: #        $subdir - directory in userfile to store the file into
 2192: #        $parser - instruction to parse file for objects ($parser = parse)    
 2193: #        $allfiles - reference to hash for embedded objects
 2194: #        $codebase - reference to hash for codebase of java objects
 2195: #        $desuname - username for permanent storage of uploaded file
 2196: #        $dsetudom - domain for permanaent storage of uploaded file
 2197: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2198: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2199: # 
 2200: # output: url of file in userspace, or error: <message> 
 2201: #             or /adm/notfound.html if failure to upload occurse
 2202: 
 2203: 
 2204: sub userfileupload {
 2205:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2206:         $destudom,$thumbwidth,$thumbheight)=@_;
 2207:     if (!defined($subdir)) { $subdir='unknown'; }
 2208:     my $fname=$env{'form.'.$formname.'.filename'};
 2209:     $fname=&clean_filename($fname);
 2210: # See if there is anything left
 2211:     unless ($fname) { return 'error: no uploaded file'; }
 2212:     chop($env{'form.'.$formname});
 2213:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2214:         my $now = time;
 2215:         my $filepath = 'tmp/helprequests/'.$now;
 2216:         my @parts=split(/\//,$filepath);
 2217:         my $fullpath = $perlvar{'lonDaemons'};
 2218:         for (my $i=0;$i<@parts;$i++) {
 2219:             $fullpath .= '/'.$parts[$i];
 2220:             if ((-e $fullpath)!=1) {
 2221:                 mkdir($fullpath,0777);
 2222:             }
 2223:         }
 2224:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2225:         print $fh $env{'form.'.$formname};
 2226:         close($fh);
 2227:         return $fullpath.'/'.$fname;
 2228:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2229:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2230:                        '_'.$env{'user.domain'}.'/pending';
 2231:         my @parts=split(/\//,$filepath);
 2232:         my $fullpath = $perlvar{'lonDaemons'};
 2233:         for (my $i=0;$i<@parts;$i++) {
 2234:             $fullpath .= '/'.$parts[$i];
 2235:             if ((-e $fullpath)!=1) {
 2236:                 mkdir($fullpath,0777);
 2237:             }
 2238:         }
 2239:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2240:         print $fh $env{'form.'.$formname};
 2241:         close($fh);
 2242:         return $fullpath.'/'.$fname;
 2243:     }
 2244:     if ($subdir eq 'scantron') {
 2245:         $fname = 'scantron_orig_'.$fname;
 2246:     } else {   
 2247: # Create the directory if not present
 2248:         $fname="$subdir/$fname";
 2249:     }
 2250:     if ($coursedoc) {
 2251: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2252: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2253:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2254:             return &finishuserfileupload($docuname,$docudom,
 2255: 					 $formname,$fname,$parser,$allfiles,
 2256: 					 $codebase,$thumbwidth,$thumbheight);
 2257:         } else {
 2258:             $fname=$env{'form.folder'}.'/'.$fname;
 2259:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2260: 				       $fname,$formname,$parser,
 2261: 				       $allfiles,$codebase);
 2262:         }
 2263:     } elsif (defined($destuname)) {
 2264:         my $docuname=$destuname;
 2265:         my $docudom=$destudom;
 2266: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2267: 				     $parser,$allfiles,$codebase,
 2268:                                      $thumbwidth,$thumbheight);
 2269:         
 2270:     } else {
 2271:         my $docuname=$env{'user.name'};
 2272:         my $docudom=$env{'user.domain'};
 2273:         if (exists($env{'form.group'})) {
 2274:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2275:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2276:         }
 2277: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2278: 				     $parser,$allfiles,$codebase,
 2279:                                      $thumbwidth,$thumbheight);
 2280:     }
 2281: }
 2282: 
 2283: sub finishuserfileupload {
 2284:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2285:         $thumbwidth,$thumbheight) = @_;
 2286:     my $path=$docudom.'/'.$docuname.'/';
 2287:     my $filepath=$perlvar{'lonDocRoot'};
 2288:   
 2289:     my ($fnamepath,$file,$fetchthumb);
 2290:     $file=$fname;
 2291:     if ($fname=~m|/|) {
 2292:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2293: 	$path.=$fnamepath.'/';
 2294:     }
 2295:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2296:     my $count;
 2297:     for ($count=4;$count<=$#parts;$count++) {
 2298:         $filepath.="/$parts[$count]";
 2299:         if ((-e $filepath)!=1) {
 2300: 	    mkdir($filepath,0777);
 2301:         }
 2302:     }
 2303: 
 2304: # Save the file
 2305:     {
 2306: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2307: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2308: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2309: 	    return '/adm/notfound.html';
 2310: 	}
 2311: 	if (!print FH ($env{'form.'.$formname})) {
 2312: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2313: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2314: 	    return '/adm/notfound.html';
 2315: 	}
 2316: 	close(FH);
 2317: 	if($upload_photo_form==1)
 2318: 	{
 2319: 		resizeImage($filepath.'/'.$file);		
 2320: 		$upload_photo_form = 0;
 2321: 	}
 2322:     }
 2323:     if ($parser eq 'parse') {
 2324:         my $mm = new File::MMagic;
 2325:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2326:         if ($mime_type eq 'text/html') {
 2327:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2328:                                                        $allfiles,$codebase);
 2329:             unless ($parse_result eq 'ok') {
 2330:                 &logthis('Failed to parse '.$filepath.$file.
 2331: 	   	         ' for embedded media: '.$parse_result); 
 2332:             }
 2333:         }
 2334:     }
 2335:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2336:         my $input = $filepath.'/'.$file;
 2337:         my $output = $filepath.'/'.'tn-'.$file;
 2338:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2339:         system("convert -sample $thumbsize $input $output");
 2340:         if (-e $filepath.'/'.'tn-'.$file) {
 2341:             $fetchthumb  = 1; 
 2342:         }
 2343:     }
 2344:  
 2345: # Notify homeserver to grep it
 2346: #
 2347:     my $docuhome=&homeserver($docuname,$docudom);	
 2348:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2349:     if ($fetchresult eq 'ok') {
 2350:         if ($fetchthumb) {
 2351:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2352:             if ($thumbresult ne 'ok') {
 2353:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2354:                          $docuhome.': '.$thumbresult);
 2355:             }
 2356:         }
 2357: #
 2358: # Return the URL to it
 2359:         return '/uploaded/'.$path.$file;
 2360:     } else {
 2361:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2362: 		 ': '.$fetchresult);
 2363:         return '/adm/notfound.html';
 2364:     }
 2365: }
 2366: 
 2367: sub extract_embedded_items {
 2368:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2369:     my @state = ();
 2370:     my %javafiles = (
 2371:                       codebase => '',
 2372:                       code => '',
 2373:                       archive => ''
 2374:                     );
 2375:     my %mediafiles = (
 2376:                       src => '',
 2377:                       movie => '',
 2378:                      );
 2379:     my $p;
 2380:     if ($content) {
 2381:         $p = HTML::LCParser->new($content);
 2382:     } else {
 2383:         $p = HTML::LCParser->new($fullpath);
 2384:     }
 2385:     while (my $t=$p->get_token()) {
 2386: 	if ($t->[0] eq 'S') {
 2387: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2388: 	    push(@state, $tagname);
 2389:             if (lc($tagname) eq 'allow') {
 2390:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2391:             }
 2392: 	    if (lc($tagname) eq 'img') {
 2393: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2394: 	    }
 2395: 	    if (lc($tagname) eq 'a') {
 2396: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2397: 	    }
 2398:             if (lc($tagname) eq 'script') {
 2399:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2400:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2401:                 } else {
 2402:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2403:                 }
 2404:             }
 2405:             if (lc($tagname) eq 'link') {
 2406:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2407:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2408:                 }
 2409:             }
 2410: 	    if (lc($tagname) eq 'object' ||
 2411: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2412: 		foreach my $item (keys(%javafiles)) {
 2413: 		    $javafiles{$item} = '';
 2414: 		}
 2415: 	    }
 2416: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2417: 		my $name = lc($attr->{'name'});
 2418: 		foreach my $item (keys(%javafiles)) {
 2419: 		    if ($name eq $item) {
 2420: 			$javafiles{$item} = $attr->{'value'};
 2421: 			last;
 2422: 		    }
 2423: 		}
 2424: 		foreach my $item (keys(%mediafiles)) {
 2425: 		    if ($name eq $item) {
 2426: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2427: 			last;
 2428: 		    }
 2429: 		}
 2430: 	    }
 2431: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2432: 		foreach my $item (keys(%javafiles)) {
 2433: 		    if ($attr->{$item}) {
 2434: 			$javafiles{$item} = $attr->{$item};
 2435: 			last;
 2436: 		    }
 2437: 		}
 2438: 		foreach my $item (keys(%mediafiles)) {
 2439: 		    if ($attr->{$item}) {
 2440: 			&add_filetype($allfiles,$attr->{$item},$item);
 2441: 			last;
 2442: 		    }
 2443: 		}
 2444: 	    }
 2445: 	} elsif ($t->[0] eq 'E') {
 2446: 	    my ($tagname) = ($t->[1]);
 2447: 	    if ($javafiles{'codebase'} ne '') {
 2448: 		$javafiles{'codebase'} .= '/';
 2449: 	    }  
 2450: 	    if (lc($tagname) eq 'applet' ||
 2451: 		lc($tagname) eq 'object' ||
 2452: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2453: 		) {
 2454: 		foreach my $item (keys(%javafiles)) {
 2455: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2456: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2457: 			&add_filetype($allfiles,$file,$item);
 2458: 		    }
 2459: 		}
 2460: 	    } 
 2461: 	    pop @state;
 2462: 	}
 2463:     }
 2464:     return 'ok';
 2465: }
 2466: 
 2467: sub add_filetype {
 2468:     my ($allfiles,$file,$type)=@_;
 2469:     if (exists($allfiles->{$file})) {
 2470: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2471: 	    push(@{$allfiles->{$file}}, &escape($type));
 2472: 	}
 2473:     } else {
 2474: 	@{$allfiles->{$file}} = (&escape($type));
 2475:     }
 2476: }
 2477: 
 2478: sub removeuploadedurl {
 2479:     my ($url)=@_;	
 2480:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2481:     return &removeuserfile($uname,$udom,$fname);
 2482: }
 2483: 
 2484: sub removeuserfile {
 2485:     my ($docuname,$docudom,$fname)=@_;
 2486:     my $home=&homeserver($docuname,$docudom);    
 2487:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2488:     if ($result eq 'ok') {	
 2489:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2490:             my $metafile = $fname.'.meta';
 2491:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2492: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2493:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2494:             my $sqlresult = 
 2495:                 &update_portfolio_table($docuname,$docudom,$file,
 2496:                                         'portfolio_metadata',$group,
 2497:                                         'delete');
 2498:         }
 2499:     }
 2500:     return $result;
 2501: }
 2502: 
 2503: sub mkdiruserfile {
 2504:     my ($docuname,$docudom,$dir)=@_;
 2505:     my $home=&homeserver($docuname,$docudom);
 2506:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2507: }
 2508: 
 2509: sub renameuserfile {
 2510:     my ($docuname,$docudom,$old,$new)=@_;
 2511:     my $home=&homeserver($docuname,$docudom);
 2512:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2513:                         &escape("$old").':'.&escape("$new"),$home);
 2514:     if ($result eq 'ok') {
 2515:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2516:             my $oldmeta = $old.'.meta';
 2517:             my $newmeta = $new.'.meta';
 2518:             my $metaresult = 
 2519:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2520: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2521:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2522:             my $sqlresult = 
 2523:                 &update_portfolio_table($docuname,$docudom,$file,
 2524:                                         'portfolio_metadata',$group,
 2525:                                         'delete');
 2526:         }
 2527:     }
 2528:     return $result;
 2529: }
 2530: 
 2531: # ------------------------------------------------------------------------- Log
 2532: 
 2533: sub log {
 2534:     my ($dom,$nam,$hom,$what)=@_;
 2535:     return critical("log:$dom:$nam:$what",$hom);
 2536: }
 2537: 
 2538: # ------------------------------------------------------------------ Course Log
 2539: #
 2540: # This routine flushes several buffers of non-mission-critical nature
 2541: #
 2542: 
 2543: sub flushcourselogs {
 2544:     &logthis('Flushing log buffers');
 2545: #
 2546: # course logs
 2547: # This is a log of all transactions in a course, which can be used
 2548: # for data mining purposes
 2549: #
 2550: # It also collects the courseid database, which lists last transaction
 2551: # times and course titles for all courseids
 2552: #
 2553:     my %courseidbuffer=();
 2554:     foreach my $crsid (keys(%courselogs)) {
 2555:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2556: 		          &escape($courselogs{$crsid}),
 2557: 		          $coursehombuf{$crsid}) eq 'ok') {
 2558: 	    delete $courselogs{$crsid};
 2559:         } else {
 2560:             &logthis('Failed to flush log buffer for '.$crsid);
 2561:             if (length($courselogs{$crsid})>40000) {
 2562:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2563:                         " exceeded maximum size, deleting.</font>");
 2564:                delete $courselogs{$crsid};
 2565:             }
 2566:         }
 2567:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2568:             'description' => $coursedescrbuf{$crsid},
 2569:             'inst_code'    => $courseinstcodebuf{$crsid},
 2570:             'type'        => $coursetypebuf{$crsid},
 2571:             'owner'       => $courseownerbuf{$crsid},
 2572:         };
 2573:     }
 2574: #
 2575: # Write course id database (reverse lookup) to homeserver of courses 
 2576: # Is used in pickcourse
 2577: #
 2578:     foreach my $crs_home (keys(%courseidbuffer)) {
 2579:         my $response = &courseidput(&host_domain($crs_home),
 2580:                                     $courseidbuffer{$crs_home},
 2581:                                     $crs_home,'timeonly');
 2582:     }
 2583: #
 2584: # File accesses
 2585: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2586: #
 2587:     foreach my $entry (keys(%accesshash)) {
 2588:         if ($entry =~ /___count$/) {
 2589:             my ($dom,$name);
 2590:             ($dom,$name,undef)=
 2591: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2592:             if (! defined($dom) || $dom eq '' || 
 2593:                 ! defined($name) || $name eq '') {
 2594:                 my $cid = $env{'request.course.id'};
 2595:                 $dom  = $env{'request.'.$cid.'.domain'};
 2596:                 $name = $env{'request.'.$cid.'.num'};
 2597:             }
 2598:             my $value = $accesshash{$entry};
 2599:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2600:             my %temphash=($url => $value);
 2601:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2602:             if ($result eq 'ok') {
 2603:                 delete $accesshash{$entry};
 2604:             } elsif ($result eq 'unknown_cmd') {
 2605:                 # Target server has old code running on it.
 2606:                 my %temphash=($entry => $value);
 2607:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2608:                     delete $accesshash{$entry};
 2609:                 }
 2610:             }
 2611:         } else {
 2612:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2613:             my %temphash=($entry => $accesshash{$entry});
 2614:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2615:                 delete $accesshash{$entry};
 2616:             }
 2617:         }
 2618:     }
 2619: #
 2620: # Roles
 2621: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2622: #
 2623:     foreach my $entry (keys(%userrolehash)) {
 2624:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2625: 	    split(/\:/,$entry);
 2626:         if (&Apache::lonnet::put('nohist_userroles',
 2627:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2628:                 $rudom,$runame) eq 'ok') {
 2629: 	    delete $userrolehash{$entry};
 2630:         }
 2631:     }
 2632: #
 2633: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2634: #
 2635:     my %domrolebuffer = ();
 2636:     foreach my $entry (keys(%domainrolehash)) {
 2637:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2638:         if ($domrolebuffer{$rudom}) {
 2639:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2640:                       '='.&escape($domainrolehash{$entry});
 2641:         } else {
 2642:             $domrolebuffer{$rudom}.=&escape($entry).
 2643:                       '='.&escape($domainrolehash{$entry});
 2644:         }
 2645:         delete $domainrolehash{$entry};
 2646:     }
 2647:     foreach my $dom (keys(%domrolebuffer)) {
 2648: 	my %servers = &get_servers($dom,'library');
 2649: 	foreach my $tryserver (keys(%servers)) {
 2650: 	    unless (&reply('domroleput:'.$dom.':'.
 2651: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2652: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2653: 	    }
 2654:         }
 2655:     }
 2656:     $dumpcount++;
 2657: }
 2658: 
 2659: sub courselog {
 2660:     my $what=shift;
 2661:     $what=time.':'.$what;
 2662:     unless ($env{'request.course.id'}) { return ''; }
 2663:     $coursedombuf{$env{'request.course.id'}}=
 2664:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2665:     $coursenumbuf{$env{'request.course.id'}}=
 2666:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2667:     $coursehombuf{$env{'request.course.id'}}=
 2668:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2669:     $coursedescrbuf{$env{'request.course.id'}}=
 2670:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2671:     $courseinstcodebuf{$env{'request.course.id'}}=
 2672:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2673:     $courseownerbuf{$env{'request.course.id'}}=
 2674:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2675:     $coursetypebuf{$env{'request.course.id'}}=
 2676:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2677:     if (defined $courselogs{$env{'request.course.id'}}) {
 2678: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2679:     } else {
 2680: 	$courselogs{$env{'request.course.id'}}.=$what;
 2681:     }
 2682:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2683: 	&flushcourselogs();
 2684:     }
 2685: }
 2686: 
 2687: sub courseacclog {
 2688:     my $fnsymb=shift;
 2689:     unless ($env{'request.course.id'}) { return ''; }
 2690:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2691:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2692:         $what.=':POST';
 2693:         # FIXME: Probably ought to escape things....
 2694: 	foreach my $key (keys(%env)) {
 2695:             if ($key=~/^form\.(.*)/) {
 2696:                 my $formitem = $1;
 2697:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2698:                     $what.=':'.$formitem.'='.$env{$key};
 2699:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2700:                     $what.=':'.$formitem.'='.$env{$key};
 2701:                 }
 2702:             }
 2703:         }
 2704:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2705:         # FIXME: We should not be depending on a form parameter that someone
 2706:         # editing lonsearchcat.pm might change in the future.
 2707:         if ($env{'form.phase'} eq 'course_search') {
 2708:             $what.= ':POST';
 2709:             # FIXME: Probably ought to escape things....
 2710:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2711:                                  'crsdiscuss') {
 2712:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2713:             }
 2714:         }
 2715:     }
 2716:     &courselog($what);
 2717: }
 2718: 
 2719: sub countacc {
 2720:     my $url=&declutter(shift);
 2721:     return if (! defined($url) || $url eq '');
 2722:     unless ($env{'request.course.id'}) { return ''; }
 2723:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2724:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2725:     $accesshash{$key}++;
 2726: }
 2727: 
 2728: sub linklog {
 2729:     my ($from,$to)=@_;
 2730:     $from=&declutter($from);
 2731:     $to=&declutter($to);
 2732:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2733:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2734: }
 2735:   
 2736: sub userrolelog {
 2737:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2738:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2739:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2740:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2741:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 2742:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2743:        $userrolehash
 2744:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2745:                     =$tend.':'.$tstart;
 2746:     }
 2747:     if (($env{'request.role'} =~ /dc\./) &&
 2748: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2749: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2750: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 2751:          ($trole=~/^co/))) {
 2752:        $userrolehash
 2753:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2754:                     =$tend.':'.$tstart;
 2755:     }
 2756:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2757:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2758:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2759:         ($trole=~/^sc/)) {
 2760:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2761:        $domainrolehash
 2762:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2763:                     = $tend.':'.$tstart;
 2764:     }
 2765: }
 2766: 
 2767: sub courserolelog {
 2768:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2769:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2770:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2771:         ($trole eq 'ta') || ($trole eq 'st') ||
 2772:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 2773:         ($trole eq 'co')) {
 2774:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2775:             my $cdom = $1;
 2776:             my $cnum = $2;
 2777:             my $sec = $3;
 2778:             my $namespace = 'rolelog';
 2779:             my %storehash = (
 2780:                                role    => $trole,
 2781:                                start   => $tstart,
 2782:                                end     => $tend,
 2783:                                selfenroll => $selfenroll,
 2784:                                context    => $context,
 2785:                             );
 2786:             if ($trole eq 'gr') {
 2787:                 $namespace = 'groupslog';
 2788:                 $storehash{'group'} = $sec;
 2789:             } else {
 2790:                 $storehash{'section'} = $sec;
 2791:             }
 2792:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2793:             if (($trole ne 'st') || ($sec ne '')) {
 2794:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2795:             }
 2796:         }
 2797:     }
 2798:     return;
 2799: }
 2800: 
 2801: sub get_course_adv_roles {
 2802:     my ($cid,$codes) = @_;
 2803:     $cid=$env{'request.course.id'} unless (defined($cid));
 2804:     my %coursehash=&coursedescription($cid);
 2805:     my $crstype = &Apache::loncommon::course_type($cid);
 2806:     my %nothide=();
 2807:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2808:         if ($user !~ /:/) {
 2809: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2810:         } else {
 2811:             $nothide{$user}=1;
 2812:         }
 2813:     }
 2814:     my %returnhash=();
 2815:     my %dumphash=
 2816:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2817:     my $now=time;
 2818:     my %privileged;
 2819:     foreach my $entry (keys(%dumphash)) {
 2820: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2821:         if (($tstart) && ($tstart<0)) { next; }
 2822:         if (($tend) && ($tend<$now)) { next; }
 2823:         if (($tstart) && ($now<$tstart)) { next; }
 2824:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2825: 	if ($username eq '' || $domain eq '') { next; }
 2826:         unless (ref($privileged{$domain}) eq 'HASH') {
 2827:             my %dompersonnel =
 2828:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2829:             $privileged{$domain} = {};
 2830:             foreach my $server (keys(%dompersonnel)) {
 2831:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2832:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2833:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2834:                         $privileged{$udom}{$uname} = 1;
 2835:                     }
 2836:                 }
 2837:             }
 2838:         }
 2839:         if ((exists($privileged{$domain}{$username})) && 
 2840:             (!$nothide{$username.':'.$domain})) { next; }
 2841: 	if ($role eq 'cr') { next; }
 2842:         if ($codes) {
 2843:             if ($section) { $role .= ':'.$section; }
 2844:             if ($returnhash{$role}) {
 2845:                 $returnhash{$role}.=','.$username.':'.$domain;
 2846:             } else {
 2847:                 $returnhash{$role}=$username.':'.$domain;
 2848:             }
 2849:         } else {
 2850:             my $key=&plaintext($role,$crstype);
 2851:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2852:             if ($returnhash{$key}) {
 2853: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2854:             } else {
 2855:                 $returnhash{$key}=$username.':'.$domain;
 2856:             }
 2857:         }
 2858:     }
 2859:     return %returnhash;
 2860: }
 2861: 
 2862: sub get_my_roles {
 2863:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2864:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2865:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2866:     my (%dumphash,%nothide);
 2867:     if ($context eq 'userroles') { 
 2868:         %dumphash = &dump('roles',$udom,$uname);
 2869:     } else {
 2870:         %dumphash=
 2871:             &dump('nohist_userroles',$udom,$uname);
 2872:         if ($hidepriv) {
 2873:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2874:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2875:                 if ($user !~ /:/) {
 2876:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2877:                 } else {
 2878:                     $nothide{$user} = 1;
 2879:                 }
 2880:             }
 2881:         }
 2882:     }
 2883:     my %returnhash=();
 2884:     my $now=time;
 2885:     my %privileged;
 2886:     foreach my $entry (keys(%dumphash)) {
 2887:         my ($role,$tend,$tstart);
 2888:         if ($context eq 'userroles') {
 2889: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2890:         } else {
 2891:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2892:         }
 2893:         if (($tstart) && ($tstart<0)) { next; }
 2894:         my $status = 'active';
 2895:         if (($tend) && ($tend<=$now)) {
 2896:             $status = 'previous';
 2897:         } 
 2898:         if (($tstart) && ($now<$tstart)) {
 2899:             $status = 'future';
 2900:         }
 2901:         if (ref($types) eq 'ARRAY') {
 2902:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2903:                 next;
 2904:             } 
 2905:         } else {
 2906:             if ($status ne 'active') {
 2907:                 next;
 2908:             }
 2909:         }
 2910:         my ($rolecode,$username,$domain,$section,$area);
 2911:         if ($context eq 'userroles') {
 2912:             ($area,$rolecode) = split(/_/,$entry);
 2913:             (undef,$domain,$username,$section) = split(/\//,$area);
 2914:         } else {
 2915:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2916:         }
 2917:         if (ref($roledoms) eq 'ARRAY') {
 2918:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2919:                 next;
 2920:             }
 2921:         }
 2922:         if (ref($roles) eq 'ARRAY') {
 2923:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2924:                 if ($role =~ /^cr\//) {
 2925:                     if (!grep(/^cr$/,@{$roles})) {
 2926:                         next;
 2927:                     }
 2928:                 } else {
 2929:                     next;
 2930:                 }
 2931:             }
 2932:         }
 2933:         if ($hidepriv) {
 2934:             if ($context eq 'userroles') {
 2935:                 if ((&privileged($username,$domain)) &&
 2936:                     (!$nothide{$username.':'.$domain})) {
 2937:                     next;
 2938:                 }
 2939:             } else {
 2940:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2941:                     my %dompersonnel =
 2942:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2943:                     $privileged{$domain} = {};
 2944:                     if (keys(%dompersonnel)) {
 2945:                         foreach my $server (keys(%dompersonnel)) {
 2946:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2947:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2948:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2949:                                     $privileged{$udom}{$uname} = $trole;
 2950:                                 }
 2951:                             }
 2952:                         }
 2953:                     }
 2954:                 }
 2955:                 if (exists($privileged{$domain}{$username})) {
 2956:                     if (!$nothide{$username.':'.$domain}) {
 2957:                         next;
 2958:                     }
 2959:                 }
 2960:             }
 2961:         }
 2962:         if ($withsec) {
 2963:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2964:                 $tstart.':'.$tend;
 2965:         } else {
 2966:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2967:         }
 2968:     }
 2969:     return %returnhash;
 2970: }
 2971: 
 2972: # ----------------------------------------------------- Frontpage Announcements
 2973: #
 2974: #
 2975: 
 2976: sub postannounce {
 2977:     my ($server,$text)=@_;
 2978:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2979:     unless ($text=~/\w/) { $text=''; }
 2980:     return &reply('setannounce:'.&escape($text),$server);
 2981: }
 2982: 
 2983: sub getannounce {
 2984: 
 2985:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2986: 	my $announcement='';
 2987: 	while (my $line = <$fh>) { $announcement .= $line; }
 2988: 	close($fh);
 2989: 	if ($announcement=~/\w/) { 
 2990: 	    return 
 2991:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2992:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2993: 	} else {
 2994: 	    return '';
 2995: 	}
 2996:     } else {
 2997: 	return '';
 2998:     }
 2999: }
 3000: 
 3001: # ---------------------------------------------------------- Course ID routines
 3002: # Deal with domain's nohist_courseid.db files
 3003: #
 3004: 
 3005: sub courseidput {
 3006:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3007:     my $outcome;
 3008:     if ($caller eq 'timeonly') {
 3009:         my $cids = '';
 3010:         foreach my $item (keys(%$storehash)) {
 3011:             $cids.=&escape($item).'&';
 3012:         }
 3013:         $cids=~s/\&$//;
 3014:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3015:                           $coursehome);       
 3016:     } else {
 3017:         my $items = '';
 3018:         foreach my $item (keys(%$storehash)) {
 3019:             $items.= &escape($item).'='.
 3020:                      &freeze_escape($$storehash{$item}).'&';
 3021:         }
 3022:         $items=~s/\&$//;
 3023:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3024:                           $coursehome);
 3025:     }
 3026:     if ($outcome eq 'unknown_cmd') {
 3027:         my $what;
 3028:         foreach my $cid (keys(%$storehash)) {
 3029:             $what .= &escape($cid).'=';
 3030:             foreach my $item ('description','inst_code','owner','type') {
 3031:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3032:             }
 3033:             $what =~ s/\:$/&/;
 3034:         }
 3035:         $what =~ s/\&$//;  
 3036:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3037:     } else {
 3038:         return $outcome;
 3039:     }
 3040: }
 3041: 
 3042: sub courseiddump {
 3043:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3044:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3045:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3046:         $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
 3047:     my $as_hash = 1;
 3048:     my %returnhash;
 3049:     if (!$domfilter) { $domfilter=''; }
 3050:     my %libserv = &all_library();
 3051:     foreach my $tryserver (keys(%libserv)) {
 3052:         if ( (  $hostidflag == 1 
 3053: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3054: 	     || (!defined($hostidflag)) ) {
 3055: 
 3056: 	    if (($domfilter eq '') ||
 3057: 		(&host_domain($tryserver) eq $domfilter)) {
 3058:                 my $rep = 
 3059:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3060:                          $sincefilter.':'.&escape($descfilter).':'.
 3061:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3062:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3063:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3064:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3065:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3066:                          &escape($cc_clone).':'.$cloneonly.':'.
 3067:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3068:                          &escape($creationcontext),$tryserver);
 3069:                 my @pairs=split(/\&/,$rep);
 3070:                 foreach my $item (@pairs) {
 3071:                     my ($key,$value)=split(/\=/,$item,2);
 3072:                     $key = &unescape($key);
 3073:                     next if ($key =~ /^error: 2 /);
 3074:                     my $result = &thaw_unescape($value);
 3075:                     if (ref($result) eq 'HASH') {
 3076:                         $returnhash{$key}=$result;
 3077:                     } else {
 3078:                         my @responses = split(/:/,$value);
 3079:                         my @items = ('description','inst_code','owner','type');
 3080:                         for (my $i=0; $i<@responses; $i++) {
 3081:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3082:                         }
 3083:                     }
 3084:                 }
 3085:             }
 3086:         }
 3087:     }
 3088:     return %returnhash;
 3089: }
 3090: 
 3091: # ---------------------------------------------------------- DC e-mail
 3092: 
 3093: sub dcmailput {
 3094:     my ($domain,$msgid,$message,$server)=@_;
 3095:     my $status = &Apache::lonnet::critical(
 3096:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3097:        &escape($message),$server);
 3098:     return $status;
 3099: }
 3100: 
 3101: sub dcmaildump {
 3102:     my ($dom,$startdate,$enddate,$senders) = @_;
 3103:     my %returnhash=();
 3104: 
 3105:     if (defined(&domain($dom,'primary'))) {
 3106:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3107:                                                          &escape($enddate).':';
 3108: 	my @esc_senders=map { &escape($_)} @$senders;
 3109: 	$cmd.=&escape(join('&',@esc_senders));
 3110: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3111:             my ($key,$value) = split(/\=/,$line,2);
 3112:             if (($key) && ($value)) {
 3113:                 $returnhash{&unescape($key)} = &unescape($value);
 3114:             }
 3115:         }
 3116:     }
 3117:     return %returnhash;
 3118: }
 3119: # ---------------------------------------------------------- Domain roles
 3120: 
 3121: sub get_domain_roles {
 3122:     my ($dom,$roles,$startdate,$enddate)=@_;
 3123:     if ((!defined($startdate)) || ($startdate eq '')) {
 3124:         $startdate = '.';
 3125:     }
 3126:     if ((!defined($enddate)) || ($enddate eq '')) {
 3127:         $enddate = '.';
 3128:     }
 3129:     my $rolelist;
 3130:     if (ref($roles) eq 'ARRAY') {
 3131:         $rolelist = join(':',@{$roles});
 3132:     }
 3133:     my %personnel = ();
 3134: 
 3135:     my %servers = &get_servers($dom,'library');
 3136:     foreach my $tryserver (keys(%servers)) {
 3137: 	%{$personnel{$tryserver}}=();
 3138: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3139: 					    &escape($startdate).':'.
 3140: 					    &escape($enddate).':'.
 3141: 					    &escape($rolelist), $tryserver))) {
 3142: 	    my ($key,$value) = split(/\=/,$line,2);
 3143: 	    if (($key) && ($value)) {
 3144: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3145: 	    }
 3146: 	}
 3147:     }
 3148:     return %personnel;
 3149: }
 3150: 
 3151: # ----------------------------------------------------------- Check out an item
 3152: 
 3153: sub get_first_access {
 3154:     my ($type,$argsymb)=@_;
 3155:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3156:     if ($argsymb) { $symb=$argsymb; }
 3157:     my ($map,$id,$res)=&decode_symb($symb);
 3158:     if ($type eq 'course') {
 3159: 	$res='course';
 3160:     } elsif ($type eq 'map') {
 3161: 	$res=&symbread($map);
 3162:     } else {
 3163: 	$res=$symb;
 3164:     }
 3165:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3166:     return $times{"$courseid\0$res"};
 3167: }
 3168: 
 3169: sub set_first_access {
 3170:     my ($type)=@_;
 3171:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3172:     my ($map,$id,$res)=&decode_symb($symb);
 3173:     if ($type eq 'course') {
 3174: 	$res='course';
 3175:     } elsif ($type eq 'map') {
 3176: 	$res=&symbread($map);
 3177:     } else {
 3178: 	$res=$symb;
 3179:     }
 3180:     my $firstaccess=&get_first_access($type,$symb);
 3181:     if (!$firstaccess) {
 3182: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3183:     }
 3184:     return 'already_set';
 3185: }
 3186: 
 3187: sub checkout {
 3188:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3189:     my $now=time;
 3190:     my $lonhost=$perlvar{'lonHostID'};
 3191:     my $infostr=&escape(
 3192:                  'CHECKOUTTOKEN&'.
 3193:                  $tuname.'&'.
 3194:                  $tudom.'&'.
 3195:                  $tcrsid.'&'.
 3196:                  $symb.'&'.
 3197: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3198:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3199:     if ($token=~/^error\:/) { 
 3200:         &logthis("<font color=\"blue\">WARNING: ".
 3201:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3202:                  "</font>");
 3203:         return ''; 
 3204:     }
 3205: 
 3206:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3207:     $token=~tr/a-z/A-Z/;
 3208: 
 3209:     my %infohash=('resource.0.outtoken' => $token,
 3210:                   'resource.0.checkouttime' => $now,
 3211:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3212: 
 3213:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3214:        return '';
 3215:     } else {
 3216:         &logthis("<font color=\"blue\">WARNING: ".
 3217:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3218:                  "</font>");
 3219:     }    
 3220: 
 3221:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3222:                          &escape('Checkout '.$infostr.' - '.
 3223:                                                  $token)) ne 'ok') {
 3224: 	return '';
 3225:     } else {
 3226:         &logthis("<font color=\"blue\">WARNING: ".
 3227:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3228:                  "</font>");
 3229:     }
 3230:     return $token;
 3231: }
 3232: 
 3233: # ------------------------------------------------------------ Check in an item
 3234: 
 3235: sub checkin {
 3236:     my $token=shift;
 3237:     my $now=time;
 3238:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3239:     $lonhost=~tr/A-Z/a-z/;
 3240:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3241:     $dtoken=~s/\W/\_/g;
 3242:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3243:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3244: 
 3245:     unless (($tuname) && ($tudom)) {
 3246:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3247:         return '';
 3248:     }
 3249:     
 3250:     unless (&allowed('mgr',$tcrsid)) {
 3251:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3252:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3253:         return '';
 3254:     }
 3255: 
 3256:     my %infohash=('resource.0.intoken' => $token,
 3257:                   'resource.0.checkintime' => $now,
 3258:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3259: 
 3260:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3261:        return '';
 3262:     }    
 3263: 
 3264:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3265:                          &escape('Checkin - '.$token)) ne 'ok') {
 3266: 	return '';
 3267:     }
 3268: 
 3269:     return ($symb,$tuname,$tudom,$tcrsid);    
 3270: }
 3271: 
 3272: # --------------------------------------------- Set Expire Date for Spreadsheet
 3273: 
 3274: sub expirespread {
 3275:     my ($uname,$udom,$stype,$usymb)=@_;
 3276:     my $cid=$env{'request.course.id'}; 
 3277:     if ($cid) {
 3278:        my $now=time;
 3279:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3280:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3281:                             $env{'course.'.$cid.'.num'}.
 3282: 	        	    ':nohist_expirationdates:'.
 3283:                             &escape($key).'='.$now,
 3284:                             $env{'course.'.$cid.'.home'})
 3285:     }
 3286:     return 'ok';
 3287: }
 3288: 
 3289: # ----------------------------------------------------- Devalidate Spreadsheets
 3290: 
 3291: sub devalidate {
 3292:     my ($symb,$uname,$udom)=@_;
 3293:     my $cid=$env{'request.course.id'}; 
 3294:     if ($cid) {
 3295:         # delete the stored spreadsheets for
 3296:         # - the student level sheet of this user in course's homespace
 3297:         # - the assessment level sheet for this resource 
 3298:         #   for this user in user's homespace
 3299: 	# - current conditional state info
 3300: 	my $key=$uname.':'.$udom.':';
 3301:         my $status=
 3302: 	    &del('nohist_calculatedsheets',
 3303: 		 [$key.'studentcalc:'],
 3304: 		 $env{'course.'.$cid.'.domain'},
 3305: 		 $env{'course.'.$cid.'.num'})
 3306: 		.' '.
 3307: 	    &del('nohist_calculatedsheets_'.$cid,
 3308: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3309:         unless ($status eq 'ok ok') {
 3310:            &logthis('Could not devalidate spreadsheet '.
 3311:                     $uname.' at '.$udom.' for '.
 3312: 		    $symb.': '.$status);
 3313:         }
 3314: 	&delenv('user.state.'.$cid);
 3315:     }
 3316: }
 3317: 
 3318: sub get_scalar {
 3319:     my ($string,$end) = @_;
 3320:     my $value;
 3321:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3322: 	$value = $1;
 3323:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3324: 	$value = $1;
 3325:     }
 3326:     return &unescape($value);
 3327: }
 3328: 
 3329: sub array2str {
 3330:   my (@array) = @_;
 3331:   my $result=&arrayref2str(\@array);
 3332:   $result=~s/^__ARRAY_REF__//;
 3333:   $result=~s/__END_ARRAY_REF__$//;
 3334:   return $result;
 3335: }
 3336: 
 3337: sub arrayref2str {
 3338:   my ($arrayref) = @_;
 3339:   my $result='__ARRAY_REF__';
 3340:   foreach my $elem (@$arrayref) {
 3341:     if(ref($elem) eq 'ARRAY') {
 3342:       $result.=&arrayref2str($elem).'&';
 3343:     } elsif(ref($elem) eq 'HASH') {
 3344:       $result.=&hashref2str($elem).'&';
 3345:     } elsif(ref($elem)) {
 3346:       #print("Got a ref of ".(ref($elem))." skipping.");
 3347:     } else {
 3348:       $result.=&escape($elem).'&';
 3349:     }
 3350:   }
 3351:   $result=~s/\&$//;
 3352:   $result .= '__END_ARRAY_REF__';
 3353:   return $result;
 3354: }
 3355: 
 3356: sub hash2str {
 3357:   my (%hash) = @_;
 3358:   my $result=&hashref2str(\%hash);
 3359:   $result=~s/^__HASH_REF__//;
 3360:   $result=~s/__END_HASH_REF__$//;
 3361:   return $result;
 3362: }
 3363: 
 3364: sub hashref2str {
 3365:   my ($hashref)=@_;
 3366:   my $result='__HASH_REF__';
 3367:   foreach my $key (sort(keys(%$hashref))) {
 3368:     if (ref($key) eq 'ARRAY') {
 3369:       $result.=&arrayref2str($key).'=';
 3370:     } elsif (ref($key) eq 'HASH') {
 3371:       $result.=&hashref2str($key).'=';
 3372:     } elsif (ref($key)) {
 3373:       $result.='=';
 3374:       #print("Got a ref of ".(ref($key))." skipping.");
 3375:     } else {
 3376: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3377:     }
 3378: 
 3379:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3380:       $result.=&arrayref2str($hashref->{$key}).'&';
 3381:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3382:       $result.=&hashref2str($hashref->{$key}).'&';
 3383:     } elsif(ref($hashref->{$key})) {
 3384:        $result.='&';
 3385:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3386:     } else {
 3387:       $result.=&escape($hashref->{$key}).'&';
 3388:     }
 3389:   }
 3390:   $result=~s/\&$//;
 3391:   $result .= '__END_HASH_REF__';
 3392:   return $result;
 3393: }
 3394: 
 3395: sub str2hash {
 3396:     my ($string)=@_;
 3397:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3398:     return %$hash;
 3399: }
 3400: 
 3401: sub str2hashref {
 3402:   my ($string) = @_;
 3403: 
 3404:   my %hash;
 3405: 
 3406:   if($string !~ /^__HASH_REF__/) {
 3407:       if (! ($string eq '' || !defined($string))) {
 3408: 	  $hash{'error'}='Not hash reference';
 3409:       }
 3410:       return (\%hash, $string);
 3411:   }
 3412: 
 3413:   $string =~ s/^__HASH_REF__//;
 3414: 
 3415:   while($string !~ /^__END_HASH_REF__/) {
 3416:       #key
 3417:       my $key='';
 3418:       if($string =~ /^__HASH_REF__/) {
 3419:           ($key, $string)=&str2hashref($string);
 3420:           if(defined($key->{'error'})) {
 3421:               $hash{'error'}='Bad data';
 3422:               return (\%hash, $string);
 3423:           }
 3424:       } elsif($string =~ /^__ARRAY_REF__/) {
 3425:           ($key, $string)=&str2arrayref($string);
 3426:           if($key->[0] eq 'Array reference error') {
 3427:               $hash{'error'}='Bad data';
 3428:               return (\%hash, $string);
 3429:           }
 3430:       } else {
 3431:           $string =~ s/^(.*?)=//;
 3432: 	  $key=&unescape($1);
 3433:       }
 3434:       $string =~ s/^=//;
 3435: 
 3436:       #value
 3437:       my $value='';
 3438:       if($string =~ /^__HASH_REF__/) {
 3439:           ($value, $string)=&str2hashref($string);
 3440:           if(defined($value->{'error'})) {
 3441:               $hash{'error'}='Bad data';
 3442:               return (\%hash, $string);
 3443:           }
 3444:       } elsif($string =~ /^__ARRAY_REF__/) {
 3445:           ($value, $string)=&str2arrayref($string);
 3446:           if($value->[0] eq 'Array reference error') {
 3447:               $hash{'error'}='Bad data';
 3448:               return (\%hash, $string);
 3449:           }
 3450:       } else {
 3451: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3452:       }
 3453:       $string =~ s/^&//;
 3454: 
 3455:       $hash{$key}=$value;
 3456:   }
 3457: 
 3458:   $string =~ s/^__END_HASH_REF__//;
 3459: 
 3460:   return (\%hash, $string);
 3461: }
 3462: 
 3463: sub str2array {
 3464:     my ($string)=@_;
 3465:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3466:     return @$array;
 3467: }
 3468: 
 3469: sub str2arrayref {
 3470:   my ($string) = @_;
 3471:   my @array;
 3472: 
 3473:   if($string !~ /^__ARRAY_REF__/) {
 3474:       if (! ($string eq '' || !defined($string))) {
 3475: 	  $array[0]='Array reference error';
 3476:       }
 3477:       return (\@array, $string);
 3478:   }
 3479: 
 3480:   $string =~ s/^__ARRAY_REF__//;
 3481: 
 3482:   while($string !~ /^__END_ARRAY_REF__/) {
 3483:       my $value='';
 3484:       if($string =~ /^__HASH_REF__/) {
 3485:           ($value, $string)=&str2hashref($string);
 3486:           if(defined($value->{'error'})) {
 3487:               $array[0] ='Array reference error';
 3488:               return (\@array, $string);
 3489:           }
 3490:       } elsif($string =~ /^__ARRAY_REF__/) {
 3491:           ($value, $string)=&str2arrayref($string);
 3492:           if($value->[0] eq 'Array reference error') {
 3493:               $array[0] ='Array reference error';
 3494:               return (\@array, $string);
 3495:           }
 3496:       } else {
 3497: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3498:       }
 3499:       $string =~ s/^&//;
 3500: 
 3501:       push(@array, $value);
 3502:   }
 3503: 
 3504:   $string =~ s/^__END_ARRAY_REF__//;
 3505: 
 3506:   return (\@array, $string);
 3507: }
 3508: 
 3509: # -------------------------------------------------------------------Temp Store
 3510: 
 3511: sub tmpreset {
 3512:   my ($symb,$namespace,$domain,$stuname) = @_;
 3513:   if (!$symb) {
 3514:     $symb=&symbread();
 3515:     if (!$symb) { $symb= $env{'request.url'}; }
 3516:   }
 3517:   $symb=escape($symb);
 3518: 
 3519:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3520:   $namespace=~s/\//\_/g;
 3521:   $namespace=~s/\W//g;
 3522: 
 3523:   if (!$domain) { $domain=$env{'user.domain'}; }
 3524:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3525:   if ($domain eq 'public' && $stuname eq 'public') {
 3526:       $stuname=$ENV{'REMOTE_ADDR'};
 3527:   }
 3528:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3529:   my %hash;
 3530:   if (tie(%hash,'GDBM_File',
 3531: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3532: 	  &GDBM_WRCREAT(),0640)) {
 3533:     foreach my $key (keys(%hash)) {
 3534:       if ($key=~ /:$symb/) {
 3535: 	delete($hash{$key});
 3536:       }
 3537:     }
 3538:   }
 3539: }
 3540: 
 3541: sub tmpstore {
 3542:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3543: 
 3544:   if (!$symb) {
 3545:     $symb=&symbread();
 3546:     if (!$symb) { $symb= $env{'request.url'}; }
 3547:   }
 3548:   $symb=escape($symb);
 3549: 
 3550:   if (!$namespace) {
 3551:     # I don't think we would ever want to store this for a course.
 3552:     # it seems this will only be used if we don't have a course.
 3553:     #$namespace=$env{'request.course.id'};
 3554:     #if (!$namespace) {
 3555:       $namespace=$env{'request.state'};
 3556:     #}
 3557:   }
 3558:   $namespace=~s/\//\_/g;
 3559:   $namespace=~s/\W//g;
 3560:   if (!$domain) { $domain=$env{'user.domain'}; }
 3561:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3562:   if ($domain eq 'public' && $stuname eq 'public') {
 3563:       $stuname=$ENV{'REMOTE_ADDR'};
 3564:   }
 3565:   my $now=time;
 3566:   my %hash;
 3567:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3568:   if (tie(%hash,'GDBM_File',
 3569: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3570: 	  &GDBM_WRCREAT(),0640)) {
 3571:     $hash{"version:$symb"}++;
 3572:     my $version=$hash{"version:$symb"};
 3573:     my $allkeys=''; 
 3574:     foreach my $key (keys(%$storehash)) {
 3575:       $allkeys.=$key.':';
 3576:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3577:     }
 3578:     $hash{"$version:$symb:timestamp"}=$now;
 3579:     $allkeys.='timestamp';
 3580:     $hash{"$version:keys:$symb"}=$allkeys;
 3581:     if (untie(%hash)) {
 3582:       return 'ok';
 3583:     } else {
 3584:       return "error:$!";
 3585:     }
 3586:   } else {
 3587:     return "error:$!";
 3588:   }
 3589: }
 3590: 
 3591: # -----------------------------------------------------------------Temp Restore
 3592: 
 3593: sub tmprestore {
 3594:   my ($symb,$namespace,$domain,$stuname) = @_;
 3595: 
 3596:   if (!$symb) {
 3597:     $symb=&symbread();
 3598:     if (!$symb) { $symb= $env{'request.url'}; }
 3599:   }
 3600:   $symb=escape($symb);
 3601: 
 3602:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3603: 
 3604:   if (!$domain) { $domain=$env{'user.domain'}; }
 3605:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3606:   if ($domain eq 'public' && $stuname eq 'public') {
 3607:       $stuname=$ENV{'REMOTE_ADDR'};
 3608:   }
 3609:   my %returnhash;
 3610:   $namespace=~s/\//\_/g;
 3611:   $namespace=~s/\W//g;
 3612:   my %hash;
 3613:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3614:   if (tie(%hash,'GDBM_File',
 3615: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3616: 	  &GDBM_READER(),0640)) {
 3617:     my $version=$hash{"version:$symb"};
 3618:     $returnhash{'version'}=$version;
 3619:     my $scope;
 3620:     for ($scope=1;$scope<=$version;$scope++) {
 3621:       my $vkeys=$hash{"$scope:keys:$symb"};
 3622:       my @keys=split(/:/,$vkeys);
 3623:       my $key;
 3624:       $returnhash{"$scope:keys"}=$vkeys;
 3625:       foreach $key (@keys) {
 3626: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3627: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3628:       }
 3629:     }
 3630:     if (!(untie(%hash))) {
 3631:       return "error:$!";
 3632:     }
 3633:   } else {
 3634:     return "error:$!";
 3635:   }
 3636:   return %returnhash;
 3637: }
 3638: 
 3639: # ----------------------------------------------------------------------- Store
 3640: 
 3641: sub store {
 3642:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3643:     my $home='';
 3644: 
 3645:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3646: 
 3647:     $symb=&symbclean($symb);
 3648:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3649: 
 3650:     if (!$domain) { $domain=$env{'user.domain'}; }
 3651:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3652: 
 3653:     &devalidate($symb,$stuname,$domain);
 3654: 
 3655:     $symb=escape($symb);
 3656:     if (!$namespace) { 
 3657:        unless ($namespace=$env{'request.course.id'}) { 
 3658:           return ''; 
 3659:        } 
 3660:     }
 3661:     if (!$home) { $home=$env{'user.home'}; }
 3662: 
 3663:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3664:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3665: 
 3666:     my $namevalue='';
 3667:     foreach my $key (keys(%$storehash)) {
 3668:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3669:     }
 3670:     $namevalue=~s/\&$//;
 3671:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3672:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3673: }
 3674: 
 3675: # -------------------------------------------------------------- Critical Store
 3676: 
 3677: sub cstore {
 3678:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3679:     my $home='';
 3680: 
 3681:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3682: 
 3683:     $symb=&symbclean($symb);
 3684:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3685: 
 3686:     if (!$domain) { $domain=$env{'user.domain'}; }
 3687:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3688: 
 3689:     &devalidate($symb,$stuname,$domain);
 3690: 
 3691:     $symb=escape($symb);
 3692:     if (!$namespace) { 
 3693:        unless ($namespace=$env{'request.course.id'}) { 
 3694:           return ''; 
 3695:        } 
 3696:     }
 3697:     if (!$home) { $home=$env{'user.home'}; }
 3698: 
 3699:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3700:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3701: 
 3702:     my $namevalue='';
 3703:     foreach my $key (keys(%$storehash)) {
 3704:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3705:     }
 3706:     $namevalue=~s/\&$//;
 3707:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3708:     return critical
 3709:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3710: }
 3711: 
 3712: # --------------------------------------------------------------------- Restore
 3713: 
 3714: sub restore {
 3715:     my ($symb,$namespace,$domain,$stuname) = @_;
 3716:     my $home='';
 3717: 
 3718:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3719: 
 3720:     if (!$symb) {
 3721:       unless ($symb=escape(&symbread())) { return ''; }
 3722:     } else {
 3723:       $symb=&escape(&symbclean($symb));
 3724:     }
 3725:     if (!$namespace) { 
 3726:        unless ($namespace=$env{'request.course.id'}) { 
 3727:           return ''; 
 3728:        } 
 3729:     }
 3730:     if (!$domain) { $domain=$env{'user.domain'}; }
 3731:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3732:     if (!$home) { $home=$env{'user.home'}; }
 3733:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3734: 
 3735:     my %returnhash=();
 3736:     foreach my $line (split(/\&/,$answer)) {
 3737: 	my ($name,$value)=split(/\=/,$line);
 3738:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3739:     }
 3740:     my $version;
 3741:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3742:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3743:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3744:        }
 3745:     }
 3746:     return %returnhash;
 3747: }
 3748: 
 3749: # ---------------------------------------------------------- Course Description
 3750: 
 3751: sub coursedescription {
 3752:     my ($courseid,$args)=@_;
 3753:     $courseid=~s/^\///;
 3754:     $courseid=~s/\_/\//g;
 3755:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3756:     my $chome=&homeserver($cnum,$cdomain);
 3757:     my $normalid=$cdomain.'_'.$cnum;
 3758:     # need to always cache even if we get errors otherwise we keep 
 3759:     # trying and trying and trying to get the course description.
 3760:     my %envhash=();
 3761:     my %returnhash=();
 3762:     
 3763:     my $expiretime=600;
 3764:     if ($env{'request.course.id'} eq $normalid) {
 3765: 	$expiretime=120;
 3766:     }
 3767: 
 3768:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3769:     if (!$args->{'freshen_cache'}
 3770: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3771: 	foreach my $key (keys(%env)) {
 3772: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3773: 	    my ($setting) = $1;
 3774: 	    $returnhash{$setting} = $env{$key};
 3775: 	}
 3776: 	return %returnhash;
 3777:     }
 3778: 
 3779:     # get the data agin
 3780:     if (!$args->{'one_time'}) {
 3781: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3782:     }
 3783: 
 3784:     if ($chome ne 'no_host') {
 3785:        %returnhash=&dump('environment',$cdomain,$cnum);
 3786:        if (!exists($returnhash{'con_lost'})) {
 3787:            $returnhash{'home'}= $chome;
 3788: 	   $returnhash{'domain'} = $cdomain;
 3789: 	   $returnhash{'num'} = $cnum;
 3790:            if (!defined($returnhash{'type'})) {
 3791:                $returnhash{'type'} = 'Course';
 3792:            }
 3793:            while (my ($name,$value) = each %returnhash) {
 3794:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3795:            }
 3796:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3797:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3798: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3799:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3800:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3801:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3802:        }
 3803:     }
 3804:     if (!$args->{'one_time'}) {
 3805: 	&appenv(\%envhash);
 3806:     }
 3807:     return %returnhash;
 3808: }
 3809: 
 3810: # -------------------------------------------------See if a user is privileged
 3811: 
 3812: sub privileged {
 3813:     my ($username,$domain)=@_;
 3814:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3815: 			&homeserver($username,$domain));
 3816:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3817:         ($rolesdump =~ /^error:/)) {
 3818:         return 0;
 3819:     }
 3820:     my $now=time;
 3821:     if ($rolesdump ne '') {
 3822:         foreach my $entry (split(/&/,$rolesdump)) {
 3823: 	    if ($entry!~/^rolesdef_/) {
 3824: 		my ($area,$role)=split(/=/,$entry);
 3825: 		$area=~s/\_\w\w$//;
 3826: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3827: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3828: 		    my $active=1;
 3829: 		    if ($tend) {
 3830: 			if ($tend<$now) { $active=0; }
 3831: 		    }
 3832: 		    if ($tstart) {
 3833: 			if ($tstart>$now) { $active=0; }
 3834: 		    }
 3835: 		    if ($active) { return 1; }
 3836: 		}
 3837: 	    }
 3838: 	}
 3839:     }
 3840:     return 0;
 3841: }
 3842: 
 3843: # -------------------------------------------------------- Get user privileges
 3844: 
 3845: sub rolesinit {
 3846:     my ($domain,$username,$authhost)=@_;
 3847:     my $now=time;
 3848:     my %userroles = ('user.login.time' => $now);
 3849:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3850:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3851:         ($rolesdump =~ /^error:/)) { 
 3852:         return \%userroles;
 3853:     }
 3854:     my %allroles=();
 3855:     my %allgroups=();   
 3856:     my $group_privs;
 3857: 
 3858:     if ($rolesdump ne '') {
 3859:         foreach my $entry (split(/&/,$rolesdump)) {
 3860: 	  if ($entry!~/^rolesdef_/) {
 3861:             my ($area,$role)=split(/=/,$entry);
 3862: 	    $area=~s/\_\w\w$//;
 3863:             my ($trole,$tend,$tstart,$group_privs);
 3864: 	    if ($role=~/^cr/) { 
 3865: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3866: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3867: 		    ($tend,$tstart)=split('_',$trest);
 3868: 		} else {
 3869: 		    $trole=$role;
 3870: 		}
 3871:             } elsif ($role =~ m|^gr/|) {
 3872:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3873:                 ($trole,$group_privs) = split(/\//,$trole);
 3874:                 $group_privs = &unescape($group_privs);
 3875: 	    } else {
 3876: 		($trole,$tend,$tstart)=split(/_/,$role);
 3877: 	    }
 3878: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3879: 					 $username);
 3880: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3881:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3882:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3883:             if (($area ne '') && ($trole ne '')) {
 3884: 		my $spec=$trole.'.'.$area;
 3885: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3886: 		if ($trole =~ /^cr\//) {
 3887:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3888:                 } elsif ($trole eq 'gr') {
 3889:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3890: 		} else {
 3891:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3892: 		}
 3893:             }
 3894:           }
 3895:         }
 3896:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3897:         $userroles{'user.adv'}    = $adv;
 3898: 	$userroles{'user.author'} = $author;
 3899:         $env{'user.adv'}=$adv;
 3900:     }
 3901:     return \%userroles;  
 3902: }
 3903: 
 3904: sub set_arearole {
 3905:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3906: # log the associated role with the area
 3907:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3908:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3909: }
 3910: 
 3911: sub custom_roleprivs {
 3912:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3913:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3914:     my $homsvr=homeserver($rauthor,$rdomain);
 3915:     if (&hostname($homsvr) ne '') {
 3916:         my ($rdummy,$roledef)=
 3917:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3918:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3919:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3920:             if (defined($syspriv)) {
 3921:                 if ($trest =~ /^$match_community$/) {
 3922:                     $syspriv =~ s/bre\&S//; 
 3923:                 }
 3924:                 $$allroles{'cm./'}.=':'.$syspriv;
 3925:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3926:             }
 3927:             if ($tdomain ne '') {
 3928:                 if (defined($dompriv)) {
 3929:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3930:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3931:                 }
 3932:                 if (($trest ne '') && (defined($coursepriv))) {
 3933:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3934:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3935:                 }
 3936:             }
 3937:         }
 3938:     }
 3939: }
 3940: 
 3941: sub group_roleprivs {
 3942:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3943:     my $access = 1;
 3944:     my $now = time;
 3945:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3946:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3947:     if ($access) {
 3948:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3949:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3950:     }
 3951: }
 3952: 
 3953: sub standard_roleprivs {
 3954:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3955:     if (defined($pr{$trole.':s'})) {
 3956:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3957:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3958:     }
 3959:     if ($tdomain ne '') {
 3960:         if (defined($pr{$trole.':d'})) {
 3961:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3962:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3963:         }
 3964:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3965:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3966:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3967:         }
 3968:     }
 3969: }
 3970: 
 3971: sub set_userprivs {
 3972:     my ($userroles,$allroles,$allgroups) = @_; 
 3973:     my $author=0;
 3974:     my $adv=0;
 3975:     my %grouproles = ();
 3976:     if (keys(%{$allgroups}) > 0) {
 3977:         foreach my $role (keys(%{$allroles})) {
 3978:             my ($trole,$area,$sec,$extendedarea);
 3979:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3980:                 $trole = $1;
 3981:                 $area = $2;
 3982:                 $sec = $3;
 3983:                 $extendedarea = $area.$sec;
 3984:                 if (exists($$allgroups{$area})) {
 3985:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3986:                         my $spec = $trole.'.'.$extendedarea;
 3987:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3988:                                                 $$allgroups{$area}{$group};
 3989:                     }
 3990:                 }
 3991:             }
 3992:         }
 3993:     }
 3994:     foreach my $group (keys(%grouproles)) {
 3995:         $$allroles{$group} = $grouproles{$group};
 3996:     }
 3997:     foreach my $role (keys(%{$allroles})) {
 3998:         my %thesepriv;
 3999:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4000:         foreach my $item (split(/:/,$$allroles{$role})) {
 4001:             if ($item ne '') {
 4002:                 my ($privilege,$restrictions)=split(/&/,$item);
 4003:                 if ($restrictions eq '') {
 4004:                     $thesepriv{$privilege}='F';
 4005:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4006:                     $thesepriv{$privilege}.=$restrictions;
 4007:                 }
 4008:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4009:             }
 4010:         }
 4011:         my $thesestr='';
 4012:         foreach my $priv (keys(%thesepriv)) {
 4013: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4014: 	}
 4015:         $userroles->{'user.priv.'.$role} = $thesestr;
 4016:     }
 4017:     return ($author,$adv);
 4018: }
 4019: 
 4020: sub role_status {
 4021:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4022:     my @pwhere = ();
 4023:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4024:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4025:         unless (!defined($$role) || $$role eq '') {
 4026:             $$where=join('.',@pwhere);
 4027:             $$trolecode=$$role.'.'.$$where;
 4028:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4029:             $$tstatus='is';
 4030:             if ($$tstart && $$tstart>$then) {
 4031:                 $$tstatus='future';
 4032:                 if ($$tstart<$now) {
 4033:                     if ($$tstart && $$tstart>$refresh) {
 4034:                         if (($$where ne '') && ($$role ne '')) {
 4035:                             my (%allroles,%allgroups,$group_privs);
 4036:                             my %userroles = (
 4037:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4038:                             );
 4039:                             my $spec=$$role.'.'.$$where;
 4040:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4041:                             if ($$role =~ /^cr\//) {
 4042:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4043:                             } elsif ($$role eq 'gr') {
 4044:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4045:                                                     $env{'user.name'});
 4046:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 4047:                                 (undef,my $group_privs) = split(/\//,$trole);
 4048:                                 $group_privs = &unescape($group_privs);
 4049:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4050:                             } else {
 4051:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4052:                             }
 4053:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4054:                             &appenv(\%userroles,[$$role,'cm']);
 4055:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4056:                         }
 4057:                     }
 4058:                     $$tstatus = 'is';
 4059:                 }
 4060:             }
 4061:             if ($$tend) {
 4062:                 if ($$tend<$then) {
 4063:                     $$tstatus='expired';
 4064:                 } elsif ($$tend<$now) {
 4065:                     $$tstatus='will_not';
 4066:                 }
 4067:             }
 4068:         }
 4069:     }
 4070: }
 4071: 
 4072: sub check_adhoc_privs {
 4073:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 4074:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4075:     if ($env{$cckey}) {
 4076:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4077:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4078:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4079:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4080:         }
 4081:     } else {
 4082:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4083:     }
 4084: }
 4085: 
 4086: sub set_adhoc_privileges {
 4087: # role can be cc or ca
 4088:     my ($dcdom,$pickedcourse,$role) = @_;
 4089:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4090:     my $spec = $role.'.'.$area;
 4091:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4092:                                   $env{'user.name'});
 4093:     my %ccrole = ();
 4094:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4095:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4096:     &appenv(\%userroles,[$role,'cm']);
 4097:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4098:     &appenv( {'request.role'        => $spec,
 4099:               'request.role.domain' => $dcdom,
 4100:               'request.course.sec'  => ''
 4101:              }
 4102:            );
 4103:     my $tadv=0;
 4104:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4105:     &appenv({'request.role.adv'    => $tadv});
 4106: }
 4107: 
 4108: # --------------------------------------------------------------- get interface
 4109: 
 4110: sub get {
 4111:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4112:    my $items='';
 4113:    foreach my $item (@$storearr) {
 4114:        $items.=&escape($item).'&';
 4115:    }
 4116:    $items=~s/\&$//;
 4117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4118:    if (!$uname) { $uname=$env{'user.name'}; }
 4119:    my $uhome=&homeserver($uname,$udomain);
 4120: 
 4121:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4122:    my @pairs=split(/\&/,$rep);
 4123:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4124:      return @pairs;
 4125:    }
 4126:    my %returnhash=();
 4127:    my $i=0;
 4128:    foreach my $item (@$storearr) {
 4129:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4130:       $i++;
 4131:    }
 4132:    return %returnhash;
 4133: }
 4134: 
 4135: # --------------------------------------------------------------- del interface
 4136: 
 4137: sub del {
 4138:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4139:    my $items='';
 4140:    foreach my $item (@$storearr) {
 4141:        $items.=&escape($item).'&';
 4142:    }
 4143: 
 4144:    $items=~s/\&$//;
 4145:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4146:    if (!$uname) { $uname=$env{'user.name'}; }
 4147:    my $uhome=&homeserver($uname,$udomain);
 4148:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4149: }
 4150: 
 4151: # -------------------------------------------------------------- dump interface
 4152: 
 4153: sub dump {
 4154:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4155:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4156:     if (!$uname) { $uname=$env{'user.name'}; }
 4157:     my $uhome=&homeserver($uname,$udomain);
 4158:     if ($regexp) {
 4159: 	$regexp=&escape($regexp);
 4160:     } else {
 4161: 	$regexp='.';
 4162:     }
 4163:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4164:     my @pairs=split(/\&/,$rep);
 4165:     my %returnhash=();
 4166:     foreach my $item (@pairs) {
 4167: 	my ($key,$value)=split(/=/,$item,2);
 4168: 	$key = &unescape($key);
 4169: 	next if ($key =~ /^error: 2 /);
 4170: 	$returnhash{$key}=&thaw_unescape($value);
 4171:     }
 4172:     return %returnhash;
 4173: }
 4174: 
 4175: # --------------------------------------------------------- dumpstore interface
 4176: 
 4177: sub dumpstore {
 4178:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4179:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4180:    if (!$uname) { $uname=$env{'user.name'}; }
 4181:    my $uhome=&homeserver($uname,$udomain);
 4182:    if ($regexp) {
 4183:        $regexp=&escape($regexp);
 4184:    } else {
 4185:        $regexp='.';
 4186:    }
 4187:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4188:    my @pairs=split(/\&/,$rep);
 4189:    my %returnhash=();
 4190:    foreach my $item (@pairs) {
 4191:        my ($key,$value)=split(/=/,$item,2);
 4192:        next if ($key =~ /^error: 2 /);
 4193:        $returnhash{$key}=&thaw_unescape($value);
 4194:    }
 4195:    return %returnhash;
 4196: }
 4197: 
 4198: # -------------------------------------------------------------- keys interface
 4199: 
 4200: sub getkeys {
 4201:    my ($namespace,$udomain,$uname)=@_;
 4202:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4203:    if (!$uname) { $uname=$env{'user.name'}; }
 4204:    my $uhome=&homeserver($uname,$udomain);
 4205:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4206:    my @keyarray=();
 4207:    foreach my $key (split(/\&/,$rep)) {
 4208:       next if ($key =~ /^error: 2 /);
 4209:       push(@keyarray,&unescape($key));
 4210:    }
 4211:    return @keyarray;
 4212: }
 4213: 
 4214: # --------------------------------------------------------------- currentdump
 4215: sub currentdump {
 4216:    my ($courseid,$sdom,$sname)=@_;
 4217:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4218:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4219:    $sname    = $env{'user.name'}         if (! defined($sname));
 4220:    my $uhome = &homeserver($sname,$sdom);
 4221:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4222:    return if ($rep =~ /^(error:|no_such_host)/);
 4223:    #
 4224:    my %returnhash=();
 4225:    #
 4226:    if ($rep eq "unknown_cmd") { 
 4227:        # an old lond will not know currentdump
 4228:        # Do a dump and make it look like a currentdump
 4229:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4230:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4231:        my %hash = @tmp;
 4232:        @tmp=();
 4233:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4234:    } else {
 4235:        my @pairs=split(/\&/,$rep);
 4236:        foreach my $pair (@pairs) {
 4237:            my ($key,$value)=split(/=/,$pair,2);
 4238:            my ($symb,$param) = split(/:/,$key);
 4239:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4240:                                                         &thaw_unescape($value);
 4241:        }
 4242:    }
 4243:    return %returnhash;
 4244: }
 4245: 
 4246: sub convert_dump_to_currentdump{
 4247:     my %hash = %{shift()};
 4248:     my %returnhash;
 4249:     # Code ripped from lond, essentially.  The only difference
 4250:     # here is the unescaping done by lonnet::dump().  Conceivably
 4251:     # we might run in to problems with parameter names =~ /^v\./
 4252:     while (my ($key,$value) = each(%hash)) {
 4253:         my ($v,$symb,$param) = split(/:/,$key);
 4254: 	$symb  = &unescape($symb);
 4255: 	$param = &unescape($param);
 4256:         next if ($v eq 'version' || $symb eq 'keys');
 4257:         next if (exists($returnhash{$symb}) &&
 4258:                  exists($returnhash{$symb}->{$param}) &&
 4259:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4260:         $returnhash{$symb}->{$param}=$value;
 4261:         $returnhash{$symb}->{'v.'.$param}=$v;
 4262:     }
 4263:     #
 4264:     # Remove all of the keys in the hashes which keep track of
 4265:     # the version of the parameter.
 4266:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4267:         # use a foreach because we are going to delete from the hash.
 4268:         foreach my $key (keys(%$param_hash)) {
 4269:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4270:         }
 4271:     }
 4272:     return \%returnhash;
 4273: }
 4274: 
 4275: # ------------------------------------------------------ critical inc interface
 4276: 
 4277: sub cinc {
 4278:     return &inc(@_,'critical');
 4279: }
 4280: 
 4281: # --------------------------------------------------------------- inc interface
 4282: 
 4283: sub inc {
 4284:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4285:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4286:     if (!$uname) { $uname=$env{'user.name'}; }
 4287:     my $uhome=&homeserver($uname,$udomain);
 4288:     my $items='';
 4289:     if (! ref($store)) {
 4290:         # got a single value, so use that instead
 4291:         $items = &escape($store).'=&';
 4292:     } elsif (ref($store) eq 'SCALAR') {
 4293:         $items = &escape($$store).'=&';        
 4294:     } elsif (ref($store) eq 'ARRAY') {
 4295:         $items = join('=&',map {&escape($_);} @{$store});
 4296:     } elsif (ref($store) eq 'HASH') {
 4297:         while (my($key,$value) = each(%{$store})) {
 4298:             $items.= &escape($key).'='.&escape($value).'&';
 4299:         }
 4300:     }
 4301:     $items=~s/\&$//;
 4302:     if ($critical) {
 4303: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4304:     } else {
 4305: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4306:     }
 4307: }
 4308: 
 4309: # --------------------------------------------------------------- put interface
 4310: 
 4311: sub put {
 4312:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4313:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4314:    if (!$uname) { $uname=$env{'user.name'}; }
 4315:    my $uhome=&homeserver($uname,$udomain);
 4316:    my $items='';
 4317:    foreach my $item (keys(%$storehash)) {
 4318:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4319:    }
 4320:    $items=~s/\&$//;
 4321:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4322: }
 4323: 
 4324: # ------------------------------------------------------------ newput interface
 4325: 
 4326: sub newput {
 4327:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4328:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4329:    if (!$uname) { $uname=$env{'user.name'}; }
 4330:    my $uhome=&homeserver($uname,$udomain);
 4331:    my $items='';
 4332:    foreach my $key (keys(%$storehash)) {
 4333:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4334:    }
 4335:    $items=~s/\&$//;
 4336:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4337: }
 4338: 
 4339: # ---------------------------------------------------------  putstore interface
 4340: 
 4341: sub putstore {
 4342:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4343:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4344:    if (!$uname) { $uname=$env{'user.name'}; }
 4345:    my $uhome=&homeserver($uname,$udomain);
 4346:    my $items='';
 4347:    foreach my $key (keys(%$storehash)) {
 4348:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4349:    }
 4350:    $items=~s/\&$//;
 4351:    my $esc_symb=&escape($symb);
 4352:    my $esc_v=&escape($version);
 4353:    my $reply =
 4354:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4355: 	      $uhome);
 4356:    if ($reply eq 'unknown_cmd') {
 4357:        # gfall back to way things use to be done
 4358:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4359: 			    $uname);
 4360:    }
 4361:    return $reply;
 4362: }
 4363: 
 4364: sub old_putstore {
 4365:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4366:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4367:     if (!$uname) { $uname=$env{'user.name'}; }
 4368:     my $uhome=&homeserver($uname,$udomain);
 4369:     my %newstorehash;
 4370:     foreach my $item (keys(%$storehash)) {
 4371: 	my $key = $version.':'.&escape($symb).':'.$item;
 4372: 	$newstorehash{$key} = $storehash->{$item};
 4373:     }
 4374:     my $items='';
 4375:     my %allitems = ();
 4376:     foreach my $item (keys(%newstorehash)) {
 4377: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4378: 	    my $key = $1.':keys:'.$2;
 4379: 	    $allitems{$key} .= $3.':';
 4380: 	}
 4381: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4382:     }
 4383:     foreach my $item (keys(%allitems)) {
 4384: 	$allitems{$item} =~ s/\:$//;
 4385: 	$items.= $item.'='.$allitems{$item}.'&';
 4386:     }
 4387:     $items=~s/\&$//;
 4388:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4389: }
 4390: 
 4391: # ------------------------------------------------------ critical put interface
 4392: 
 4393: sub cput {
 4394:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4395:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4396:    if (!$uname) { $uname=$env{'user.name'}; }
 4397:    my $uhome=&homeserver($uname,$udomain);
 4398:    my $items='';
 4399:    foreach my $item (keys(%$storehash)) {
 4400:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4401:    }
 4402:    $items=~s/\&$//;
 4403:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4404: }
 4405: 
 4406: # -------------------------------------------------------------- eget interface
 4407: 
 4408: sub eget {
 4409:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4410:    my $items='';
 4411:    foreach my $item (@$storearr) {
 4412:        $items.=&escape($item).'&';
 4413:    }
 4414:    $items=~s/\&$//;
 4415:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4416:    if (!$uname) { $uname=$env{'user.name'}; }
 4417:    my $uhome=&homeserver($uname,$udomain);
 4418:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4419:    my @pairs=split(/\&/,$rep);
 4420:    my %returnhash=();
 4421:    my $i=0;
 4422:    foreach my $item (@$storearr) {
 4423:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4424:       $i++;
 4425:    }
 4426:    return %returnhash;
 4427: }
 4428: 
 4429: # ------------------------------------------------------------ tmpput interface
 4430: sub tmpput {
 4431:     my ($storehash,$server,$context)=@_;
 4432:     my $items='';
 4433:     foreach my $item (keys(%$storehash)) {
 4434: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4435:     }
 4436:     $items=~s/\&$//;
 4437:     if (defined($context)) {
 4438:         $items .= ':'.&escape($context);
 4439:     }
 4440:     return &reply("tmpput:$items",$server);
 4441: }
 4442: 
 4443: # ------------------------------------------------------------ tmpget interface
 4444: sub tmpget {
 4445:     my ($token,$server)=@_;
 4446:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4447:     my $rep=&reply("tmpget:$token",$server);
 4448:     my %returnhash;
 4449:     foreach my $item (split(/\&/,$rep)) {
 4450: 	my ($key,$value)=split(/=/,$item);
 4451:         next if ($key =~ /^error: 2 /);
 4452: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4453:     }
 4454:     return %returnhash;
 4455: }
 4456: 
 4457: # ------------------------------------------------------------ tmpget interface
 4458: sub tmpdel {
 4459:     my ($token,$server)=@_;
 4460:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4461:     return &reply("tmpdel:$token",$server);
 4462: }
 4463: 
 4464: # -------------------------------------------------- portfolio access checking
 4465: 
 4466: sub portfolio_access {
 4467:     my ($requrl) = @_;
 4468:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4469:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4470:     if ($result) {
 4471:         my %setters;
 4472:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4473:             my ($startblock,$endblock) =
 4474:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4475:             if ($startblock && $endblock) {
 4476:                 return 'B';
 4477:             }
 4478:         } else {
 4479:             my ($startblock,$endblock) =
 4480:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4481:             if ($startblock && $endblock) {
 4482:                 return 'B';
 4483:             }
 4484:         }
 4485:     }
 4486:     if ($result eq 'ok') {
 4487:        return 'F';
 4488:     } elsif ($result =~ /^[^:]+:guest_/) {
 4489:        return 'A';
 4490:     }
 4491:     return '';
 4492: }
 4493: 
 4494: sub get_portfolio_access {
 4495:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4496: 
 4497:     if (!ref($access_hash)) {
 4498: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4499: 	my %access_controls = &get_access_controls($current_perms,$group,
 4500: 						   $file_name);
 4501: 	$access_hash = $access_controls{$file_name};
 4502:     }
 4503: 
 4504:     my ($public,$guest,@domains,@users,@courses,@groups);
 4505:     my $now = time;
 4506:     if (ref($access_hash) eq 'HASH') {
 4507:         foreach my $key (keys(%{$access_hash})) {
 4508:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4509:             if ($start > $now) {
 4510:                 next;
 4511:             }
 4512:             if ($end && $end<$now) {
 4513:                 next;
 4514:             }
 4515:             if ($scope eq 'public') {
 4516:                 $public = $key;
 4517:                 last;
 4518:             } elsif ($scope eq 'guest') {
 4519:                 $guest = $key;
 4520:             } elsif ($scope eq 'domains') {
 4521:                 push(@domains,$key);
 4522:             } elsif ($scope eq 'users') {
 4523:                 push(@users,$key);
 4524:             } elsif ($scope eq 'course') {
 4525:                 push(@courses,$key);
 4526:             } elsif ($scope eq 'group') {
 4527:                 push(@groups,$key);
 4528:             }
 4529:         }
 4530:         if ($public) {
 4531:             return 'ok';
 4532:         }
 4533:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4534:             if ($guest) {
 4535:                 return $guest;
 4536:             }
 4537:         } else {
 4538:             if (@domains > 0) {
 4539:                 foreach my $domkey (@domains) {
 4540:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4541:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4542:                             return 'ok';
 4543:                         }
 4544:                     }
 4545:                 }
 4546:             }
 4547:             if (@users > 0) {
 4548:                 foreach my $userkey (@users) {
 4549:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4550:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4551:                             if (ref($item) eq 'HASH') {
 4552:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4553:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4554:                                     return 'ok';
 4555:                                 }
 4556:                             }
 4557:                         }
 4558:                     } 
 4559:                 }
 4560:             }
 4561:             my %roleshash;
 4562:             my @courses_and_groups = @courses;
 4563:             push(@courses_and_groups,@groups); 
 4564:             if (@courses_and_groups > 0) {
 4565:                 my (%allgroups,%allroles); 
 4566:                 my ($start,$end,$role,$sec,$group);
 4567:                 foreach my $envkey (%env) {
 4568:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4569:                         my $cid = $2.'_'.$3; 
 4570:                         if ($1 eq 'gr') {
 4571:                             $group = $4;
 4572:                             $allgroups{$cid}{$group} = $env{$envkey};
 4573:                         } else {
 4574:                             if ($4 eq '') {
 4575:                                 $sec = 'none';
 4576:                             } else {
 4577:                                 $sec = $4;
 4578:                             }
 4579:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4580:                         }
 4581:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4582:                         my $cid = $2.'_'.$3;
 4583:                         if ($4 eq '') {
 4584:                             $sec = 'none';
 4585:                         } else {
 4586:                             $sec = $4;
 4587:                         }
 4588:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4589:                     }
 4590:                 }
 4591:                 if (keys(%allroles) == 0) {
 4592:                     return;
 4593:                 }
 4594:                 foreach my $key (@courses_and_groups) {
 4595:                     my %content = %{$$access_hash{$key}};
 4596:                     my $cnum = $content{'number'};
 4597:                     my $cdom = $content{'domain'};
 4598:                     my $cid = $cdom.'_'.$cnum;
 4599:                     if (!exists($allroles{$cid})) {
 4600:                         next;
 4601:                     }    
 4602:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4603:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4604:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4605:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4606:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4607:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4608:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4609:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4610:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4611:                                         if (grep/^all$/,@sections) {
 4612:                                             return 'ok';
 4613:                                         } else {
 4614:                                             if (grep/^$sec$/,@sections) {
 4615:                                                 return 'ok';
 4616:                                             }
 4617:                                         }
 4618:                                     }
 4619:                                 }
 4620:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4621:                                     if (grep/^none$/,@groups) {
 4622:                                         return 'ok';
 4623:                                     }
 4624:                                 } else {
 4625:                                     if (grep/^all$/,@groups) {
 4626:                                         return 'ok';
 4627:                                     } 
 4628:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4629:                                         if (grep/^$group$/,@groups) {
 4630:                                             return 'ok';
 4631:                                         }
 4632:                                     }
 4633:                                 } 
 4634:                             }
 4635:                         }
 4636:                     }
 4637:                 }
 4638:             }
 4639:             if ($guest) {
 4640:                 return $guest;
 4641:             }
 4642:         }
 4643:     }
 4644:     return;
 4645: }
 4646: 
 4647: sub course_group_datechecker {
 4648:     my ($dates,$now,$status) = @_;
 4649:     my ($start,$end) = split(/\./,$dates);
 4650:     if (!$start && !$end) {
 4651:         return 'ok';
 4652:     }
 4653:     if (grep/^active$/,@{$status}) {
 4654:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4655:             return 'ok';
 4656:         }
 4657:     }
 4658:     if (grep/^previous$/,@{$status}) {
 4659:         if ($end > $now ) {
 4660:             return 'ok';
 4661:         }
 4662:     }
 4663:     if (grep/^future$/,@{$status}) {
 4664:         if ($start > $now) {
 4665:             return 'ok';
 4666:         }
 4667:     }
 4668:     return; 
 4669: }
 4670: 
 4671: sub parse_portfolio_url {
 4672:     my ($url) = @_;
 4673: 
 4674:     my ($type,$udom,$unum,$group,$file_name);
 4675:     
 4676:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4677: 	$type = 1;
 4678:         $udom = $1;
 4679:         $unum = $2;
 4680:         $file_name = $3;
 4681:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4682: 	$type = 2;
 4683:         $udom = $1;
 4684:         $unum = $2;
 4685:         $group = $3;
 4686:         $file_name = $3.'/'.$4;
 4687:     }
 4688:     if (wantarray) {
 4689: 	return ($type,$udom,$unum,$file_name,$group);
 4690:     }
 4691:     return $type;
 4692: }
 4693: 
 4694: sub is_portfolio_url {
 4695:     my ($url) = @_;
 4696:     return scalar(&parse_portfolio_url($url));
 4697: }
 4698: 
 4699: sub is_portfolio_file {
 4700:     my ($file) = @_;
 4701:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4702:         return 1;
 4703:     }
 4704:     return;
 4705: }
 4706: 
 4707: sub usertools_access {
 4708:     my ($uname,$udom,$tool,$action,$context) = @_;
 4709:     my ($access,%tools);
 4710:     if ($context eq '') {
 4711:         $context = 'tools';
 4712:     }
 4713:     if ($context eq 'requestcourses') {
 4714:         %tools = (
 4715:                       official   => 1,
 4716:                       unofficial => 1,
 4717:                       community  => 1,
 4718:                  );
 4719:     } else {
 4720:         %tools = (
 4721:                       aboutme   => 1,
 4722:                       blog      => 1,
 4723:                       portfolio => 1,
 4724:                  );
 4725:     }
 4726:     return if (!defined($tools{$tool}));
 4727: 
 4728:     if ((!defined($udom)) || (!defined($uname))) {
 4729:         $udom = $env{'user.domain'};
 4730:         $uname = $env{'user.name'};
 4731:     }
 4732: 
 4733:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4734:         if ($action ne 'reload') {
 4735:             if ($context eq 'requestcourses') {
 4736:                 return $env{'environment.canrequest.'.$tool};
 4737:             } else {
 4738:                 return $env{'environment.availabletools.'.$tool};
 4739:             }
 4740:         }
 4741:     }
 4742: 
 4743:     my ($toolstatus,$inststatus);
 4744: 
 4745:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4746:          ($action ne 'reload')) {
 4747:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4748:         $inststatus = $env{'environment.inststatus'};
 4749:     } else {
 4750:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 4751:         $toolstatus = $userenv{$context.'.'.$tool};
 4752:         $inststatus = $userenv{'inststatus'};
 4753:     }
 4754: 
 4755:     if ($toolstatus ne '') {
 4756:         if ($toolstatus) {
 4757:             $access = 1;
 4758:         } else {
 4759:             $access = 0;
 4760:         }
 4761:         return $access;
 4762:     }
 4763: 
 4764:     my $is_adv = &is_advanced_user($udom,$uname);
 4765:     my %domdef = &get_domain_defaults($udom);
 4766:     if (ref($domdef{$tool}) eq 'HASH') {
 4767:         if ($is_adv) {
 4768:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4769:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4770:                     $access = 1;
 4771:                 } else {
 4772:                     $access = 0;
 4773:                 }
 4774:                 return $access;
 4775:             }
 4776:         }
 4777:         if ($inststatus ne '') {
 4778:             my ($hasaccess,$hasnoaccess);
 4779:             foreach my $affiliation (split(/:/,$inststatus)) {
 4780:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4781:                     if ($domdef{$tool}{$affiliation}) {
 4782:                         $hasaccess = 1;
 4783:                     } else {
 4784:                         $hasnoaccess = 1;
 4785:                     }
 4786:                 }
 4787:             }
 4788:             if ($hasaccess || $hasnoaccess) {
 4789:                 if ($hasaccess) {
 4790:                     $access = 1;
 4791:                 } elsif ($hasnoaccess) {
 4792:                     $access = 0; 
 4793:                 }
 4794:                 return $access;
 4795:             }
 4796:         } else {
 4797:             if ($domdef{$tool}{'default'} ne '') {
 4798:                 if ($domdef{$tool}{'default'}) {
 4799:                     $access = 1;
 4800:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4801:                     $access = 0;
 4802:                 }
 4803:                 return $access;
 4804:             }
 4805:         }
 4806:     } else {
 4807:         if ($context eq 'tools') {
 4808:             $access = 1;
 4809:         } else {
 4810:             $access = 0;
 4811:         }
 4812:         return $access;
 4813:     }
 4814: }
 4815: 
 4816: sub is_course_owner {
 4817:     my ($cdom,$cnum,$udom,$uname) = @_;
 4818:     if (($udom eq '') || ($uname eq '')) {
 4819:         $udom = $env{'user.domain'};
 4820:         $uname = $env{'user.name'};
 4821:     }
 4822:     unless (($udom eq '') || ($uname eq '')) {
 4823:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 4824:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 4825:                 return 1;
 4826:             } else {
 4827:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 4828:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 4829:                     return 1;
 4830:                 }
 4831:             }
 4832:         }
 4833:     }
 4834:     return;
 4835: }
 4836: 
 4837: sub is_advanced_user {
 4838:     my ($udom,$uname) = @_;
 4839:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4840:     my %allroles;
 4841:     my $is_adv;
 4842:     foreach my $role (keys(%roleshash)) {
 4843:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4844:         my $area = '/'.$tdomain.'/'.$trest;
 4845:         if ($sec ne '') {
 4846:             $area .= '/'.$sec;
 4847:         }
 4848:         if (($area ne '') && ($trole ne '')) {
 4849:             my $spec=$trole.'.'.$area;
 4850:             if ($trole =~ /^cr\//) {
 4851:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4852:             } elsif ($trole ne 'gr') {
 4853:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4854:             }
 4855:         }
 4856:     }
 4857:     foreach my $role (keys(%allroles)) {
 4858:         last if ($is_adv);
 4859:         foreach my $item (split(/:/,$allroles{$role})) {
 4860:             if ($item ne '') {
 4861:                 my ($privilege,$restrictions)=split(/&/,$item);
 4862:                 if ($privilege eq 'adv') {
 4863:                     $is_adv = 1;
 4864:                     last;
 4865:                 }
 4866:             }
 4867:         }
 4868:     }
 4869:     return $is_adv;
 4870: }
 4871: 
 4872: sub check_can_request {
 4873:     my ($dom,$can_request,$request_domains) = @_;
 4874:     my $canreq = 0;
 4875:     my ($types,$typename) = &Apache::loncommon::course_types();
 4876:     my @options = ('approval','validate','autolimit');
 4877:     my $optregex = join('|',@options);
 4878:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 4879:         foreach my $type (@{$types}) {
 4880:             if (&usertools_access($env{'user.name'},
 4881:                                   $env{'user.domain'},
 4882:                                   $type,undef,'requestcourses')) {
 4883:                 $canreq ++;
 4884:                 if (ref($request_domains) eq 'HASH') {
 4885:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 4886:                 }
 4887:                 if ($dom eq $env{'user.domain'}) {
 4888:                     $can_request->{$type} = 1;
 4889:                 }
 4890:             }
 4891:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 4892:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 4893:                 if (@curr > 0) {
 4894:                     foreach my $item (@curr) {
 4895:                         if (ref($request_domains) eq 'HASH') {
 4896:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 4897:                             if ($otherdom ne '') {
 4898:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 4899:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 4900:                                         push(@{$request_domains->{$type}},$otherdom);
 4901:                                     }
 4902:                                 } else {
 4903:                                     push(@{$request_domains->{$type}},$otherdom);
 4904:                                 }
 4905:                             }
 4906:                         }
 4907:                     }
 4908:                     unless($dom eq $env{'user.domain'}) {
 4909:                         $canreq ++;
 4910:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 4911:                             $can_request->{$type} = 1;
 4912:                         }
 4913:                     }
 4914:                 }
 4915:             }
 4916:         }
 4917:     }
 4918:     return $canreq;
 4919: }
 4920: 
 4921: # ---------------------------------------------- Custom access rule evaluation
 4922: 
 4923: sub customaccess {
 4924:     my ($priv,$uri)=@_;
 4925:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4926:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4927:     $udom = &LONCAPA::clean_domain($udom);
 4928:     $ucrs = &LONCAPA::clean_username($ucrs);
 4929:     my $access=0;
 4930:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4931: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4932: 	if ($type eq 'user') {
 4933: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4934: 		my ($tdom,$tuname)=split(m{/},$scope);
 4935: 		if ($tdom) {
 4936: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4937: 		}
 4938: 		if ($tuname) {
 4939: 		    if ($tuname ne $env{'user.name'}) { next; }
 4940: 		}
 4941: 		$access=($effect eq 'allow');
 4942: 		last;
 4943: 	    }
 4944: 	} else {
 4945: 	    if ($role) {
 4946: 		if ($role ne $urole) { next; }
 4947: 	    }
 4948: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4949: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4950: 		if ($tdom) {
 4951: 		    if ($tdom ne $udom) { next; }
 4952: 		}
 4953: 		if ($tcrs) {
 4954: 		    if ($tcrs ne $ucrs) { next; }
 4955: 		}
 4956: 		if ($tsec) {
 4957: 		    if ($tsec ne $usec) { next; }
 4958: 		}
 4959: 		$access=($effect eq 'allow');
 4960: 		last;
 4961: 	    }
 4962: 	    if ($realm eq '' && $role eq '') {
 4963: 		$access=($effect eq 'allow');
 4964: 	    }
 4965: 	}
 4966:     }
 4967:     return $access;
 4968: }
 4969: 
 4970: # ------------------------------------------------- Check for a user privilege
 4971: 
 4972: sub allowed {
 4973:     my ($priv,$uri,$symb,$role)=@_;
 4974:     my $ver_orguri=$uri;
 4975:     $uri=&deversion($uri);
 4976:     my $orguri=$uri;
 4977:     $uri=&declutter($uri);
 4978: 
 4979:     if ($priv eq 'evb') {
 4980: # Evade communication block restrictions for specified role in a course
 4981:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4982:             return $1;
 4983:         } else {
 4984:             return;
 4985:         }
 4986:     }
 4987: 
 4988:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4989: # Free bre access to adm and meta resources
 4990:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4991: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4992: 	&& ($priv eq 'bre')) {
 4993: 	return 'F';
 4994:     }
 4995: 
 4996: # Free bre access to user's own portfolio contents
 4997:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4998:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4999: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5000:         my %setters;
 5001:         my ($startblock,$endblock) = 
 5002:             &Apache::loncommon::blockcheck(\%setters,'port');
 5003:         if ($startblock && $endblock) {
 5004:             return 'B';
 5005:         } else {
 5006:             return 'F';
 5007:         }
 5008:     }
 5009: 
 5010: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5011:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5012:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5013:         if (exists($env{'request.course.id'})) {
 5014:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5015:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5016:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5017:                 my $courseprivid=$env{'request.course.id'};
 5018:                 $courseprivid=~s/\_/\//;
 5019:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5020:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5021:                     return $1; 
 5022:                 } else {
 5023:                     if ($env{'request.course.sec'}) {
 5024:                         $courseprivid.='/'.$env{'request.course.sec'};
 5025:                     }
 5026:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5027:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5028:                         return $2;
 5029:                     }
 5030:                 }
 5031:             }
 5032:         }
 5033:     }
 5034: 
 5035: # Free bre to public access
 5036: 
 5037:     if ($priv eq 'bre') {
 5038:         my $copyright=&metadata($uri,'copyright');
 5039: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5040:            return 'F'; 
 5041:         }
 5042:         if ($copyright eq 'priv') {
 5043:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5044: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5045: 		return '';
 5046:             }
 5047:         }
 5048:         if ($copyright eq 'domain') {
 5049:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5050: 	    unless (($env{'user.domain'} eq $1) ||
 5051:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5052: 		return '';
 5053:             }
 5054:         }
 5055:         if ($env{'request.role'}=~ /li\.\//) {
 5056:             # Library role, so allow browsing of resources in this domain.
 5057:             return 'F';
 5058:         }
 5059:         if ($copyright eq 'custom') {
 5060: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5061:         }
 5062:     }
 5063:     # Domain coordinator is trying to create a course
 5064:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5065:         # uri is the requested domain in this case.
 5066:         # comparison to 'request.role.domain' shows if the user has selected
 5067:         # a role of dc for the domain in question.
 5068:         return 'F' if ($uri eq $env{'request.role.domain'});
 5069:     }
 5070: 
 5071:     my $thisallowed='';
 5072:     my $statecond=0;
 5073:     my $courseprivid='';
 5074: 
 5075:     my $ownaccess;
 5076:     # Community Coordinator or Assistant Co-author browsing resource space.
 5077:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5078:         if ($uri eq '') {
 5079:             $ownaccess = 1;
 5080:         } else {
 5081:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5082:                 my $udom = $env{'user.domain'};
 5083:                 my $uname = $env{'user.name'};
 5084:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5085:                     $ownaccess = 1;
 5086:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5087:                     unless ($uri =~ m{\.\./}) {
 5088:                         $ownaccess = 1;
 5089:                     }
 5090:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5091:                     my $now = time;
 5092:                     if ($uri =~ m{^([^/]+)/?$}) {
 5093:                         my $adom = $1;
 5094:                         foreach my $key (keys(%env)) {
 5095:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5096:                                 my ($start,$end) = split('.',$env{$key});
 5097:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5098:                                     $ownaccess = 1;
 5099:                                     last;
 5100:                                 }
 5101:                             }
 5102:                         }
 5103:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5104:                         my $adom = $1;
 5105:                         my $aname = $2;
 5106:                         foreach my $role ('ca','aa') { 
 5107:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5108:                                 my ($start,$end) =
 5109:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5110:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5111:                                     $ownaccess = 1;
 5112:                                     last;
 5113:                                 }
 5114:                             }
 5115:                         }
 5116:                     }
 5117:                 }
 5118:             }
 5119:         }
 5120:     }
 5121: 
 5122: # Course
 5123: 
 5124:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5125:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5126:             $thisallowed.=$1;
 5127:         }
 5128:     }
 5129: 
 5130: # Domain
 5131: 
 5132:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5133:        =~/\Q$priv\E\&([^\:]*)/) {
 5134:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5135:             $thisallowed.=$1;
 5136:         }
 5137:     }
 5138: 
 5139: # Course: uri itself is a course
 5140:     my $courseuri=$uri;
 5141:     $courseuri=~s/\_(\d)/\/$1/;
 5142:     $courseuri=~s/^([^\/])/\/$1/;
 5143: 
 5144:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5145:        =~/\Q$priv\E\&([^\:]*)/) {
 5146:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5147:             $thisallowed.=$1;
 5148:         }
 5149:     }
 5150: 
 5151: # URI is an uploaded document for this course, default permissions don't matter
 5152: # not allowing 'edit' access (editupload) to uploaded course docs
 5153:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5154: 	$thisallowed='';
 5155:         my ($match)=&is_on_map($uri);
 5156:         if ($match) {
 5157:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5158:                   =~/\Q$priv\E\&([^\:]*)/) {
 5159:                 $thisallowed.=$1;
 5160:             }
 5161:         } else {
 5162:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5163:             if ($refuri) {
 5164:                 if ($refuri =~ m|^/adm/|) {
 5165:                     $thisallowed='F';
 5166:                 } else {
 5167:                     $refuri=&declutter($refuri);
 5168:                     my ($match) = &is_on_map($refuri);
 5169:                     if ($match) {
 5170:                         $thisallowed='F';
 5171:                     }
 5172:                 }
 5173:             }
 5174:         }
 5175:     }
 5176: 
 5177:     if ($priv eq 'bre'
 5178: 	&& $thisallowed ne 'F' 
 5179: 	&& $thisallowed ne '2'
 5180: 	&& &is_portfolio_url($uri)) {
 5181: 	$thisallowed = &portfolio_access($uri);
 5182:     }
 5183:     
 5184: # Full access at system, domain or course-wide level? Exit.
 5185:     if ($thisallowed=~/F/) {
 5186: 	return 'F';
 5187:     }
 5188: 
 5189: # If this is generating or modifying users, exit with special codes
 5190: 
 5191:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5192: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5193: 	    my ($audom,$auname)=split('/',$uri);
 5194: # no author name given, so this just checks on the general right to make a co-author in this domain
 5195: 	    unless ($auname) { return $thisallowed; }
 5196: # an author name is given, so we are about to actually make a co-author for a certain account
 5197: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5198: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5199: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5200: 	}
 5201: 	return $thisallowed;
 5202:     }
 5203: #
 5204: # Gathered so far: system, domain and course wide privileges
 5205: #
 5206: # Course: See if uri or referer is an individual resource that is part of 
 5207: # the course
 5208: 
 5209:     if ($env{'request.course.id'}) {
 5210: 
 5211:        $courseprivid=$env{'request.course.id'};
 5212:        if ($env{'request.course.sec'}) {
 5213:           $courseprivid.='/'.$env{'request.course.sec'};
 5214:        }
 5215:        $courseprivid=~s/\_/\//;
 5216:        my $checkreferer=1;
 5217:        my ($match,$cond)=&is_on_map($uri);
 5218:        if ($match) {
 5219:            $statecond=$cond;
 5220:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5221:                =~/\Q$priv\E\&([^\:]*)/) {
 5222:                $thisallowed.=$1;
 5223:                $checkreferer=0;
 5224:            }
 5225:        }
 5226:        
 5227:        if ($checkreferer) {
 5228: 	  my $refuri=$env{'httpref.'.$orguri};
 5229:             unless ($refuri) {
 5230:                 foreach my $key (keys(%env)) {
 5231: 		    if ($key=~/^httpref\..*\*/) {
 5232: 			my $pattern=$key;
 5233:                         $pattern=~s/^httpref\.\/res\///;
 5234:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5235:                         $pattern=~s/\//\\\//g;
 5236:                         if ($orguri=~/$pattern/) {
 5237: 			    $refuri=$env{$key};
 5238:                         }
 5239:                     }
 5240:                 }
 5241:             }
 5242: 
 5243:          if ($refuri) { 
 5244: 	  $refuri=&declutter($refuri);
 5245:           my ($match,$cond)=&is_on_map($refuri);
 5246:             if ($match) {
 5247:               my $refstatecond=$cond;
 5248:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5249:                   =~/\Q$priv\E\&([^\:]*)/) {
 5250:                   $thisallowed.=$1;
 5251:                   $uri=$refuri;
 5252:                   $statecond=$refstatecond;
 5253:               }
 5254:           }
 5255:         }
 5256:        }
 5257:    }
 5258: 
 5259: #
 5260: # Gathered now: all privileges that could apply, and condition number
 5261: # 
 5262: #
 5263: # Full or no access?
 5264: #
 5265: 
 5266:     if ($thisallowed=~/F/) {
 5267: 	return 'F';
 5268:     }
 5269: 
 5270:     unless ($thisallowed) {
 5271:         return '';
 5272:     }
 5273: 
 5274: # Restrictions exist, deal with them
 5275: #
 5276: #   C:according to course preferences
 5277: #   R:according to resource settings
 5278: #   L:unless locked
 5279: #   X:according to user session state
 5280: #
 5281: 
 5282: # Possibly locked functionality, check all courses
 5283: # Locks might take effect only after 10 minutes cache expiration for other
 5284: # courses, and 2 minutes for current course
 5285: 
 5286:     my $envkey;
 5287:     if ($thisallowed=~/L/) {
 5288:         foreach $envkey (keys(%env)) {
 5289:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5290:                my $courseid=$2;
 5291:                my $roleid=$1.'.'.$2;
 5292:                $courseid=~s/^\///;
 5293:                my $expiretime=600;
 5294:                if ($env{'request.role'} eq $roleid) {
 5295: 		  $expiretime=120;
 5296:                }
 5297: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5298:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5299:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5300: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5301:                }
 5302:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5303:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5304: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5305:                        &log($env{'user.domain'},$env{'user.name'},
 5306:                             $env{'user.home'},
 5307:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5308:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5309:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5310: 		       return '';
 5311:                    }
 5312:                }
 5313:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5314:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5315: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5316:                        &log($env{'user.domain'},$env{'user.name'},
 5317:                             $env{'user.home'},
 5318:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5319:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5320:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5321: 		       return '';
 5322:                    }
 5323:                }
 5324: 	   }
 5325:        }
 5326:     }
 5327:    
 5328: #
 5329: # Rest of the restrictions depend on selected course
 5330: #
 5331: 
 5332:     unless ($env{'request.course.id'}) {
 5333: 	if ($thisallowed eq 'A') {
 5334: 	    return 'A';
 5335:         } elsif ($thisallowed eq 'B') {
 5336:             return 'B';
 5337: 	} else {
 5338: 	    return '1';
 5339: 	}
 5340:     }
 5341: 
 5342: #
 5343: # Now user is definitely in a course
 5344: #
 5345: 
 5346: 
 5347: # Course preferences
 5348: 
 5349:    if ($thisallowed=~/C/) {
 5350:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5351:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5352:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5353: 	   =~/\Q$rolecode\E/) {
 5354: 	   if ($priv ne 'pch') { 
 5355: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5356: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5357: 			$env{'request.course.id'});
 5358: 	   }
 5359:            return '';
 5360:        }
 5361: 
 5362:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5363: 	   =~/\Q$unamedom\E/) {
 5364: 	   if ($priv ne 'pch') { 
 5365: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5366: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5367: 			$env{'request.course.id'});
 5368: 	   }
 5369:            return '';
 5370:        }
 5371:    }
 5372: 
 5373: # Resource preferences
 5374: 
 5375:    if ($thisallowed=~/R/) {
 5376:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5377:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5378: 	   if ($priv ne 'pch') { 
 5379: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5380: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5381: 	   }
 5382: 	   return '';
 5383:        }
 5384:    }
 5385: 
 5386: # Restricted by state or randomout?
 5387: 
 5388:    if ($thisallowed=~/X/) {
 5389:       if ($env{'acc.randomout'}) {
 5390: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5391:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5392:             return ''; 
 5393:          }
 5394:       }
 5395:       if (&condval($statecond)) {
 5396: 	 return '2';
 5397:       } else {
 5398:          return '';
 5399:       }
 5400:    }
 5401: 
 5402:     if ($thisallowed eq 'A') {
 5403: 	return 'A';
 5404:     } elsif ($thisallowed eq 'B') {
 5405:         return 'B';
 5406:     }
 5407:    return 'F';
 5408: }
 5409: 
 5410: sub split_uri_for_cond {
 5411:     my $uri=&deversion(&declutter(shift));
 5412:     my @uriparts=split(/\//,$uri);
 5413:     my $filename=pop(@uriparts);
 5414:     my $pathname=join('/',@uriparts);
 5415:     return ($pathname,$filename);
 5416: }
 5417: # --------------------------------------------------- Is a resource on the map?
 5418: 
 5419: sub is_on_map {
 5420:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5421:     #Trying to find the conditional for the file
 5422:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5423: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5424:     if ($match) {
 5425: 	return (1,$1);
 5426:     } else {
 5427: 	return (0,0);
 5428:     }
 5429: }
 5430: 
 5431: # --------------------------------------------------------- Get symb from alias
 5432: 
 5433: sub get_symb_from_alias {
 5434:     my $symb=shift;
 5435:     my ($map,$resid,$url)=&decode_symb($symb);
 5436: # Already is a symb
 5437:     if ($url) { return $symb; }
 5438: # Must be an alias
 5439:     my $aliassymb='';
 5440:     my %bighash;
 5441:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5442:                             &GDBM_READER(),0640)) {
 5443:         my $rid=$bighash{'mapalias_'.$symb};
 5444: 	if ($rid) {
 5445: 	    my ($mapid,$resid)=split(/\./,$rid);
 5446: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5447: 				    $resid,$bighash{'src_'.$rid});
 5448: 	}
 5449:         untie %bighash;
 5450:     }
 5451:     return $aliassymb;
 5452: }
 5453: 
 5454: # ----------------------------------------------------------------- Define Role
 5455: 
 5456: sub definerole {
 5457:   if (allowed('mcr','/')) {
 5458:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5459:     foreach my $role (split(':',$sysrole)) {
 5460: 	my ($crole,$cqual)=split(/\&/,$role);
 5461:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5462:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5463: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5464:                return "refused:s:$crole&$cqual"; 
 5465:             }
 5466:         }
 5467:     }
 5468:     foreach my $role (split(':',$domrole)) {
 5469: 	my ($crole,$cqual)=split(/\&/,$role);
 5470:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5471:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5472: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5473:                return "refused:d:$crole&$cqual"; 
 5474:             }
 5475:         }
 5476:     }
 5477:     foreach my $role (split(':',$courole)) {
 5478: 	my ($crole,$cqual)=split(/\&/,$role);
 5479:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5480:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5481: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5482:                return "refused:c:$crole&$cqual"; 
 5483:             }
 5484:         }
 5485:     }
 5486:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5487:                 "$env{'user.domain'}:$env{'user.name'}:".
 5488: 	        "rolesdef_$rolename=".
 5489:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5490:     return reply($command,$env{'user.home'});
 5491:   } else {
 5492:     return 'refused';
 5493:   }
 5494: }
 5495: 
 5496: # ---------------- Make a metadata query against the network of library servers
 5497: 
 5498: sub metadata_query {
 5499:     my ($query,$custom,$customshow,$server_array)=@_;
 5500:     my %rhash;
 5501:     my %libserv = &all_library();
 5502:     my @server_list = (defined($server_array) ? @$server_array
 5503:                                               : keys(%libserv) );
 5504:     for my $server (@server_list) {
 5505: 	unless ($custom or $customshow) {
 5506: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5507: 	    $rhash{$server}=$reply;
 5508: 	}
 5509: 	else {
 5510: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5511: 			     &escape($custom).':'.&escape($customshow),
 5512: 			     $server);
 5513: 	    $rhash{$server}=$reply;
 5514: 	}
 5515:     }
 5516:     return \%rhash;
 5517: }
 5518: 
 5519: # ----------------------------------------- Send log queries and wait for reply
 5520: 
 5521: sub log_query {
 5522:     my ($uname,$udom,$query,%filters)=@_;
 5523:     my $uhome=&homeserver($uname,$udom);
 5524:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5525:     my $uhost=&hostname($uhome);
 5526:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5527:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5528:                        $uhome);
 5529:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5530:     return get_query_reply($queryid);
 5531: }
 5532: 
 5533: # -------------------------- Update MySQL table for portfolio file
 5534: 
 5535: sub update_portfolio_table {
 5536:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5537:     if ($group ne '') {
 5538:         $file_name =~s /^\Q$group\E//;
 5539:     }
 5540:     my $homeserver = &homeserver($uname,$udom);
 5541:     my $queryid=
 5542:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5543:                ':'.&escape($file_name).':'.$action,$homeserver);
 5544:     my $reply = &get_query_reply($queryid);
 5545:     return $reply;
 5546: }
 5547: 
 5548: # -------------------------- Update MySQL allusers table
 5549: 
 5550: sub update_allusers_table {
 5551:     my ($uname,$udom,$names) = @_;
 5552:     my $homeserver = &homeserver($uname,$udom);
 5553:     my $queryid=
 5554:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5555:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5556:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5557:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5558:                'generation='.&escape($names->{'generation'}).'%%'.
 5559:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5560:                'id='.&escape($names->{'id'}),$homeserver);
 5561:     my $reply = &get_query_reply($queryid);
 5562:     return $reply;
 5563: }
 5564: 
 5565: # ------- Request retrieval of institutional classlists for course(s)
 5566: 
 5567: sub fetch_enrollment_query {
 5568:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5569:     my $homeserver;
 5570:     my $maxtries = 1;
 5571:     if ($context eq 'automated') {
 5572:         $homeserver = $perlvar{'lonHostID'};
 5573:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5574:     } else {
 5575:         $homeserver = &homeserver($cnum,$dom);
 5576:     }
 5577:     my $host=&hostname($homeserver);
 5578:     my $cmd = '';
 5579:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5580:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5581:     }
 5582:     $cmd =~ s/%%$//;
 5583:     $cmd = &escape($cmd);
 5584:     my $query = 'fetchenrollment';
 5585:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5586:     unless ($queryid=~/^\Q$host\E\_/) { 
 5587:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5588:         return 'error: '.$queryid;
 5589:     }
 5590:     my $reply = &get_query_reply($queryid);
 5591:     my $tries = 1;
 5592:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5593:         $reply = &get_query_reply($queryid);
 5594:         $tries ++;
 5595:     }
 5596:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5597:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5598:     } else {
 5599:         my @responses = split(/:/,$reply);
 5600:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5601:             foreach my $line (@responses) {
 5602:                 my ($key,$value) = split(/=/,$line,2);
 5603:                 $$replyref{$key} = $value;
 5604:             }
 5605:         } else {
 5606:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5607:             foreach my $line (@responses) {
 5608:                 my ($key,$value) = split(/=/,$line);
 5609:                 $$replyref{$key} = $value;
 5610:                 if ($value > 0) {
 5611:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5612:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5613:                         my $destname = $pathname.'/'.$filename;
 5614:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5615:                         if ($xml_classlist =~ /^error/) {
 5616:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5617:                         } else {
 5618:                             if ( open(FILE,">$destname") ) {
 5619:                                 print FILE &unescape($xml_classlist);
 5620:                                 close(FILE);
 5621:                             } else {
 5622:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5623:                             }
 5624:                         }
 5625:                     }
 5626:                 }
 5627:             }
 5628:         }
 5629:         return 'ok';
 5630:     }
 5631:     return 'error';
 5632: }
 5633: 
 5634: sub get_query_reply {
 5635:     my $queryid=shift;
 5636:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5637:     my $reply='';
 5638:     for (1..100) {
 5639: 	sleep 2;
 5640:         if (-e $replyfile.'.end') {
 5641: 	    if (open(my $fh,$replyfile)) {
 5642: 		$reply = join('',<$fh>);
 5643: 		close($fh);
 5644: 	   } else { return 'error: reply_file_error'; }
 5645:            return &unescape($reply);
 5646: 	}
 5647:     }
 5648:     return 'timeout:'.$queryid;
 5649: }
 5650: 
 5651: sub courselog_query {
 5652: #
 5653: # possible filters:
 5654: # url: url or symb
 5655: # username
 5656: # domain
 5657: # action: view, submit, grade
 5658: # start: timestamp
 5659: # end: timestamp
 5660: #
 5661:     my (%filters)=@_;
 5662:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5663:     if ($filters{'url'}) {
 5664: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5665:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5666:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5667:     }
 5668:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5669:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5670:     return &log_query($cname,$cdom,'courselog',%filters);
 5671: }
 5672: 
 5673: sub userlog_query {
 5674: #
 5675: # possible filters:
 5676: # action: log check role
 5677: # start: timestamp
 5678: # end: timestamp
 5679: #
 5680:     my ($uname,$udom,%filters)=@_;
 5681:     return &log_query($uname,$udom,'userlog',%filters);
 5682: }
 5683: 
 5684: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5685: 
 5686: sub auto_run {
 5687:     my ($cnum,$cdom) = @_;
 5688:     my $response = 0;
 5689:     my $settings;
 5690:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5691:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5692:         $settings = $domconfig{'autoenroll'};
 5693:         if ($settings->{'run'} eq '1') {
 5694:             $response = 1;
 5695:         }
 5696:     } else {
 5697:         my $homeserver;
 5698:         if (&is_course($cdom,$cnum)) {
 5699:             $homeserver = &homeserver($cnum,$cdom);
 5700:         } else {
 5701:             $homeserver = &domain($cdom,'primary');
 5702:         }
 5703:         if ($homeserver ne 'no_host') {
 5704:             $response = &reply('autorun:'.$cdom,$homeserver);
 5705:         }
 5706:     }
 5707:     return $response;
 5708: }
 5709: 
 5710: sub auto_get_sections {
 5711:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5712:     my $homeserver;
 5713:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5714:         $homeserver = &homeserver($cnum,$cdom);
 5715:     }
 5716:     if (!defined($homeserver)) { 
 5717:         if ($cdom =~ /^$match_domain$/) {
 5718:             $homeserver = &domain($cdom,'primary');
 5719:         }
 5720:     }
 5721:     my @secs;
 5722:     if (defined($homeserver)) {
 5723:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5724:         unless ($response eq 'refused') {
 5725:             @secs = split(/:/,$response);
 5726:         }
 5727:     }
 5728:     return @secs;
 5729: }
 5730: 
 5731: sub auto_new_course {
 5732:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5733:     my $homeserver = &homeserver($cnum,$cdom);
 5734:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5735:     return $response;
 5736: }
 5737: 
 5738: sub auto_validate_courseID {
 5739:     my ($cnum,$cdom,$inst_course_id) = @_;
 5740:     my $homeserver = &homeserver($cnum,$cdom);
 5741:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5742:     return $response;
 5743: }
 5744: 
 5745: sub auto_validate_instcode {
 5746:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5747:     my ($homeserver,$response);
 5748:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5749:         $homeserver = &homeserver($cnum,$cdom);
 5750:     }
 5751:     if (!defined($homeserver)) {
 5752:         if ($cdom =~ /^$match_domain$/) {
 5753:             $homeserver = &domain($cdom,'primary');
 5754:         }
 5755:     }
 5756:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5757:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5758:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 5759:     return ($outcome,$description);
 5760: }
 5761: 
 5762: sub auto_create_password {
 5763:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5764:     my ($homeserver,$response);
 5765:     my $create_passwd = 0;
 5766:     my $authchk = '';
 5767:     if ($udom =~ /^$match_domain$/) {
 5768:         $homeserver = &domain($udom,'primary');
 5769:     }
 5770:     if ($homeserver eq '') {
 5771:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5772:             $homeserver = &homeserver($cnum,$cdom);
 5773:         }
 5774:     }
 5775:     if ($homeserver eq '') {
 5776:         $authchk = 'nodomain';
 5777:     } else {
 5778:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5779:         if ($response eq 'refused') {
 5780:             $authchk = 'refused';
 5781:         } else {
 5782:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5783:         }
 5784:     }
 5785:     return ($authparam,$create_passwd,$authchk);
 5786: }
 5787: 
 5788: sub auto_photo_permission {
 5789:     my ($cnum,$cdom,$students) = @_;
 5790:     my $homeserver = &homeserver($cnum,$cdom);
 5791:     my ($outcome,$perm_reqd,$conditions) = 
 5792: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5793:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5794: 	return (undef,undef);
 5795:     }
 5796:     return ($outcome,$perm_reqd,$conditions);
 5797: }
 5798: 
 5799: sub auto_checkphotos {
 5800:     my ($uname,$udom,$pid) = @_;
 5801:     my $homeserver = &homeserver($uname,$udom);
 5802:     my ($result,$resulttype);
 5803:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5804: 				   &escape($uname).':'.&escape($pid),
 5805: 				   $homeserver));
 5806:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5807: 	return (undef,undef);
 5808:     }
 5809:     if ($outcome) {
 5810:         ($result,$resulttype) = split(/:/,$outcome);
 5811:     } 
 5812:     return ($result,$resulttype);
 5813: }
 5814: 
 5815: sub auto_photochoice {
 5816:     my ($cnum,$cdom) = @_;
 5817:     my $homeserver = &homeserver($cnum,$cdom);
 5818:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5819: 						       &escape($cdom),
 5820: 						       $homeserver)));
 5821:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5822: 	return (undef,undef);
 5823:     }
 5824:     return ($update,$comment);
 5825: }
 5826: 
 5827: sub auto_photoupdate {
 5828:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5829:     my $homeserver = &homeserver($cnum,$dom);
 5830:     my $host=&hostname($homeserver);
 5831:     my $cmd = '';
 5832:     my $maxtries = 1;
 5833:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5834:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5835:     }
 5836:     $cmd =~ s/%%$//;
 5837:     $cmd = &escape($cmd);
 5838:     my $query = 'institutionalphotos';
 5839:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5840:     unless ($queryid=~/^\Q$host\E\_/) {
 5841:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5842:         return 'error: '.$queryid;
 5843:     }
 5844:     my $reply = &get_query_reply($queryid);
 5845:     my $tries = 1;
 5846:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5847:         $reply = &get_query_reply($queryid);
 5848:         $tries ++;
 5849:     }
 5850:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5851:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5852:     } else {
 5853:         my @responses = split(/:/,$reply);
 5854:         my $outcome = shift(@responses); 
 5855:         foreach my $item (@responses) {
 5856:             my ($key,$value) = split(/=/,$item);
 5857:             $$photo{$key} = $value;
 5858:         }
 5859:         return $outcome;
 5860:     }
 5861:     return 'error';
 5862: }
 5863: 
 5864: sub auto_instcode_format {
 5865:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5866: 	$cat_order) = @_;
 5867:     my $courses = '';
 5868:     my @homeservers;
 5869:     if ($caller eq 'global') {
 5870: 	my %servers = &get_servers($codedom,'library');
 5871: 	foreach my $tryserver (keys(%servers)) {
 5872: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5873: 		push(@homeservers,$tryserver);
 5874: 	    }
 5875:         }
 5876:     } elsif ($caller eq 'requests') {
 5877:         if ($codedom =~ /^$match_domain$/) {
 5878:             my $chome = &domain($codedom,'primary');
 5879:             unless ($chome eq 'no_host') {
 5880:                 push(@homeservers,$chome);
 5881:             }
 5882:         }
 5883:     } else {
 5884:         push(@homeservers,&homeserver($caller,$codedom));
 5885:     }
 5886:     foreach my $code (keys(%{$instcodes})) {
 5887:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5888:     }
 5889:     chop($courses);
 5890:     my $ok_response = 0;
 5891:     my $response;
 5892:     while (@homeservers > 0 && $ok_response == 0) {
 5893:         my $server = shift(@homeservers); 
 5894:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5895:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5896:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5897: 		split(/:/,$response);
 5898:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5899:             push(@{$codetitles},&str2array($codetitles_str));
 5900:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5901:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5902:             $ok_response = 1;
 5903:         }
 5904:     }
 5905:     if ($ok_response) {
 5906:         return 'ok';
 5907:     } else {
 5908:         return $response;
 5909:     }
 5910: }
 5911: 
 5912: sub auto_instcode_defaults {
 5913:     my ($domain,$returnhash,$code_order) = @_;
 5914:     my @homeservers;
 5915: 
 5916:     my %servers = &get_servers($domain,'library');
 5917:     foreach my $tryserver (keys(%servers)) {
 5918: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5919: 	    push(@homeservers,$tryserver);
 5920: 	}
 5921:     }
 5922: 
 5923:     my $response;
 5924:     foreach my $server (@homeservers) {
 5925:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5926:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5927: 	
 5928: 	foreach my $pair (split(/\&/,$response)) {
 5929: 	    my ($name,$value)=split(/\=/,$pair);
 5930: 	    if ($name eq 'code_order') {
 5931: 		@{$code_order} = split(/\&/,&unescape($value));
 5932: 	    } else {
 5933: 		$returnhash->{&unescape($name)}=&unescape($value);
 5934: 	    }
 5935: 	}
 5936: 	return 'ok';
 5937:     }
 5938: 
 5939:     return $response;
 5940: }
 5941: 
 5942: sub auto_possible_instcodes {
 5943:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 5944:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 5945:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 5946:         return;
 5947:     }
 5948:     my (@homeservers,$uhome);
 5949:     if (defined(&domain($domain,'primary'))) {
 5950:         $uhome=&domain($domain,'primary');
 5951:         push(@homeservers,&domain($domain,'primary'));
 5952:     } else {
 5953:         my %servers = &get_servers($domain,'library');
 5954:         foreach my $tryserver (keys(%servers)) {
 5955:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5956:                 push(@homeservers,$tryserver);
 5957:             }
 5958:         }
 5959:     }
 5960:     my $response;
 5961:     foreach my $server (@homeservers) {
 5962:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 5963:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5964:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 5965:             split(':',$response);
 5966:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 5967:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 5968:         foreach my $item (split('&',$cat_title)) {   
 5969:             my ($name,$value)=split('=',$item);
 5970:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 5971:         }
 5972:         foreach my $item (split('&',$cat_order)) {
 5973:             my ($name,$value)=split('=',$item);
 5974:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 5975:         }
 5976:         return 'ok';
 5977:     }
 5978:     return $response;
 5979: }
 5980: 
 5981: sub auto_courserequest_checks {
 5982:     my ($dom) = @_;
 5983:     my ($homeserver,%validations);
 5984:     if ($dom =~ /^$match_domain$/) {
 5985:         $homeserver = &domain($dom,'primary');
 5986:     }
 5987:     unless ($homeserver eq 'no_host') {
 5988:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 5989:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 5990:             my @items = split(/&/,$response);
 5991:             foreach my $item (@items) {
 5992:                 my ($key,$value) = split('=',$item);
 5993:                 $validations{&unescape($key)} = &thaw_unescape($value);
 5994:             }
 5995:         }
 5996:     }
 5997:     return %validations; 
 5998: }
 5999: 
 6000: sub auto_courserequest_validation {
 6001:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 6002:     my ($homeserver,$response);
 6003:     if ($dom =~ /^$match_domain$/) {
 6004:         $homeserver = &domain($dom,'primary');
 6005:     }
 6006:     unless ($homeserver eq 'no_host') {  
 6007:           
 6008:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 6009:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 6010:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 6011:                                     $homeserver));
 6012:     }
 6013:     return $response;
 6014: }
 6015: 
 6016: sub auto_validate_class_sec {
 6017:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 6018:     my $homeserver = &homeserver($cnum,$cdom);
 6019:     my $ownerlist;
 6020:     if (ref($owners) eq 'ARRAY') {
 6021:         $ownerlist = join(',',@{$owners});
 6022:     } else {
 6023:         $ownerlist = $owners;
 6024:     }
 6025:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6026:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6027:     return $response;
 6028: }
 6029: 
 6030: # ------------------------------------------------------- Course Group routines
 6031: 
 6032: sub get_coursegroups {
 6033:     my ($cdom,$cnum,$group,$namespace) = @_;
 6034:     return(&dump($namespace,$cdom,$cnum,$group));
 6035: }
 6036: 
 6037: sub modify_coursegroup {
 6038:     my ($cdom,$cnum,$groupsettings) = @_;
 6039:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6040: }
 6041: 
 6042: sub toggle_coursegroup_status {
 6043:     my ($cdom,$cnum,$group,$action) = @_;
 6044:     my ($from_namespace,$to_namespace);
 6045:     if ($action eq 'delete') {
 6046:         $from_namespace = 'coursegroups';
 6047:         $to_namespace = 'deleted_groups';
 6048:     } else {
 6049:         $from_namespace = 'deleted_groups';
 6050:         $to_namespace = 'coursegroups';
 6051:     }
 6052:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6053:     if (my $tmp = &error(%curr_group)) {
 6054:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6055:         return ('read error',$tmp);
 6056:     } else {
 6057:         my %savedsettings = %curr_group; 
 6058:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6059:         my $deloutcome;
 6060:         if ($result eq 'ok') {
 6061:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6062:         } else {
 6063:             return ('write error',$result);
 6064:         }
 6065:         if ($deloutcome eq 'ok') {
 6066:             return 'ok';
 6067:         } else {
 6068:             return ('delete error',$deloutcome);
 6069:         }
 6070:     }
 6071: }
 6072: 
 6073: sub modify_group_roles {
 6074:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6075:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6076:     my $role = 'gr/'.&escape($userprivs);
 6077:     my ($uname,$udom) = split(/:/,$user);
 6078:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6079:     if ($result eq 'ok') {
 6080:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6081:     }
 6082:     return $result;
 6083: }
 6084: 
 6085: sub modify_coursegroup_membership {
 6086:     my ($cdom,$cnum,$membership) = @_;
 6087:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6088:     return $result;
 6089: }
 6090: 
 6091: sub get_active_groups {
 6092:     my ($udom,$uname,$cdom,$cnum) = @_;
 6093:     my $now = time;
 6094:     my %groups = ();
 6095:     foreach my $key (keys(%env)) {
 6096:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6097:             my ($start,$end) = split(/\./,$env{$key});
 6098:             if (($end!=0) && ($end<$now)) { next; }
 6099:             if (($start!=0) && ($start>$now)) { next; }
 6100:             if ($1 eq $cdom && $2 eq $cnum) {
 6101:                 $groups{$3} = $env{$key} ;
 6102:             }
 6103:         }
 6104:     }
 6105:     return %groups;
 6106: }
 6107: 
 6108: sub get_group_membership {
 6109:     my ($cdom,$cnum,$group) = @_;
 6110:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6111: }
 6112: 
 6113: sub get_users_groups {
 6114:     my ($udom,$uname,$courseid) = @_;
 6115:     my @usersgroups;
 6116:     my $cachetime=1800;
 6117: 
 6118:     my $hashid="$udom:$uname:$courseid";
 6119:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6120:     if (defined($cached)) {
 6121:         @usersgroups = split(/:/,$grouplist);
 6122:     } else {  
 6123:         $grouplist = '';
 6124:         my $courseurl = &courseid_to_courseurl($courseid);
 6125:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 6126:         my $access_end = $env{'course.'.$courseid.
 6127:                               '.default_enrollment_end_date'};
 6128:         my $now = time;
 6129:         foreach my $key (keys(%roleshash)) {
 6130:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6131:                 my $group = $1;
 6132:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6133:                     my $start = $2;
 6134:                     my $end = $1;
 6135:                     if ($start == -1) { next; } # deleted from group
 6136:                     if (($start!=0) && ($start>$now)) { next; }
 6137:                     if (($end!=0) && ($end<$now)) {
 6138:                         if ($access_end && $access_end < $now) {
 6139:                             if ($access_end - $end < 86400) {
 6140:                                 push(@usersgroups,$group);
 6141:                             }
 6142:                         }
 6143:                         next;
 6144:                     }
 6145:                     push(@usersgroups,$group);
 6146:                 }
 6147:             }
 6148:         }
 6149:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6150:         $grouplist = join(':',@usersgroups);
 6151:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6152:     }
 6153:     return @usersgroups;
 6154: }
 6155: 
 6156: sub devalidate_getgroups_cache {
 6157:     my ($udom,$uname,$cdom,$cnum)=@_;
 6158:     my $courseid = $cdom.'_'.$cnum;
 6159: 
 6160:     my $hashid="$udom:$uname:$courseid";
 6161:     &devalidate_cache_new('getgroups',$hashid);
 6162: }
 6163: 
 6164: # ------------------------------------------------------------------ Plain Text
 6165: 
 6166: sub plaintext {
 6167:     my ($short,$type,$cid,$forcedefault) = @_;
 6168:     if ($short =~ m{^cr/}) {
 6169: 	return (split('/',$short))[-1];
 6170:     }
 6171:     if (!defined($cid)) {
 6172:         $cid = $env{'request.course.id'};
 6173:     }
 6174:     my %rolenames = (
 6175:                       Course    => 'std',
 6176:                       Community => 'alt1',
 6177:                     );
 6178:     if ($cid ne '') {
 6179:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6180:             unless ($forcedefault) {
 6181:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6182:                 &Apache::lonlocal::mt_escape(\$roletext);
 6183:                 return &Apache::lonlocal::mt($roletext);
 6184:             }
 6185:         }
 6186:     }
 6187:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6188:         (defined($rolenames{$type})) && 
 6189:         (defined($prp{$short}{$rolenames{$type}}))) {
 6190:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6191:     } elsif ($cid ne '') {
 6192:         my $crstype = $env{'course.'.$cid.'.type'};
 6193:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6194:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 6195:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 6196:         }
 6197:     }
 6198:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 6199: }
 6200: 
 6201: # ----------------------------------------------------------------- Assign Role
 6202: 
 6203: sub assignrole {
 6204:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6205:         $context)=@_;
 6206:     my $mrole;
 6207:     if ($role =~ /^cr\//) {
 6208:         my $cwosec=$url;
 6209:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6210: 	unless (&allowed('ccr',$cwosec)) {
 6211:            my $refused = 1;
 6212:            if ($context eq 'requestcourses') {
 6213:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 6214:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 6215:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 6216:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6217:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6218:                            if ($crsenv{'internal.courseowner'} eq
 6219:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 6220:                                $refused = '';
 6221:                            }
 6222:                        }
 6223:                    }
 6224:                }
 6225:            }
 6226:            if ($refused) {
 6227:                &logthis('Refused custom assignrole: '.
 6228:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 6229:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 6230:                return 'refused';
 6231:            }
 6232:         }
 6233:         $mrole='cr';
 6234:     } elsif ($role =~ /^gr\//) {
 6235:         my $cwogrp=$url;
 6236:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 6237:         unless (&allowed('mdg',$cwogrp)) {
 6238:             &logthis('Refused group assignrole: '.
 6239:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6240:                     $env{'user.name'}.' at '.$env{'user.domain'});
 6241:             return 'refused';
 6242:         }
 6243:         $mrole='gr';
 6244:     } else {
 6245:         my $cwosec=$url;
 6246:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6247:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 6248:             my $refused;
 6249:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 6250:                 if (!(&allowed('c'.$role,$url))) {
 6251:                     $refused = 1;
 6252:                 }
 6253:             } else {
 6254:                 $refused = 1;
 6255:             }
 6256:             if ($refused) {
 6257:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6258:                 if (!$selfenroll && $context eq 'course') {
 6259:                     my %crsenv;
 6260:                     if ($role eq 'cc' || $role eq 'co') {
 6261:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6262:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 6263:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 6264:                                 if ($crsenv{'internal.courseowner'} eq 
 6265:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6266:                                     $refused = '';
 6267:                                 }
 6268:                             }
 6269:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 6270:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 6271:                                 if ($crsenv{'internal.courseowner'} eq 
 6272:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6273:                                     $refused = '';
 6274:                                 }
 6275:                             }
 6276:                         }
 6277:                     }
 6278:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6279:                     $refused = '';
 6280:                 } elsif ($context eq 'requestcourses') {
 6281:                     my @possroles = ('st','ta','ep','in','cc','co');
 6282:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 6283:                         my $wrongcc;
 6284:                         if ($cnum =~ /^$match_community$/) {
 6285:                             $wrongcc = 1 if ($role eq 'cc');
 6286:                         } else {
 6287:                             $wrongcc = 1 if ($role eq 'co');
 6288:                         }
 6289:                         unless ($wrongcc) {
 6290:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6291:                             if ($crsenv{'internal.courseowner'} eq 
 6292:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 6293:                                 $refused = '';
 6294:                             }
 6295:                         }
 6296:                     }
 6297:                 }
 6298:                 if ($refused) {
 6299:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6300:                              ' '.$role.' '.$end.' '.$start.' by '.
 6301: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6302:                     return 'refused';
 6303:                 }
 6304:             }
 6305:         }
 6306:         $mrole=$role;
 6307:     }
 6308:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6309:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6310:     if ($end) { $command.='_'.$end; }
 6311:     if ($start) {
 6312: 	if ($end) { 
 6313:            $command.='_'.$start; 
 6314:         } else {
 6315:            $command.='_0_'.$start;
 6316:         }
 6317:     }
 6318:     my $origstart = $start;
 6319:     my $origend = $end;
 6320:     my $delflag;
 6321: # actually delete
 6322:     if ($deleteflag) {
 6323: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6324: # modify command to delete the role
 6325:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6326:                 "$udom:$uname:$url".'_'."$mrole";
 6327: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6328: # set start and finish to negative values for userrolelog
 6329:            $start=-1;
 6330:            $end=-1;
 6331:            $delflag = 1;
 6332:         }
 6333:     }
 6334: # send command
 6335:     my $answer=&reply($command,&homeserver($uname,$udom));
 6336: # log new user role if status is ok
 6337:     if ($answer eq 'ok') {
 6338: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6339: # for course roles, perform group memberships changes triggered by role change.
 6340:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6341:         unless ($role =~ /^gr/) {
 6342:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6343:                                              $origstart,$selfenroll,$context);
 6344:         }
 6345:     }
 6346:     return $answer;
 6347: }
 6348: 
 6349: # -------------------------------------------------- Modify user authentication
 6350: # Overrides without validation
 6351: 
 6352: sub modifyuserauth {
 6353:     my ($udom,$uname,$umode,$upass)=@_;
 6354:     my $uhome=&homeserver($uname,$udom);
 6355:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6356:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6357:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6358:              ' in domain '.$env{'request.role.domain'});  
 6359:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6360: 		     &escape($upass),$uhome);
 6361:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6362:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6363:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6364:     &log($udom,,$uname,$uhome,
 6365:         'Authentication changed by '.$env{'user.domain'}.', '.
 6366:                                      $env{'user.name'}.', '.$umode.
 6367:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6368:     unless ($reply eq 'ok') {
 6369:         &logthis('Authentication mode error: '.$reply);
 6370: 	return 'error: '.$reply;
 6371:     }   
 6372:     return 'ok';
 6373: }
 6374: 
 6375: # --------------------------------------------------------------- Modify a user
 6376: 
 6377: sub modifyuser {
 6378:     my ($udom,    $uname, $uid,
 6379:         $umode,   $upass, $first,
 6380:         $middle,  $last,  $gene,
 6381:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6382:     $udom= &LONCAPA::clean_domain($udom);
 6383:     $uname=&LONCAPA::clean_username($uname);
 6384:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6385:              $umode.', '.$first.', '.$middle.', '.
 6386: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6387:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6388:                                      ' desiredhome not specified'). 
 6389:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6390:              ' in domain '.$env{'request.role.domain'});
 6391:     my $uhome=&homeserver($uname,$udom,'true');
 6392: # ----------------------------------------------------------------- Create User
 6393:     if (($uhome eq 'no_host') && 
 6394: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6395:         my $unhome='';
 6396:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6397:             $unhome = $desiredhome;
 6398: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6399: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6400:         } else { # load balancing routine for determining $unhome
 6401:             my $loadm=10000000;
 6402: 	    my %servers = &get_servers($udom,'library');
 6403: 	    foreach my $tryserver (keys(%servers)) {
 6404: 		my $answer=reply('load',$tryserver);
 6405: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6406: 		    $loadm=$answer;
 6407: 		    $unhome=$tryserver;
 6408: 		}
 6409: 	    }
 6410:         }
 6411:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6412: 	    return 'error: unable to find a home server for '.$uname.
 6413:                    ' in domain '.$udom;
 6414:         }
 6415:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6416:                          &escape($upass),$unhome);
 6417: 	unless ($reply eq 'ok') {
 6418:             return 'error: '.$reply;
 6419:         }   
 6420:         $uhome=&homeserver($uname,$udom,'true');
 6421:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6422: 	    return 'error: unable verify users home machine.';
 6423:         }
 6424:     }   # End of creation of new user
 6425: # ---------------------------------------------------------------------- Add ID
 6426:     if ($uid) {
 6427:        $uid=~tr/A-Z/a-z/;
 6428:        my %uidhash=&idrget($udom,$uname);
 6429:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6430:          && (!$forceid)) {
 6431: 	  unless ($uid eq $uidhash{$uname}) {
 6432: 	      return 'error: user id "'.$uid.'" does not match '.
 6433:                   'current user id "'.$uidhash{$uname}.'".';
 6434:           }
 6435:        } else {
 6436: 	  &idput($udom,($uname => $uid));
 6437:        }
 6438:     }
 6439: # -------------------------------------------------------------- Add names, etc
 6440:     my @tmp=&get('environment',
 6441: 		   ['firstname','middlename','lastname','generation','id',
 6442:                     'permanentemail','inststatus'],
 6443: 		   $udom,$uname);
 6444:     my %names;
 6445:     if ($tmp[0] =~ m/^error:.*/) { 
 6446:         %names=(); 
 6447:     } else {
 6448:         %names = @tmp;
 6449:     }
 6450: #
 6451: # Make sure to not trash student environment if instructor does not bother
 6452: # to supply name and email information
 6453: #
 6454:     if ($first)  { $names{'firstname'}  = $first; }
 6455:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6456:     if ($last)   { $names{'lastname'}   = $last; }
 6457:     if (defined($gene))   { $names{'generation'} = $gene; }
 6458:     if ($email) {
 6459:        $email=~s/[^\w\@\.\-\,]//gs;
 6460:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6461:     }
 6462:     if ($uid) { $names{'id'}  = $uid; }
 6463:     if (defined($inststatus)) {
 6464:         $names{'inststatus'} = '';
 6465:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6466:         if (ref($usertypes) eq 'HASH') {
 6467:             my @okstatuses; 
 6468:             foreach my $item (split(/:/,$inststatus)) {
 6469:                 if (defined($usertypes->{$item})) {
 6470:                     push(@okstatuses,$item);  
 6471:                 }
 6472:             }
 6473:             if (@okstatuses) {
 6474:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6475:             }
 6476:         }
 6477:     }
 6478:     my $reply = &put('environment', \%names, $udom,$uname);
 6479:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6480:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6481:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6482:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6483:                  $umode.', '.$first.', '.$middle.', '.
 6484: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6485:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6486:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6487:     } else {
 6488:         $logmsg .= ' during self creation';
 6489:     }
 6490:     &logthis($logmsg);
 6491:     return 'ok';
 6492: }
 6493: 
 6494: # -------------------------------------------------------------- Modify student
 6495: 
 6496: sub modifystudent {
 6497:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6498:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6499:         $selfenroll,$context,$inststatus)=@_;
 6500:     if (!$cid) {
 6501: 	unless ($cid=$env{'request.course.id'}) {
 6502: 	    return 'not_in_class';
 6503: 	}
 6504:     }
 6505: # --------------------------------------------------------------- Make the user
 6506:     my $reply=&modifyuser
 6507: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6508:          $desiredhome,$email,$inststatus);
 6509:     unless ($reply eq 'ok') { return $reply; }
 6510:     # This will cause &modify_student_enrollment to get the uid from the
 6511:     # students environment
 6512:     $uid = undef if (!$forceid);
 6513:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6514: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6515:     return $reply;
 6516: }
 6517: 
 6518: sub modify_student_enrollment {
 6519:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6520:     my ($cdom,$cnum,$chome);
 6521:     if (!$cid) {
 6522: 	unless ($cid=$env{'request.course.id'}) {
 6523: 	    return 'not_in_class';
 6524: 	}
 6525: 	$cdom=$env{'course.'.$cid.'.domain'};
 6526: 	$cnum=$env{'course.'.$cid.'.num'};
 6527:     } else {
 6528: 	($cdom,$cnum)=split(/_/,$cid);
 6529:     }
 6530:     $chome=$env{'course.'.$cid.'.home'};
 6531:     if (!$chome) {
 6532: 	$chome=&homeserver($cnum,$cdom);
 6533:     }
 6534:     if (!$chome) { return 'unknown_course'; }
 6535:     # Make sure the user exists
 6536:     my $uhome=&homeserver($uname,$udom);
 6537:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6538: 	return 'error: no such user';
 6539:     }
 6540:     # Get student data if we were not given enough information
 6541:     if (!defined($first)  || $first  eq '' || 
 6542:         !defined($last)   || $last   eq '' || 
 6543:         !defined($uid)    || $uid    eq '' || 
 6544:         !defined($middle) || $middle eq '' || 
 6545:         !defined($gene)   || $gene   eq '') {
 6546:         # They did not supply us with enough data to enroll the student, so
 6547:         # we need to pick up more information.
 6548:         my %tmp = &get('environment',
 6549:                        ['firstname','middlename','lastname', 'generation','id']
 6550:                        ,$udom,$uname);
 6551: 
 6552:         #foreach my $key (keys(%tmp)) {
 6553:         #    &logthis("key $key = ".$tmp{$key});
 6554:         #}
 6555:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6556:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6557:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6558:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6559:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6560:     }
 6561:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6562:     my $reply=cput('classlist',
 6563: 		   {"$uname:$udom" => 
 6564: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6565: 		   $cdom,$cnum);
 6566:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6567: 	return 'error: '.$reply;
 6568:     } else {
 6569: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6570:     }
 6571:     # Add student role to user
 6572:     my $uurl='/'.$cid;
 6573:     $uurl=~s/\_/\//g;
 6574:     if ($usec) {
 6575: 	$uurl.='/'.$usec;
 6576:     }
 6577:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6578: }
 6579: 
 6580: sub format_name {
 6581:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6582:     my $name;
 6583:     if ($first ne 'lastname') {
 6584: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6585:     } else {
 6586: 	if ($lastname=~/\S/) {
 6587: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6588: 	    $name=~s/\s+,/,/;
 6589: 	} else {
 6590: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6591: 	}
 6592:     }
 6593:     $name=~s/^\s+//;
 6594:     $name=~s/\s+$//;
 6595:     $name=~s/\s+/ /g;
 6596:     return $name;
 6597: }
 6598: 
 6599: # ------------------------------------------------- Write to course preferences
 6600: 
 6601: sub writecoursepref {
 6602:     my ($courseid,%prefs)=@_;
 6603:     $courseid=~s/^\///;
 6604:     $courseid=~s/\_/\//g;
 6605:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6606:     my $chome=homeserver($cnum,$cdomain);
 6607:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6608: 	return 'error: no such course';
 6609:     }
 6610:     my $cstring='';
 6611:     foreach my $pref (keys(%prefs)) {
 6612: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6613:     }
 6614:     $cstring=~s/\&$//;
 6615:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6616: }
 6617: 
 6618: # ---------------------------------------------------------- Make/modify course
 6619: 
 6620: sub createcourse {
 6621:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6622:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 6623:     $url=&declutter($url);
 6624:     my $cid='';
 6625:     if ($context eq 'requestcourses') {
 6626:         my $can_create = 0;
 6627:         my ($ownername,$ownerdom) = split(':',$course_owner);
 6628:         if ($udom eq $ownerdom) {
 6629:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 6630:                                   $context)) {
 6631:                 $can_create = 1;
 6632:             }
 6633:         } else {
 6634:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 6635:                                            $category);
 6636:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 6637:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 6638:                 if (@curr > 0) {
 6639:                     my @options = qw(approval validate autolimit);
 6640:                     my $optregex = join('|',@options);
 6641:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 6642:                         $can_create = 1;
 6643:                     }
 6644:                 }
 6645:             }
 6646:         }
 6647:         if ($can_create) {
 6648:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 6649:                 unless (&allowed('ccc',$udom)) {
 6650:                     return 'refused'; 
 6651:                 }
 6652:             }
 6653:         } else {
 6654:             return 'refused';
 6655:         }
 6656:     } elsif (!&allowed('ccc',$udom)) {
 6657:         return 'refused';
 6658:     }
 6659: # --------------------------------------------------------------- Get Unique ID
 6660:     my $uname;
 6661:     if ($cnum =~ /^$match_courseid$/) {
 6662:         my $chome=&homeserver($cnum,$udom,'true');
 6663:         if (($chome eq '') || ($chome eq 'no_host')) {
 6664:             $uname = $cnum;
 6665:         } else {
 6666:             $uname = &generate_coursenum($udom,$crstype);
 6667:         }
 6668:     } else {
 6669:         $uname = &generate_coursenum($udom,$crstype);
 6670:     }
 6671:     return $uname if ($uname =~ /^error/);
 6672: # -------------------------------------------------- Check supplied server name
 6673:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6674:     if (! &is_library($course_server)) {
 6675:         return 'error:bad server name '.$course_server;
 6676:     }
 6677: # ------------------------------------------------------------- Make the course
 6678:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6679:                       $course_server);
 6680:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6681:     my $uhome=&homeserver($uname,$udom,'true');
 6682:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6683: 	return 'error: no such course';
 6684:     }
 6685: # ----------------------------------------------------------------- Course made
 6686: # log existence
 6687:     my $now = time;
 6688:     my $newcourse = {
 6689:                     $udom.'_'.$uname => {
 6690:                                      description => $description,
 6691:                                      inst_code   => $inst_code,
 6692:                                      owner       => $course_owner,
 6693:                                      type        => $crstype,
 6694:                                      creator     => $env{'user.name'}.':'.
 6695:                                                     $env{'user.domain'},
 6696:                                      created     => $now,
 6697:                                      context     => $context,
 6698:                                                 },
 6699:                     };
 6700:     &courseidput($udom,$newcourse,$uhome,'notime');
 6701: # set toplevel url
 6702:     my $topurl=$url;
 6703:     unless ($nonstandard) {
 6704: # ------------------------------------------ For standard courses, make top url
 6705:         my $mapurl=&clutter($url);
 6706:         if ($mapurl eq '/res/') { $mapurl=''; }
 6707:         $env{'form.initmap'}=(<<ENDINITMAP);
 6708: <map>
 6709: <resource id="1" type="start"></resource>
 6710: <resource id="2" src="$mapurl"></resource>
 6711: <resource id="3" type="finish"></resource>
 6712: <link index="1" from="1" to="2"></link>
 6713: <link index="2" from="2" to="3"></link>
 6714: </map>
 6715: ENDINITMAP
 6716:         $topurl=&declutter(
 6717:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6718:                           );
 6719:     }
 6720: # ----------------------------------------------------------- Write preferences
 6721:     &writecoursepref($udom.'_'.$uname,
 6722:                      ('description' => $description,
 6723:                       'url'         => $topurl));
 6724:     return '/'.$udom.'/'.$uname;
 6725: }
 6726: 
 6727: # ------------------------------------------------------------------- Create ID
 6728: sub generate_coursenum {
 6729:     my ($udom,$crstype) = @_;
 6730:     my $domdesc = &domain($udom);
 6731:     return 'error: invalid domain' if ($domdesc eq '');
 6732:     my $first;
 6733:     if ($crstype eq 'Community') {
 6734:         $first = '0';
 6735:     } else {
 6736:         $first = int(1+rand(9)); 
 6737:     } 
 6738:     my $uname=$first.
 6739:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6740:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6741:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6742: # ----------------------------------------------- Make sure that does not exist
 6743:     my $uhome=&homeserver($uname,$udom,'true');
 6744:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6745:         if ($crstype eq 'Community') {
 6746:             $first = '0';
 6747:         } else {
 6748:             $first = int(1+rand(9));
 6749:         }
 6750:         $uname=$first.
 6751:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6752:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6753:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6754:         $uhome=&homeserver($uname,$udom,'true');
 6755:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6756:             return 'error: unable to generate unique course-ID';
 6757:         }
 6758:     }
 6759:     return $uname;
 6760: }
 6761: 
 6762: sub is_course {
 6763:     my ($cdom,$cnum) = @_;
 6764:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6765: 				undef,'.');
 6766:     if (exists($courses{$cdom.'_'.$cnum})) {
 6767:         return 1;
 6768:     }
 6769:     return 0;
 6770: }
 6771: 
 6772: sub store_userdata {
 6773:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 6774:     my $result;
 6775:     if ($datakey ne '') {
 6776:         if (ref($storehash) eq 'HASH') {
 6777:             if ($udom eq '' || $uname eq '') {
 6778:                 $udom = $env{'user.domain'};
 6779:                 $uname = $env{'user.name'};
 6780:             }
 6781:             my $uhome=&homeserver($uname,$udom);
 6782:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 6783:                 $result = 'error: no_host';
 6784:             } else {
 6785:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 6786:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 6787: 
 6788:                 my $namevalue='';
 6789:                 foreach my $key (keys(%{$storehash})) {
 6790:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6791:                 }
 6792:                 $namevalue=~s/\&$//;
 6793:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
 6794:                                   "$namespace:$datakey:$namevalue",$uhome);
 6795:             }
 6796:         } else {
 6797:             $result = 'error: data to store was not a hash reference'; 
 6798:         }
 6799:     } else {
 6800:         $result= 'error: invalid requestkey'; 
 6801:     }
 6802:     return $result;
 6803: }
 6804: 
 6805: # ---------------------------------------------------------- Assign Custom Role
 6806: 
 6807: sub assigncustomrole {
 6808:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6809:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6810:                        $end,$start,$deleteflag,$selfenroll,$context);
 6811: }
 6812: 
 6813: # ----------------------------------------------------------------- Revoke Role
 6814: 
 6815: sub revokerole {
 6816:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6817:     my $now=time;
 6818:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6819: }
 6820: 
 6821: # ---------------------------------------------------------- Revoke Custom Role
 6822: 
 6823: sub revokecustomrole {
 6824:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6825:     my $now=time;
 6826:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6827:            $deleteflag,$selfenroll,$context);
 6828: }
 6829: 
 6830: # ------------------------------------------------------------ Disk usage
 6831: sub diskusage {
 6832:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6833:     $directorypath =~ s/\/$//;
 6834:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6835:                        .&escape($getpropath).':'.&escape($uname).':'
 6836:                        .&escape($udom),homeserver($uname,$udom));
 6837:     if ($listing eq 'unknown_cmd') {
 6838:         if ($getpropath) {
 6839:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6840:         }
 6841:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6842:     }
 6843:     return $listing;
 6844: }
 6845: 
 6846: sub is_locked {
 6847:     my ($file_name, $domain, $user) = @_;
 6848:     my @check;
 6849:     my $is_locked;
 6850:     push @check, $file_name;
 6851:     my %locked = &get('file_permissions',\@check,
 6852: 		      $env{'user.domain'},$env{'user.name'});
 6853:     my ($tmp)=keys(%locked);
 6854:     if ($tmp=~/^error:/) { undef(%locked); }
 6855:     
 6856:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6857:         $is_locked = 'false';
 6858:         foreach my $entry (@{$locked{$file_name}}) {
 6859:            if (ref($entry) eq 'ARRAY') { 
 6860:                $is_locked = 'true';
 6861:                last;
 6862:            }
 6863:        }
 6864:     } else {
 6865:         $is_locked = 'false';
 6866:     }
 6867: }
 6868: 
 6869: sub declutter_portfile {
 6870:     my ($file) = @_;
 6871:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6872:     return $file;
 6873: }
 6874: 
 6875: # ------------------------------------------------------------- Mark as Read Only
 6876: 
 6877: sub mark_as_readonly {
 6878:     my ($domain,$user,$files,$what) = @_;
 6879:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6880:     my ($tmp)=keys(%current_permissions);
 6881:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6882:     foreach my $file (@{$files}) {
 6883: 	$file = &declutter_portfile($file);
 6884:         push(@{$current_permissions{$file}},$what);
 6885:     }
 6886:     &put('file_permissions',\%current_permissions,$domain,$user);
 6887:     return;
 6888: }
 6889: 
 6890: # ------------------------------------------------------------Save Selected Files
 6891: 
 6892: sub save_selected_files {
 6893:     my ($user, $path, @files) = @_;
 6894:     my $filename = $user."savedfiles";
 6895:     my @other_files = &files_not_in_path($user, $path);
 6896:     open (OUT, '>'.$tmpdir.$filename);
 6897:     foreach my $file (@files) {
 6898:         print (OUT $env{'form.currentpath'}.$file."\n");
 6899:     }
 6900:     foreach my $file (@other_files) {
 6901:         print (OUT $file."\n");
 6902:     }
 6903:     close (OUT);
 6904:     return 'ok';
 6905: }
 6906: 
 6907: sub clear_selected_files {
 6908:     my ($user) = @_;
 6909:     my $filename = $user."savedfiles";
 6910:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6911:     print (OUT undef);
 6912:     close (OUT);
 6913:     return ("ok");    
 6914: }
 6915: 
 6916: sub files_in_path {
 6917:     my ($user, $path) = @_;
 6918:     my $filename = $user."savedfiles";
 6919:     my %return_files;
 6920:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6921:     while (my $line_in = <IN>) {
 6922:         chomp ($line_in);
 6923:         my @paths_and_file = split (m!/!, $line_in);
 6924:         my $file_part = pop (@paths_and_file);
 6925:         my $path_part = join ('/', @paths_and_file);
 6926:         $path_part.='/';
 6927:         my $path_and_file = $path_part.$file_part;
 6928:         if ($path_part eq $path) {
 6929:             $return_files{$file_part}= 'selected';
 6930:         }
 6931:     }
 6932:     close (IN);
 6933:     return (\%return_files);
 6934: }
 6935: 
 6936: # called in portfolio select mode, to show files selected NOT in current directory
 6937: sub files_not_in_path {
 6938:     my ($user, $path) = @_;
 6939:     my $filename = $user."savedfiles";
 6940:     my @return_files;
 6941:     my $path_part;
 6942:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6943:     while (my $line = <IN>) {
 6944:         #ok, I know it's clunky, but I want it to work
 6945:         my @paths_and_file = split(m|/|, $line);
 6946:         my $file_part = pop(@paths_and_file);
 6947:         chomp($file_part);
 6948:         my $path_part = join('/', @paths_and_file);
 6949:         $path_part .= '/';
 6950:         my $path_and_file = $path_part.$file_part;
 6951:         if ($path_part ne $path) {
 6952:             push(@return_files, ($path_and_file));
 6953:         }
 6954:     }
 6955:     close(OUT);
 6956:     return (@return_files);
 6957: }
 6958: 
 6959: #----------------------------------------------Get portfolio file permissions
 6960: 
 6961: sub get_portfile_permissions {
 6962:     my ($domain,$user) = @_;
 6963:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6964:     my ($tmp)=keys(%current_permissions);
 6965:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6966:     return \%current_permissions;
 6967: }
 6968: 
 6969: #---------------------------------------------Get portfolio file access controls
 6970: 
 6971: sub get_access_controls {
 6972:     my ($current_permissions,$group,$file) = @_;
 6973:     my %access;
 6974:     my $real_file = $file;
 6975:     $file =~ s/\.meta$//;
 6976:     if (defined($file)) {
 6977:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6978:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6979:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6980:             }
 6981:         }
 6982:     } else {
 6983:         foreach my $key (keys(%{$current_permissions})) {
 6984:             if ($key =~ /\0accesscontrol$/) {
 6985:                 if (defined($group)) {
 6986:                     if ($key !~ m-^\Q$group\E/-) {
 6987:                         next;
 6988:                     }
 6989:                 }
 6990:                 my ($fullpath) = split(/\0/,$key);
 6991:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6992:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6993:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6994:                     }
 6995:                 }
 6996:             }
 6997:         }
 6998:     }
 6999:     return %access;
 7000: }
 7001: 
 7002: sub modify_access_controls {
 7003:     my ($file_name,$changes,$domain,$user)=@_;
 7004:     my ($outcome,$deloutcome);
 7005:     my %store_permissions;
 7006:     my %new_values;
 7007:     my %new_control;
 7008:     my %translation;
 7009:     my @deletions = ();
 7010:     my $now = time;
 7011:     if (exists($$changes{'activate'})) {
 7012:         if (ref($$changes{'activate'}) eq 'HASH') {
 7013:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 7014:             my $numnew = scalar(@newitems);
 7015:             for (my $i=0; $i<$numnew; $i++) {
 7016:                 my $newkey = $newitems[$i];
 7017:                 my $newid = &Apache::loncommon::get_cgi_id();
 7018:                 if ($newkey =~ /^\d+:/) { 
 7019:                     $newkey =~ s/^(\d+)/$newid/;
 7020:                     $translation{$1} = $newid;
 7021:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 7022:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 7023:                     $translation{$1} = $newid;
 7024:                 }
 7025:                 $new_values{$file_name."\0".$newkey} = 
 7026:                                           $$changes{'activate'}{$newitems[$i]};
 7027:                 $new_control{$newkey} = $now;
 7028:             }
 7029:         }
 7030:     }
 7031:     my %todelete;
 7032:     my %changed_items;
 7033:     foreach my $action ('delete','update') {
 7034:         if (exists($$changes{$action})) {
 7035:             if (ref($$changes{$action}) eq 'HASH') {
 7036:                 foreach my $key (keys(%{$$changes{$action}})) {
 7037:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 7038:                     if ($action eq 'delete') { 
 7039:                         $todelete{$itemnum} = 1;
 7040:                     } else {
 7041:                         $changed_items{$itemnum} = $key;
 7042:                     }
 7043:                 }
 7044:             }
 7045:         }
 7046:     }
 7047:     # get lock on access controls for file.
 7048:     my $lockhash = {
 7049:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 7050:                                                        ':'.$env{'user.domain'},
 7051:                    }; 
 7052:     my $tries = 0;
 7053:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7054:    
 7055:     while (($gotlock ne 'ok') && $tries <3) {
 7056:         $tries ++;
 7057:         sleep 1;
 7058:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7059:     }
 7060:     if ($gotlock eq 'ok') {
 7061:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 7062:         my ($tmp)=keys(%curr_permissions);
 7063:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 7064:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 7065:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 7066:             if (ref($curr_controls) eq 'HASH') {
 7067:                 foreach my $control_item (keys(%{$curr_controls})) {
 7068:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 7069:                     if (defined($todelete{$itemnum})) {
 7070:                         push(@deletions,$file_name."\0".$control_item);
 7071:                     } else {
 7072:                         if (defined($changed_items{$itemnum})) {
 7073:                             $new_control{$changed_items{$itemnum}} = $now;
 7074:                             push(@deletions,$file_name."\0".$control_item);
 7075:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 7076:                         } else {
 7077:                             $new_control{$control_item} = $$curr_controls{$control_item};
 7078:                         }
 7079:                     }
 7080:                 }
 7081:             }
 7082:         }
 7083:         my ($group);
 7084:         if (&is_course($domain,$user)) {
 7085:             ($group,my $file) = split(/\//,$file_name,2);
 7086:         }
 7087:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 7088:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 7089:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 7090:         #  remove lock
 7091:         my @del_lock = ($file_name."\0".'locked_access_records');
 7092:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 7093:         my $sqlresult =
 7094:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 7095:                                     $group);
 7096:     } else {
 7097:         $outcome = "error: could not obtain lockfile\n";  
 7098:     }
 7099:     return ($outcome,$deloutcome,\%new_values,\%translation);
 7100: }
 7101: 
 7102: sub make_public_indefinitely {
 7103:     my ($requrl) = @_;
 7104:     my $now = time;
 7105:     my $action = 'activate';
 7106:     my $aclnum = 0;
 7107:     if (&is_portfolio_url($requrl)) {
 7108:         my (undef,$udom,$unum,$file_name,$group) =
 7109:             &parse_portfolio_url($requrl);
 7110:         my $current_perms = &get_portfile_permissions($udom,$unum);
 7111:         my %access_controls = &get_access_controls($current_perms,
 7112:                                                    $group,$file_name);
 7113:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 7114:             my ($num,$scope,$end,$start) = 
 7115:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7116:             if ($scope eq 'public') {
 7117:                 if ($start <= $now && $end == 0) {
 7118:                     $action = 'none';
 7119:                 } else {
 7120:                     $action = 'update';
 7121:                     $aclnum = $num;
 7122:                 }
 7123:                 last;
 7124:             }
 7125:         }
 7126:         if ($action eq 'none') {
 7127:              return 'ok';
 7128:         } else {
 7129:             my %changes;
 7130:             my $newend = 0;
 7131:             my $newstart = $now;
 7132:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 7133:             $changes{$action}{$newkey} = {
 7134:                 type => 'public',
 7135:                 time => {
 7136:                     start => $newstart,
 7137:                     end   => $newend,
 7138:                 },
 7139:             };
 7140:             my ($outcome,$deloutcome,$new_values,$translation) =
 7141:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 7142:             return $outcome;
 7143:         }
 7144:     } else {
 7145:         return 'invalid';
 7146:     }
 7147: }
 7148: 
 7149: #------------------------------------------------------Get Marked as Read Only
 7150: 
 7151: sub get_marked_as_readonly {
 7152:     my ($domain,$user,$what,$group) = @_;
 7153:     my $current_permissions = &get_portfile_permissions($domain,$user);
 7154:     my @readonly_files;
 7155:     my $cmp1=$what;
 7156:     if (ref($what)) { $cmp1=join('',@{$what}) };
 7157:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7158:         if (defined($group)) {
 7159:             if ($file_name !~ m-^\Q$group\E/-) {
 7160:                 next;
 7161:             }
 7162:         }
 7163:         if (ref($value) eq "ARRAY"){
 7164:             foreach my $stored_what (@{$value}) {
 7165:                 my $cmp2=$stored_what;
 7166:                 if (ref($stored_what) eq 'ARRAY') {
 7167:                     $cmp2=join('',@{$stored_what});
 7168:                 }
 7169:                 if ($cmp1 eq $cmp2) {
 7170:                     push(@readonly_files, $file_name);
 7171:                     last;
 7172:                 } elsif (!defined($what)) {
 7173:                     push(@readonly_files, $file_name);
 7174:                     last;
 7175:                 }
 7176:             }
 7177:         }
 7178:     }
 7179:     return @readonly_files;
 7180: }
 7181: #-----------------------------------------------------------Get Marked as Read Only Hash
 7182: 
 7183: sub get_marked_as_readonly_hash {
 7184:     my ($current_permissions,$group,$what) = @_;
 7185:     my %readonly_files;
 7186:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7187:         if (defined($group)) {
 7188:             if ($file_name !~ m-^\Q$group\E/-) {
 7189:                 next;
 7190:             }
 7191:         }
 7192:         if (ref($value) eq "ARRAY"){
 7193:             foreach my $stored_what (@{$value}) {
 7194:                 if (ref($stored_what) eq 'ARRAY') {
 7195:                     foreach my $lock_descriptor(@{$stored_what}) {
 7196:                         if ($lock_descriptor eq 'graded') {
 7197:                             $readonly_files{$file_name} = 'graded';
 7198:                         } elsif ($lock_descriptor eq 'handback') {
 7199:                             $readonly_files{$file_name} = 'handback';
 7200:                         } else {
 7201:                             if (!exists($readonly_files{$file_name})) {
 7202:                                 $readonly_files{$file_name} = 'locked';
 7203:                             }
 7204:                         }
 7205:                     }
 7206:                 } 
 7207:             }
 7208:         } 
 7209:     }
 7210:     return %readonly_files;
 7211: }
 7212: # ------------------------------------------------------------ Unmark as Read Only
 7213: 
 7214: sub unmark_as_readonly {
 7215:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 7216:     # for portfolio submissions, $what contains [$symb,$crsid] 
 7217:     my ($domain,$user,$what,$file_name,$group) = @_;
 7218:     $file_name = &declutter_portfile($file_name);
 7219:     my $symb_crs = $what;
 7220:     if (ref($what)) { $symb_crs=join('',@$what); }
 7221:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 7222:     my ($tmp)=keys(%current_permissions);
 7223:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7224:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 7225:     foreach my $file (@readonly_files) {
 7226: 	my $clean_file = &declutter_portfile($file);
 7227: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 7228: 	my $current_locks = $current_permissions{$file};
 7229:         my @new_locks;
 7230:         my @del_keys;
 7231:         if (ref($current_locks) eq "ARRAY"){
 7232:             foreach my $locker (@{$current_locks}) {
 7233:                 my $compare=$locker;
 7234:                 if (ref($locker) eq 'ARRAY') {
 7235:                     $compare=join('',@{$locker});
 7236:                     if ($compare ne $symb_crs) {
 7237:                         push(@new_locks, $locker);
 7238:                     }
 7239:                 }
 7240:             }
 7241:             if (scalar(@new_locks) > 0) {
 7242:                 $current_permissions{$file} = \@new_locks;
 7243:             } else {
 7244:                 push(@del_keys, $file);
 7245:                 &del('file_permissions',\@del_keys, $domain, $user);
 7246:                 delete($current_permissions{$file});
 7247:             }
 7248:         }
 7249:     }
 7250:     &put('file_permissions',\%current_permissions,$domain,$user);
 7251:     return;
 7252: }
 7253: 
 7254: # ------------------------------------------------------------ Directory lister
 7255: 
 7256: sub dirlist {
 7257:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 7258:     $uri=~s/^\///;
 7259:     $uri=~s/\/$//;
 7260:     my ($udom, $uname);
 7261:     if ($getuserdir) {
 7262:         $udom = $userdomain;
 7263:         $uname = $username;
 7264:     } else {
 7265:         (undef,$udom,$uname)=split(/\//,$uri);
 7266:         if(defined($userdomain)) {
 7267:             $udom = $userdomain;
 7268:         }
 7269:         if(defined($username)) {
 7270:             $uname = $username;
 7271:         }
 7272:     }
 7273:     my ($dirRoot,$listing,@listing_results);
 7274: 
 7275:     $dirRoot = $perlvar{'lonDocRoot'};
 7276:     if (defined($getpropath)) {
 7277:         $dirRoot = &propath($udom,$uname);
 7278:         $dirRoot =~ s/\/$//;
 7279:     } elsif (defined($getuserdir)) {
 7280:         my $subdir=$uname.'__';
 7281:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 7282:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 7283:                    ."/$udom/$subdir/$uname";
 7284:     } elsif (defined($alternateRoot)) {
 7285:         $dirRoot = $alternateRoot;
 7286:     }
 7287: 
 7288:     if($udom) {
 7289:         if($uname) {
 7290:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 7291:                               .$getuserdir.':'.&escape($dirRoot)
 7292:                               .':'.&escape($uname).':'.&escape($udom),
 7293:                               &homeserver($uname,$udom));
 7294:             if ($listing eq 'unknown_cmd') {
 7295:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 7296:                                   &homeserver($uname,$udom));
 7297:             } else {
 7298:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7299:             }
 7300:             if ($listing eq 'unknown_cmd') {
 7301:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 7302: 				  &homeserver($uname,$udom));
 7303:                 @listing_results = split(/:/,$listing);
 7304:             } else {
 7305:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7306:             }
 7307:             return @listing_results;
 7308:         } elsif(!$alternateRoot) {
 7309:             my %allusers;
 7310: 	    my %servers = &get_servers($udom,'library');
 7311:  	    foreach my $tryserver (keys(%servers)) {
 7312:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 7313:                                   &escape($udom),$tryserver);
 7314:                 if ($listing eq 'unknown_cmd') {
 7315: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 7316: 				      $udom, $tryserver);
 7317:                 } else {
 7318:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 7319:                 }
 7320: 		if ($listing eq 'unknown_cmd') {
 7321: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 7322: 				      $udom, $tryserver);
 7323: 		    @listing_results = split(/:/,$listing);
 7324: 		} else {
 7325: 		    @listing_results =
 7326: 			map { &unescape($_); } split(/:/,$listing);
 7327: 		}
 7328: 		if ($listing_results[0] ne 'no_such_dir' && 
 7329: 		    $listing_results[0] ne 'empty'       &&
 7330: 		    $listing_results[0] ne 'con_lost') {
 7331: 		    foreach my $line (@listing_results) {
 7332: 			my ($entry) = split(/&/,$line,2);
 7333: 			$allusers{$entry} = 1;
 7334: 		    }
 7335: 		}
 7336:             }
 7337:             my $alluserstr='';
 7338:             foreach my $user (sort(keys(%allusers))) {
 7339:                 $alluserstr.=$user.'&user:';
 7340:             }
 7341:             $alluserstr=~s/:$//;
 7342:             return split(/:/,$alluserstr);
 7343:         } else {
 7344:             return ('missing user name');
 7345:         }
 7346:     } elsif(!defined($getpropath)) {
 7347:         my @all_domains = sort(&all_domains());
 7348:         foreach my $domain (@all_domains) {
 7349:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 7350:         }
 7351:         return @all_domains;
 7352:     } else {
 7353:         return ('missing domain');
 7354:     }
 7355: }
 7356: 
 7357: # --------------------------------------------- GetFileTimestamp
 7358: # This function utilizes dirlist and returns the date stamp for
 7359: # when it was last modified.  It will also return an error of -1
 7360: # if an error occurs
 7361: 
 7362: sub GetFileTimestamp {
 7363:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 7364:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 7365:     $studentName   = &LONCAPA::clean_username($studentName);
 7366:     my ($fileStat) = 
 7367:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 7368:                                  undef,$getuserdir);
 7369:     my @stats = split('&', $fileStat);
 7370:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7371:         # @stats contains first the filename, then the stat output
 7372:         return $stats[10]; # so this is 10 instead of 9.
 7373:     } else {
 7374:         return -1;
 7375:     }
 7376: }
 7377: 
 7378: sub stat_file {
 7379:     my ($uri) = @_;
 7380:     $uri = &clutter_with_no_wrapper($uri);
 7381: 
 7382:     my ($udom,$uname,$file);
 7383:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7384: 	($udom,$uname,$file) =
 7385: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7386: 	$file = 'userfiles/'.$file;
 7387:     }
 7388:     if ($uri =~ m-^/res/-) {
 7389: 	($udom,$uname) = 
 7390: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7391: 	$file = $uri;
 7392:     }
 7393: 
 7394:     if (!$udom || !$uname || !$file) {
 7395: 	# unable to handle the uri
 7396: 	return ();
 7397:     }
 7398:     my $getpropath;
 7399:     if ($file =~ /^userfiles\//) {
 7400:         $getpropath = 1;
 7401:     }
 7402:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7403:     my @stats = split('&', $result);
 7404:     
 7405:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7406: 	shift(@stats); #filename is first
 7407: 	return @stats;
 7408:     }
 7409:     return ();
 7410: }
 7411: 
 7412: # -------------------------------------------------------- Value of a Condition
 7413: 
 7414: # gets the value of a specific preevaluated condition
 7415: #    stored in the string  $env{user.state.<cid>}
 7416: # or looks up a condition reference in the bighash and if if hasn't
 7417: # already been evaluated recurses into docondval to get the value of
 7418: # the condition, then memoizing it to 
 7419: #   $env{user.state.<cid>.<condition>}
 7420: sub directcondval {
 7421:     my $number=shift;
 7422:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7423: 	&Apache::lonuserstate::evalstate();
 7424:     }
 7425:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7426: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7427:     } elsif ($number =~ /^_/) {
 7428: 	my $sub_condition;
 7429: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7430: 		&GDBM_READER(),0640)) {
 7431: 	    $sub_condition=$bighash{'conditions'.$number};
 7432: 	    untie(%bighash);
 7433: 	}
 7434: 	my $value = &docondval($sub_condition);
 7435: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7436: 	return $value;
 7437:     }
 7438:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7439:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7440:     } else {
 7441:        return 2;
 7442:     }
 7443: }
 7444: 
 7445: # get the collection of conditions for this resource
 7446: sub condval {
 7447:     my $condidx=shift;
 7448:     my $allpathcond='';
 7449:     foreach my $cond (split(/\|/,$condidx)) {
 7450: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7451: 	    $allpathcond.=
 7452: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7453: 	}
 7454:     }
 7455:     $allpathcond=~s/\|$//;
 7456:     return &docondval($allpathcond);
 7457: }
 7458: 
 7459: #evaluates an expression of conditions
 7460: sub docondval {
 7461:     my ($allpathcond) = @_;
 7462:     my $result=0;
 7463:     if ($env{'request.course.id'}
 7464: 	&& defined($allpathcond)) {
 7465: 	my $operand='|';
 7466: 	my @stack;
 7467: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7468: 	    if ($chunk eq '(') {
 7469: 		push @stack,($operand,$result);
 7470: 	    } elsif ($chunk eq ')') {
 7471: 		my $before=pop @stack;
 7472: 		if (pop @stack eq '&') {
 7473: 		    $result=$result>$before?$before:$result;
 7474: 		} else {
 7475: 		    $result=$result>$before?$result:$before;
 7476: 		}
 7477: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7478: 		$operand=$chunk;
 7479: 	    } else {
 7480: 		my $new=directcondval($chunk);
 7481: 		if ($operand eq '&') {
 7482: 		    $result=$result>$new?$new:$result;
 7483: 		} else {
 7484: 		    $result=$result>$new?$result:$new;
 7485: 		}
 7486: 	    }
 7487: 	}
 7488:     }
 7489:     return $result;
 7490: }
 7491: 
 7492: # ---------------------------------------------------- Devalidate courseresdata
 7493: 
 7494: sub devalidatecourseresdata {
 7495:     my ($coursenum,$coursedomain)=@_;
 7496:     my $hashid=$coursenum.':'.$coursedomain;
 7497:     &devalidate_cache_new('courseres',$hashid);
 7498: }
 7499: 
 7500: 
 7501: # --------------------------------------------------- Course Resourcedata Query
 7502: #
 7503: #  Parameters:
 7504: #      $coursenum    - Number of the course.
 7505: #      $coursedomain - Domain at which the course was created.
 7506: #  Returns:
 7507: #     A hash of the course parameters along (I think) with timestamps
 7508: #     and version info.
 7509: 
 7510: sub get_courseresdata {
 7511:     my ($coursenum,$coursedomain)=@_;
 7512:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7513:     my $hashid=$coursenum.':'.$coursedomain;
 7514:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7515:     my %dumpreply;
 7516:     unless (defined($cached)) {
 7517: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7518: 	$result=\%dumpreply;
 7519: 	my ($tmp) = keys(%dumpreply);
 7520: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7521: 	    &do_cache_new('courseres',$hashid,$result,600);
 7522: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7523: 	    return $tmp;
 7524: 	} elsif ($tmp =~ /^(error)/) {
 7525: 	    $result=undef;
 7526: 	    &do_cache_new('courseres',$hashid,$result,600);
 7527: 	}
 7528:     }
 7529:     return $result;
 7530: }
 7531: 
 7532: sub devalidateuserresdata {
 7533:     my ($uname,$udom)=@_;
 7534:     my $hashid="$udom:$uname";
 7535:     &devalidate_cache_new('userres',$hashid);
 7536: }
 7537: 
 7538: sub get_userresdata {
 7539:     my ($uname,$udom)=@_;
 7540:     #most student don\'t have any data set, check if there is some data
 7541:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7542: 
 7543:     my $hashid="$udom:$uname";
 7544:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7545:     if (!defined($cached)) {
 7546: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7547: 	$result=\%resourcedata;
 7548: 	&do_cache_new('userres',$hashid,$result,600);
 7549:     }
 7550:     my ($tmp)=keys(%$result);
 7551:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7552: 	return $result;
 7553:     }
 7554:     #error 2 occurs when the .db doesn't exist
 7555:     if ($tmp!~/error: 2 /) {
 7556: 	&logthis("<font color=\"blue\">WARNING:".
 7557: 		 " Trying to get resource data for ".
 7558: 		 $uname." at ".$udom.": ".
 7559: 		 $tmp."</font>");
 7560:     } elsif ($tmp=~/error: 2 /) {
 7561: 	#&EXT_cache_set($udom,$uname);
 7562: 	&do_cache_new('userres',$hashid,undef,600);
 7563: 	undef($tmp); # not really an error so don't send it back
 7564:     }
 7565:     return $tmp;
 7566: }
 7567: #----------------------------------------------- resdata - return resource data
 7568: #  Purpose:
 7569: #    Return resource data for either users or for a course.
 7570: #  Parameters:
 7571: #     $name      - Course/user name.
 7572: #     $domain    - Name of the domain the user/course is registered on.
 7573: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7574: #     @which     - Array of names of resources desired.
 7575: #  Returns:
 7576: #     The value of the first reasource in @which that is found in the
 7577: #     resource hash.
 7578: #  Exceptional Conditions:
 7579: #     If the $type passed in is not valid (not the string 'course' or 
 7580: #     'user', an undefined  reference is returned.
 7581: #     If none of the resources are found, an undef is returned
 7582: sub resdata {
 7583:     my ($name,$domain,$type,@which)=@_;
 7584:     my $result;
 7585:     if ($type eq 'course') {
 7586: 	$result=&get_courseresdata($name,$domain);
 7587:     } elsif ($type eq 'user') {
 7588: 	$result=&get_userresdata($name,$domain);
 7589:     }
 7590:     if (!ref($result)) { return $result; }    
 7591:     foreach my $item (@which) {
 7592: 	if (defined($result->{$item->[0]})) {
 7593: 	    return [$result->{$item->[0]},$item->[1]];
 7594: 	}
 7595:     }
 7596:     return undef;
 7597: }
 7598: 
 7599: #
 7600: # EXT resource caching routines
 7601: #
 7602: 
 7603: sub clear_EXT_cache_status {
 7604:     &delenv('cache.EXT.');
 7605: }
 7606: 
 7607: sub EXT_cache_status {
 7608:     my ($target_domain,$target_user) = @_;
 7609:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7610:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7611:         # We know already the user has no data
 7612:         return 1;
 7613:     } else {
 7614:         return 0;
 7615:     }
 7616: }
 7617: 
 7618: sub EXT_cache_set {
 7619:     my ($target_domain,$target_user) = @_;
 7620:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7621:     #&appenv({$cachename => time});
 7622: }
 7623: 
 7624: # --------------------------------------------------------- Value of a Variable
 7625: sub EXT {
 7626: 
 7627:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7628:     unless ($varname) { return ''; }
 7629:     #get real user name/domain, courseid and symb
 7630:     my $courseid;
 7631:     my $publicuser;
 7632:     if ($symbparm) {
 7633: 	$symbparm=&get_symb_from_alias($symbparm);
 7634:     }
 7635:     if (!($uname && $udom)) {
 7636:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7637:       if (!$symbparm) {	$symbparm=$cursymb; }
 7638:     } else {
 7639: 	$courseid=$env{'request.course.id'};
 7640:     }
 7641:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7642:     my $rest;
 7643:     if (defined($therest[0])) {
 7644:        $rest=join('.',@therest);
 7645:     } else {
 7646:        $rest='';
 7647:     }
 7648: 
 7649:     my $qualifierrest=$qualifier;
 7650:     if ($rest) { $qualifierrest.='.'.$rest; }
 7651:     my $spacequalifierrest=$space;
 7652:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7653:     if ($realm eq 'user') {
 7654: # --------------------------------------------------------------- user.resource
 7655: 	if ($space eq 'resource') {
 7656: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7657: 		  || defined($Apache::lonhomework::parsing_a_task))
 7658: 		 &&
 7659: 		 ($symbparm eq &symbread()) ) {	
 7660: 		# if we are in the middle of processing the resource the
 7661: 		# get the value we are planning on committing
 7662:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7663:                     return $Apache::lonhomework::results{$qualifierrest};
 7664:                 } else {
 7665:                     return $Apache::lonhomework::history{$qualifierrest};
 7666:                 }
 7667: 	    } else {
 7668: 		my %restored;
 7669: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7670: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7671: 		} else {
 7672: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7673: 		}
 7674: 		return $restored{$qualifierrest};
 7675: 	    }
 7676: # ----------------------------------------------------------------- user.access
 7677:         } elsif ($space eq 'access') {
 7678: 	    # FIXME - not supporting calls for a specific user
 7679:             return &allowed($qualifier,$rest);
 7680: # ------------------------------------------ user.preferences, user.environment
 7681:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7682: 	    if (($uname eq $env{'user.name'}) &&
 7683: 		($udom eq $env{'user.domain'})) {
 7684: 		return $env{join('.',('environment',$qualifierrest))};
 7685: 	    } else {
 7686: 		my %returnhash;
 7687: 		if (!$publicuser) {
 7688: 		    %returnhash=&userenvironment($udom,$uname,
 7689: 						 $qualifierrest);
 7690: 		}
 7691: 		return $returnhash{$qualifierrest};
 7692: 	    }
 7693: # ----------------------------------------------------------------- user.course
 7694:         } elsif ($space eq 'course') {
 7695: 	    # FIXME - not supporting calls for a specific user
 7696:             return $env{join('.',('request.course',$qualifier))};
 7697: # ------------------------------------------------------------------- user.role
 7698:         } elsif ($space eq 'role') {
 7699: 	    # FIXME - not supporting calls for a specific user
 7700:             my ($role,$where)=split(/\./,$env{'request.role'});
 7701:             if ($qualifier eq 'value') {
 7702: 		return $role;
 7703:             } elsif ($qualifier eq 'extent') {
 7704:                 return $where;
 7705:             }
 7706: # ----------------------------------------------------------------- user.domain
 7707:         } elsif ($space eq 'domain') {
 7708:             return $udom;
 7709: # ------------------------------------------------------------------- user.name
 7710:         } elsif ($space eq 'name') {
 7711:             return $uname;
 7712: # ---------------------------------------------------- Any other user namespace
 7713:         } else {
 7714: 	    my %reply;
 7715: 	    if (!$publicuser) {
 7716: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7717: 	    }
 7718: 	    return $reply{$qualifierrest};
 7719:         }
 7720:     } elsif ($realm eq 'query') {
 7721: # ---------------------------------------------- pull stuff out of query string
 7722:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7723: 						[$spacequalifierrest]);
 7724: 	return $env{'form.'.$spacequalifierrest}; 
 7725:    } elsif ($realm eq 'request') {
 7726: # ------------------------------------------------------------- request.browser
 7727:         if ($space eq 'browser') {
 7728: 	    if ($qualifier eq 'textremote') {
 7729: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7730: 		    return 1;
 7731: 		} else {
 7732: 		    return 0;
 7733: 		}
 7734: 	    } else {
 7735: 		return $env{'browser.'.$qualifier};
 7736: 	    }
 7737: # ------------------------------------------------------------ request.filename
 7738:         } else {
 7739:             return $env{'request.'.$spacequalifierrest};
 7740:         }
 7741:     } elsif ($realm eq 'course') {
 7742: # ---------------------------------------------------------- course.description
 7743:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7744:     } elsif ($realm eq 'resource') {
 7745: 
 7746: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7747: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7748: 	}
 7749: 
 7750: 	if ($space eq 'title') {
 7751: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7752: 	    return &gettitle($symbparm);
 7753: 	}
 7754: 	
 7755: 	if ($space eq 'map') {
 7756: 	    my ($map) = &decode_symb($symbparm);
 7757: 	    return &symbread($map);
 7758: 	}
 7759: 	if ($space eq 'filename') {
 7760: 	    if ($symbparm) {
 7761: 		return &clutter((&decode_symb($symbparm))[2]);
 7762: 	    }
 7763: 	    return &hreflocation('',$env{'request.filename'});
 7764: 	}
 7765: 
 7766: 	my ($section, $group, @groups);
 7767: 	my ($courselevelm,$courselevel);
 7768: 	if ($symbparm && defined($courseid) && 
 7769: 	    $courseid eq $env{'request.course.id'}) {
 7770: 
 7771: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7772: 
 7773: # ----------------------------------------------------- Cascading lookup scheme
 7774: 	    my $symbp=$symbparm;
 7775: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7776: 
 7777: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7778: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7779: 
 7780: 	    if (($env{'user.name'} eq $uname) &&
 7781: 		($env{'user.domain'} eq $udom)) {
 7782: 		$section=$env{'request.course.sec'};
 7783:                 @groups = split(/:/,$env{'request.course.groups'});  
 7784:                 @groups=&sort_course_groups($courseid,@groups); 
 7785: 	    } else {
 7786: 		if (! defined($usection)) {
 7787: 		    $section=&getsection($udom,$uname,$courseid);
 7788: 		} else {
 7789: 		    $section = $usection;
 7790: 		}
 7791:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7792: 	    }
 7793: 
 7794: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7795: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7796: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7797: 
 7798: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7799: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7800: 	    $courselevelm=$courseid.'.'.$mapparm;
 7801: 
 7802: # ----------------------------------------------------------- first, check user
 7803: 
 7804: 	    my $userreply=&resdata($uname,$udom,'user',
 7805: 				       ([$courselevelr,'resource'],
 7806: 					[$courselevelm,'map'     ],
 7807: 					[$courselevel, 'course'  ]));
 7808: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7809: 
 7810: # ------------------------------------------------ second, check some of course
 7811:             my $coursereply;
 7812:             if (@groups > 0) {
 7813:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7814:                                        $mapparm,$spacequalifierrest);
 7815:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7816:             }
 7817: 
 7818: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7819: 				  $env{'course.'.$courseid.'.domain'},
 7820: 				  'course',
 7821: 				  ([$seclevelr,   'resource'],
 7822: 				   [$seclevelm,   'map'     ],
 7823: 				   [$seclevel,    'course'  ],
 7824: 				   [$courselevelr,'resource']));
 7825: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7826: 
 7827: # ------------------------------------------------------ third, check map parms
 7828: 	    my %parmhash=();
 7829: 	    my $thisparm='';
 7830: 	    if (tie(%parmhash,'GDBM_File',
 7831: 		    $env{'request.course.fn'}.'_parms.db',
 7832: 		    &GDBM_READER(),0640)) {
 7833: 		$thisparm=$parmhash{$symbparm};
 7834: 		untie(%parmhash);
 7835: 	    }
 7836: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7837: 	}
 7838: # ------------------------------------------ fourth, look in resource metadata
 7839: 
 7840: 	$spacequalifierrest=~s/\./\_/;
 7841: 	my $filename;
 7842: 	if (!$symbparm) { $symbparm=&symbread(); }
 7843: 	if ($symbparm) {
 7844: 	    $filename=(&decode_symb($symbparm))[2];
 7845: 	} else {
 7846: 	    $filename=$env{'request.filename'};
 7847: 	}
 7848: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7849: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7850: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7851: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7852: 
 7853: # ---------------------------------------------- fourth, look in rest of course
 7854: 	if ($symbparm && defined($courseid) && 
 7855: 	    $courseid eq $env{'request.course.id'}) {
 7856: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7857: 				     $env{'course.'.$courseid.'.domain'},
 7858: 				     'course',
 7859: 				     ([$courselevelm,'map'   ],
 7860: 				      [$courselevel, 'course']));
 7861: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7862: 	}
 7863: # ------------------------------------------------------------------ Cascade up
 7864: 	unless ($space eq '0') {
 7865: 	    my @parts=split(/_/,$space);
 7866: 	    my $id=pop(@parts);
 7867: 	    my $part=join('_',@parts);
 7868: 	    if ($part eq '') { $part='0'; }
 7869: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7870: 				 $symbparm,$udom,$uname,$section,1);
 7871: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7872: 	}
 7873: 	if ($recurse) { return undef; }
 7874: 	my $pack_def=&packages_tab_default($filename,$varname);
 7875: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7876: # ---------------------------------------------------- Any other user namespace
 7877:     } elsif ($realm eq 'environment') {
 7878: # ----------------------------------------------------------------- environment
 7879: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7880: 	    return $env{'environment.'.$spacequalifierrest};
 7881: 	} else {
 7882: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7883: 		return '';
 7884: 	    }
 7885: 	    my %returnhash=&userenvironment($udom,$uname,
 7886: 					    $spacequalifierrest);
 7887: 	    return $returnhash{$spacequalifierrest};
 7888: 	}
 7889:     } elsif ($realm eq 'system') {
 7890: # ----------------------------------------------------------------- system.time
 7891: 	if ($space eq 'time') {
 7892: 	    return time;
 7893:         }
 7894:     } elsif ($realm eq 'server') {
 7895: # ----------------------------------------------------------------- system.time
 7896: 	if ($space eq 'name') {
 7897: 	    return $ENV{'SERVER_NAME'};
 7898:         }
 7899:     }
 7900:     return '';
 7901: }
 7902: 
 7903: sub get_reply {
 7904:     my ($reply_value) = @_;
 7905:     if (ref($reply_value) eq 'ARRAY') {
 7906:         if (wantarray) {
 7907: 	    return @$reply_value;
 7908:         }
 7909:         return $reply_value->[0];
 7910:     } else {
 7911:         return $reply_value;
 7912:     }
 7913: }
 7914: 
 7915: sub check_group_parms {
 7916:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7917:     my @groupitems = ();
 7918:     my $resultitem;
 7919:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7920:     foreach my $group (@{$groups}) {
 7921:         foreach my $level (@levels) {
 7922:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7923:              push(@groupitems,[$item,$level->[1]]);
 7924:         }
 7925:     }
 7926:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7927:                             $env{'course.'.$courseid.'.domain'},
 7928:                                      'course',@groupitems);
 7929:     return $coursereply;
 7930: }
 7931: 
 7932: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7933:     my ($courseid,@groups) = @_;
 7934:     @groups = sort(@groups);
 7935:     return @groups;
 7936: }
 7937: 
 7938: sub packages_tab_default {
 7939:     my ($uri,$varname)=@_;
 7940:     my (undef,$part,$name)=split(/\./,$varname);
 7941: 
 7942:     my (@extension,@specifics,$do_default);
 7943:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7944: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7945: 	if ($pack_type eq 'default') {
 7946: 	    $do_default=1;
 7947: 	} elsif ($pack_type eq 'extension') {
 7948: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7949: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7950: 	    # only look at packages defaults for packages that this id is
 7951: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7952: 	}
 7953:     }
 7954:     # first look for a package that matches the requested part id
 7955:     foreach my $package (@specifics) {
 7956: 	my (undef,$pack_type,$pack_part)=@{$package};
 7957: 	next if ($pack_part ne $part);
 7958: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7959: 	    return $packagetab{"$pack_type&$name&default"};
 7960: 	}
 7961:     }
 7962:     # look for any possible matching non extension_ package
 7963:     foreach my $package (@specifics) {
 7964: 	my (undef,$pack_type,$pack_part)=@{$package};
 7965: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7966: 	    return $packagetab{"$pack_type&$name&default"};
 7967: 	}
 7968: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7969: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7970: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7971: 	}
 7972:     }
 7973:     # look for any posible extension_ match
 7974:     foreach my $package (@extension) {
 7975: 	my ($package,$pack_type)=@{$package};
 7976: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7977: 	    return $packagetab{"$pack_type&$name&default"};
 7978: 	}
 7979: 	if (defined($packagetab{$package."&$name&default"})) {
 7980: 	    return $packagetab{$package."&$name&default"};
 7981: 	}
 7982:     }
 7983:     # look for a global default setting
 7984:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7985: 	return $packagetab{"default&$name&default"};
 7986:     }
 7987:     return undef;
 7988: }
 7989: 
 7990: sub add_prefix_and_part {
 7991:     my ($prefix,$part)=@_;
 7992:     my $keyroot;
 7993:     if (defined($prefix) && $prefix !~ /^__/) {
 7994: 	# prefix that has a part already
 7995: 	$keyroot=$prefix;
 7996:     } elsif (defined($prefix)) {
 7997: 	# prefix that is missing a part
 7998: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7999:     } else {
 8000: 	# no prefix at all
 8001: 	if (defined($part)) { $keyroot='_'.$part; }
 8002:     }
 8003:     return $keyroot;
 8004: }
 8005: 
 8006: # ---------------------------------------------------------------- Get metadata
 8007: 
 8008: my %metaentry;
 8009: sub metadata {
 8010:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 8011:     $uri=&declutter($uri);
 8012:     # if it is a non metadata possible uri return quickly
 8013:     if (($uri eq '') || 
 8014: 	(($uri =~ m|^/*adm/|) && 
 8015: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 8016:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 8017: 	return undef;
 8018:     }
 8019:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 8020: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 8021: 	return undef;
 8022:     }
 8023:     my $filename=$uri;
 8024:     $uri=~s/\.meta$//;
 8025: #
 8026: # Is the metadata already cached?
 8027: # Look at timestamp of caching
 8028: # Everything is cached by the main uri, libraries are never directly cached
 8029: #
 8030:     if (!defined($liburi)) {
 8031: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 8032: 	if (defined($cached)) { return $result->{':'.$what}; }
 8033:     }
 8034:     {
 8035: #
 8036: # Is this a recursive call for a library?
 8037: #
 8038: #	if (! exists($metacache{$uri})) {
 8039: #	    $metacache{$uri}={};
 8040: #	}
 8041: 	my $cachetime = 60*60;
 8042:         if ($liburi) {
 8043: 	    $liburi=&declutter($liburi);
 8044:             $filename=$liburi;
 8045:         } else {
 8046: 	    &devalidate_cache_new('meta',$uri);
 8047: 	    undef(%metaentry);
 8048: 	}
 8049:         my %metathesekeys=();
 8050:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 8051: 	my $metastring;
 8052: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 8053: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 8054: 	    $metastring = 
 8055: 		&Apache::lonnet::ssi_body($which,
 8056: 					  ('grade_target' => 'meta'));
 8057: 	    $cachetime = 1; # only want this cached in the child not long term
 8058: 	} elsif ($uri !~ m -^(editupload)/-) {
 8059: 	    my $file=&filelocation('',&clutter($filename));
 8060: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 8061: 	    $metastring=&getfile($file);
 8062: 	}
 8063:         my $parser=HTML::LCParser->new(\$metastring);
 8064:         my $token;
 8065:         undef %metathesekeys;
 8066:         while ($token=$parser->get_token) {
 8067: 	    if ($token->[0] eq 'S') {
 8068: 		if (defined($token->[2]->{'package'})) {
 8069: #
 8070: # This is a package - get package info
 8071: #
 8072: 		    my $package=$token->[2]->{'package'};
 8073: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8074: 		    if (defined($token->[2]->{'id'})) { 
 8075: 			$keyroot.='_'.$token->[2]->{'id'}; 
 8076: 		    }
 8077: 		    if ($metaentry{':packages'}) {
 8078: 			$metaentry{':packages'}.=','.$package.$keyroot;
 8079: 		    } else {
 8080: 			$metaentry{':packages'}=$package.$keyroot;
 8081: 		    }
 8082: 		    foreach my $pack_entry (keys(%packagetab)) {
 8083: 			my $part=$keyroot;
 8084: 			$part=~s/^\_//;
 8085: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 8086: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 8087: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 8088: 			    # ignore package.tab specified default values
 8089:                             # here &package_tab_default() will fetch those
 8090: 			    if ($subp eq 'default') { next; }
 8091: 			    my $value=$packagetab{$pack_entry};
 8092: 			    my $unikey;
 8093: 			    if ($pack =~ /_0$/) {
 8094: 				$unikey='parameter_0_'.$name;
 8095: 				$part=0;
 8096: 			    } else {
 8097: 				$unikey='parameter'.$keyroot.'_'.$name;
 8098: 			    }
 8099: 			    if ($subp eq 'display') {
 8100: 				$value.=' [Part: '.$part.']';
 8101: 			    }
 8102: 			    $metaentry{':'.$unikey.'.part'}=$part;
 8103: 			    $metathesekeys{$unikey}=1;
 8104: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8105: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 8106: 			    }
 8107: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 8108: 				$metaentry{':'.$unikey}=
 8109: 				    $metaentry{':'.$unikey.'.default'};
 8110: 			    }
 8111: 			}
 8112: 		    }
 8113: 		} else {
 8114: #
 8115: # This is not a package - some other kind of start tag
 8116: #
 8117: 		    my $entry=$token->[1];
 8118: 		    my $unikey;
 8119: 		    if ($entry eq 'import') {
 8120: 			$unikey='';
 8121: 		    } else {
 8122: 			$unikey=$entry;
 8123: 		    }
 8124: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8125: 
 8126: 		    if (defined($token->[2]->{'id'})) { 
 8127: 			$unikey.='_'.$token->[2]->{'id'}; 
 8128: 		    }
 8129: 
 8130: 		    if ($entry eq 'import') {
 8131: #
 8132: # Importing a library here
 8133: #
 8134: 			if ($depthcount<20) {
 8135: 			    my $location=$parser->get_text('/import');
 8136: 			    my $dir=$filename;
 8137: 			    $dir=~s|[^/]*$||;
 8138: 			    $location=&filelocation($dir,$location);
 8139: 			    my $metadata = 
 8140: 				&metadata($uri,'keys', $location,$unikey,
 8141: 					  $depthcount+1);
 8142: 			    foreach my $meta (split(',',$metadata)) {
 8143: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 8144: 				$metathesekeys{$meta}=1;
 8145: 			    }
 8146: 			}
 8147: 		    } else { 
 8148: 			
 8149: 			if (defined($token->[2]->{'name'})) { 
 8150: 			    $unikey.='_'.$token->[2]->{'name'}; 
 8151: 			}
 8152: 			$metathesekeys{$unikey}=1;
 8153: 			foreach my $param (@{$token->[3]}) {
 8154: 			    $metaentry{':'.$unikey.'.'.$param} =
 8155: 				$token->[2]->{$param};
 8156: 			}
 8157: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 8158: 			my $default=$metaentry{':'.$unikey.'.default'};
 8159: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 8160: 		 # only ws inside the tag, and not in default, so use default
 8161: 		 # as value
 8162: 			    $metaentry{':'.$unikey}=$default;
 8163: 			} elsif ( $internaltext =~ /\S/ ) {
 8164: 		  # something interesting inside the tag
 8165: 			    $metaentry{':'.$unikey}=$internaltext;
 8166: 			} else {
 8167: 		  # no interesting values, don't set a default
 8168: 			}
 8169: # end of not-a-package not-a-library import
 8170: 		    }
 8171: # end of not-a-package start tag
 8172: 		}
 8173: # the next is the end of "start tag"
 8174: 	    }
 8175: 	}
 8176: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 8177: 	$extension = lc($extension);
 8178: 	if ($extension eq 'htm') { $extension='html'; }
 8179: 
 8180: 	foreach my $key (keys(%packagetab)) {
 8181: 	    #no specific packages #how's our extension
 8182: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 8183: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 8184: 					 \%metathesekeys);
 8185: 	}
 8186: 
 8187: 	if (!exists($metaentry{':packages'})
 8188: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 8189: 	    foreach my $key (keys(%packagetab)) {
 8190: 		#no specific packages well let's get default then
 8191: 		if ($key!~/^default&/) { next; }
 8192: 		&metadata_create_package_def($uri,$key,'default',
 8193: 					     \%metathesekeys);
 8194: 	    }
 8195: 	}
 8196: # are there custom rights to evaluate
 8197: 	if ($metaentry{':copyright'} eq 'custom') {
 8198: 
 8199:     #
 8200:     # Importing a rights file here
 8201:     #
 8202: 	    unless ($depthcount) {
 8203: 		my $location=$metaentry{':customdistributionfile'};
 8204: 		my $dir=$filename;
 8205: 		$dir=~s|[^/]*$||;
 8206: 		$location=&filelocation($dir,$location);
 8207: 		my $rights_metadata =
 8208: 		    &metadata($uri,'keys',$location,'_rights',
 8209: 			      $depthcount+1);
 8210: 		foreach my $rights (split(',',$rights_metadata)) {
 8211: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 8212: 		    $metathesekeys{$rights}=1;
 8213: 		}
 8214: 	    }
 8215: 	}
 8216: 	# uniqifiy package listing
 8217: 	my %seen;
 8218: 	my @uniq_packages =
 8219: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 8220: 	$metaentry{':packages'} = join(',',@uniq_packages);
 8221: 
 8222: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 8223: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 8224: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 8225: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 8226: # this is the end of "was not already recently cached
 8227:     }
 8228:     return $metaentry{':'.$what};
 8229: }
 8230: 
 8231: sub metadata_create_package_def {
 8232:     my ($uri,$key,$package,$metathesekeys)=@_;
 8233:     my ($pack,$name,$subp)=split(/\&/,$key);
 8234:     if ($subp eq 'default') { next; }
 8235:     
 8236:     if (defined($metaentry{':packages'})) {
 8237: 	$metaentry{':packages'}.=','.$package;
 8238:     } else {
 8239: 	$metaentry{':packages'}=$package;
 8240:     }
 8241:     my $value=$packagetab{$key};
 8242:     my $unikey;
 8243:     $unikey='parameter_0_'.$name;
 8244:     $metaentry{':'.$unikey.'.part'}=0;
 8245:     $$metathesekeys{$unikey}=1;
 8246:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8247: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 8248:     }
 8249:     if (defined($metaentry{':'.$unikey.'.default'})) {
 8250: 	$metaentry{':'.$unikey}=
 8251: 	    $metaentry{':'.$unikey.'.default'};
 8252:     }
 8253: }
 8254: 
 8255: sub metadata_generate_part0 {
 8256:     my ($metadata,$metacache,$uri) = @_;
 8257:     my %allnames;
 8258:     foreach my $metakey (keys(%$metadata)) {
 8259: 	if ($metakey=~/^parameter\_(.*)/) {
 8260: 	  my $part=$$metacache{':'.$metakey.'.part'};
 8261: 	  my $name=$$metacache{':'.$metakey.'.name'};
 8262: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 8263: 	    $allnames{$name}=$part;
 8264: 	  }
 8265: 	}
 8266:     }
 8267:     foreach my $name (keys(%allnames)) {
 8268:       $$metadata{"parameter_0_$name"}=1;
 8269:       my $key=":parameter_0_$name";
 8270:       $$metacache{"$key.part"}='0';
 8271:       $$metacache{"$key.name"}=$name;
 8272:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 8273: 					   $allnames{$name}.'_'.$name.
 8274: 					   '.type'};
 8275:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 8276: 			     '.display'};
 8277:       my $expr='[Part: '.$allnames{$name}.']';
 8278:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 8279:       $$metacache{"$key.display"}=$olddis;
 8280:     }
 8281: }
 8282: 
 8283: # ------------------------------------------------------ Devalidate title cache
 8284: 
 8285: sub devalidate_title_cache {
 8286:     my ($url)=@_;
 8287:     if (!$env{'request.course.id'}) { return; }
 8288:     my $symb=&symbread($url);
 8289:     if (!$symb) { return; }
 8290:     my $key=$env{'request.course.id'}."\0".$symb;
 8291:     &devalidate_cache_new('title',$key);
 8292: }
 8293: 
 8294: # ------------------------------------------------- Get the title of a course
 8295: 
 8296: sub current_course_title {
 8297:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 8298: }
 8299: # ------------------------------------------------- Get the title of a resource
 8300: 
 8301: sub gettitle {
 8302:     my $urlsymb=shift;
 8303:     my $symb=&symbread($urlsymb);
 8304:     if ($symb) {
 8305: 	my $key=$env{'request.course.id'}."\0".$symb;
 8306: 	my ($result,$cached)=&is_cached_new('title',$key);
 8307: 	if (defined($cached)) { 
 8308: 	    return $result;
 8309: 	}
 8310: 	my ($map,$resid,$url)=&decode_symb($symb);
 8311: 	my $title='';
 8312: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 8313: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 8314: 	} else {
 8315: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8316: 		    &GDBM_READER(),0640)) {
 8317: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 8318: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 8319: 		untie(%bighash);
 8320: 	    }
 8321: 	}
 8322: 	$title=~s/\&colon\;/\:/gs;
 8323: 	if ($title) {
 8324: 	    return &do_cache_new('title',$key,$title,600);
 8325: 	}
 8326: 	$urlsymb=$url;
 8327:     }
 8328:     my $title=&metadata($urlsymb,'title');
 8329:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 8330:     return $title;
 8331: }
 8332: 
 8333: sub get_slot {
 8334:     my ($which,$cnum,$cdom)=@_;
 8335:     if (!$cnum || !$cdom) {
 8336: 	(undef,my $courseid)=&whichuser();
 8337: 	$cdom=$env{'course.'.$courseid.'.domain'};
 8338: 	$cnum=$env{'course.'.$courseid.'.num'};
 8339:     }
 8340:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 8341:     my %slotinfo;
 8342:     if (exists($remembered{$key})) {
 8343: 	$slotinfo{$which} = $remembered{$key};
 8344:     } else {
 8345: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 8346: 	&Apache::lonhomework::showhash(%slotinfo);
 8347: 	my ($tmp)=keys(%slotinfo);
 8348: 	if ($tmp=~/^error:/) { return (); }
 8349: 	$remembered{$key} = $slotinfo{$which};
 8350:     }
 8351:     if (ref($slotinfo{$which}) eq 'HASH') {
 8352: 	return %{$slotinfo{$which}};
 8353:     }
 8354:     return $slotinfo{$which};
 8355: }
 8356: # ------------------------------------------------- Update symbolic store links
 8357: 
 8358: sub symblist {
 8359:     my ($mapname,%newhash)=@_;
 8360:     $mapname=&deversion(&declutter($mapname));
 8361:     my %hash;
 8362:     if (($env{'request.course.fn'}) && (%newhash)) {
 8363:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8364:                       &GDBM_WRCREAT(),0640)) {
 8365: 	    foreach my $url (keys(%newhash)) {
 8366: 		next if ($url eq 'last_known'
 8367: 			 && $env{'form.no_update_last_known'});
 8368: 		$hash{declutter($url)}=&encode_symb($mapname,
 8369: 						    $newhash{$url}->[1],
 8370: 						    $newhash{$url}->[0]);
 8371:             }
 8372:             if (untie(%hash)) {
 8373: 		return 'ok';
 8374:             }
 8375:         }
 8376:     }
 8377:     return 'error';
 8378: }
 8379: 
 8380: # --------------------------------------------------------------- Verify a symb
 8381: 
 8382: sub symbverify {
 8383:     my ($symb,$thisurl)=@_;
 8384:     my $thisfn=$thisurl;
 8385:     $thisfn=&declutter($thisfn);
 8386: # direct jump to resource in page or to a sequence - will construct own symbs
 8387:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8388: # check URL part
 8389:     my ($map,$resid,$url)=&decode_symb($symb);
 8390: 
 8391:     unless ($url eq $thisfn) { return 0; }
 8392: 
 8393:     $symb=&symbclean($symb);
 8394:     $thisurl=&deversion($thisurl);
 8395:     $thisfn=&deversion($thisfn);
 8396: 
 8397:     my %bighash;
 8398:     my $okay=0;
 8399: 
 8400:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8401:                             &GDBM_READER(),0640)) {
 8402:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 8403:             $thisurl =~ s/\?.+$//;
 8404:         }
 8405:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8406:         unless ($ids) { 
 8407:            $ids=$bighash{'ids_/'.$thisurl};
 8408:         }
 8409:         if ($ids) {
 8410: # ------------------------------------------------------------------- Has ID(s)
 8411: 	    foreach my $id (split(/\,/,$ids)) {
 8412: 	       my ($mapid,$resid)=split(/\./,$id);
 8413:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 8414:                    $symb =~ s/\?.+$//;
 8415:                }
 8416:                if (
 8417:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8418:    eq $symb) { 
 8419: 		   if (($env{'request.role.adv'}) ||
 8420: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8421: 		       $okay=1; 
 8422: 		   }
 8423: 	       }
 8424: 	   }
 8425:         }
 8426: 	untie(%bighash);
 8427:     }
 8428:     return $okay;
 8429: }
 8430: 
 8431: # --------------------------------------------------------------- Clean-up symb
 8432: 
 8433: sub symbclean {
 8434:     my $symb=shift;
 8435:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8436: # remove version from map
 8437:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8438: 
 8439: # remove version from URL
 8440:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8441: 
 8442: # remove wrapper
 8443: 
 8444:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8445:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8446:     return $symb;
 8447: }
 8448: 
 8449: # ---------------------------------------------- Split symb to find map and url
 8450: 
 8451: sub encode_symb {
 8452:     my ($map,$resid,$url)=@_;
 8453:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8454: }
 8455: 
 8456: sub decode_symb {
 8457:     my $symb=shift;
 8458:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8459:     my ($map,$resid,$url)=split(/___/,$symb);
 8460:     return (&fixversion($map),$resid,&fixversion($url));
 8461: }
 8462: 
 8463: sub fixversion {
 8464:     my $fn=shift;
 8465:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8466:     my %bighash;
 8467:     my $uri=&clutter($fn);
 8468:     my $key=$env{'request.course.id'}.'_'.$uri;
 8469: # is this cached?
 8470:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8471:     if (defined($cached)) { return $result; }
 8472: # unfortunately not cached, or expired
 8473:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8474: 	    &GDBM_READER(),0640)) {
 8475:  	if ($bighash{'version_'.$uri}) {
 8476:  	    my $version=$bighash{'version_'.$uri};
 8477:  	    unless (($version eq 'mostrecent') || 
 8478: 		    ($version==&getversion($uri))) {
 8479:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8480:  	    }
 8481:  	}
 8482:  	untie %bighash;
 8483:     }
 8484:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8485: }
 8486: 
 8487: sub deversion {
 8488:     my $url=shift;
 8489:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8490:     return $url;
 8491: }
 8492: 
 8493: # ------------------------------------------------------ Return symb list entry
 8494: 
 8495: sub symbread {
 8496:     my ($thisfn,$donotrecurse)=@_;
 8497:     my $cache_str='request.symbread.cached.'.$thisfn;
 8498:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8499: # no filename provided? try from environment
 8500:     unless ($thisfn) {
 8501:         if ($env{'request.symb'}) {
 8502: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8503: 	}
 8504: 	$thisfn=$env{'request.filename'};
 8505:     }
 8506:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8507: # is that filename actually a symb? Verify, clean, and return
 8508:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8509: 	if (&symbverify($thisfn,$1)) {
 8510: 	    return $env{$cache_str}=&symbclean($thisfn);
 8511: 	}
 8512:     }
 8513:     $thisfn=declutter($thisfn);
 8514:     my %hash;
 8515:     my %bighash;
 8516:     my $syval='';
 8517:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8518:         my $targetfn = $thisfn;
 8519:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8520:             $targetfn = 'adm/wrapper/'.$thisfn;
 8521:         }
 8522: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8523: 	    $targetfn=$1;
 8524: 	}
 8525:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8526:                       &GDBM_READER(),0640)) {
 8527: 	    $syval=$hash{$targetfn};
 8528:             untie(%hash);
 8529:         }
 8530: # ---------------------------------------------------------- There was an entry
 8531:         if ($syval) {
 8532: 	    #unless ($syval=~/\_\d+$/) {
 8533: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8534: 		    #&appenv({'request.ambiguous' => $thisfn});
 8535: 		    #return $env{$cache_str}='';
 8536: 		#}    
 8537: 		#$syval.=$1;
 8538: 	    #}
 8539:         } else {
 8540: # ------------------------------------------------------- Was not in symb table
 8541:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8542:                             &GDBM_READER(),0640)) {
 8543: # ---------------------------------------------- Get ID(s) for current resource
 8544:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8545:               unless ($ids) { 
 8546:                  $ids=$bighash{'ids_/'.$thisfn};
 8547:               }
 8548:               unless ($ids) {
 8549: # alias?
 8550: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8551:               }
 8552:               if ($ids) {
 8553: # ------------------------------------------------------------------- Has ID(s)
 8554:                  my @possibilities=split(/\,/,$ids);
 8555:                  if ($#possibilities==0) {
 8556: # ----------------------------------------------- There is only one possibility
 8557: 		     my ($mapid,$resid)=split(/\./,$ids);
 8558: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8559: 						    $resid,$thisfn);
 8560:                  } elsif (!$donotrecurse) {
 8561: # ------------------------------------------ There is more than one possibility
 8562:                      my $realpossible=0;
 8563:                      foreach my $id (@possibilities) {
 8564: 			 my $file=$bighash{'src_'.$id};
 8565:                          if (&allowed('bre',$file)) {
 8566:          		    my ($mapid,$resid)=split(/\./,$id);
 8567:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8568: 				$realpossible++;
 8569:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8570: 						    $resid,$thisfn);
 8571:                             }
 8572: 			 }
 8573:                      }
 8574: 		     if ($realpossible!=1) { $syval=''; }
 8575:                  } else {
 8576:                      $syval='';
 8577:                  }
 8578: 	      }
 8579:               untie(%bighash)
 8580:            }
 8581:         }
 8582:         if ($syval) {
 8583: 	    return $env{$cache_str}=$syval;
 8584:         }
 8585:     }
 8586:     &appenv({'request.ambiguous' => $thisfn});
 8587:     return $env{$cache_str}='';
 8588: }
 8589: 
 8590: # ---------------------------------------------------------- Return random seed
 8591: 
 8592: sub numval {
 8593:     my $txt=shift;
 8594:     $txt=~tr/A-J/0-9/;
 8595:     $txt=~tr/a-j/0-9/;
 8596:     $txt=~tr/K-T/0-9/;
 8597:     $txt=~tr/k-t/0-9/;
 8598:     $txt=~tr/U-Z/0-5/;
 8599:     $txt=~tr/u-z/0-5/;
 8600:     $txt=~s/\D//g;
 8601:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8602:     return int($txt);
 8603: }
 8604: 
 8605: sub numval2 {
 8606:     my $txt=shift;
 8607:     $txt=~tr/A-J/0-9/;
 8608:     $txt=~tr/a-j/0-9/;
 8609:     $txt=~tr/K-T/0-9/;
 8610:     $txt=~tr/k-t/0-9/;
 8611:     $txt=~tr/U-Z/0-5/;
 8612:     $txt=~tr/u-z/0-5/;
 8613:     $txt=~s/\D//g;
 8614:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8615:     my $total;
 8616:     foreach my $val (@txts) { $total+=$val; }
 8617:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8618:     return int($total);
 8619: }
 8620: 
 8621: sub numval3 {
 8622:     use integer;
 8623:     my $txt=shift;
 8624:     $txt=~tr/A-J/0-9/;
 8625:     $txt=~tr/a-j/0-9/;
 8626:     $txt=~tr/K-T/0-9/;
 8627:     $txt=~tr/k-t/0-9/;
 8628:     $txt=~tr/U-Z/0-5/;
 8629:     $txt=~tr/u-z/0-5/;
 8630:     $txt=~s/\D//g;
 8631:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8632:     my $total;
 8633:     foreach my $val (@txts) { $total+=$val; }
 8634:     if ($_64bit) { $total=(($total<<32)>>32); }
 8635:     return $total;
 8636: }
 8637: 
 8638: sub digest {
 8639:     my ($data)=@_;
 8640:     my $digest=&Digest::MD5::md5($data);
 8641:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8642:     my ($e,$f);
 8643:     {
 8644:         use integer;
 8645:         $e=($a+$b);
 8646:         $f=($c+$d);
 8647:         if ($_64bit) {
 8648:             $e=(($e<<32)>>32);
 8649:             $f=(($f<<32)>>32);
 8650:         }
 8651:     }
 8652:     if (wantarray) {
 8653: 	return ($e,$f);
 8654:     } else {
 8655: 	my $g;
 8656: 	{
 8657: 	    use integer;
 8658: 	    $g=($e+$f);
 8659: 	    if ($_64bit) {
 8660: 		$g=(($g<<32)>>32);
 8661: 	    }
 8662: 	}
 8663: 	return $g;
 8664:     }
 8665: }
 8666: 
 8667: sub latest_rnd_algorithm_id {
 8668:     return '64bit5';
 8669: }
 8670: 
 8671: sub get_rand_alg {
 8672:     my ($courseid)=@_;
 8673:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8674:     if ($courseid) {
 8675: 	return $env{"course.$courseid.rndseed"};
 8676:     }
 8677:     return &latest_rnd_algorithm_id();
 8678: }
 8679: 
 8680: sub validCODE {
 8681:     my ($CODE)=@_;
 8682:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8683:     return 0;
 8684: }
 8685: 
 8686: sub getCODE {
 8687:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8688:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8689: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8690: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8691: 	return $Apache::lonhomework::history{'resource.CODE'};
 8692:     }
 8693:     return undef;
 8694: }
 8695: 
 8696: sub rndseed {
 8697:     my ($symb,$courseid,$domain,$username)=@_;
 8698:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8699:     if (!defined($symb)) {
 8700: 	unless ($symb=$wsymb) { return time; }
 8701:     }
 8702:     if (!$courseid) { $courseid=$wcourseid; }
 8703:     if (!$domain) { $domain=$wdomain; }
 8704:     if (!$username) { $username=$wusername }
 8705:     my $which=&get_rand_alg();
 8706: 
 8707:     if (defined(&getCODE())) {
 8708: 	if ($which eq '64bit5') {
 8709: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8710: 	} elsif ($which eq '64bit4') {
 8711: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8712: 	} else {
 8713: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8714: 	}
 8715:     } elsif ($which eq '64bit5') {
 8716: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8717:     } elsif ($which eq '64bit4') {
 8718: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8719:     } elsif ($which eq '64bit3') {
 8720: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8721:     } elsif ($which eq '64bit2') {
 8722: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8723:     } elsif ($which eq '64bit') {
 8724: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8725:     }
 8726:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8727: }
 8728: 
 8729: sub rndseed_32bit {
 8730:     my ($symb,$courseid,$domain,$username)=@_;
 8731:     {
 8732: 	use integer;
 8733: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8734: 	my $symbseed=numval($symb) << 22;
 8735: 	my $namechck=unpack("%32C*",$username) << 17;
 8736: 	my $nameseed=numval($username) << 12;
 8737: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8738: 	my $courseseed=unpack("%32C*",$courseid);
 8739: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8740: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8741: 	#&logthis("rndseed :$num:$symb");
 8742: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8743: 	return $num;
 8744:     }
 8745: }
 8746: 
 8747: sub rndseed_64bit {
 8748:     my ($symb,$courseid,$domain,$username)=@_;
 8749:     {
 8750: 	use integer;
 8751: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8752: 	my $symbseed=numval($symb) << 10;
 8753: 	my $namechck=unpack("%32S*",$username);
 8754: 	
 8755: 	my $nameseed=numval($username) << 21;
 8756: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8757: 	my $courseseed=unpack("%32S*",$courseid);
 8758: 	
 8759: 	my $num1=$symbchck+$symbseed+$namechck;
 8760: 	my $num2=$nameseed+$domainseed+$courseseed;
 8761: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8762: 	#&logthis("rndseed :$num:$symb");
 8763: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8764: 	return "$num1,$num2";
 8765:     }
 8766: }
 8767: 
 8768: sub rndseed_64bit2 {
 8769:     my ($symb,$courseid,$domain,$username)=@_;
 8770:     {
 8771: 	use integer;
 8772: 	# strings need to be an even # of cahracters long, it it is odd the
 8773:         # last characters gets thrown away
 8774: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8775: 	my $symbseed=numval($symb) << 10;
 8776: 	my $namechck=unpack("%32S*",$username.' ');
 8777: 	
 8778: 	my $nameseed=numval($username) << 21;
 8779: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8780: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8781: 	
 8782: 	my $num1=$symbchck+$symbseed+$namechck;
 8783: 	my $num2=$nameseed+$domainseed+$courseseed;
 8784: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8785: 	#&logthis("rndseed :$num:$symb");
 8786: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8787: 	return "$num1,$num2";
 8788:     }
 8789: }
 8790: 
 8791: sub rndseed_64bit3 {
 8792:     my ($symb,$courseid,$domain,$username)=@_;
 8793:     {
 8794: 	use integer;
 8795: 	# strings need to be an even # of cahracters long, it it is odd the
 8796:         # last characters gets thrown away
 8797: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8798: 	my $symbseed=numval2($symb) << 10;
 8799: 	my $namechck=unpack("%32S*",$username.' ');
 8800: 	
 8801: 	my $nameseed=numval2($username) << 21;
 8802: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8803: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8804: 	
 8805: 	my $num1=$symbchck+$symbseed+$namechck;
 8806: 	my $num2=$nameseed+$domainseed+$courseseed;
 8807: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8808: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8809: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8810: 	
 8811: 	return "$num1:$num2";
 8812:     }
 8813: }
 8814: 
 8815: sub rndseed_64bit4 {
 8816:     my ($symb,$courseid,$domain,$username)=@_;
 8817:     {
 8818: 	use integer;
 8819: 	# strings need to be an even # of cahracters long, it it is odd the
 8820:         # last characters gets thrown away
 8821: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8822: 	my $symbseed=numval3($symb) << 10;
 8823: 	my $namechck=unpack("%32S*",$username.' ');
 8824: 	
 8825: 	my $nameseed=numval3($username) << 21;
 8826: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8827: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8828: 	
 8829: 	my $num1=$symbchck+$symbseed+$namechck;
 8830: 	my $num2=$nameseed+$domainseed+$courseseed;
 8831: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8832: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8833: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8834: 	
 8835: 	return "$num1:$num2";
 8836:     }
 8837: }
 8838: 
 8839: sub rndseed_64bit5 {
 8840:     my ($symb,$courseid,$domain,$username)=@_;
 8841:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8842:     return "$num1:$num2";
 8843: }
 8844: 
 8845: sub rndseed_CODE_64bit {
 8846:     my ($symb,$courseid,$domain,$username)=@_;
 8847:     {
 8848: 	use integer;
 8849: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8850: 	my $symbseed=numval2($symb);
 8851: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8852: 	my $CODEseed=numval(&getCODE());
 8853: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8854: 	my $num1=$symbseed+$CODEchck;
 8855: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8856: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8857: 	#&logthis("rndseed :$num1:$num2:$symb");
 8858: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8859: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8860: 	return "$num1:$num2";
 8861:     }
 8862: }
 8863: 
 8864: sub rndseed_CODE_64bit4 {
 8865:     my ($symb,$courseid,$domain,$username)=@_;
 8866:     {
 8867: 	use integer;
 8868: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8869: 	my $symbseed=numval3($symb);
 8870: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8871: 	my $CODEseed=numval3(&getCODE());
 8872: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8873: 	my $num1=$symbseed+$CODEchck;
 8874: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8875: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8876: 	#&logthis("rndseed :$num1:$num2:$symb");
 8877: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8878: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8879: 	return "$num1:$num2";
 8880:     }
 8881: }
 8882: 
 8883: sub rndseed_CODE_64bit5 {
 8884:     my ($symb,$courseid,$domain,$username)=@_;
 8885:     my $code = &getCODE();
 8886:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8887:     return "$num1:$num2";
 8888: }
 8889: 
 8890: sub setup_random_from_rndseed {
 8891:     my ($rndseed)=@_;
 8892:     if ($rndseed =~/([,:])/) {
 8893: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8894: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8895:     } else {
 8896: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8897:     }
 8898: }
 8899: 
 8900: sub latest_receipt_algorithm_id {
 8901:     return 'receipt3';
 8902: }
 8903: 
 8904: sub recunique {
 8905:     my $fucourseid=shift;
 8906:     my $unique;
 8907:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8908: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8909: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8910:     } else {
 8911: 	$unique=$perlvar{'lonReceipt'};
 8912:     }
 8913:     return unpack("%32C*",$unique);
 8914: }
 8915: 
 8916: sub recprefix {
 8917:     my $fucourseid=shift;
 8918:     my $prefix;
 8919:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8920: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8921: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8922:     } else {
 8923: 	$prefix=$perlvar{'lonHostID'};
 8924:     }
 8925:     return unpack("%32C*",$prefix);
 8926: }
 8927: 
 8928: sub ireceipt {
 8929:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8930: 
 8931:     my $return =&recprefix($fucourseid).'-';
 8932: 
 8933:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8934: 	$env{'request.state'} eq 'construct') {
 8935: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8936: 	return $return;
 8937:     }
 8938: 
 8939:     my $cuname=unpack("%32C*",$funame);
 8940:     my $cudom=unpack("%32C*",$fudom);
 8941:     my $cucourseid=unpack("%32C*",$fucourseid);
 8942:     my $cusymb=unpack("%32C*",$fusymb);
 8943:     my $cunique=&recunique($fucourseid);
 8944:     my $cpart=unpack("%32S*",$part);
 8945:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8946: 
 8947: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8948: 			       
 8949: 	$return.= ($cunique%$cuname+
 8950: 		   $cunique%$cudom+
 8951: 		   $cusymb%$cuname+
 8952: 		   $cusymb%$cudom+
 8953: 		   $cucourseid%$cuname+
 8954: 		   $cucourseid%$cudom+
 8955: 		   $cpart%$cuname+
 8956: 		   $cpart%$cudom);
 8957:     } else {
 8958: 	$return.= ($cunique%$cuname+
 8959: 		   $cunique%$cudom+
 8960: 		   $cusymb%$cuname+
 8961: 		   $cusymb%$cudom+
 8962: 		   $cucourseid%$cuname+
 8963: 		   $cucourseid%$cudom);
 8964:     }
 8965:     return $return;
 8966: }
 8967: 
 8968: sub receipt {
 8969:     my ($part)=@_;
 8970:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8971:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8972: }
 8973: 
 8974: sub whichuser {
 8975:     my ($passedsymb)=@_;
 8976:     my ($symb,$courseid,$domain,$name,$publicuser);
 8977:     if (defined($env{'form.grade_symb'})) {
 8978: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8979: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8980: 	if (!$allowed &&
 8981: 	    exists($env{'request.course.sec'}) &&
 8982: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8983: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8984: 			      '/'.$env{'request.course.sec'});
 8985: 	}
 8986: 	if ($allowed) {
 8987: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8988: 	    $courseid=$tmp_courseid;
 8989: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8990: 	    ($name)=&get_env_multiple('form.grade_username');
 8991: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8992: 	}
 8993:     }
 8994:     if (!$passedsymb) {
 8995: 	$symb=&symbread();
 8996:     } else {
 8997: 	$symb=$passedsymb;
 8998:     }
 8999:     $courseid=$env{'request.course.id'};
 9000:     $domain=$env{'user.domain'};
 9001:     $name=$env{'user.name'};
 9002:     if ($name eq 'public' && $domain eq 'public') {
 9003: 	if (!defined($env{'form.username'})) {
 9004: 	    $env{'form.username'}.=time.rand(10000000);
 9005: 	}
 9006: 	$name.=$env{'form.username'};
 9007:     }
 9008:     return ($symb,$courseid,$domain,$name,$publicuser);
 9009: 
 9010: }
 9011: 
 9012: # ------------------------------------------------------------ Serves up a file
 9013: # returns either the contents of the file or 
 9014: # -1 if the file doesn't exist
 9015: #
 9016: # if the target is a file that was uploaded via DOCS, 
 9017: # a check will be made to see if a current copy exists on the local server,
 9018: # if it does this will be served, otherwise a copy will be retrieved from
 9019: # the home server for the course and stored in /home/httpd/html/userfiles on
 9020: # the local server.   
 9021: 
 9022: sub getfile {
 9023:     my ($file) = @_;
 9024:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9025:     &repcopy($file);
 9026:     return &readfile($file);
 9027: }
 9028: 
 9029: sub repcopy_userfile {
 9030:     my ($file)=@_;
 9031:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9032:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 9033:     my ($cdom,$cnum,$filename) = 
 9034: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 9035:     my $uri="/uploaded/$cdom/$cnum/$filename";
 9036:     if (-e "$file") {
 9037: # we already have a local copy, check it out
 9038: 	my @fileinfo = stat($file);
 9039: 	my $rtncode;
 9040: 	my $info;
 9041: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 9042: 	if ($lwpresp ne 'ok') {
 9043: # there is no such file anymore, even though we had a local copy
 9044: 	    if ($rtncode eq '404') {
 9045: 		unlink($file);
 9046: 	    }
 9047: 	    return -1;
 9048: 	}
 9049: 	if ($info < $fileinfo[9]) {
 9050: # nice, the file we have is up-to-date, just say okay
 9051: 	    return 'ok';
 9052: 	} else {
 9053: # the file is outdated, get rid of it
 9054: 	    unlink($file);
 9055: 	}
 9056:     }
 9057: # one way or the other, at this point, we don't have the file
 9058: # construct the correct path for the file
 9059:     my @parts = ($cdom,$cnum); 
 9060:     if ($filename =~ m|^(.+)/[^/]+$|) {
 9061: 	push @parts, split(/\//,$1);
 9062:     }
 9063:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 9064:     foreach my $part (@parts) {
 9065: 	$path .= '/'.$part;
 9066: 	if (!-e $path) {
 9067: 	    mkdir($path,0770);
 9068: 	}
 9069:     }
 9070: # now the path exists for sure
 9071: # get a user agent
 9072:     my $ua=new LWP::UserAgent;
 9073:     my $transferfile=$file.'.in.transfer';
 9074: # FIXME: this should flock
 9075:     if (-e $transferfile) { return 'ok'; }
 9076:     my $request;
 9077:     $uri=~s/^\///;
 9078:     my $homeserver = &homeserver($cnum,$cdom);
 9079:     my $protocol = $protocol{$homeserver};
 9080:     $protocol = 'http' if ($protocol ne 'https');
 9081:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 9082:     my $response=$ua->request($request,$transferfile);
 9083: # did it work?
 9084:     if ($response->is_error()) {
 9085: 	unlink($transferfile);
 9086: 	&logthis("Userfile repcopy failed for $uri");
 9087: 	return -1;
 9088:     }
 9089: # worked, rename the transfer file
 9090:     rename($transferfile,$file);
 9091:     return 'ok';
 9092: }
 9093: 
 9094: sub tokenwrapper {
 9095:     my $uri=shift;
 9096:     $uri=~s|^https?\://([^/]+)||;
 9097:     $uri=~s|^/||;
 9098:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 9099:     my $token=$1;
 9100:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 9101:     if ($udom && $uname && $file) {
 9102: 	$file=~s|(\?\.*)*$||;
 9103:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 9104:         my $homeserver = &homeserver($uname,$udom);
 9105:         my $protocol = $protocol{$homeserver};
 9106:         $protocol = 'http' if ($protocol ne 'https');
 9107:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 9108:                (($uri=~/\?/)?'&':'?').'token='.$token.
 9109:                                '&tokenissued='.$perlvar{'lonHostID'};
 9110:     } else {
 9111:         return '/adm/notfound.html';
 9112:     }
 9113: }
 9114: 
 9115: # call with reqtype HEAD: get last modification time
 9116: # call with reqtype GET: get the file contents
 9117: # Do not call this with reqtype GET for large files! It loads everything into memory
 9118: #
 9119: sub getuploaded {
 9120:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 9121:     $uri=~s/^\///;
 9122:     my $homeserver = &homeserver($cnum,$cdom);
 9123:     my $protocol = $protocol{$homeserver};
 9124:     $protocol = 'http' if ($protocol ne 'https');
 9125:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 9126:     my $ua=new LWP::UserAgent;
 9127:     my $request=new HTTP::Request($reqtype,$uri);
 9128:     my $response=$ua->request($request);
 9129:     $$rtncode = $response->code;
 9130:     if (! $response->is_success()) {
 9131: 	return 'failed';
 9132:     }      
 9133:     if ($reqtype eq 'HEAD') {
 9134: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 9135:     } elsif ($reqtype eq 'GET') {
 9136: 	$$info = $response->content;
 9137:     }
 9138:     return 'ok';
 9139: }
 9140: 
 9141: sub readfile {
 9142:     my $file = shift;
 9143:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 9144:     my $fh;
 9145:     open($fh,"<$file");
 9146:     my $a='';
 9147:     while (my $line = <$fh>) { $a .= $line; }
 9148:     return $a;
 9149: }
 9150: 
 9151: sub filelocation {
 9152:     my ($dir,$file) = @_;
 9153:     my $location;
 9154:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 9155: 
 9156:     if ($file =~ m-^/adm/-) {
 9157: 	$file=~s-^/adm/wrapper/-/-;
 9158: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9159:     }
 9160: 
 9161:     if ($file=~m:^/~:) { # is a contruction space reference
 9162:         $location = $file;
 9163:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 9164:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 9165: 	# is a correct contruction space reference
 9166:         $location = $file;
 9167:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 9168:         $location = $file;
 9169:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 9170:         my ($udom,$uname,$filename)=
 9171:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 9172:         my $home=&homeserver($uname,$udom);
 9173:         my $is_me=0;
 9174:         my @ids=&current_machine_ids();
 9175:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 9176:         if ($is_me) {
 9177:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 9178:         } else {
 9179:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 9180:   	      $udom.'/'.$uname.'/'.$filename;
 9181:         }
 9182:     } elsif ($file =~ m-^/adm/-) {
 9183: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 9184:     } else {
 9185:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9186:         $file=~s:^/res/:/:;
 9187:         if ( !( $file =~ m:^/:) ) {
 9188:             $location = $dir. '/'.$file;
 9189:         } else {
 9190:             $location = '/home/httpd/html/res'.$file;
 9191:         }
 9192:     }
 9193:     $location=~s://+:/:g; # remove duplicate /
 9194:     while ($location=~m{/\.\./}) {
 9195: 	if ($location =~ m{/[^/]+/\.\./}) {
 9196: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 9197: 	} else {
 9198: 	    $location=~ s{/\.\./}{/}g;
 9199: 	}
 9200:     } #remove dir/..
 9201:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 9202:     return $location;
 9203: }
 9204: 
 9205: sub hreflocation {
 9206:     my ($dir,$file)=@_;
 9207:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 9208: 	$file=filelocation($dir,$file);
 9209:     } elsif ($file=~m-^/adm/-) {
 9210: 	$file=~s-^/adm/wrapper/-/-;
 9211: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9212:     }
 9213:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 9214: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 9215:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 9216: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 9217:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 9218: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 9219: 	    -/uploaded/$1/$2/-x;
 9220:     }
 9221:     if ($file=~ m{^/userfiles/}) {
 9222: 	$file =~ s{^/userfiles/}{/uploaded/};
 9223:     }
 9224:     return $file;
 9225: }
 9226: 
 9227: sub current_machine_domains {
 9228:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 9229: }
 9230: 
 9231: sub machine_domains {
 9232:     my ($hostname) = @_;
 9233:     my @domains;
 9234:     my %hostname = &all_hostnames();
 9235:     while( my($id, $name) = each(%hostname)) {
 9236: #	&logthis("-$id-$name-$hostname-");
 9237: 	if ($hostname eq $name) {
 9238: 	    push(@domains,&host_domain($id));
 9239: 	}
 9240:     }
 9241:     return @domains;
 9242: }
 9243: 
 9244: sub current_machine_ids {
 9245:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 9246: }
 9247: 
 9248: sub machine_ids {
 9249:     my ($hostname) = @_;
 9250:     $hostname ||= &hostname($perlvar{'lonHostID'});
 9251:     my @ids;
 9252:     my %name_to_host = &all_names();
 9253:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 9254: 	return @{ $name_to_host{$hostname} };
 9255:     }
 9256:     return;
 9257: }
 9258: 
 9259: sub additional_machine_domains {
 9260:     my @domains;
 9261:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 9262:     while( my $line = <$fh>) {
 9263:         $line =~ s/\s//g;
 9264:         push(@domains,$line);
 9265:     }
 9266:     return @domains;
 9267: }
 9268: 
 9269: sub default_login_domain {
 9270:     my $domain = $perlvar{'lonDefDomain'};
 9271:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 9272:     foreach my $posdom (&current_machine_domains(),
 9273:                         &additional_machine_domains()) {
 9274:         if (lc($posdom) eq lc($testdomain)) {
 9275:             $domain=$posdom;
 9276:             last;
 9277:         }
 9278:     }
 9279:     return $domain;
 9280: }
 9281: 
 9282: # ------------------------------------------------------------- Declutters URLs
 9283: 
 9284: sub declutter {
 9285:     my $thisfn=shift;
 9286:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9287:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9288:     $thisfn=~s/^\///;
 9289:     $thisfn=~s|^adm/wrapper/||;
 9290:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 9291:     $thisfn=~s/^res\///;
 9292:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
 9293:         $thisfn=~s/\?.+$//;
 9294:     }
 9295:     return $thisfn;
 9296: }
 9297: 
 9298: # ------------------------------------------------------------- Clutter up URLs
 9299: 
 9300: sub clutter {
 9301:     my $thisfn='/'.&declutter(shift);
 9302:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 9303: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 9304:        $thisfn='/res'.$thisfn; 
 9305:     }
 9306:     if ($thisfn !~m|^/adm|) {
 9307: 	if ($thisfn =~ m|^/ext/|) {
 9308: 	    $thisfn='/adm/wrapper'.$thisfn;
 9309: 	} else {
 9310: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 9311: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 9312: 	    if ($embstyle eq 'ssi'
 9313: 		|| ($embstyle eq 'hdn')
 9314: 		|| ($embstyle eq 'rat')
 9315: 		|| ($embstyle eq 'prv')
 9316: 		|| ($embstyle eq 'ign')) {
 9317: 		#do nothing with these
 9318: 	    } elsif (($embstyle eq 'img') 
 9319: 		|| ($embstyle eq 'emb')
 9320: 		|| ($embstyle eq 'wrp')) {
 9321: 		$thisfn='/adm/wrapper'.$thisfn;
 9322: 	    } elsif ($embstyle eq 'unk'
 9323: 		     && $thisfn!~/\.(sequence|page)$/) {
 9324: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 9325: 	    } else {
 9326: #		&logthis("Got a blank emb style");
 9327: 	    }
 9328: 	}
 9329:     }
 9330:     return $thisfn;
 9331: }
 9332: 
 9333: sub clutter_with_no_wrapper {
 9334:     my $uri = &clutter(shift);
 9335:     if ($uri =~ m-^/adm/-) {
 9336: 	$uri =~ s-^/adm/wrapper/-/-;
 9337: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 9338:     }
 9339:     return $uri;
 9340: }
 9341: 
 9342: sub freeze_escape {
 9343:     my ($value)=@_;
 9344:     if (ref($value)) {
 9345: 	$value=&nfreeze($value);
 9346: 	return '__FROZEN__'.&escape($value);
 9347:     }
 9348:     return &escape($value);
 9349: }
 9350: 
 9351: 
 9352: sub thaw_unescape {
 9353:     my ($value)=@_;
 9354:     if ($value =~ /^__FROZEN__/) {
 9355: 	substr($value,0,10,undef);
 9356: 	$value=&unescape($value);
 9357: 	return &thaw($value);
 9358:     }
 9359:     return &unescape($value);
 9360: }
 9361: 
 9362: sub correct_line_ends {
 9363:     my ($result)=@_;
 9364:     $$result =~s/\r\n/\n/mg;
 9365:     $$result =~s/\r/\n/mg;
 9366: }
 9367: # ================================================================ Main Program
 9368: 
 9369: sub goodbye {
 9370:    &logthis("Starting Shut down");
 9371: #not converted to using infrastruture and probably shouldn't be
 9372:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 9373: #converted
 9374: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 9375:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 9376: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 9377: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 9378: #1.1 only
 9379: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 9380: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 9381: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 9382: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 9383:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 9384:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 9385:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 9386:    &flushcourselogs();
 9387:    &logthis("Shutting down");
 9388: }
 9389: 
 9390: sub get_dns {
 9391:     my ($url,$func,$ignore_cache) = @_;
 9392:     if (!$ignore_cache) {
 9393: 	my ($content,$cached)=
 9394: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9395: 	if ($cached) {
 9396: 	    &$func($content);
 9397: 	    return;
 9398: 	}
 9399:     }
 9400: 
 9401:     my %alldns;
 9402:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9403:     foreach my $dns (<$config>) {
 9404: 	next if ($dns !~ /^\^(\S*)/x);
 9405:         my $line = $1;
 9406:         my ($host,$protocol) = split(/:/,$line);
 9407:         if ($protocol ne 'https') {
 9408:             $protocol = 'http';
 9409:         }
 9410: 	$alldns{$host} = $protocol;
 9411:     }
 9412:     while (%alldns) {
 9413: 	my ($dns) = keys(%alldns);
 9414: 	my $ua=new LWP::UserAgent;
 9415: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9416: 	my $response=$ua->request($request);
 9417:         delete($alldns{$dns});
 9418: 	next if ($response->is_error());
 9419: 	my @content = split("\n",$response->content);
 9420: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9421: 	&$func(\@content);
 9422: 	return;
 9423:     }
 9424:     close($config);
 9425:     my $which = (split('/',$url))[3];
 9426:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9427:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9428:     my @content = <$config>;
 9429:     &$func(\@content);
 9430:     return;
 9431: }
 9432: # ------------------------------------------------------------ Read domain file
 9433: {
 9434:     my $loaded;
 9435:     my %domain;
 9436: 
 9437:     sub parse_domain_tab {
 9438: 	my ($lines) = @_;
 9439: 	foreach my $line (@$lines) {
 9440: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9441: 
 9442: 	    chomp($line);
 9443: 	    my ($name,@elements) = split(/:/,$line,9);
 9444: 	    my %this_domain;
 9445: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9446: 			       'lang_def', 'city', 'longi', 'lati',
 9447: 			       'primary') {
 9448: 		$this_domain{$field} = shift(@elements);
 9449: 	    }
 9450: 	    $domain{$name} = \%this_domain;
 9451: 	}
 9452:     }
 9453: 
 9454:     sub reset_domain_info {
 9455: 	undef($loaded);
 9456: 	undef(%domain);
 9457:     }
 9458: 
 9459:     sub load_domain_tab {
 9460: 	my ($ignore_cache) = @_;
 9461: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9462: 	my $fh;
 9463: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9464: 	    my @lines = <$fh>;
 9465: 	    &parse_domain_tab(\@lines);
 9466: 	}
 9467: 	close($fh);
 9468: 	$loaded = 1;
 9469:     }
 9470: 
 9471:     sub domain {
 9472: 	&load_domain_tab() if (!$loaded);
 9473: 
 9474: 	my ($name,$what) = @_;
 9475: 	return if ( !exists($domain{$name}) );
 9476: 
 9477: 	if (!$what) {
 9478: 	    return $domain{$name}{'description'};
 9479: 	}
 9480: 	return $domain{$name}{$what};
 9481:     }
 9482: 
 9483:     sub domain_info {
 9484:         &load_domain_tab() if (!$loaded);
 9485:         return %domain;
 9486:     }
 9487: 
 9488: }
 9489: 
 9490: 
 9491: # ------------------------------------------------------------- Read hosts file
 9492: {
 9493:     my %hostname;
 9494:     my %hostdom;
 9495:     my %libserv;
 9496:     my $loaded;
 9497:     my %name_to_host;
 9498: 
 9499:     sub parse_hosts_tab {
 9500: 	my ($file) = @_;
 9501: 	foreach my $configline (@$file) {
 9502: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9503: 	    next if ($configline =~ /^\^/);
 9504: 	    chomp($configline);
 9505: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9506: 	    $name=~s/\s//g;
 9507: 	    if ($id && $domain && $role && $name) {
 9508: 		$hostname{$id}=$name;
 9509: 		push(@{$name_to_host{$name}}, $id);
 9510: 		$hostdom{$id}=$domain;
 9511: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9512:                 if (defined($protocol)) {
 9513:                     if ($protocol eq 'https') {
 9514:                         $protocol{$id} = $protocol;
 9515:                     } else {
 9516:                         $protocol{$id} = 'http'; 
 9517:                     }
 9518:                 } else {
 9519:                     $protocol{$id} = 'http';
 9520:                 }
 9521: 	    }
 9522: 	}
 9523:     }
 9524:     
 9525:     sub reset_hosts_info {
 9526: 	&purge_remembered();
 9527: 	&reset_domain_info();
 9528: 	&reset_hosts_ip_info();
 9529: 	undef(%name_to_host);
 9530: 	undef(%hostname);
 9531: 	undef(%hostdom);
 9532: 	undef(%libserv);
 9533: 	undef($loaded);
 9534:     }
 9535: 
 9536:     sub load_hosts_tab {
 9537: 	my ($ignore_cache) = @_;
 9538: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9539: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9540: 	my @config = <$config>;
 9541: 	&parse_hosts_tab(\@config);
 9542: 	close($config);
 9543: 	$loaded=1;
 9544:     }
 9545: 
 9546:     sub hostname {
 9547: 	&load_hosts_tab() if (!$loaded);
 9548: 
 9549: 	my ($lonid) = @_;
 9550: 	return $hostname{$lonid};
 9551:     }
 9552: 
 9553:     sub all_hostnames {
 9554: 	&load_hosts_tab() if (!$loaded);
 9555: 
 9556: 	return %hostname;
 9557:     }
 9558: 
 9559:     sub all_names {
 9560: 	&load_hosts_tab() if (!$loaded);
 9561: 
 9562: 	return %name_to_host;
 9563:     }
 9564: 
 9565:     sub all_host_domain {
 9566:         &load_hosts_tab() if (!$loaded);
 9567:         return %hostdom;
 9568:     }
 9569: 
 9570:     sub is_library {
 9571: 	&load_hosts_tab() if (!$loaded);
 9572: 
 9573: 	return exists($libserv{$_[0]});
 9574:     }
 9575: 
 9576:     sub all_library {
 9577: 	&load_hosts_tab() if (!$loaded);
 9578: 
 9579: 	return %libserv;
 9580:     }
 9581: 
 9582:     sub get_servers {
 9583: 	&load_hosts_tab() if (!$loaded);
 9584: 
 9585: 	my ($domain,$type) = @_;
 9586: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9587: 	                                          : %hostname;
 9588: 	my %result;
 9589: 	if (ref($domain) eq 'ARRAY') {
 9590: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9591: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9592: 		    $result{$host} = $hostname;
 9593: 		}
 9594: 	    }
 9595: 	} else {
 9596: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9597: 		if ($hostdom{$host} eq $domain) {
 9598: 		    $result{$host} = $hostname;
 9599: 		}
 9600: 	    }
 9601: 	}
 9602: 	return %result;
 9603:     }
 9604: 
 9605:     sub host_domain {
 9606: 	&load_hosts_tab() if (!$loaded);
 9607: 
 9608: 	my ($lonid) = @_;
 9609: 	return $hostdom{$lonid};
 9610:     }
 9611: 
 9612:     sub all_domains {
 9613: 	&load_hosts_tab() if (!$loaded);
 9614: 
 9615: 	my %seen;
 9616: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9617: 	return @uniq;
 9618:     }
 9619: }
 9620: 
 9621: { 
 9622:     my %iphost;
 9623:     my %name_to_ip;
 9624:     my %lonid_to_ip;
 9625: 
 9626:     sub get_hosts_from_ip {
 9627: 	my ($ip) = @_;
 9628: 	my %iphosts = &get_iphost();
 9629: 	if (ref($iphosts{$ip})) {
 9630: 	    return @{$iphosts{$ip}};
 9631: 	}
 9632: 	return;
 9633:     }
 9634:     
 9635:     sub reset_hosts_ip_info {
 9636: 	undef(%iphost);
 9637: 	undef(%name_to_ip);
 9638: 	undef(%lonid_to_ip);
 9639:     }
 9640: 
 9641:     sub get_host_ip {
 9642: 	my ($lonid) = @_;
 9643: 	if (exists($lonid_to_ip{$lonid})) {
 9644: 	    return $lonid_to_ip{$lonid};
 9645: 	}
 9646: 	my $name=&hostname($lonid);
 9647:    	my $ip = gethostbyname($name);
 9648: 	return if (!$ip || length($ip) ne 4);
 9649: 	$ip=inet_ntoa($ip);
 9650: 	$name_to_ip{$name}   = $ip;
 9651: 	$lonid_to_ip{$lonid} = $ip;
 9652: 	return $ip;
 9653:     }
 9654:     
 9655:     sub get_iphost {
 9656: 	my ($ignore_cache) = @_;
 9657: 
 9658: 	if (!$ignore_cache) {
 9659: 	    if (%iphost) {
 9660: 		return %iphost;
 9661: 	    }
 9662: 	    my ($ip_info,$cached)=
 9663: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9664: 	    if ($cached) {
 9665: 		%iphost      = %{$ip_info->[0]};
 9666: 		%name_to_ip  = %{$ip_info->[1]};
 9667: 		%lonid_to_ip = %{$ip_info->[2]};
 9668: 		return %iphost;
 9669: 	    }
 9670: 	}
 9671: 
 9672: 	# get yesterday's info for fallback
 9673: 	my %old_name_to_ip;
 9674: 	my ($ip_info,$cached)=
 9675: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9676: 	if ($cached) {
 9677: 	    %old_name_to_ip = %{$ip_info->[1]};
 9678: 	}
 9679: 
 9680: 	my %name_to_host = &all_names();
 9681: 	foreach my $name (keys(%name_to_host)) {
 9682: 	    my $ip;
 9683: 	    if (!exists($name_to_ip{$name})) {
 9684: 		$ip = gethostbyname($name);
 9685: 		if (!$ip || length($ip) ne 4) {
 9686: 		    if (defined($old_name_to_ip{$name})) {
 9687: 			$ip = $old_name_to_ip{$name};
 9688: 			&logthis("Can't find $name defaulting to old $ip");
 9689: 		    } else {
 9690: 			&logthis("Name $name no IP found");
 9691: 			next;
 9692: 		    }
 9693: 		} else {
 9694: 		    $ip=inet_ntoa($ip);
 9695: 		}
 9696: 		$name_to_ip{$name} = $ip;
 9697: 	    } else {
 9698: 		$ip = $name_to_ip{$name};
 9699: 	    }
 9700: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9701: 		$lonid_to_ip{$id} = $ip;
 9702: 	    }
 9703: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9704: 	}
 9705: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9706: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9707: 				      48*60*60);
 9708: 
 9709: 	return %iphost;
 9710:     }
 9711: 
 9712:     #
 9713:     #  Given a DNS returns the loncapa host name for that DNS 
 9714:     # 
 9715:     sub host_from_dns {
 9716:         my ($dns) = @_;
 9717:         my @hosts;
 9718:         my $ip;
 9719: 
 9720:         if (exists($name_to_ip{$dns})) {
 9721:             $ip = $name_to_ip{$dns};
 9722:         }
 9723:         if (!$ip) {
 9724:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9725:             if (length($ip) == 4) { 
 9726: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9727:             }
 9728:         }
 9729:         if ($ip) {
 9730: 	    @hosts = get_hosts_from_ip($ip);
 9731: 	    return $hosts[0];
 9732:         }
 9733:         return undef;
 9734:     }
 9735: 
 9736: }
 9737: 
 9738: BEGIN {
 9739: 
 9740: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9741:     unless ($readit) {
 9742: {
 9743:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9744:     %perlvar = (%perlvar,%{$configvars});
 9745: }
 9746: 
 9747: 
 9748: # ------------------------------------------------------ Read spare server file
 9749: {
 9750:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9751: 
 9752:     while (my $configline=<$config>) {
 9753:        chomp($configline);
 9754:        if ($configline) {
 9755: 	   my ($host,$type) = split(':',$configline,2);
 9756: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9757: 	   push(@{ $spareid{$type} }, $host);
 9758:        }
 9759:     }
 9760:     close($config);
 9761: }
 9762: # ------------------------------------------------------------ Read permissions
 9763: {
 9764:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9765: 
 9766:     while (my $configline=<$config>) {
 9767: 	chomp($configline);
 9768: 	if ($configline) {
 9769: 	    my ($role,$perm)=split(/ /,$configline);
 9770: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9771: 	}
 9772:     }
 9773:     close($config);
 9774: }
 9775: 
 9776: # -------------------------------------------- Read plain texts for permissions
 9777: {
 9778:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9779: 
 9780:     while (my $configline=<$config>) {
 9781: 	chomp($configline);
 9782: 	if ($configline) {
 9783: 	    my ($short,@plain)=split(/:/,$configline);
 9784:             %{$prp{$short}} = ();
 9785: 	    if (@plain > 0) {
 9786:                 $prp{$short}{'std'} = $plain[0];
 9787:                 for (my $i=1; $i<@plain; $i++) {
 9788:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9789:                 }
 9790:             }
 9791: 	}
 9792:     }
 9793:     close($config);
 9794: }
 9795: 
 9796: # ---------------------------------------------------------- Read package table
 9797: {
 9798:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9799: 
 9800:     while (my $configline=<$config>) {
 9801: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9802: 	chomp($configline);
 9803: 	my ($short,$plain)=split(/:/,$configline);
 9804: 	my ($pack,$name)=split(/\&/,$short);
 9805: 	if ($plain ne '') {
 9806: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9807: 	    $packagetab{$short}=$plain; 
 9808: 	}
 9809:     }
 9810:     close($config);
 9811: }
 9812: 
 9813: # ------------- set up temporary directory
 9814: {
 9815:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9816: 
 9817: }
 9818: 
 9819: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9820: 				'compress_threshold'=> 20_000,
 9821:  			        });
 9822: 
 9823: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9824: $dumpcount=0;
 9825: $locknum=0;
 9826: 
 9827: &logtouch();
 9828: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9829: $readit=1;
 9830:     {
 9831: 	use integer;
 9832: 	my $test=(2**32)+1;
 9833: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9834: 	&logthis(" Detected 64bit platform ($_64bit)");
 9835:     }
 9836: }
 9837: }
 9838: 
 9839: 1;
 9840: __END__
 9841: 
 9842: =pod
 9843: 
 9844: =head1 NAME
 9845: 
 9846: Apache::lonnet - Subroutines to ask questions about things in the network.
 9847: 
 9848: =head1 SYNOPSIS
 9849: 
 9850: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9851: 
 9852:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9853: 
 9854: Common parameters:
 9855: 
 9856: =over 4
 9857: 
 9858: =item *
 9859: 
 9860: $uname : an internal username (if $cname expecting a course Id specifically)
 9861: 
 9862: =item *
 9863: 
 9864: $udom : a domain (if $cdom expecting a course's domain specifically)
 9865: 
 9866: =item *
 9867: 
 9868: $symb : a resource instance identifier
 9869: 
 9870: =item *
 9871: 
 9872: $namespace : the name of a .db file that contains the data needed or
 9873: being set.
 9874: 
 9875: =back
 9876: 
 9877: =head1 OVERVIEW
 9878: 
 9879: lonnet provides subroutines which interact with the
 9880: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9881: about classes, users, and resources.
 9882: 
 9883: For many of these objects you can also use this to store data about
 9884: them or modify them in various ways.
 9885: 
 9886: =head2 Symbs
 9887: 
 9888: To identify a specific instance of a resource, LON-CAPA uses symbols
 9889: or "symbs"X<symb>. These identifiers are built from the URL of the
 9890: map, the resource number of the resource in the map, and the URL of
 9891: the resource itself. The latter is somewhat redundant, but might help
 9892: if maps change.
 9893: 
 9894: An example is
 9895: 
 9896:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9897: 
 9898: The respective map entry is
 9899: 
 9900:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9901:   title="Problem 2">
 9902:  </resource>
 9903: 
 9904: Symbs are used by the random number generator, as well as to store and
 9905: restore data specific to a certain instance of for example a problem.
 9906: 
 9907: =head2 Storing And Retrieving Data
 9908: 
 9909: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9910: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9911: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9912: is is the non-critical message twin of cstore. These functions are for
 9913: handlers to store a perl hash to a user's permanent data space in an
 9914: easy manner, and to retrieve it again on another call. It is expected
 9915: that a handler would use this once at the beginning to retrieve data,
 9916: and then again once at the end to send only the new data back.
 9917: 
 9918: The data is stored in the user's data directory on the user's
 9919: homeserver under the ID of the course.
 9920: 
 9921: The hash that is returned by restore will have all of the previous
 9922: value for all of the elements of the hash.
 9923: 
 9924: Example:
 9925: 
 9926:  #creating a hash
 9927:  my %hash;
 9928:  $hash{'foo'}='bar';
 9929: 
 9930:  #storing it
 9931:  &Apache::lonnet::cstore(\%hash);
 9932: 
 9933:  #changing a value
 9934:  $hash{'foo'}='notbar';
 9935: 
 9936:  #adding a new value
 9937:  $hash{'bar'}='foo';
 9938:  &Apache::lonnet::cstore(\%hash);
 9939: 
 9940:  #retrieving the hash
 9941:  my %history=&Apache::lonnet::restore();
 9942: 
 9943:  #print the hash
 9944:  foreach my $key (sort(keys(%history))) {
 9945:    print("\%history{$key} = $history{$key}");
 9946:  }
 9947: 
 9948: Will print out:
 9949: 
 9950:  %history{1:foo} = bar
 9951:  %history{1:keys} = foo:timestamp
 9952:  %history{1:timestamp} = 990455579
 9953:  %history{2:bar} = foo
 9954:  %history{2:foo} = notbar
 9955:  %history{2:keys} = foo:bar:timestamp
 9956:  %history{2:timestamp} = 990455580
 9957:  %history{bar} = foo
 9958:  %history{foo} = notbar
 9959:  %history{timestamp} = 990455580
 9960:  %history{version} = 2
 9961: 
 9962: Note that the special hash entries C<keys>, C<version> and
 9963: C<timestamp> were added to the hash. C<version> will be equal to the
 9964: total number of versions of the data that have been stored. The
 9965: C<timestamp> attribute will be the UNIX time the hash was
 9966: stored. C<keys> is available in every historical section to list which
 9967: keys were added or changed at a specific historical revision of a
 9968: hash.
 9969: 
 9970: B<Warning>: do not store the hash that restore returns directly. This
 9971: will cause a mess since it will restore the historical keys as if the
 9972: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9973: 
 9974: Calling convention:
 9975: 
 9976:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9977:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9978: 
 9979: For more detailed information, see lonnet specific documentation.
 9980: 
 9981: =head1 RETURN MESSAGES
 9982: 
 9983: =over 4
 9984: 
 9985: =item * B<con_lost>: unable to contact remote host
 9986: 
 9987: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9988: when the connection is brought back up
 9989: 
 9990: =item * B<con_failed>: unable to contact remote host and unable to save message
 9991: for later delivery
 9992: 
 9993: =item * B<error:>: an error a occurred, a description of the error follows the :
 9994: 
 9995: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9996: that was requested
 9997: 
 9998: =back
 9999: 
10000: =head1 PUBLIC SUBROUTINES
10001: 
10002: =head2 Session Environment Functions
10003: 
10004: =over 4
10005: 
10006: =item * 
10007: X<appenv()>
10008: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
10009: the user envirnoment file, and will be restored for each access this
10010: user makes during this session, also modifies the %env for the current
10011: process. Optional rolesarrayref - if defined contains a reference to an array
10012: of roles which are exempt from the restriction on modifying user.role entries 
10013: in the user's environment.db and in %env.    
10014: 
10015: =item *
10016: X<delenv()>
10017: B<delenv($delthis,$regexp)>: removes all items from the session
10018: environment file that begin with $delthis. If the 
10019: optional second arg - $regexp - is true, $delthis is treated as a 
10020: regular expression, otherwise \Q$delthis\E is used. 
10021: The values are also deleted from the current processes %env.
10022: 
10023: =item * get_env_multiple($name) 
10024: 
10025: gets $name from the %env hash, it seemlessly handles the cases where multiple
10026: values may be defined and end up as an array ref.
10027: 
10028: returns an array of values
10029: 
10030: =back
10031: 
10032: =head2 User Information
10033: 
10034: =over 4
10035: 
10036: =item *
10037: X<queryauthenticate()>
10038: B<queryauthenticate($uname,$udom)>: try to determine user's current 
10039: authentication scheme
10040: 
10041: =item *
10042: X<authenticate()>
10043: B<authenticate($uname,$upass,$udom)>: try to
10044: authenticate user from domain's lib servers (first use the current
10045: one). C<$upass> should be the users password.
10046: 
10047: =item *
10048: X<homeserver()>
10049: B<homeserver($uname,$udom)>: find the server which has
10050: the user's directory and files (there must be only one), this caches
10051: the answer, and also caches if there is a borken connection.
10052: 
10053: =item *
10054: X<idget()>
10055: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10056: (IDs are a unique resource in a domain, there must be only 1 ID per
10057: username, and only 1 username per ID in a specific domain) (returns
10058: hash: id=>name,id=>name)
10059: 
10060: =item *
10061: X<idrget()>
10062: B<idrget($udom,@unames)>: find the IDs behind a list of
10063: usernames (returns hash: name=>id,name=>id)
10064: 
10065: =item *
10066: X<idput()>
10067: B<idput($udom,%ids)>: store away a list of names and associated IDs
10068: 
10069: =item *
10070: X<rolesinit()>
10071: B<rolesinit($udom,$username,$authhost)>: get user privileges
10072: 
10073: =item *
10074: X<getsection()>
10075: B<getsection($udom,$uname,$cname)>: finds the section of student in the
10076: course $cname, return section name/number or '' for "not in course"
10077: and '-1' for "no section"
10078: 
10079: =item *
10080: X<userenvironment()>
10081: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
10082: passed in @what from the requested user's environment, returns a hash
10083: 
10084: =item * 
10085: X<userlog_query()>
10086: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10087: activity.log file. %filters defines filters applied when parsing the
10088: log file. These can be start or end timestamps, or the type of action
10089: - log to look for Login or Logout events, check for Checkin or
10090: Checkout, role for role selection. The response is in the form
10091: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
10092: escaped strings of the action recorded in the activity.log file.
10093: 
10094: =back
10095: 
10096: =head2 User Roles
10097: 
10098: =over 4
10099: 
10100: =item *
10101: 
10102: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
10103:  F: full access
10104:  U,I,K: authentication modes (cxx only)
10105:  '': forbidden
10106:  1: user needs to choose course
10107:  2: browse allowed
10108:  A: passphrase authentication needed
10109: 
10110: =item *
10111: 
10112: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10113: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10114: and course level
10115: 
10116: =item *
10117: 
10118: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
10119: (rolesplain.tab); plain text explanation of a user role term.
10120: $type is Course (default) or Community.
10121: If $forcedefault evaluates to true, text returned will be default 
10122: text for $type. Otherwise, if this is a course, the text returned 
10123: will be a custom name for the role (if defined in the course's 
10124: environment).  If no custom name is defined the default is returned.
10125:    
10126: =item *
10127: 
10128: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
10129: All arguments are optional. Returns a hash of a roles, either for
10130: co-author/assistant author roles for a user's Construction Space
10131: (default), or if $context is 'userroles', roles for the user himself,
10132: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10133: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10134: For each key, value is set to colon-separated start and end times for
10135: the role.  If no username and domain are specified, will default to
10136: current user/domain. Types, roles, and roledoms are references to arrays
10137: of role statuses (active, future or previous), roles 
10138: (e.g., cc,in, st etc.) and domains of the roles which can be used
10139: to restrict the list of roles reported. If no array ref is 
10140: provided for types, will default to return only active roles.
10141: 
10142: =back
10143: 
10144: =head2 User Modification
10145: 
10146: =over 4
10147: 
10148: =item *
10149: 
10150: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10151: user for the level given by URL.  Optional start and end dates (leave empty
10152: string or zero for "no date")
10153: 
10154: =item *
10155: 
10156: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10157: change a users, password, possible return values are: ok,
10158: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10159: refused
10160: 
10161: =item *
10162: 
10163: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10164: 
10165: =item *
10166: 
10167: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
10168:            $forceid,$desiredhome,$email,$inststatus) : 
10169: modify user
10170: 
10171: =item *
10172: 
10173: modifystudent
10174: 
10175: modify a student's enrollment and identification information.
10176: The course id is resolved based on the current users environment.  
10177: This means the envoking user must be a course coordinator or otherwise
10178: associated with a course.
10179: 
10180: This call is essentially a wrapper for lonnet::modifyuser and
10181: lonnet::modify_student_enrollment
10182: 
10183: Inputs: 
10184: 
10185: =over 4
10186: 
10187: =item B<$udom> Student's loncapa domain
10188: 
10189: =item B<$uname> Student's loncapa login name
10190: 
10191: =item B<$uid> Student/Employee ID
10192: 
10193: =item B<$umode> Student's authentication mode
10194: 
10195: =item B<$upass> Student's password
10196: 
10197: =item B<$first> Student's first name
10198: 
10199: =item B<$middle> Student's middle name
10200: 
10201: =item B<$last> Student's last name
10202: 
10203: =item B<$gene> Student's generation
10204: 
10205: =item B<$usec> Student's section in course
10206: 
10207: =item B<$end> Unix time of the roles expiration
10208: 
10209: =item B<$start> Unix time of the roles start date
10210: 
10211: =item B<$forceid> If defined, allow $uid to be changed
10212: 
10213: =item B<$desiredhome> server to use as home server for student
10214: 
10215: =item B<$email> Student's permanent e-mail address
10216: 
10217: =item B<$type> Type of enrollment (auto or manual)
10218: 
10219: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
10220: 
10221: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10222: 
10223: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10224: 
10225: =item B<$context> role change context (shown in User Management Logs display in a course)
10226: 
10227: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
10228: 
10229: =back
10230: 
10231: =item *
10232: 
10233: modify_student_enrollment
10234: 
10235: Change a students enrollment status in a class.  The environment variable
10236: 'role.request.course' must be defined for this function to proceed.
10237: 
10238: Inputs:
10239: 
10240: =over 4
10241: 
10242: =item $udom, students domain
10243: 
10244: =item $uname, students name
10245: 
10246: =item $uid, students user id
10247: 
10248: =item $first, students first name
10249: 
10250: =item $middle
10251: 
10252: =item $last
10253: 
10254: =item $gene
10255: 
10256: =item $usec
10257: 
10258: =item $end
10259: 
10260: =item $start
10261: 
10262: =item $type
10263: 
10264: =item $locktype
10265: 
10266: =item $cid
10267: 
10268: =item $selfenroll
10269: 
10270: =item $context
10271: 
10272: =back
10273: 
10274: 
10275: =item *
10276: 
10277: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10278: custom role; give a custom role to a user for the level given by URL.  Specify
10279: name and domain of role author, and role name
10280: 
10281: =item *
10282: 
10283: revokerole($udom,$uname,$url,$role) : revoke a role for url
10284: 
10285: =item *
10286: 
10287: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10288: 
10289: =back
10290: 
10291: =head2 Course Infomation
10292: 
10293: =over 4
10294: 
10295: =item *
10296: 
10297: coursedescription($courseid) : returns a hash of information about the
10298: specified course id, including all environment settings for the
10299: course, the description of the course will be in the hash under the
10300: key 'description'
10301: 
10302: =item *
10303: 
10304: resdata($name,$domain,$type,@which) : request for current parameter
10305: setting for a specific $type, where $type is either 'course' or 'user',
10306: @what should be a list of parameters to ask about. This routine caches
10307: answers for 5 minutes.
10308: 
10309: =item *
10310: 
10311: get_courseresdata($courseid, $domain) : dump the entire course resource
10312: data base, returning a hash that is keyed by the resource name and has
10313: values that are the resource value.  I believe that the timestamps and
10314: versions are also returned.
10315: 
10316: 
10317: =back
10318: 
10319: =head2 Course Modification
10320: 
10321: =over 4
10322: 
10323: =item *
10324: 
10325: writecoursepref($courseid,%prefs) : write preferences (environment
10326: database) for a course
10327: 
10328: =item *
10329: 
10330: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10331: 
10332: =item *
10333: 
10334: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
10335: 
10336: =back
10337: 
10338: =head2 Resource Subroutines
10339: 
10340: =over 4
10341: 
10342: =item *
10343: 
10344: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10345: 
10346: =item *
10347: 
10348: repcopy($filename) : subscribes to the requested file, and attempts to
10349: replicate from the owning library server, Might return
10350: 'unavailable', 'not_found', 'forbidden', 'ok', or
10351: 'bad_request', also attempts to grab the metadata for the
10352: resource. Expects the local filesystem pathname
10353: (/home/httpd/html/res/....)
10354: 
10355: =back
10356: 
10357: =head2 Resource Information
10358: 
10359: =over 4
10360: 
10361: =item *
10362: 
10363: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10364: a vairety of different possible values, $varname should be a request
10365: string, and the other parameters can be used to specify who and what
10366: one is asking about.
10367: 
10368: Possible values for $varname are environment.lastname (or other item
10369: from the envirnment hash), user.name (or someother aspect about the
10370: user), resource.0.maxtries (or some other part and parameter of a
10371: resource)
10372: 
10373: =item *
10374: 
10375: directcondval($number) : get current value of a condition; reads from a state
10376: string
10377: 
10378: =item *
10379: 
10380: condval($condidx) : value of condition index based on state
10381: 
10382: =item *
10383: 
10384: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10385: resource's metadata, $what should be either a specific key, or either
10386: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10387: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10388: 
10389: this function automatically caches all requests
10390: 
10391: =item *
10392: 
10393: metadata_query($query,$custom,$customshow) : make a metadata query against the
10394: network of library servers; returns file handle of where SQL and regex results
10395: will be stored for query
10396: 
10397: =item *
10398: 
10399: symbread($filename) : return symbolic list entry (filename argument optional);
10400: returns the data handle
10401: 
10402: =item *
10403: 
10404: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10405: a possible symb for the URL in $thisfn, and if is an encryypted
10406: resource that the user accessed using /enc/ returns a 1 on success, 0
10407: on failure, user must be in a course, as it assumes the existance of
10408: the course initial hash, and uses $env('request.course.id'}
10409: 
10410: 
10411: =item *
10412: 
10413: symbclean($symb) : removes versions numbers from a symb, returns the
10414: cleaned symb
10415: 
10416: =item *
10417: 
10418: is_on_map($uri) : checks if the $uri is somewhere on the current
10419: course map, user must be in a course for it to work.
10420: 
10421: =item *
10422: 
10423: numval($salt) : return random seed value (addend for rndseed)
10424: 
10425: =item *
10426: 
10427: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10428: a random seed, all arguments are optional, if they aren't sent it uses the
10429: environment to derive them. Note: if symb isn't sent and it can't get one
10430: from &symbread it will use the current time as its return value
10431: 
10432: =item *
10433: 
10434: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10435: unfakeable, receipt
10436: 
10437: =item *
10438: 
10439: receipt() : API to ireceipt working off of env values; given out to users
10440: 
10441: =item *
10442: 
10443: countacc($url) : count the number of accesses to a given URL
10444: 
10445: =item *
10446: 
10447: 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
10448: 
10449: =item *
10450: 
10451: 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)
10452: 
10453: =item *
10454: 
10455: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10456: 
10457: =item *
10458: 
10459: devalidate($symb) : devalidate temporary spreadsheet calculations,
10460: forcing spreadsheet to reevaluate the resource scores next time.
10461: 
10462: =back
10463: 
10464: =head2 Storing/Retreiving Data
10465: 
10466: =over 4
10467: 
10468: =item *
10469: 
10470: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10471: for this url; hashref needs to be given and should be a \%hashname; the
10472: remaining args aren't required and if they aren't passed or are '' they will
10473: be derived from the env
10474: 
10475: =item *
10476: 
10477: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10478: uses critical subroutine
10479: 
10480: =item *
10481: 
10482: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10483: all args are optional
10484: 
10485: =item *
10486: 
10487: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10488: dumps the complete (or key matching regexp) namespace into a hash
10489: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10490: normally &store()ed into
10491: 
10492: $range should be either an integer '100' (give me the first 100
10493:                                            matching records)
10494:               or be  two integers sperated by a - with no spaces
10495:                  '30-50' (give me the 30th through the 50th matching
10496:                           records)
10497: 
10498: 
10499: =item *
10500: 
10501: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10502: replaces a &store() version of data with a replacement set of data
10503: for a particular resource in a namespace passed in the $storehash hash 
10504: reference
10505: 
10506: =item *
10507: 
10508: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10509: works very similar to store/cstore, but all data is stored in a
10510: temporary location and can be reset using tmpreset, $storehash should
10511: be a hash reference, returns nothing on success
10512: 
10513: =item *
10514: 
10515: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10516: similar to restore, but all data is stored in a temporary location and
10517: can be reset using tmpreset. Returns a hash of values on success,
10518: error string otherwise.
10519: 
10520: =item *
10521: 
10522: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10523: deltes all keys for $symb form the temporary storage hash.
10524: 
10525: =item *
10526: 
10527: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10528: reference filled in from namesp ($udom and $uname are optional)
10529: 
10530: =item *
10531: 
10532: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10533: namesp ($udom and $uname are optional)
10534: 
10535: =item *
10536: 
10537: dump($namespace,$udom,$uname,$regexp,$range) : 
10538: dumps the complete (or key matching regexp) namespace into a hash
10539: ($udom, $uname, $regexp, $range are optional)
10540: 
10541: $range should be either an integer '100' (give me the first 100
10542:                                            matching records)
10543:               or be  two integers sperated by a - with no spaces
10544:                  '30-50' (give me the 30th through the 50th matching
10545:                           records)
10546: =item *
10547: 
10548: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10549: $store can be a scalar, an array reference, or if the amount to be 
10550: incremented is > 1, a hash reference.
10551: 
10552: ($udom and $uname are optional)
10553: 
10554: =item *
10555: 
10556: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10557: ($udom and $uname are optional)
10558: 
10559: =item *
10560: 
10561: cput($namespace,$storehash,$udom,$uname) : critical put
10562: ($udom and $uname are optional)
10563: 
10564: =item *
10565: 
10566: newput($namespace,$storehash,$udom,$uname) :
10567: 
10568: Attempts to store the items in the $storehash, but only if they don't
10569: currently exist, if this succeeds you can be certain that you have 
10570: successfully created a new key value pair in the $namespace db.
10571: 
10572: 
10573: Args:
10574:  $namespace: name of database to store values to
10575:  $storehash: hashref to store to the db
10576:  $udom: (optional) domain of user containing the db
10577:  $uname: (optional) name of user caontaining the db
10578: 
10579: Returns:
10580:  'ok' -> succeeded in storing all keys of $storehash
10581:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10582:                         least <key> already existed in the db (other
10583:                         requested keys may also already exist)
10584:  'error: <msg>' -> unable to tie the DB or other error occurred
10585:  'con_lost' -> unable to contact request server
10586:  'refused' -> action was not allowed by remote machine
10587: 
10588: 
10589: =item *
10590: 
10591: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10592: reference filled in from namesp (encrypts the return communication)
10593: ($udom and $uname are optional)
10594: 
10595: =item *
10596: 
10597: log($udom,$name,$home,$message) : write to permanent log for user; use
10598: critical subroutine
10599: 
10600: =item *
10601: 
10602: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10603: array reference filled in from namespace found in domain level on either
10604: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10605: 
10606: =item *
10607: 
10608: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10609: domain level either on specified domain server ($uhome) or primary domain 
10610: server ($udom and $uhome are optional)
10611: 
10612: =item * 
10613: 
10614: get_domain_defaults($target_domain) : returns hash with defaults for
10615: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10616: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10617: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10618: Values are retrieved from cache (if current), or from domain's configuration.db
10619: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10620: or lonTabs/domain.tab. 
10621: 
10622: %domdefaults = &get_auth_defaults($target_domain);
10623: 
10624: =back
10625: 
10626: =head2 Network Status Functions
10627: 
10628: =over 4
10629: 
10630: =item *
10631: 
10632: dirlist($uri) : return directory list based on URI
10633: 
10634: =item *
10635: 
10636: spareserver() : find server with least workload from spare.tab
10637: 
10638: 
10639: =item *
10640: 
10641: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10642: if there is no corresponding loncapa host.
10643: 
10644: =back
10645: 
10646: 
10647: =head2 Apache Request
10648: 
10649: =over 4
10650: 
10651: =item *
10652: 
10653: ssi($url,%hash) : server side include, does a complete request cycle on url to
10654: localhost, posts hash
10655: 
10656: =back
10657: 
10658: =head2 Data to String to Data
10659: 
10660: =over 4
10661: 
10662: =item *
10663: 
10664: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10665: and '&' separators, supports elements that are arrayrefs and hashrefs
10666: 
10667: =item *
10668: 
10669: hashref2str($hashref) : convert a hashref into a string complete with
10670: escaping and '=' and '&' separators, supports elements that are
10671: arrayrefs and hashrefs
10672: 
10673: =item *
10674: 
10675: arrayref2str($arrayref) : convert an arrayref into a string complete
10676: with escaping and '&' separators, supports elements that are arrayrefs
10677: and hashrefs
10678: 
10679: =item *
10680: 
10681: str2hash($string) : convert string to hash using unescaping and
10682: splitting on '=' and '&', supports elements that are arrayrefs and
10683: hashrefs
10684: 
10685: =item *
10686: 
10687: str2array($string) : convert string to hash using unescaping and
10688: splitting on '&', supports elements that are arrayrefs and hashrefs
10689: 
10690: =back
10691: 
10692: =head2 Logging Routines
10693: 
10694: =over 4
10695: 
10696: These routines allow one to make log messages in the lonnet.log and
10697: lonnet.perm logfiles.
10698: 
10699: =item *
10700: 
10701: logtouch() : make sure the logfile, lonnet.log, exists
10702: 
10703: =item *
10704: 
10705: logthis() : append message to the normal lonnet.log file, it gets
10706: preiodically rolled over and deleted.
10707: 
10708: =item *
10709: 
10710: logperm() : append a permanent message to lonnet.perm.log, this log
10711: file never gets deleted by any automated portion of the system, only
10712: messages of critical importance should go in here.
10713: 
10714: =back
10715: 
10716: =head2 General File Helper Routines
10717: 
10718: =over 4
10719: 
10720: =item *
10721: 
10722: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10723: (a) files in /uploaded
10724:   (i) If a local copy of the file exists - 
10725:       compares modification date of local copy with last-modified date for 
10726:       definitive version stored on home server for course. If local copy is 
10727:       stale, requests a new version from the home server and stores it. 
10728:       If the original has been removed from the home server, then local copy 
10729:       is unlinked.
10730:   (ii) If local copy does not exist -
10731:       requests the file from the home server and stores it. 
10732:   
10733:   If $caller is 'uploadrep':  
10734:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10735:     for request for files originally uploaded via DOCS. 
10736:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10737:   
10738:   Otherwise:
10739:      This indicates a call from the content generation phase of the request.
10740:      -  returns the entire contents of the file or -1.
10741:      
10742: (b) files in /res
10743:    - returns the entire contents of a file or -1; 
10744:    it properly subscribes to and replicates the file if neccessary.
10745: 
10746: 
10747: =item *
10748: 
10749: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10750:                   reference
10751: 
10752: returns either a stat() list of data about the file or an empty list
10753: if the file doesn't exist or couldn't find out about it (connection
10754: problems or user unknown)
10755: 
10756: =item *
10757: 
10758: filelocation($dir,$file) : returns file system location of a file
10759: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10760: directory that relative $file lookups are to looked in ($dir of /a/dir
10761: and a file of ../bob will become /a/bob)
10762: 
10763: =item *
10764: 
10765: hreflocation($dir,$file) : returns file system location or a URL; same as
10766: filelocation except for hrefs
10767: 
10768: =item *
10769: 
10770: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10771: 
10772: =back
10773: 
10774: =head2 Usererfile file routines (/uploaded*)
10775: 
10776: =over 4
10777: 
10778: =item *
10779: 
10780: userfileupload(): main rotine for putting a file in a user or course's
10781:                   filespace, arguments are,
10782: 
10783:  formname - required - this is the name of the element in $env where the
10784:            filename, and the contents of the file to create/modifed exist
10785:            the filename is in $env{'form.'.$formname.'.filename'} and the
10786:            contents of the file is located in $env{'form.'.$formname}
10787:  coursedoc - if true, store the file in the course of the active role
10788:              of the current user
10789:  subdir - required - subdirectory to put the file in under ../userfiles/
10790:          if undefined, it will be placed in "unknown"
10791: 
10792:  (This routine calls clean_filename() to remove any dangerous
10793:  characters from the filename, and then calls finuserfileupload() to
10794:  complete the transaction)
10795: 
10796:  returns either the url of the uploaded file (/uploaded/....) if successful
10797:  and /adm/notfound.html if unsuccessful
10798: 
10799: =item *
10800: 
10801: clean_filename(): routine for cleaing a filename up for storage in
10802:                  userfile space, argument is:
10803: 
10804:  filename - proposed filename
10805: 
10806: returns: the new clean filename
10807: 
10808: =item *
10809: 
10810: finishuserfileupload(): routine that creaes and sends the file to
10811: userspace, probably shouldn't be called directly
10812: 
10813:   docuname: username or courseid of destination for the file
10814:   docudom: domain of user/course of destination for the file
10815:   formname: same as for userfileupload()
10816:   fname: filename (inculding subdirectories) for the file
10817: 
10818:  returns either the url of the uploaded file (/uploaded/....) if successful
10819:  and /adm/notfound.html if unsuccessful
10820: 
10821: =item *
10822: 
10823: renameuserfile(): renames an existing userfile to a new name
10824: 
10825:   Args:
10826:    docuname: username or courseid of destination for the file
10827:    docudom: domain of user/course of destination for the file
10828:    old: current file name (including any subdirs under userfiles)
10829:    new: desired file name (including any subdirs under userfiles)
10830: 
10831: =item *
10832: 
10833: mkdiruserfile(): creates a directory is a userfiles dir
10834: 
10835:   Args:
10836:    docuname: username or courseid of destination for the file
10837:    docudom: domain of user/course of destination for the file
10838:    dir: dir to create (including any subdirs under userfiles)
10839: 
10840: =item *
10841: 
10842: removeuserfile(): removes a file that exists in userfiles
10843: 
10844:   Args:
10845:    docuname: username or courseid of destination for the file
10846:    docudom: domain of user/course of destination for the file
10847:    fname: filname to delete (including any subdirs under userfiles)
10848: 
10849: =item *
10850: 
10851: removeuploadedurl(): convience function for removeuserfile()
10852: 
10853:   Args:
10854:    url:  a full /uploaded/... url to delete
10855: 
10856: =item * 
10857: 
10858: get_portfile_permissions():
10859:   Args:
10860:     domain: domain of user or course contain the portfolio files
10861:     user: name of user or num of course contain the portfolio files
10862:   Returns:
10863:     hashref of a dump of the proper file_permissions.db
10864:    
10865: 
10866: =item * 
10867: 
10868: get_access_controls():
10869: 
10870: Args:
10871:   current_permissions: the hash ref returned from get_portfile_permissions()
10872:   group: (optional) the group you want the files associated with
10873:   file: (optional) the file you want access info on
10874: 
10875: Returns:
10876:     a hash (keys are file names) of hashes containing
10877:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10878:         values are XML containing access control settings (see below) 
10879: 
10880: Internal notes:
10881: 
10882:  access controls are stored in file_permissions.db as key=value pairs.
10883:     key -> path to file/file_name\0uniqueID:scope_end_start
10884:         where scope -> public,guest,course,group,domains or users.
10885:               end -> UNIX time for end of access (0 -> no end date)
10886:               start -> UNIX time for start of access
10887: 
10888:     value -> XML description of access control
10889:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10890:             <start></start>
10891:             <end></end>
10892: 
10893:             <password></password>  for scope type = guest
10894: 
10895:             <domain></domain>     for scope type = course or group
10896:             <number></number>
10897:             <roles id="">
10898:              <role></role>
10899:              <access></access>
10900:              <section></section>
10901:              <group></group>
10902:             </roles>
10903: 
10904:             <dom></dom>         for scope type = domains
10905: 
10906:             <users>             for scope type = users
10907:              <user>
10908:               <uname></uname>
10909:               <udom></udom>
10910:              </user>
10911:             </users>
10912:            </scope> 
10913:               
10914:  Access data is also aggregated for each file in an additional key=value pair:
10915:  key -> path to file/file_name\0accesscontrol 
10916:  value -> reference to hash
10917:           hash contains key = value pairs
10918:           where key = uniqueID:scope_end_start
10919:                 value = UNIX time record was last updated
10920: 
10921:           Used to improve speed of look-ups of access controls for each file.  
10922:  
10923:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10924: 
10925: modify_access_controls():
10926: 
10927: Modifies access controls for a portfolio file
10928: Args
10929: 1. file name
10930: 2. reference to hash of required changes,
10931: 3. domain
10932: 4. username
10933:   where domain,username are the domain of the portfolio owner 
10934:   (either a user or a course) 
10935: 
10936: Returns:
10937: 1. result of additions or updates ('ok' or 'error', with error message). 
10938: 2. result of deletions ('ok' or 'error', with error message).
10939: 3. reference to hash of any new or updated access controls.
10940: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10941:    key = integer (inbound ID)
10942:    value = uniqueID  
10943: 
10944: =back
10945: 
10946: =head2 HTTP Helper Routines
10947: 
10948: =over 4
10949: 
10950: =item *
10951: 
10952: escape() : unpack non-word characters into CGI-compatible hex codes
10953: 
10954: =item *
10955: 
10956: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10957: 
10958: =back
10959: 
10960: =head1 PRIVATE SUBROUTINES
10961: 
10962: =head2 Underlying communication routines (Shouldn't call)
10963: 
10964: =over 4
10965: 
10966: =item *
10967: 
10968: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10969: 
10970: =item *
10971: 
10972: reply() : uses subreply to send a message to remote machine, logs all failures
10973: 
10974: =item *
10975: 
10976: critical() : passes a critical message to another server; if cannot
10977: get through then place message in connection buffer directory and
10978: returns con_delayed, if incapable of saving message, returns
10979: con_failed
10980: 
10981: =item *
10982: 
10983: reconlonc() : tries to reconnect lonc client processes.
10984: 
10985: =back
10986: 
10987: =head2 Resource Access Logging
10988: 
10989: =over 4
10990: 
10991: =item *
10992: 
10993: flushcourselogs() : flush (save) buffer logs and access logs
10994: 
10995: =item *
10996: 
10997: courselog($what) : save message for course in hash
10998: 
10999: =item *
11000: 
11001: courseacclog($what) : save message for course using &courselog().  Perform
11002: special processing for specific resource types (problems, exams, quizzes, etc).
11003: 
11004: =item *
11005: 
11006: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11007: as a PerlChildExitHandler
11008: 
11009: =back
11010: 
11011: =head2 Other
11012: 
11013: =over 4
11014: 
11015: =item *
11016: 
11017: symblist($mapname,%newhash) : update symbolic storage links
11018: 
11019: =back
11020: 
11021: =cut
11022: 

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