File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1043: download - view: text, annotated - select for diffs
Thu Nov 12 15:58:34 2009 UTC (14 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Accommodate Communities
  - Custom role template depends on course type.
  - System-wide bre priv unavailable in custom roles used in Communities.
  - System-wide bro priv (own authored/co-authored published resources)
     available for custom roles in Communities.
  - Community Roles (including custom roles) will not be displayed in LON-CAPA
    versions 2.9 or older.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1043 2009/11/12 15:58:34 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'],$domain);
 1357:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1358:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1359:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1360:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1361:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1362:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1363:     } else {
 1364:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1365:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1366:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1367:     }
 1368:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1369:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1370:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1371:         } else {
 1372:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1373:         } 
 1374:         my @usertools = ('aboutme','blog','portfolio');
 1375:         foreach my $item (@usertools) {
 1376:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1377:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1378:             }
 1379:         }
 1380:     }
 1381:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1382:         foreach my $item ('official','unofficial','community') {
 1383:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1384:         }
 1385:     }
 1386:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1387:         foreach my $item ('inststatustypes','inststatusorder') {
 1388:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1389:         }
 1390:     }
 1391:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1392:                                   $cachetime);
 1393:     return %domdefaults;
 1394: }
 1395: 
 1396: # --------------------------------------------------- Assign a key to a student
 1397: 
 1398: sub assign_access_key {
 1399: #
 1400: # a valid key looks like uname:udom#comments
 1401: # comments are being appended
 1402: #
 1403:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1404:     $kdom=
 1405:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1406:     $knum=
 1407:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1408:     $cdom=
 1409:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1410:     $cnum=
 1411:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1412:     $udom=$env{'user.name'} unless (defined($udom));
 1413:     $uname=$env{'user.domain'} unless (defined($uname));
 1414:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1415:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1416:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1417:                                                   # assigned to this person
 1418:                                                   # - this should not happen,
 1419:                                                   # unless something went wrong
 1420:                                                   # the first time around
 1421: # ready to assign
 1422:         $logentry=$1.'; '.$logentry;
 1423:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1424:                                                  $kdom,$knum) eq 'ok') {
 1425: # key now belongs to user
 1426: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1427:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1428:                 &appenv({'environment.'.$envkey => $ckey});
 1429:                 return 'ok';
 1430:             } else {
 1431:                 return 
 1432:   'error: Count not permanently assign key, will need to be re-entered later.';
 1433: 	    }
 1434:         } else {
 1435:             return 'error: Could not assign key, try again later.';
 1436:         }
 1437:     } elsif (!$existing{$ckey}) {
 1438: # the key does not exist
 1439: 	return 'error: The key does not exist';
 1440:     } else {
 1441: # the key is somebody else's
 1442: 	return 'error: The key is already in use';
 1443:     }
 1444: }
 1445: 
 1446: # ------------------------------------------ put an additional comment on a key
 1447: 
 1448: sub comment_access_key {
 1449: #
 1450: # a valid key looks like uname:udom#comments
 1451: # comments are being appended
 1452: #
 1453:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1454:     $cdom=
 1455:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1456:     $cnum=
 1457:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1458:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1459:     if ($existing{$ckey}) {
 1460:         $existing{$ckey}.='; '.$logentry;
 1461: # ready to assign
 1462:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1463:                                                  $cdom,$cnum) eq 'ok') {
 1464: 	    return 'ok';
 1465:         } else {
 1466: 	    return 'error: Count not store comment.';
 1467:         }
 1468:     } else {
 1469: # the key does not exist
 1470: 	return 'error: The key does not exist';
 1471:     }
 1472: }
 1473: 
 1474: # ------------------------------------------------------ Generate a set of keys
 1475: 
 1476: sub generate_access_keys {
 1477:     my ($number,$cdom,$cnum,$logentry)=@_;
 1478:     $cdom=
 1479:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1480:     $cnum=
 1481:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1482:     unless (&allowed('mky',$cdom)) { return 0; }
 1483:     unless (($cdom) && ($cnum)) { return 0; }
 1484:     if ($number>10000) { return 0; }
 1485:     sleep(2); # make sure don't get same seed twice
 1486:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1487:     my $total=0;
 1488:     for (my $i=1;$i<=$number;$i++) {
 1489:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1490:                   sprintf("%lx",int(100000*rand)).'-'.
 1491:                   sprintf("%lx",int(100000*rand));
 1492:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1493:        $newkey=~s/0/h/g; # and also 0 and O
 1494:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1495:        if ($existing{$newkey}) {
 1496:            $i--;
 1497:        } else {
 1498: 	  if (&put('accesskeys',
 1499:               { $newkey => '# generated '.localtime().
 1500:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1501:                            '; '.$logentry },
 1502: 		   $cdom,$cnum) eq 'ok') {
 1503:               $total++;
 1504: 	  }
 1505:        }
 1506:     }
 1507:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1508:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1509:     return $total;
 1510: }
 1511: 
 1512: # ------------------------------------------------------- Validate an accesskey
 1513: 
 1514: sub validate_access_key {
 1515:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1516:     $cdom=
 1517:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1518:     $cnum=
 1519:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1520:     $udom=$env{'user.domain'} unless (defined($udom));
 1521:     $uname=$env{'user.name'} unless (defined($uname));
 1522:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1523:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1524: }
 1525: 
 1526: # ------------------------------------- Find the section of student in a course
 1527: sub devalidate_getsection_cache {
 1528:     my ($udom,$unam,$courseid)=@_;
 1529:     my $hashid="$udom:$unam:$courseid";
 1530:     &devalidate_cache_new('getsection',$hashid);
 1531: }
 1532: 
 1533: sub courseid_to_courseurl {
 1534:     my ($courseid) = @_;
 1535:     #already url style courseid
 1536:     return $courseid if ($courseid =~ m{^/});
 1537: 
 1538:     if (exists($env{'course.'.$courseid.'.num'})) {
 1539: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1540: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1541: 	return "/$cdom/$cnum";
 1542:     }
 1543: 
 1544:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1545:     if (exists($courseinfo{'num'})) {
 1546: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1547:     }
 1548: 
 1549:     return undef;
 1550: }
 1551: 
 1552: sub getsection {
 1553:     my ($udom,$unam,$courseid)=@_;
 1554:     my $cachetime=1800;
 1555: 
 1556:     my $hashid="$udom:$unam:$courseid";
 1557:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1558:     if (defined($cached)) { return $result; }
 1559: 
 1560:     my %Pending; 
 1561:     my %Expired;
 1562:     #
 1563:     # Each role can either have not started yet (pending), be active, 
 1564:     #    or have expired.
 1565:     #
 1566:     # If there is an active role, we are done.
 1567:     #
 1568:     # If there is more than one role which has not started yet, 
 1569:     #     choose the one which will start sooner
 1570:     # If there is one role which has not started yet, return it.
 1571:     #
 1572:     # If there is more than one expired role, choose the one which ended last.
 1573:     # If there is a role which has expired, return it.
 1574:     #
 1575:     $courseid = &courseid_to_courseurl($courseid);
 1576:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1577:     foreach my $key (keys(%roleshash)) {
 1578:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1579:         my $section=$1;
 1580:         if ($key eq $courseid.'_st') { $section=''; }
 1581:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1582:         my $now=time;
 1583:         if (defined($end) && $end && ($now > $end)) {
 1584:             $Expired{$end}=$section;
 1585:             next;
 1586:         }
 1587:         if (defined($start) && $start && ($now < $start)) {
 1588:             $Pending{$start}=$section;
 1589:             next;
 1590:         }
 1591:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1592:     }
 1593:     #
 1594:     # Presumedly there will be few matching roles from the above
 1595:     # loop and the sorting time will be negligible.
 1596:     if (scalar(keys(%Pending))) {
 1597:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1598:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1599:     } 
 1600:     if (scalar(keys(%Expired))) {
 1601:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1602:         my $time = pop(@sorted);
 1603:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1604:     }
 1605:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1606: }
 1607: 
 1608: sub save_cache {
 1609:     &purge_remembered();
 1610:     #&Apache::loncommon::validate_page();
 1611:     undef(%env);
 1612:     undef($env_loaded);
 1613: }
 1614: 
 1615: my $to_remember=-1;
 1616: my %remembered;
 1617: my %accessed;
 1618: my $kicks=0;
 1619: my $hits=0;
 1620: sub make_key {
 1621:     my ($name,$id) = @_;
 1622:     if (length($id) > 65 
 1623: 	&& length(&escape($id)) > 200) {
 1624: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1625:     }
 1626:     return &escape($name.':'.$id);
 1627: }
 1628: 
 1629: sub devalidate_cache_new {
 1630:     my ($name,$id,$debug) = @_;
 1631:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1632:     $id=&make_key($name,$id);
 1633:     $memcache->delete($id);
 1634:     delete($remembered{$id});
 1635:     delete($accessed{$id});
 1636: }
 1637: 
 1638: sub is_cached_new {
 1639:     my ($name,$id,$debug) = @_;
 1640:     $id=&make_key($name,$id);
 1641:     if (exists($remembered{$id})) {
 1642: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1643: 	$accessed{$id}=[&gettimeofday()];
 1644: 	$hits++;
 1645: 	return ($remembered{$id},1);
 1646:     }
 1647:     my $value = $memcache->get($id);
 1648:     if (!(defined($value))) {
 1649: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1650: 	return (undef,undef);
 1651:     }
 1652:     if ($value eq '__undef__') {
 1653: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1654: 	$value=undef;
 1655:     }
 1656:     &make_room($id,$value,$debug);
 1657:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1658:     return ($value,1);
 1659: }
 1660: 
 1661: sub do_cache_new {
 1662:     my ($name,$id,$value,$time,$debug) = @_;
 1663:     $id=&make_key($name,$id);
 1664:     my $setvalue=$value;
 1665:     if (!defined($setvalue)) {
 1666: 	$setvalue='__undef__';
 1667:     }
 1668:     if (!defined($time) ) {
 1669: 	$time=600;
 1670:     }
 1671:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1672:     my $result = $memcache->set($id,$setvalue,$time);
 1673:     if (! $result) {
 1674: 	&logthis("caching of id -> $id  failed");
 1675: 	$memcache->disconnect_all();
 1676:     }
 1677:     # need to make a copy of $value
 1678:     &make_room($id,$value,$debug);
 1679:     return $value;
 1680: }
 1681: 
 1682: sub make_room {
 1683:     my ($id,$value,$debug)=@_;
 1684: 
 1685:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1686:                                     : $value;
 1687:     if ($to_remember<0) { return; }
 1688:     $accessed{$id}=[&gettimeofday()];
 1689:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1690:     my $to_kick;
 1691:     my $max_time=0;
 1692:     foreach my $other (keys(%accessed)) {
 1693: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1694: 	    $to_kick=$other;
 1695: 	    $max_time=&tv_interval($accessed{$other});
 1696: 	}
 1697:     }
 1698:     delete($remembered{$to_kick});
 1699:     delete($accessed{$to_kick});
 1700:     $kicks++;
 1701:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1702:     return;
 1703: }
 1704: 
 1705: sub purge_remembered {
 1706:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1707:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1708:     undef(%remembered);
 1709:     undef(%accessed);
 1710: }
 1711: # ------------------------------------- Read an entry from a user's environment
 1712: 
 1713: sub userenvironment {
 1714:     my ($udom,$unam,@what)=@_;
 1715:     my $items;
 1716:     foreach my $item (@what) {
 1717:         $items.=&escape($item).'&';
 1718:     }
 1719:     $items=~s/\&$//;
 1720:     my %returnhash=();
 1721:     my $uhome = &homeserver($unam,$udom);
 1722:     unless ($uhome eq 'no_host') {
 1723:         my @answer=split(/\&/, 
 1724:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 1725:         my $i;
 1726:         for ($i=0;$i<=$#what;$i++) {
 1727: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 1728:         }
 1729:     }
 1730:     return %returnhash;
 1731: }
 1732: 
 1733: # ---------------------------------------------------------- Get a studentphoto
 1734: sub studentphoto {
 1735:     my ($udom,$unam,$ext) = @_;
 1736:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1737:     if (defined($env{'request.course.id'})) {
 1738:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1739:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1740:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1741:             } else {
 1742:                 my ($result,$perm_reqd)=
 1743: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1744:                 if ($result eq 'ok') {
 1745:                     if (!($perm_reqd eq 'yes')) {
 1746:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1747:                     }
 1748:                 }
 1749:             }
 1750:         }
 1751:     } else {
 1752:         my ($result,$perm_reqd) = 
 1753: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1754:         if ($result eq 'ok') {
 1755:             if (!($perm_reqd eq 'yes')) {
 1756:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1757:             }
 1758:         }
 1759:     }
 1760:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1761: }
 1762: 
 1763: sub retrievestudentphoto {
 1764:     my ($udom,$unam,$ext,$type) = @_;
 1765:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1766:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1767:     if ($ret eq 'ok') {
 1768:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1769:         if ($type eq 'thumbnail') {
 1770:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1771:         }
 1772:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1773:         return $tokenurl;
 1774:     } else {
 1775:         if ($type eq 'thumbnail') {
 1776:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1777:         } else { 
 1778:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1779:         }
 1780:     }
 1781: }
 1782: 
 1783: # -------------------------------------------------------------------- New chat
 1784: 
 1785: sub chatsend {
 1786:     my ($newentry,$anon,$group)=@_;
 1787:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1788:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1789:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1790:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1791: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1792: 		   &escape($newentry)).':'.$group,$chome);
 1793: }
 1794: 
 1795: # ------------------------------------------ Find current version of a resource
 1796: 
 1797: sub getversion {
 1798:     my $fname=&clutter(shift);
 1799:     unless ($fname=~/^\/res\//) { return -1; }
 1800:     return &currentversion(&filelocation('',$fname));
 1801: }
 1802: 
 1803: sub currentversion {
 1804:     my $fname=shift;
 1805:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1806:     if (defined($cached)) { return $result; }
 1807:     my $author=$fname;
 1808:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1809:     my ($udom,$uname)=split(/\//,$author);
 1810:     my $home=homeserver($uname,$udom);
 1811:     if ($home eq 'no_host') { 
 1812:         return -1; 
 1813:     }
 1814:     my $answer=reply("currentversion:$fname",$home);
 1815:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1816: 	return -1;
 1817:     }
 1818:     return &do_cache_new('resversion',$fname,$answer,600);
 1819: }
 1820: 
 1821: # ----------------------------- Subscribe to a resource, return URL if possible
 1822: 
 1823: sub subscribe {
 1824:     my $fname=shift;
 1825:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1826:     $fname=~s/[\n\r]//g;
 1827:     my $author=$fname;
 1828:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1829:     my ($udom,$uname)=split(/\//,$author);
 1830:     my $home=homeserver($uname,$udom);
 1831:     if ($home eq 'no_host') {
 1832:         return 'not_found';
 1833:     }
 1834:     my $answer=reply("sub:$fname",$home);
 1835:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1836: 	$answer.=' by '.$home;
 1837:     }
 1838:     return $answer;
 1839: }
 1840:     
 1841: # -------------------------------------------------------------- Replicate file
 1842: 
 1843: sub repcopy {
 1844:     my $filename=shift;
 1845:     $filename=~s/\/+/\//g;
 1846:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1847:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1848:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1849: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1850: 	return &repcopy_userfile($filename);
 1851:     }
 1852:     $filename=~s/[\n\r]//g;
 1853:     my $transname="$filename.in.transfer";
 1854: # FIXME: this should flock
 1855:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1856:     my $remoteurl=subscribe($filename);
 1857:     if ($remoteurl =~ /^con_lost by/) {
 1858: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1859:            return 'unavailable';
 1860:     } elsif ($remoteurl eq 'not_found') {
 1861: 	   #&logthis("Subscribe returned not_found: $filename");
 1862: 	   return 'not_found';
 1863:     } elsif ($remoteurl =~ /^rejected by/) {
 1864: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1865:            return 'forbidden';
 1866:     } elsif ($remoteurl eq 'directory') {
 1867:            return 'ok';
 1868:     } else {
 1869:         my $author=$filename;
 1870:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1871:         my ($udom,$uname)=split(/\//,$author);
 1872:         my $home=homeserver($uname,$udom);
 1873:         unless ($home eq $perlvar{'lonHostID'}) {
 1874:            my @parts=split(/\//,$filename);
 1875:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1876:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1877:                &logthis("Malconfiguration for replication: $filename");
 1878: 	       return 'bad_request';
 1879:            }
 1880:            my $count;
 1881:            for ($count=5;$count<$#parts;$count++) {
 1882:                $path.="/$parts[$count]";
 1883:                if ((-e $path)!=1) {
 1884: 		   mkdir($path,0777);
 1885:                }
 1886:            }
 1887:            my $ua=new LWP::UserAgent;
 1888:            my $request=new HTTP::Request('GET',"$remoteurl");
 1889:            my $response=$ua->request($request,$transname);
 1890:            if ($response->is_error()) {
 1891: 	       unlink($transname);
 1892:                my $message=$response->status_line;
 1893:                &logthis("<font color=\"blue\">WARNING:"
 1894:                        ." LWP get: $message: $filename</font>");
 1895:                return 'unavailable';
 1896:            } else {
 1897: 	       if ($remoteurl!~/\.meta$/) {
 1898:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1899:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1900:                   if ($mresponse->is_error()) {
 1901: 		      unlink($filename.'.meta');
 1902:                       &logthis(
 1903:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1904:                   }
 1905: 	       }
 1906:                rename($transname,$filename);
 1907:                return 'ok';
 1908:            }
 1909:        }
 1910:     }
 1911: }
 1912: 
 1913: # ------------------------------------------------ Get server side include body
 1914: sub ssi_body {
 1915:     my ($filelink,%form)=@_;
 1916:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1917:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1918:     }
 1919:     my $output='';
 1920:     my $response;
 1921:     if ($filelink=~/^https?\:/) {
 1922:        ($output,$response)=&externalssi($filelink);
 1923:     } else {
 1924:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 1925:        $filelink .= 'inhibitmenu=yes';
 1926:        ($output,$response)=&ssi($filelink,%form);
 1927:     }
 1928:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1929:     $output=~s/^.*?\<body[^\>]*\>//si;
 1930:     $output=~s/\<\/body\s*\>.*?$//si;
 1931:     if (wantarray) {
 1932:         return ($output, $response);
 1933:     } else {
 1934:         return $output;
 1935:     }
 1936: }
 1937: 
 1938: # --------------------------------------------------------- Server Side Include
 1939: 
 1940: sub absolute_url {
 1941:     my ($host_name) = @_;
 1942:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1943:     if ($host_name eq '') {
 1944: 	$host_name = $ENV{'SERVER_NAME'};
 1945:     }
 1946:     return $protocol.$host_name;
 1947: }
 1948: 
 1949: #
 1950: #   Server side include.
 1951: # Parameters:
 1952: #  fn     Possibly encrypted resource name/id.
 1953: #  form   Hash that describes how the rendering should be done
 1954: #         and other things.
 1955: # Returns:
 1956: #   Scalar context: The content of the response.
 1957: #   Array context:  2 element list of the content and the full response object.
 1958: #     
 1959: sub ssi {
 1960: 
 1961:     my ($fn,%form)=@_;
 1962:     my $ua=new LWP::UserAgent;
 1963:     my $request;
 1964: 
 1965:     $form{'no_update_last_known'}=1;
 1966:     &Apache::lonenc::check_encrypt(\$fn);
 1967:     if (%form) {
 1968:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1969:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1970:     } else {
 1971:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1972:     }
 1973: 
 1974:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1975:     my $response=$ua->request($request);
 1976: 
 1977:     if (wantarray) {
 1978: 	return ($response->content, $response);
 1979:     } else {
 1980: 	return $response->content;
 1981:     }
 1982: }
 1983: 
 1984: sub externalssi {
 1985:     my ($url)=@_;
 1986:     my $ua=new LWP::UserAgent;
 1987:     my $request=new HTTP::Request('GET',$url);
 1988:     my $response=$ua->request($request);
 1989:     if (wantarray) {
 1990:         return ($response->content, $response);
 1991:     } else {
 1992:         return $response->content;
 1993:     }
 1994: }
 1995: 
 1996: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1997: 
 1998: sub allowuploaded {
 1999:     my ($srcurl,$url)=@_;
 2000:     $url=&clutter(&declutter($url));
 2001:     my $dir=$url;
 2002:     $dir=~s/\/[^\/]+$//;
 2003:     my %httpref=();
 2004:     my $httpurl=&hreflocation('',$url);
 2005:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2006:     &Apache::lonnet::appenv(\%httpref);
 2007: }
 2008: 
 2009: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2010: # input: action, courseID, current domain, intended
 2011: #        path to file, source of file, instruction to parse file for objects,
 2012: #        ref to hash for embedded objects,
 2013: #        ref to hash for codebase of java objects.
 2014: #
 2015: # output: url to file (if action was uploaddoc), 
 2016: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2017: #
 2018: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2019: # course.
 2020: #
 2021: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2022: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2023: #          course's home server.
 2024: #
 2025: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2026: #          be copied from $source (current location) to 
 2027: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2028: #         and will then be copied to
 2029: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2030: #         course's home server.
 2031: #
 2032: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2033: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2034: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2035: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2036: #         in course's home server.
 2037: #
 2038: 
 2039: sub process_coursefile {
 2040:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 2041:     my $fetchresult;
 2042:     my $home=&homeserver($docuname,$docudom);
 2043:     if ($action eq 'propagate') {
 2044:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2045: 			     $home);
 2046:     } else {
 2047:         my $fpath = '';
 2048:         my $fname = $file;
 2049:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2050:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2051:         my $filepath = &build_filepath($fpath);
 2052:         if ($action eq 'copy') {
 2053:             if ($source eq '') {
 2054:                 $fetchresult = 'no source file';
 2055:                 return $fetchresult;
 2056:             } else {
 2057:                 my $destination = $filepath.'/'.$fname;
 2058:                 rename($source,$destination);
 2059:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2060:                                  $home);
 2061:             }
 2062:         } elsif ($action eq 'uploaddoc') {
 2063:             open(my $fh,'>'.$filepath.'/'.$fname);
 2064:             print $fh $env{'form.'.$source};
 2065:             close($fh);
 2066:             if ($parser eq 'parse') {
 2067:                 my $mm = new File::MMagic;
 2068:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
 2069:                 if ($mime_type eq 'text/html') {
 2070:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2071:                     unless ($parse_result eq 'ok') {
 2072:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2073:                     }
 2074:                 }
 2075:             }
 2076:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2077:                                  $home);
 2078:             if ($fetchresult eq 'ok') {
 2079:                 return '/uploaded/'.$fpath.'/'.$fname;
 2080:             } else {
 2081:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2082:                         ' to host '.$home.': '.$fetchresult);
 2083:                 return '/adm/notfound.html';
 2084:             }
 2085:         }
 2086:     }
 2087:     unless ( $fetchresult eq 'ok') {
 2088:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2089:              ' to host '.$home.': '.$fetchresult);
 2090:     }
 2091:     return $fetchresult;
 2092: }
 2093: 
 2094: sub build_filepath {
 2095:     my ($fpath) = @_;
 2096:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2097:     unless ($fpath eq '') {
 2098:         my @parts=split('/',$fpath);
 2099:         foreach my $part (@parts) {
 2100:             $filepath.= '/'.$part;
 2101:             if ((-e $filepath)!=1) {
 2102:                 mkdir($filepath,0777);
 2103:             }
 2104:         }
 2105:     }
 2106:     return $filepath;
 2107: }
 2108: 
 2109: sub store_edited_file {
 2110:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2111:     my $file = $primary_url;
 2112:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2113:     my $fpath = '';
 2114:     my $fname = $file;
 2115:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2116:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2117:     my $filepath = &build_filepath($fpath);
 2118:     open(my $fh,'>'.$filepath.'/'.$fname);
 2119:     print $fh $content;
 2120:     close($fh);
 2121:     my $home=&homeserver($docuname,$docudom);
 2122:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2123: 			  $home);
 2124:     if ($$fetchresult eq 'ok') {
 2125:         return '/uploaded/'.$fpath.'/'.$fname;
 2126:     } else {
 2127:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2128: 		 ' to host '.$home.': '.$$fetchresult);
 2129:         return '/adm/notfound.html';
 2130:     }
 2131: }
 2132: 
 2133: sub clean_filename {
 2134:     my ($fname,$args)=@_;
 2135: # Replace Windows backslashes by forward slashes
 2136:     $fname=~s/\\/\//g;
 2137:     if (!$args->{'keep_path'}) {
 2138:         # Get rid of everything but the actual filename
 2139: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2140:     }
 2141: # Replace spaces by underscores
 2142:     $fname=~s/\s+/\_/g;
 2143: # Replace all other weird characters by nothing
 2144:     $fname=~s{[^/\w\.\-]}{}g;
 2145: # Replace all .\d. sequences with _\d. so they no longer look like version
 2146: # numbers
 2147:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2148:     return $fname;
 2149: }
 2150: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2151: sub resizeImage {
 2152: 	my($img_url) = @_;	
 2153: 	my $ima = Image::Magick->new;                       
 2154:         $ima->Read($img_url);
 2155: 	if($ima->Get('width') > 400)
 2156: 	{
 2157: 		my $factor = $ima->Get('width')/400;
 2158:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2159: 	}
 2160: 	if($ima->Get('height') > 500)
 2161:         {
 2162:         	my $factor = $ima->Get('height')/500;
 2163:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2164:         } 
 2165: 		
 2166: 	$ima->Write($img_url);
 2167: }
 2168: 
 2169: #Wrapper function for userphotoupload
 2170: sub userphotoupload
 2171: {
 2172: 	my($formname,$subdir) = @_;
 2173: 	$upload_photo_form = 1;
 2174: 	return &userfileupload($formname,undef,$subdir);
 2175: }
 2176: 
 2177: # --------------- Take an uploaded file and put it into the userfiles directory
 2178: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2179: #                    the desired filenam is in $env{"form.$formname.filename"}
 2180: #        $coursedoc - if true up to the current course
 2181: #                     if false
 2182: #        $subdir - directory in userfile to store the file into
 2183: #        $parser - instruction to parse file for objects ($parser = parse)    
 2184: #        $allfiles - reference to hash for embedded objects
 2185: #        $codebase - reference to hash for codebase of java objects
 2186: #        $desuname - username for permanent storage of uploaded file
 2187: #        $dsetudom - domain for permanaent storage of uploaded file
 2188: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2189: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2190: # 
 2191: # output: url of file in userspace, or error: <message> 
 2192: #             or /adm/notfound.html if failure to upload occurse
 2193: 
 2194: 
 2195: sub userfileupload {
 2196:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2197:         $destudom,$thumbwidth,$thumbheight)=@_;
 2198:     if (!defined($subdir)) { $subdir='unknown'; }
 2199:     my $fname=$env{'form.'.$formname.'.filename'};
 2200:     $fname=&clean_filename($fname);
 2201: # See if there is anything left
 2202:     unless ($fname) { return 'error: no uploaded file'; }
 2203:     chop($env{'form.'.$formname});
 2204:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2205:         my $now = time;
 2206:         my $filepath = 'tmp/helprequests/'.$now;
 2207:         my @parts=split(/\//,$filepath);
 2208:         my $fullpath = $perlvar{'lonDaemons'};
 2209:         for (my $i=0;$i<@parts;$i++) {
 2210:             $fullpath .= '/'.$parts[$i];
 2211:             if ((-e $fullpath)!=1) {
 2212:                 mkdir($fullpath,0777);
 2213:             }
 2214:         }
 2215:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2216:         print $fh $env{'form.'.$formname};
 2217:         close($fh);
 2218:         return $fullpath.'/'.$fname;
 2219:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2220:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2221:                        '_'.$env{'user.domain'}.'/pending';
 2222:         my @parts=split(/\//,$filepath);
 2223:         my $fullpath = $perlvar{'lonDaemons'};
 2224:         for (my $i=0;$i<@parts;$i++) {
 2225:             $fullpath .= '/'.$parts[$i];
 2226:             if ((-e $fullpath)!=1) {
 2227:                 mkdir($fullpath,0777);
 2228:             }
 2229:         }
 2230:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2231:         print $fh $env{'form.'.$formname};
 2232:         close($fh);
 2233:         return $fullpath.'/'.$fname;
 2234:     }
 2235:     if ($subdir eq 'scantron') {
 2236:         $fname = 'scantron_orig_'.$fname;
 2237:     } else {   
 2238: # Create the directory if not present
 2239:         $fname="$subdir/$fname";
 2240:     }
 2241:     if ($coursedoc) {
 2242: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2243: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2244:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2245:             return &finishuserfileupload($docuname,$docudom,
 2246: 					 $formname,$fname,$parser,$allfiles,
 2247: 					 $codebase,$thumbwidth,$thumbheight);
 2248:         } else {
 2249:             $fname=$env{'form.folder'}.'/'.$fname;
 2250:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2251: 				       $fname,$formname,$parser,
 2252: 				       $allfiles,$codebase);
 2253:         }
 2254:     } elsif (defined($destuname)) {
 2255:         my $docuname=$destuname;
 2256:         my $docudom=$destudom;
 2257: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2258: 				     $parser,$allfiles,$codebase,
 2259:                                      $thumbwidth,$thumbheight);
 2260:         
 2261:     } else {
 2262:         my $docuname=$env{'user.name'};
 2263:         my $docudom=$env{'user.domain'};
 2264:         if (exists($env{'form.group'})) {
 2265:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2266:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2267:         }
 2268: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2269: 				     $parser,$allfiles,$codebase,
 2270:                                      $thumbwidth,$thumbheight);
 2271:     }
 2272: }
 2273: 
 2274: sub finishuserfileupload {
 2275:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2276:         $thumbwidth,$thumbheight) = @_;
 2277:     my $path=$docudom.'/'.$docuname.'/';
 2278:     my $filepath=$perlvar{'lonDocRoot'};
 2279:   
 2280:     my ($fnamepath,$file,$fetchthumb);
 2281:     $file=$fname;
 2282:     if ($fname=~m|/|) {
 2283:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2284: 	$path.=$fnamepath.'/';
 2285:     }
 2286:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2287:     my $count;
 2288:     for ($count=4;$count<=$#parts;$count++) {
 2289:         $filepath.="/$parts[$count]";
 2290:         if ((-e $filepath)!=1) {
 2291: 	    mkdir($filepath,0777);
 2292:         }
 2293:     }
 2294: 
 2295: # Save the file
 2296:     {
 2297: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2298: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2299: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2300: 	    return '/adm/notfound.html';
 2301: 	}
 2302: 	if (!print FH ($env{'form.'.$formname})) {
 2303: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2304: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2305: 	    return '/adm/notfound.html';
 2306: 	}
 2307: 	close(FH);
 2308: 	if($upload_photo_form==1)
 2309: 	{
 2310: 		resizeImage($filepath.'/'.$file);		
 2311: 		$upload_photo_form = 0;
 2312: 	}
 2313:     }
 2314:     if ($parser eq 'parse') {
 2315:         my $mm = new File::MMagic;
 2316:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2317:         if ($mime_type eq 'text/html') {
 2318:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2319:                                                        $allfiles,$codebase);
 2320:             unless ($parse_result eq 'ok') {
 2321:                 &logthis('Failed to parse '.$filepath.$file.
 2322: 	   	         ' for embedded media: '.$parse_result); 
 2323:             }
 2324:         }
 2325:     }
 2326:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2327:         my $input = $filepath.'/'.$file;
 2328:         my $output = $filepath.'/'.'tn-'.$file;
 2329:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2330:         system("convert -sample $thumbsize $input $output");
 2331:         if (-e $filepath.'/'.'tn-'.$file) {
 2332:             $fetchthumb  = 1; 
 2333:         }
 2334:     }
 2335:  
 2336: # Notify homeserver to grep it
 2337: #
 2338:     my $docuhome=&homeserver($docuname,$docudom);	
 2339:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2340:     if ($fetchresult eq 'ok') {
 2341:         if ($fetchthumb) {
 2342:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2343:             if ($thumbresult ne 'ok') {
 2344:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2345:                          $docuhome.': '.$thumbresult);
 2346:             }
 2347:         }
 2348: #
 2349: # Return the URL to it
 2350:         return '/uploaded/'.$path.$file;
 2351:     } else {
 2352:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2353: 		 ': '.$fetchresult);
 2354:         return '/adm/notfound.html';
 2355:     }
 2356: }
 2357: 
 2358: sub extract_embedded_items {
 2359:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2360:     my @state = ();
 2361:     my %javafiles = (
 2362:                       codebase => '',
 2363:                       code => '',
 2364:                       archive => ''
 2365:                     );
 2366:     my %mediafiles = (
 2367:                       src => '',
 2368:                       movie => '',
 2369:                      );
 2370:     my $p;
 2371:     if ($content) {
 2372:         $p = HTML::LCParser->new($content);
 2373:     } else {
 2374:         $p = HTML::LCParser->new($fullpath);
 2375:     }
 2376:     while (my $t=$p->get_token()) {
 2377: 	if ($t->[0] eq 'S') {
 2378: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2379: 	    push(@state, $tagname);
 2380:             if (lc($tagname) eq 'allow') {
 2381:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2382:             }
 2383: 	    if (lc($tagname) eq 'img') {
 2384: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2385: 	    }
 2386: 	    if (lc($tagname) eq 'a') {
 2387: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2388: 	    }
 2389:             if (lc($tagname) eq 'script') {
 2390:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2391:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2392:                 } else {
 2393:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2394:                 }
 2395:             }
 2396:             if (lc($tagname) eq 'link') {
 2397:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2398:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2399:                 }
 2400:             }
 2401: 	    if (lc($tagname) eq 'object' ||
 2402: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2403: 		foreach my $item (keys(%javafiles)) {
 2404: 		    $javafiles{$item} = '';
 2405: 		}
 2406: 	    }
 2407: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2408: 		my $name = lc($attr->{'name'});
 2409: 		foreach my $item (keys(%javafiles)) {
 2410: 		    if ($name eq $item) {
 2411: 			$javafiles{$item} = $attr->{'value'};
 2412: 			last;
 2413: 		    }
 2414: 		}
 2415: 		foreach my $item (keys(%mediafiles)) {
 2416: 		    if ($name eq $item) {
 2417: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2418: 			last;
 2419: 		    }
 2420: 		}
 2421: 	    }
 2422: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2423: 		foreach my $item (keys(%javafiles)) {
 2424: 		    if ($attr->{$item}) {
 2425: 			$javafiles{$item} = $attr->{$item};
 2426: 			last;
 2427: 		    }
 2428: 		}
 2429: 		foreach my $item (keys(%mediafiles)) {
 2430: 		    if ($attr->{$item}) {
 2431: 			&add_filetype($allfiles,$attr->{$item},$item);
 2432: 			last;
 2433: 		    }
 2434: 		}
 2435: 	    }
 2436: 	} elsif ($t->[0] eq 'E') {
 2437: 	    my ($tagname) = ($t->[1]);
 2438: 	    if ($javafiles{'codebase'} ne '') {
 2439: 		$javafiles{'codebase'} .= '/';
 2440: 	    }  
 2441: 	    if (lc($tagname) eq 'applet' ||
 2442: 		lc($tagname) eq 'object' ||
 2443: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2444: 		) {
 2445: 		foreach my $item (keys(%javafiles)) {
 2446: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2447: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2448: 			&add_filetype($allfiles,$file,$item);
 2449: 		    }
 2450: 		}
 2451: 	    } 
 2452: 	    pop @state;
 2453: 	}
 2454:     }
 2455:     return 'ok';
 2456: }
 2457: 
 2458: sub add_filetype {
 2459:     my ($allfiles,$file,$type)=@_;
 2460:     if (exists($allfiles->{$file})) {
 2461: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2462: 	    push(@{$allfiles->{$file}}, &escape($type));
 2463: 	}
 2464:     } else {
 2465: 	@{$allfiles->{$file}} = (&escape($type));
 2466:     }
 2467: }
 2468: 
 2469: sub removeuploadedurl {
 2470:     my ($url)=@_;	
 2471:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2472:     return &removeuserfile($uname,$udom,$fname);
 2473: }
 2474: 
 2475: sub removeuserfile {
 2476:     my ($docuname,$docudom,$fname)=@_;
 2477:     my $home=&homeserver($docuname,$docudom);    
 2478:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2479:     if ($result eq 'ok') {	
 2480:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2481:             my $metafile = $fname.'.meta';
 2482:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2483: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2484:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2485:             my $sqlresult = 
 2486:                 &update_portfolio_table($docuname,$docudom,$file,
 2487:                                         'portfolio_metadata',$group,
 2488:                                         'delete');
 2489:         }
 2490:     }
 2491:     return $result;
 2492: }
 2493: 
 2494: sub mkdiruserfile {
 2495:     my ($docuname,$docudom,$dir)=@_;
 2496:     my $home=&homeserver($docuname,$docudom);
 2497:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2498: }
 2499: 
 2500: sub renameuserfile {
 2501:     my ($docuname,$docudom,$old,$new)=@_;
 2502:     my $home=&homeserver($docuname,$docudom);
 2503:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2504:                         &escape("$old").':'.&escape("$new"),$home);
 2505:     if ($result eq 'ok') {
 2506:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2507:             my $oldmeta = $old.'.meta';
 2508:             my $newmeta = $new.'.meta';
 2509:             my $metaresult = 
 2510:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2511: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2512:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2513:             my $sqlresult = 
 2514:                 &update_portfolio_table($docuname,$docudom,$file,
 2515:                                         'portfolio_metadata',$group,
 2516:                                         'delete');
 2517:         }
 2518:     }
 2519:     return $result;
 2520: }
 2521: 
 2522: # ------------------------------------------------------------------------- Log
 2523: 
 2524: sub log {
 2525:     my ($dom,$nam,$hom,$what)=@_;
 2526:     return critical("log:$dom:$nam:$what",$hom);
 2527: }
 2528: 
 2529: # ------------------------------------------------------------------ Course Log
 2530: #
 2531: # This routine flushes several buffers of non-mission-critical nature
 2532: #
 2533: 
 2534: sub flushcourselogs {
 2535:     &logthis('Flushing log buffers');
 2536: #
 2537: # course logs
 2538: # This is a log of all transactions in a course, which can be used
 2539: # for data mining purposes
 2540: #
 2541: # It also collects the courseid database, which lists last transaction
 2542: # times and course titles for all courseids
 2543: #
 2544:     my %courseidbuffer=();
 2545:     foreach my $crsid (keys(%courselogs)) {
 2546:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2547: 		          &escape($courselogs{$crsid}),
 2548: 		          $coursehombuf{$crsid}) eq 'ok') {
 2549: 	    delete $courselogs{$crsid};
 2550:         } else {
 2551:             &logthis('Failed to flush log buffer for '.$crsid);
 2552:             if (length($courselogs{$crsid})>40000) {
 2553:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2554:                         " exceeded maximum size, deleting.</font>");
 2555:                delete $courselogs{$crsid};
 2556:             }
 2557:         }
 2558:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2559:             'description' => $coursedescrbuf{$crsid},
 2560:             'inst_code'    => $courseinstcodebuf{$crsid},
 2561:             'type'        => $coursetypebuf{$crsid},
 2562:             'owner'       => $courseownerbuf{$crsid},
 2563:         };
 2564:     }
 2565: #
 2566: # Write course id database (reverse lookup) to homeserver of courses 
 2567: # Is used in pickcourse
 2568: #
 2569:     foreach my $crs_home (keys(%courseidbuffer)) {
 2570:         my $response = &courseidput(&host_domain($crs_home),
 2571:                                     $courseidbuffer{$crs_home},
 2572:                                     $crs_home,'timeonly');
 2573:     }
 2574: #
 2575: # File accesses
 2576: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2577: #
 2578:     foreach my $entry (keys(%accesshash)) {
 2579:         if ($entry =~ /___count$/) {
 2580:             my ($dom,$name);
 2581:             ($dom,$name,undef)=
 2582: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2583:             if (! defined($dom) || $dom eq '' || 
 2584:                 ! defined($name) || $name eq '') {
 2585:                 my $cid = $env{'request.course.id'};
 2586:                 $dom  = $env{'request.'.$cid.'.domain'};
 2587:                 $name = $env{'request.'.$cid.'.num'};
 2588:             }
 2589:             my $value = $accesshash{$entry};
 2590:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2591:             my %temphash=($url => $value);
 2592:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2593:             if ($result eq 'ok') {
 2594:                 delete $accesshash{$entry};
 2595:             } elsif ($result eq 'unknown_cmd') {
 2596:                 # Target server has old code running on it.
 2597:                 my %temphash=($entry => $value);
 2598:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2599:                     delete $accesshash{$entry};
 2600:                 }
 2601:             }
 2602:         } else {
 2603:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2604:             my %temphash=($entry => $accesshash{$entry});
 2605:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2606:                 delete $accesshash{$entry};
 2607:             }
 2608:         }
 2609:     }
 2610: #
 2611: # Roles
 2612: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2613: #
 2614:     foreach my $entry (keys(%userrolehash)) {
 2615:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2616: 	    split(/\:/,$entry);
 2617:         if (&Apache::lonnet::put('nohist_userroles',
 2618:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2619:                 $rudom,$runame) eq 'ok') {
 2620: 	    delete $userrolehash{$entry};
 2621:         }
 2622:     }
 2623: #
 2624: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2625: #
 2626:     my %domrolebuffer = ();
 2627:     foreach my $entry (keys(%domainrolehash)) {
 2628:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2629:         if ($domrolebuffer{$rudom}) {
 2630:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2631:                       '='.&escape($domainrolehash{$entry});
 2632:         } else {
 2633:             $domrolebuffer{$rudom}.=&escape($entry).
 2634:                       '='.&escape($domainrolehash{$entry});
 2635:         }
 2636:         delete $domainrolehash{$entry};
 2637:     }
 2638:     foreach my $dom (keys(%domrolebuffer)) {
 2639: 	my %servers = &get_servers($dom,'library');
 2640: 	foreach my $tryserver (keys(%servers)) {
 2641: 	    unless (&reply('domroleput:'.$dom.':'.
 2642: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2643: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2644: 	    }
 2645:         }
 2646:     }
 2647:     $dumpcount++;
 2648: }
 2649: 
 2650: sub courselog {
 2651:     my $what=shift;
 2652:     $what=time.':'.$what;
 2653:     unless ($env{'request.course.id'}) { return ''; }
 2654:     $coursedombuf{$env{'request.course.id'}}=
 2655:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2656:     $coursenumbuf{$env{'request.course.id'}}=
 2657:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2658:     $coursehombuf{$env{'request.course.id'}}=
 2659:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2660:     $coursedescrbuf{$env{'request.course.id'}}=
 2661:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2662:     $courseinstcodebuf{$env{'request.course.id'}}=
 2663:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2664:     $courseownerbuf{$env{'request.course.id'}}=
 2665:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2666:     $coursetypebuf{$env{'request.course.id'}}=
 2667:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2668:     if (defined $courselogs{$env{'request.course.id'}}) {
 2669: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2670:     } else {
 2671: 	$courselogs{$env{'request.course.id'}}.=$what;
 2672:     }
 2673:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2674: 	&flushcourselogs();
 2675:     }
 2676: }
 2677: 
 2678: sub courseacclog {
 2679:     my $fnsymb=shift;
 2680:     unless ($env{'request.course.id'}) { return ''; }
 2681:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2682:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2683:         $what.=':POST';
 2684:         # FIXME: Probably ought to escape things....
 2685: 	foreach my $key (keys(%env)) {
 2686:             if ($key=~/^form\.(.*)/) {
 2687:                 my $formitem = $1;
 2688:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2689:                     $what.=':'.$formitem.'='.$env{$key};
 2690:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2691:                     $what.=':'.$formitem.'='.$env{$key};
 2692:                 }
 2693:             }
 2694:         }
 2695:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2696:         # FIXME: We should not be depending on a form parameter that someone
 2697:         # editing lonsearchcat.pm might change in the future.
 2698:         if ($env{'form.phase'} eq 'course_search') {
 2699:             $what.= ':POST';
 2700:             # FIXME: Probably ought to escape things....
 2701:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2702:                                  'crsdiscuss') {
 2703:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2704:             }
 2705:         }
 2706:     }
 2707:     &courselog($what);
 2708: }
 2709: 
 2710: sub countacc {
 2711:     my $url=&declutter(shift);
 2712:     return if (! defined($url) || $url eq '');
 2713:     unless ($env{'request.course.id'}) { return ''; }
 2714:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2715:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2716:     $accesshash{$key}++;
 2717: }
 2718: 
 2719: sub linklog {
 2720:     my ($from,$to)=@_;
 2721:     $from=&declutter($from);
 2722:     $to=&declutter($to);
 2723:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2724:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2725: }
 2726:   
 2727: sub userrolelog {
 2728:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2729:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2730:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2731:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2732:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 2733:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2734:        $userrolehash
 2735:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2736:                     =$tend.':'.$tstart;
 2737:     }
 2738:     if (($env{'request.role'} =~ /dc\./) &&
 2739: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2740: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2741: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 2742:          ($trole=~/^co/))) {
 2743:        $userrolehash
 2744:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2745:                     =$tend.':'.$tstart;
 2746:     }
 2747:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2748:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2749:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2750:         ($trole=~/^sc/)) {
 2751:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2752:        $domainrolehash
 2753:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2754:                     = $tend.':'.$tstart;
 2755:     }
 2756: }
 2757: 
 2758: sub courserolelog {
 2759:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2760:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2761:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2762:         ($trole eq 'ta') || ($trole eq 'st') ||
 2763:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2764:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2765:             my $cdom = $1;
 2766:             my $cnum = $2;
 2767:             my $sec = $3;
 2768:             my $namespace = 'rolelog';
 2769:             my %storehash = (
 2770:                                role    => $trole,
 2771:                                start   => $tstart,
 2772:                                end     => $tend,
 2773:                                selfenroll => $selfenroll,
 2774:                                context    => $context,
 2775:                             );
 2776:             if ($trole eq 'gr') {
 2777:                 $namespace = 'groupslog';
 2778:                 $storehash{'group'} = $sec;
 2779:             } else {
 2780:                 $storehash{'section'} = $sec;
 2781:             }
 2782:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2783:             if (($trole ne 'st') || ($sec ne '')) {
 2784:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2785:             }
 2786:         }
 2787:     }
 2788:     return;
 2789: }
 2790: 
 2791: sub get_course_adv_roles {
 2792:     my ($cid,$codes) = @_;
 2793:     $cid=$env{'request.course.id'} unless (defined($cid));
 2794:     my %coursehash=&coursedescription($cid);
 2795:     my $crstype = &Apache::loncommon::course_type($cid);
 2796:     my %nothide=();
 2797:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2798:         if ($user !~ /:/) {
 2799: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2800:         } else {
 2801:             $nothide{$user}=1;
 2802:         }
 2803:     }
 2804:     my %returnhash=();
 2805:     my %dumphash=
 2806:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2807:     my $now=time;
 2808:     my %privileged;
 2809:     foreach my $entry (keys(%dumphash)) {
 2810: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2811:         if (($tstart) && ($tstart<0)) { next; }
 2812:         if (($tend) && ($tend<$now)) { next; }
 2813:         if (($tstart) && ($now<$tstart)) { next; }
 2814:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2815: 	if ($username eq '' || $domain eq '') { next; }
 2816:         unless (ref($privileged{$domain}) eq 'HASH') {
 2817:             my %dompersonnel =
 2818:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2819:             $privileged{$domain} = {};
 2820:             foreach my $server (keys(%dompersonnel)) {
 2821:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2822:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2823:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2824:                         $privileged{$udom}{$uname} = 1;
 2825:                     }
 2826:                 }
 2827:             }
 2828:         }
 2829:         if ((exists($privileged{$domain}{$username})) && 
 2830:             (!$nothide{$username.':'.$domain})) { next; }
 2831: 	if ($role eq 'cr') { next; }
 2832:         if ($codes) {
 2833:             if ($section) { $role .= ':'.$section; }
 2834:             if ($returnhash{$role}) {
 2835:                 $returnhash{$role}.=','.$username.':'.$domain;
 2836:             } else {
 2837:                 $returnhash{$role}=$username.':'.$domain;
 2838:             }
 2839:         } else {
 2840:             my $key=&plaintext($role,$crstype);
 2841:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2842:             if ($returnhash{$key}) {
 2843: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2844:             } else {
 2845:                 $returnhash{$key}=$username.':'.$domain;
 2846:             }
 2847:         }
 2848:     }
 2849:     return %returnhash;
 2850: }
 2851: 
 2852: sub get_my_roles {
 2853:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2854:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2855:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2856:     my (%dumphash,%nothide);
 2857:     if ($context eq 'userroles') { 
 2858:         %dumphash = &dump('roles',$udom,$uname);
 2859:     } else {
 2860:         %dumphash=
 2861:             &dump('nohist_userroles',$udom,$uname);
 2862:         if ($hidepriv) {
 2863:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2864:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2865:                 if ($user !~ /:/) {
 2866:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2867:                 } else {
 2868:                     $nothide{$user} = 1;
 2869:                 }
 2870:             }
 2871:         }
 2872:     }
 2873:     my %returnhash=();
 2874:     my $now=time;
 2875:     my %privileged;
 2876:     foreach my $entry (keys(%dumphash)) {
 2877:         my ($role,$tend,$tstart);
 2878:         if ($context eq 'userroles') {
 2879: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2880:         } else {
 2881:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2882:         }
 2883:         if (($tstart) && ($tstart<0)) { next; }
 2884:         my $status = 'active';
 2885:         if (($tend) && ($tend<=$now)) {
 2886:             $status = 'previous';
 2887:         } 
 2888:         if (($tstart) && ($now<$tstart)) {
 2889:             $status = 'future';
 2890:         }
 2891:         if (ref($types) eq 'ARRAY') {
 2892:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2893:                 next;
 2894:             } 
 2895:         } else {
 2896:             if ($status ne 'active') {
 2897:                 next;
 2898:             }
 2899:         }
 2900:         my ($rolecode,$username,$domain,$section,$area);
 2901:         if ($context eq 'userroles') {
 2902:             ($area,$rolecode) = split(/_/,$entry);
 2903:             (undef,$domain,$username,$section) = split(/\//,$area);
 2904:         } else {
 2905:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2906:         }
 2907:         if (ref($roledoms) eq 'ARRAY') {
 2908:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2909:                 next;
 2910:             }
 2911:         }
 2912:         if (ref($roles) eq 'ARRAY') {
 2913:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2914:                 if ($role =~ /^cr\//) {
 2915:                     if (!grep(/^cr$/,@{$roles})) {
 2916:                         next;
 2917:                     }
 2918:                 } else {
 2919:                     next;
 2920:                 }
 2921:             }
 2922:         }
 2923:         if ($hidepriv) {
 2924:             if ($context eq 'userroles') {
 2925:                 if ((&privileged($username,$domain)) &&
 2926:                     (!$nothide{$username.':'.$domain})) {
 2927:                     next;
 2928:                 }
 2929:             } else {
 2930:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2931:                     my %dompersonnel =
 2932:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2933:                     $privileged{$domain} = {};
 2934:                     if (keys(%dompersonnel)) {
 2935:                         foreach my $server (keys(%dompersonnel)) {
 2936:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2937:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2938:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2939:                                     $privileged{$udom}{$uname} = $trole;
 2940:                                 }
 2941:                             }
 2942:                         }
 2943:                     }
 2944:                 }
 2945:                 if (exists($privileged{$domain}{$username})) {
 2946:                     if (!$nothide{$username.':'.$domain}) {
 2947:                         next;
 2948:                     }
 2949:                 }
 2950:             }
 2951:         }
 2952:         if ($withsec) {
 2953:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2954:                 $tstart.':'.$tend;
 2955:         } else {
 2956:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2957:         }
 2958:     }
 2959:     return %returnhash;
 2960: }
 2961: 
 2962: # ----------------------------------------------------- Frontpage Announcements
 2963: #
 2964: #
 2965: 
 2966: sub postannounce {
 2967:     my ($server,$text)=@_;
 2968:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2969:     unless ($text=~/\w/) { $text=''; }
 2970:     return &reply('setannounce:'.&escape($text),$server);
 2971: }
 2972: 
 2973: sub getannounce {
 2974: 
 2975:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2976: 	my $announcement='';
 2977: 	while (my $line = <$fh>) { $announcement .= $line; }
 2978: 	close($fh);
 2979: 	if ($announcement=~/\w/) { 
 2980: 	    return 
 2981:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2982:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2983: 	} else {
 2984: 	    return '';
 2985: 	}
 2986:     } else {
 2987: 	return '';
 2988:     }
 2989: }
 2990: 
 2991: # ---------------------------------------------------------- Course ID routines
 2992: # Deal with domain's nohist_courseid.db files
 2993: #
 2994: 
 2995: sub courseidput {
 2996:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2997:     my $outcome;
 2998:     if ($caller eq 'timeonly') {
 2999:         my $cids = '';
 3000:         foreach my $item (keys(%$storehash)) {
 3001:             $cids.=&escape($item).'&';
 3002:         }
 3003:         $cids=~s/\&$//;
 3004:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3005:                           $coursehome);       
 3006:     } else {
 3007:         my $items = '';
 3008:         foreach my $item (keys(%$storehash)) {
 3009:             $items.= &escape($item).'='.
 3010:                      &freeze_escape($$storehash{$item}).'&';
 3011:         }
 3012:         $items=~s/\&$//;
 3013:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3014:                           $coursehome);
 3015:     }
 3016:     if ($outcome eq 'unknown_cmd') {
 3017:         my $what;
 3018:         foreach my $cid (keys(%$storehash)) {
 3019:             $what .= &escape($cid).'=';
 3020:             foreach my $item ('description','inst_code','owner','type') {
 3021:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3022:             }
 3023:             $what =~ s/\:$/&/;
 3024:         }
 3025:         $what =~ s/\&$//;  
 3026:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3027:     } else {
 3028:         return $outcome;
 3029:     }
 3030: }
 3031: 
 3032: sub courseiddump {
 3033:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3034:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3035:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3036:         $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
 3037:     my $as_hash = 1;
 3038:     my %returnhash;
 3039:     if (!$domfilter) { $domfilter=''; }
 3040:     my %libserv = &all_library();
 3041:     foreach my $tryserver (keys(%libserv)) {
 3042:         if ( (  $hostidflag == 1 
 3043: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3044: 	     || (!defined($hostidflag)) ) {
 3045: 
 3046: 	    if (($domfilter eq '') ||
 3047: 		(&host_domain($tryserver) eq $domfilter)) {
 3048:                 my $rep = 
 3049:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3050:                          $sincefilter.':'.&escape($descfilter).':'.
 3051:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3052:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3053:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3054:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3055:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3056:                          &escape($cc_clone).':'.$cloneonly.':'.
 3057:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3058:                          &escape($creationcontext),$tryserver);
 3059:                 my @pairs=split(/\&/,$rep);
 3060:                 foreach my $item (@pairs) {
 3061:                     my ($key,$value)=split(/\=/,$item,2);
 3062:                     $key = &unescape($key);
 3063:                     next if ($key =~ /^error: 2 /);
 3064:                     my $result = &thaw_unescape($value);
 3065:                     if (ref($result) eq 'HASH') {
 3066:                         $returnhash{$key}=$result;
 3067:                     } else {
 3068:                         my @responses = split(/:/,$value);
 3069:                         my @items = ('description','inst_code','owner','type');
 3070:                         for (my $i=0; $i<@responses; $i++) {
 3071:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3072:                         }
 3073:                     }
 3074:                 }
 3075:             }
 3076:         }
 3077:     }
 3078:     return %returnhash;
 3079: }
 3080: 
 3081: # ---------------------------------------------------------- DC e-mail
 3082: 
 3083: sub dcmailput {
 3084:     my ($domain,$msgid,$message,$server)=@_;
 3085:     my $status = &Apache::lonnet::critical(
 3086:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3087:        &escape($message),$server);
 3088:     return $status;
 3089: }
 3090: 
 3091: sub dcmaildump {
 3092:     my ($dom,$startdate,$enddate,$senders) = @_;
 3093:     my %returnhash=();
 3094: 
 3095:     if (defined(&domain($dom,'primary'))) {
 3096:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3097:                                                          &escape($enddate).':';
 3098: 	my @esc_senders=map { &escape($_)} @$senders;
 3099: 	$cmd.=&escape(join('&',@esc_senders));
 3100: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3101:             my ($key,$value) = split(/\=/,$line,2);
 3102:             if (($key) && ($value)) {
 3103:                 $returnhash{&unescape($key)} = &unescape($value);
 3104:             }
 3105:         }
 3106:     }
 3107:     return %returnhash;
 3108: }
 3109: # ---------------------------------------------------------- Domain roles
 3110: 
 3111: sub get_domain_roles {
 3112:     my ($dom,$roles,$startdate,$enddate)=@_;
 3113:     if ((!defined($startdate)) || ($startdate eq '')) {
 3114:         $startdate = '.';
 3115:     }
 3116:     if ((!defined($enddate)) || ($enddate eq '')) {
 3117:         $enddate = '.';
 3118:     }
 3119:     my $rolelist;
 3120:     if (ref($roles) eq 'ARRAY') {
 3121:         $rolelist = join(':',@{$roles});
 3122:     }
 3123:     my %personnel = ();
 3124: 
 3125:     my %servers = &get_servers($dom,'library');
 3126:     foreach my $tryserver (keys(%servers)) {
 3127: 	%{$personnel{$tryserver}}=();
 3128: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3129: 					    &escape($startdate).':'.
 3130: 					    &escape($enddate).':'.
 3131: 					    &escape($rolelist), $tryserver))) {
 3132: 	    my ($key,$value) = split(/\=/,$line,2);
 3133: 	    if (($key) && ($value)) {
 3134: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3135: 	    }
 3136: 	}
 3137:     }
 3138:     return %personnel;
 3139: }
 3140: 
 3141: # ----------------------------------------------------------- Check out an item
 3142: 
 3143: sub get_first_access {
 3144:     my ($type,$argsymb)=@_;
 3145:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3146:     if ($argsymb) { $symb=$argsymb; }
 3147:     my ($map,$id,$res)=&decode_symb($symb);
 3148:     if ($type eq 'course') {
 3149: 	$res='course';
 3150:     } elsif ($type eq 'map') {
 3151: 	$res=&symbread($map);
 3152:     } else {
 3153: 	$res=$symb;
 3154:     }
 3155:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3156:     return $times{"$courseid\0$res"};
 3157: }
 3158: 
 3159: sub set_first_access {
 3160:     my ($type)=@_;
 3161:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3162:     my ($map,$id,$res)=&decode_symb($symb);
 3163:     if ($type eq 'course') {
 3164: 	$res='course';
 3165:     } elsif ($type eq 'map') {
 3166: 	$res=&symbread($map);
 3167:     } else {
 3168: 	$res=$symb;
 3169:     }
 3170:     my $firstaccess=&get_first_access($type,$symb);
 3171:     if (!$firstaccess) {
 3172: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3173:     }
 3174:     return 'already_set';
 3175: }
 3176: 
 3177: sub checkout {
 3178:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3179:     my $now=time;
 3180:     my $lonhost=$perlvar{'lonHostID'};
 3181:     my $infostr=&escape(
 3182:                  'CHECKOUTTOKEN&'.
 3183:                  $tuname.'&'.
 3184:                  $tudom.'&'.
 3185:                  $tcrsid.'&'.
 3186:                  $symb.'&'.
 3187: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3188:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3189:     if ($token=~/^error\:/) { 
 3190:         &logthis("<font color=\"blue\">WARNING: ".
 3191:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3192:                  "</font>");
 3193:         return ''; 
 3194:     }
 3195: 
 3196:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3197:     $token=~tr/a-z/A-Z/;
 3198: 
 3199:     my %infohash=('resource.0.outtoken' => $token,
 3200:                   'resource.0.checkouttime' => $now,
 3201:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3202: 
 3203:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3204:        return '';
 3205:     } else {
 3206:         &logthis("<font color=\"blue\">WARNING: ".
 3207:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3208:                  "</font>");
 3209:     }    
 3210: 
 3211:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3212:                          &escape('Checkout '.$infostr.' - '.
 3213:                                                  $token)) ne 'ok') {
 3214: 	return '';
 3215:     } else {
 3216:         &logthis("<font color=\"blue\">WARNING: ".
 3217:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3218:                  "</font>");
 3219:     }
 3220:     return $token;
 3221: }
 3222: 
 3223: # ------------------------------------------------------------ Check in an item
 3224: 
 3225: sub checkin {
 3226:     my $token=shift;
 3227:     my $now=time;
 3228:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3229:     $lonhost=~tr/A-Z/a-z/;
 3230:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3231:     $dtoken=~s/\W/\_/g;
 3232:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3233:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3234: 
 3235:     unless (($tuname) && ($tudom)) {
 3236:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3237:         return '';
 3238:     }
 3239:     
 3240:     unless (&allowed('mgr',$tcrsid)) {
 3241:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3242:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3243:         return '';
 3244:     }
 3245: 
 3246:     my %infohash=('resource.0.intoken' => $token,
 3247:                   'resource.0.checkintime' => $now,
 3248:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3249: 
 3250:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3251:        return '';
 3252:     }    
 3253: 
 3254:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3255:                          &escape('Checkin - '.$token)) ne 'ok') {
 3256: 	return '';
 3257:     }
 3258: 
 3259:     return ($symb,$tuname,$tudom,$tcrsid);    
 3260: }
 3261: 
 3262: # --------------------------------------------- Set Expire Date for Spreadsheet
 3263: 
 3264: sub expirespread {
 3265:     my ($uname,$udom,$stype,$usymb)=@_;
 3266:     my $cid=$env{'request.course.id'}; 
 3267:     if ($cid) {
 3268:        my $now=time;
 3269:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3270:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3271:                             $env{'course.'.$cid.'.num'}.
 3272: 	        	    ':nohist_expirationdates:'.
 3273:                             &escape($key).'='.$now,
 3274:                             $env{'course.'.$cid.'.home'})
 3275:     }
 3276:     return 'ok';
 3277: }
 3278: 
 3279: # ----------------------------------------------------- Devalidate Spreadsheets
 3280: 
 3281: sub devalidate {
 3282:     my ($symb,$uname,$udom)=@_;
 3283:     my $cid=$env{'request.course.id'}; 
 3284:     if ($cid) {
 3285:         # delete the stored spreadsheets for
 3286:         # - the student level sheet of this user in course's homespace
 3287:         # - the assessment level sheet for this resource 
 3288:         #   for this user in user's homespace
 3289: 	# - current conditional state info
 3290: 	my $key=$uname.':'.$udom.':';
 3291:         my $status=
 3292: 	    &del('nohist_calculatedsheets',
 3293: 		 [$key.'studentcalc:'],
 3294: 		 $env{'course.'.$cid.'.domain'},
 3295: 		 $env{'course.'.$cid.'.num'})
 3296: 		.' '.
 3297: 	    &del('nohist_calculatedsheets_'.$cid,
 3298: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3299:         unless ($status eq 'ok ok') {
 3300:            &logthis('Could not devalidate spreadsheet '.
 3301:                     $uname.' at '.$udom.' for '.
 3302: 		    $symb.': '.$status);
 3303:         }
 3304: 	&delenv('user.state.'.$cid);
 3305:     }
 3306: }
 3307: 
 3308: sub get_scalar {
 3309:     my ($string,$end) = @_;
 3310:     my $value;
 3311:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3312: 	$value = $1;
 3313:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3314: 	$value = $1;
 3315:     }
 3316:     return &unescape($value);
 3317: }
 3318: 
 3319: sub array2str {
 3320:   my (@array) = @_;
 3321:   my $result=&arrayref2str(\@array);
 3322:   $result=~s/^__ARRAY_REF__//;
 3323:   $result=~s/__END_ARRAY_REF__$//;
 3324:   return $result;
 3325: }
 3326: 
 3327: sub arrayref2str {
 3328:   my ($arrayref) = @_;
 3329:   my $result='__ARRAY_REF__';
 3330:   foreach my $elem (@$arrayref) {
 3331:     if(ref($elem) eq 'ARRAY') {
 3332:       $result.=&arrayref2str($elem).'&';
 3333:     } elsif(ref($elem) eq 'HASH') {
 3334:       $result.=&hashref2str($elem).'&';
 3335:     } elsif(ref($elem)) {
 3336:       #print("Got a ref of ".(ref($elem))." skipping.");
 3337:     } else {
 3338:       $result.=&escape($elem).'&';
 3339:     }
 3340:   }
 3341:   $result=~s/\&$//;
 3342:   $result .= '__END_ARRAY_REF__';
 3343:   return $result;
 3344: }
 3345: 
 3346: sub hash2str {
 3347:   my (%hash) = @_;
 3348:   my $result=&hashref2str(\%hash);
 3349:   $result=~s/^__HASH_REF__//;
 3350:   $result=~s/__END_HASH_REF__$//;
 3351:   return $result;
 3352: }
 3353: 
 3354: sub hashref2str {
 3355:   my ($hashref)=@_;
 3356:   my $result='__HASH_REF__';
 3357:   foreach my $key (sort(keys(%$hashref))) {
 3358:     if (ref($key) eq 'ARRAY') {
 3359:       $result.=&arrayref2str($key).'=';
 3360:     } elsif (ref($key) eq 'HASH') {
 3361:       $result.=&hashref2str($key).'=';
 3362:     } elsif (ref($key)) {
 3363:       $result.='=';
 3364:       #print("Got a ref of ".(ref($key))." skipping.");
 3365:     } else {
 3366: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3367:     }
 3368: 
 3369:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3370:       $result.=&arrayref2str($hashref->{$key}).'&';
 3371:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3372:       $result.=&hashref2str($hashref->{$key}).'&';
 3373:     } elsif(ref($hashref->{$key})) {
 3374:        $result.='&';
 3375:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3376:     } else {
 3377:       $result.=&escape($hashref->{$key}).'&';
 3378:     }
 3379:   }
 3380:   $result=~s/\&$//;
 3381:   $result .= '__END_HASH_REF__';
 3382:   return $result;
 3383: }
 3384: 
 3385: sub str2hash {
 3386:     my ($string)=@_;
 3387:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3388:     return %$hash;
 3389: }
 3390: 
 3391: sub str2hashref {
 3392:   my ($string) = @_;
 3393: 
 3394:   my %hash;
 3395: 
 3396:   if($string !~ /^__HASH_REF__/) {
 3397:       if (! ($string eq '' || !defined($string))) {
 3398: 	  $hash{'error'}='Not hash reference';
 3399:       }
 3400:       return (\%hash, $string);
 3401:   }
 3402: 
 3403:   $string =~ s/^__HASH_REF__//;
 3404: 
 3405:   while($string !~ /^__END_HASH_REF__/) {
 3406:       #key
 3407:       my $key='';
 3408:       if($string =~ /^__HASH_REF__/) {
 3409:           ($key, $string)=&str2hashref($string);
 3410:           if(defined($key->{'error'})) {
 3411:               $hash{'error'}='Bad data';
 3412:               return (\%hash, $string);
 3413:           }
 3414:       } elsif($string =~ /^__ARRAY_REF__/) {
 3415:           ($key, $string)=&str2arrayref($string);
 3416:           if($key->[0] eq 'Array reference error') {
 3417:               $hash{'error'}='Bad data';
 3418:               return (\%hash, $string);
 3419:           }
 3420:       } else {
 3421:           $string =~ s/^(.*?)=//;
 3422: 	  $key=&unescape($1);
 3423:       }
 3424:       $string =~ s/^=//;
 3425: 
 3426:       #value
 3427:       my $value='';
 3428:       if($string =~ /^__HASH_REF__/) {
 3429:           ($value, $string)=&str2hashref($string);
 3430:           if(defined($value->{'error'})) {
 3431:               $hash{'error'}='Bad data';
 3432:               return (\%hash, $string);
 3433:           }
 3434:       } elsif($string =~ /^__ARRAY_REF__/) {
 3435:           ($value, $string)=&str2arrayref($string);
 3436:           if($value->[0] eq 'Array reference error') {
 3437:               $hash{'error'}='Bad data';
 3438:               return (\%hash, $string);
 3439:           }
 3440:       } else {
 3441: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3442:       }
 3443:       $string =~ s/^&//;
 3444: 
 3445:       $hash{$key}=$value;
 3446:   }
 3447: 
 3448:   $string =~ s/^__END_HASH_REF__//;
 3449: 
 3450:   return (\%hash, $string);
 3451: }
 3452: 
 3453: sub str2array {
 3454:     my ($string)=@_;
 3455:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3456:     return @$array;
 3457: }
 3458: 
 3459: sub str2arrayref {
 3460:   my ($string) = @_;
 3461:   my @array;
 3462: 
 3463:   if($string !~ /^__ARRAY_REF__/) {
 3464:       if (! ($string eq '' || !defined($string))) {
 3465: 	  $array[0]='Array reference error';
 3466:       }
 3467:       return (\@array, $string);
 3468:   }
 3469: 
 3470:   $string =~ s/^__ARRAY_REF__//;
 3471: 
 3472:   while($string !~ /^__END_ARRAY_REF__/) {
 3473:       my $value='';
 3474:       if($string =~ /^__HASH_REF__/) {
 3475:           ($value, $string)=&str2hashref($string);
 3476:           if(defined($value->{'error'})) {
 3477:               $array[0] ='Array reference error';
 3478:               return (\@array, $string);
 3479:           }
 3480:       } elsif($string =~ /^__ARRAY_REF__/) {
 3481:           ($value, $string)=&str2arrayref($string);
 3482:           if($value->[0] eq 'Array reference error') {
 3483:               $array[0] ='Array reference error';
 3484:               return (\@array, $string);
 3485:           }
 3486:       } else {
 3487: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3488:       }
 3489:       $string =~ s/^&//;
 3490: 
 3491:       push(@array, $value);
 3492:   }
 3493: 
 3494:   $string =~ s/^__END_ARRAY_REF__//;
 3495: 
 3496:   return (\@array, $string);
 3497: }
 3498: 
 3499: # -------------------------------------------------------------------Temp Store
 3500: 
 3501: sub tmpreset {
 3502:   my ($symb,$namespace,$domain,$stuname) = @_;
 3503:   if (!$symb) {
 3504:     $symb=&symbread();
 3505:     if (!$symb) { $symb= $env{'request.url'}; }
 3506:   }
 3507:   $symb=escape($symb);
 3508: 
 3509:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3510:   $namespace=~s/\//\_/g;
 3511:   $namespace=~s/\W//g;
 3512: 
 3513:   if (!$domain) { $domain=$env{'user.domain'}; }
 3514:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3515:   if ($domain eq 'public' && $stuname eq 'public') {
 3516:       $stuname=$ENV{'REMOTE_ADDR'};
 3517:   }
 3518:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3519:   my %hash;
 3520:   if (tie(%hash,'GDBM_File',
 3521: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3522: 	  &GDBM_WRCREAT(),0640)) {
 3523:     foreach my $key (keys(%hash)) {
 3524:       if ($key=~ /:$symb/) {
 3525: 	delete($hash{$key});
 3526:       }
 3527:     }
 3528:   }
 3529: }
 3530: 
 3531: sub tmpstore {
 3532:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3533: 
 3534:   if (!$symb) {
 3535:     $symb=&symbread();
 3536:     if (!$symb) { $symb= $env{'request.url'}; }
 3537:   }
 3538:   $symb=escape($symb);
 3539: 
 3540:   if (!$namespace) {
 3541:     # I don't think we would ever want to store this for a course.
 3542:     # it seems this will only be used if we don't have a course.
 3543:     #$namespace=$env{'request.course.id'};
 3544:     #if (!$namespace) {
 3545:       $namespace=$env{'request.state'};
 3546:     #}
 3547:   }
 3548:   $namespace=~s/\//\_/g;
 3549:   $namespace=~s/\W//g;
 3550:   if (!$domain) { $domain=$env{'user.domain'}; }
 3551:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3552:   if ($domain eq 'public' && $stuname eq 'public') {
 3553:       $stuname=$ENV{'REMOTE_ADDR'};
 3554:   }
 3555:   my $now=time;
 3556:   my %hash;
 3557:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3558:   if (tie(%hash,'GDBM_File',
 3559: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3560: 	  &GDBM_WRCREAT(),0640)) {
 3561:     $hash{"version:$symb"}++;
 3562:     my $version=$hash{"version:$symb"};
 3563:     my $allkeys=''; 
 3564:     foreach my $key (keys(%$storehash)) {
 3565:       $allkeys.=$key.':';
 3566:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3567:     }
 3568:     $hash{"$version:$symb:timestamp"}=$now;
 3569:     $allkeys.='timestamp';
 3570:     $hash{"$version:keys:$symb"}=$allkeys;
 3571:     if (untie(%hash)) {
 3572:       return 'ok';
 3573:     } else {
 3574:       return "error:$!";
 3575:     }
 3576:   } else {
 3577:     return "error:$!";
 3578:   }
 3579: }
 3580: 
 3581: # -----------------------------------------------------------------Temp Restore
 3582: 
 3583: sub tmprestore {
 3584:   my ($symb,$namespace,$domain,$stuname) = @_;
 3585: 
 3586:   if (!$symb) {
 3587:     $symb=&symbread();
 3588:     if (!$symb) { $symb= $env{'request.url'}; }
 3589:   }
 3590:   $symb=escape($symb);
 3591: 
 3592:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3593: 
 3594:   if (!$domain) { $domain=$env{'user.domain'}; }
 3595:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3596:   if ($domain eq 'public' && $stuname eq 'public') {
 3597:       $stuname=$ENV{'REMOTE_ADDR'};
 3598:   }
 3599:   my %returnhash;
 3600:   $namespace=~s/\//\_/g;
 3601:   $namespace=~s/\W//g;
 3602:   my %hash;
 3603:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3604:   if (tie(%hash,'GDBM_File',
 3605: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3606: 	  &GDBM_READER(),0640)) {
 3607:     my $version=$hash{"version:$symb"};
 3608:     $returnhash{'version'}=$version;
 3609:     my $scope;
 3610:     for ($scope=1;$scope<=$version;$scope++) {
 3611:       my $vkeys=$hash{"$scope:keys:$symb"};
 3612:       my @keys=split(/:/,$vkeys);
 3613:       my $key;
 3614:       $returnhash{"$scope:keys"}=$vkeys;
 3615:       foreach $key (@keys) {
 3616: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3617: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3618:       }
 3619:     }
 3620:     if (!(untie(%hash))) {
 3621:       return "error:$!";
 3622:     }
 3623:   } else {
 3624:     return "error:$!";
 3625:   }
 3626:   return %returnhash;
 3627: }
 3628: 
 3629: # ----------------------------------------------------------------------- Store
 3630: 
 3631: sub store {
 3632:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3633:     my $home='';
 3634: 
 3635:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3636: 
 3637:     $symb=&symbclean($symb);
 3638:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3639: 
 3640:     if (!$domain) { $domain=$env{'user.domain'}; }
 3641:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3642: 
 3643:     &devalidate($symb,$stuname,$domain);
 3644: 
 3645:     $symb=escape($symb);
 3646:     if (!$namespace) { 
 3647:        unless ($namespace=$env{'request.course.id'}) { 
 3648:           return ''; 
 3649:        } 
 3650:     }
 3651:     if (!$home) { $home=$env{'user.home'}; }
 3652: 
 3653:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3654:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3655: 
 3656:     my $namevalue='';
 3657:     foreach my $key (keys(%$storehash)) {
 3658:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3659:     }
 3660:     $namevalue=~s/\&$//;
 3661:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3662:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3663: }
 3664: 
 3665: # -------------------------------------------------------------- Critical Store
 3666: 
 3667: sub cstore {
 3668:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3669:     my $home='';
 3670: 
 3671:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3672: 
 3673:     $symb=&symbclean($symb);
 3674:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3675: 
 3676:     if (!$domain) { $domain=$env{'user.domain'}; }
 3677:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3678: 
 3679:     &devalidate($symb,$stuname,$domain);
 3680: 
 3681:     $symb=escape($symb);
 3682:     if (!$namespace) { 
 3683:        unless ($namespace=$env{'request.course.id'}) { 
 3684:           return ''; 
 3685:        } 
 3686:     }
 3687:     if (!$home) { $home=$env{'user.home'}; }
 3688: 
 3689:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3690:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3691: 
 3692:     my $namevalue='';
 3693:     foreach my $key (keys(%$storehash)) {
 3694:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3695:     }
 3696:     $namevalue=~s/\&$//;
 3697:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3698:     return critical
 3699:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3700: }
 3701: 
 3702: # --------------------------------------------------------------------- Restore
 3703: 
 3704: sub restore {
 3705:     my ($symb,$namespace,$domain,$stuname) = @_;
 3706:     my $home='';
 3707: 
 3708:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3709: 
 3710:     if (!$symb) {
 3711:       unless ($symb=escape(&symbread())) { return ''; }
 3712:     } else {
 3713:       $symb=&escape(&symbclean($symb));
 3714:     }
 3715:     if (!$namespace) { 
 3716:        unless ($namespace=$env{'request.course.id'}) { 
 3717:           return ''; 
 3718:        } 
 3719:     }
 3720:     if (!$domain) { $domain=$env{'user.domain'}; }
 3721:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3722:     if (!$home) { $home=$env{'user.home'}; }
 3723:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3724: 
 3725:     my %returnhash=();
 3726:     foreach my $line (split(/\&/,$answer)) {
 3727: 	my ($name,$value)=split(/\=/,$line);
 3728:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3729:     }
 3730:     my $version;
 3731:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3732:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3733:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3734:        }
 3735:     }
 3736:     return %returnhash;
 3737: }
 3738: 
 3739: # ---------------------------------------------------------- Course Description
 3740: 
 3741: sub coursedescription {
 3742:     my ($courseid,$args)=@_;
 3743:     $courseid=~s/^\///;
 3744:     $courseid=~s/\_/\//g;
 3745:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3746:     my $chome=&homeserver($cnum,$cdomain);
 3747:     my $normalid=$cdomain.'_'.$cnum;
 3748:     # need to always cache even if we get errors otherwise we keep 
 3749:     # trying and trying and trying to get the course description.
 3750:     my %envhash=();
 3751:     my %returnhash=();
 3752:     
 3753:     my $expiretime=600;
 3754:     if ($env{'request.course.id'} eq $normalid) {
 3755: 	$expiretime=120;
 3756:     }
 3757: 
 3758:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3759:     if (!$args->{'freshen_cache'}
 3760: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3761: 	foreach my $key (keys(%env)) {
 3762: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3763: 	    my ($setting) = $1;
 3764: 	    $returnhash{$setting} = $env{$key};
 3765: 	}
 3766: 	return %returnhash;
 3767:     }
 3768: 
 3769:     # get the data agin
 3770:     if (!$args->{'one_time'}) {
 3771: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3772:     }
 3773: 
 3774:     if ($chome ne 'no_host') {
 3775:        %returnhash=&dump('environment',$cdomain,$cnum);
 3776:        if (!exists($returnhash{'con_lost'})) {
 3777:            $returnhash{'home'}= $chome;
 3778: 	   $returnhash{'domain'} = $cdomain;
 3779: 	   $returnhash{'num'} = $cnum;
 3780:            if (!defined($returnhash{'type'})) {
 3781:                $returnhash{'type'} = 'Course';
 3782:            }
 3783:            while (my ($name,$value) = each %returnhash) {
 3784:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3785:            }
 3786:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3787:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3788: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3789:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3790:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3791:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3792:        }
 3793:     }
 3794:     if (!$args->{'one_time'}) {
 3795: 	&appenv(\%envhash);
 3796:     }
 3797:     return %returnhash;
 3798: }
 3799: 
 3800: # -------------------------------------------------See if a user is privileged
 3801: 
 3802: sub privileged {
 3803:     my ($username,$domain)=@_;
 3804:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3805: 			&homeserver($username,$domain));
 3806:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3807:         ($rolesdump =~ /^error:/)) {
 3808:         return 0;
 3809:     }
 3810:     my $now=time;
 3811:     if ($rolesdump ne '') {
 3812:         foreach my $entry (split(/&/,$rolesdump)) {
 3813: 	    if ($entry!~/^rolesdef_/) {
 3814: 		my ($area,$role)=split(/=/,$entry);
 3815: 		$area=~s/\_\w\w$//;
 3816: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3817: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3818: 		    my $active=1;
 3819: 		    if ($tend) {
 3820: 			if ($tend<$now) { $active=0; }
 3821: 		    }
 3822: 		    if ($tstart) {
 3823: 			if ($tstart>$now) { $active=0; }
 3824: 		    }
 3825: 		    if ($active) { return 1; }
 3826: 		}
 3827: 	    }
 3828: 	}
 3829:     }
 3830:     return 0;
 3831: }
 3832: 
 3833: # -------------------------------------------------------- Get user privileges
 3834: 
 3835: sub rolesinit {
 3836:     my ($domain,$username,$authhost)=@_;
 3837:     my $now=time;
 3838:     my %userroles = ('user.login.time' => $now);
 3839:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3840:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3841:         ($rolesdump =~ /^error:/)) { 
 3842:         return \%userroles;
 3843:     }
 3844:     my %allroles=();
 3845:     my %allgroups=();   
 3846:     my $group_privs;
 3847: 
 3848:     if ($rolesdump ne '') {
 3849:         foreach my $entry (split(/&/,$rolesdump)) {
 3850: 	  if ($entry!~/^rolesdef_/) {
 3851:             my ($area,$role)=split(/=/,$entry);
 3852: 	    $area=~s/\_\w\w$//;
 3853:             my ($trole,$tend,$tstart,$group_privs);
 3854: 	    if ($role=~/^cr/) { 
 3855: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3856: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3857: 		    ($tend,$tstart)=split('_',$trest);
 3858: 		} else {
 3859: 		    $trole=$role;
 3860: 		}
 3861:             } elsif ($role =~ m|^gr/|) {
 3862:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3863:                 ($trole,$group_privs) = split(/\//,$trole);
 3864:                 $group_privs = &unescape($group_privs);
 3865: 	    } else {
 3866: 		($trole,$tend,$tstart)=split(/_/,$role);
 3867: 	    }
 3868: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3869: 					 $username);
 3870: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3871:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3872:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3873:             if (($area ne '') && ($trole ne '')) {
 3874: 		my $spec=$trole.'.'.$area;
 3875: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3876: 		if ($trole =~ /^cr\//) {
 3877:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3878:                 } elsif ($trole eq 'gr') {
 3879:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3880: 		} else {
 3881:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3882: 		}
 3883:             }
 3884:           }
 3885:         }
 3886:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3887:         $userroles{'user.adv'}    = $adv;
 3888: 	$userroles{'user.author'} = $author;
 3889:         $env{'user.adv'}=$adv;
 3890:     }
 3891:     return \%userroles;  
 3892: }
 3893: 
 3894: sub set_arearole {
 3895:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3896: # log the associated role with the area
 3897:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3898:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3899: }
 3900: 
 3901: sub custom_roleprivs {
 3902:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3903:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3904:     my $homsvr=homeserver($rauthor,$rdomain);
 3905:     if (&hostname($homsvr) ne '') {
 3906:         my ($rdummy,$roledef)=
 3907:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3908:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3909:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3910:             if (defined($syspriv)) {
 3911:                 if ($trest =~ /^$match_community$/) {
 3912:                     $syspriv =~ s/bre\&S//; 
 3913:                 }
 3914:                 $$allroles{'cm./'}.=':'.$syspriv;
 3915:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3916:             }
 3917:             if ($tdomain ne '') {
 3918:                 if (defined($dompriv)) {
 3919:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3920:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3921:                 }
 3922:                 if (($trest ne '') && (defined($coursepriv))) {
 3923:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3924:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3925:                 }
 3926:             }
 3927:         }
 3928:     }
 3929: }
 3930: 
 3931: sub group_roleprivs {
 3932:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3933:     my $access = 1;
 3934:     my $now = time;
 3935:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3936:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3937:     if ($access) {
 3938:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3939:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3940:     }
 3941: }
 3942: 
 3943: sub standard_roleprivs {
 3944:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3945:     if (defined($pr{$trole.':s'})) {
 3946:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3947:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3948:     }
 3949:     if ($tdomain ne '') {
 3950:         if (defined($pr{$trole.':d'})) {
 3951:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3952:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3953:         }
 3954:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3955:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3956:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3957:         }
 3958:     }
 3959: }
 3960: 
 3961: sub set_userprivs {
 3962:     my ($userroles,$allroles,$allgroups) = @_; 
 3963:     my $author=0;
 3964:     my $adv=0;
 3965:     my %grouproles = ();
 3966:     if (keys(%{$allgroups}) > 0) {
 3967:         foreach my $role (keys(%{$allroles})) {
 3968:             my ($trole,$area,$sec,$extendedarea);
 3969:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3970:                 $trole = $1;
 3971:                 $area = $2;
 3972:                 $sec = $3;
 3973:                 $extendedarea = $area.$sec;
 3974:                 if (exists($$allgroups{$area})) {
 3975:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3976:                         my $spec = $trole.'.'.$extendedarea;
 3977:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3978:                                                 $$allgroups{$area}{$group};
 3979:                     }
 3980:                 }
 3981:             }
 3982:         }
 3983:     }
 3984:     foreach my $group (keys(%grouproles)) {
 3985:         $$allroles{$group} = $grouproles{$group};
 3986:     }
 3987:     foreach my $role (keys(%{$allroles})) {
 3988:         my %thesepriv;
 3989:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3990:         foreach my $item (split(/:/,$$allroles{$role})) {
 3991:             if ($item ne '') {
 3992:                 my ($privilege,$restrictions)=split(/&/,$item);
 3993:                 if ($restrictions eq '') {
 3994:                     $thesepriv{$privilege}='F';
 3995:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3996:                     $thesepriv{$privilege}.=$restrictions;
 3997:                 }
 3998:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3999:             }
 4000:         }
 4001:         my $thesestr='';
 4002:         foreach my $priv (keys(%thesepriv)) {
 4003: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4004: 	}
 4005:         $userroles->{'user.priv.'.$role} = $thesestr;
 4006:     }
 4007:     return ($author,$adv);
 4008: }
 4009: 
 4010: sub role_status {
 4011:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4012:     my @pwhere = ();
 4013:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4014:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4015:         unless (!defined($$role) || $$role eq '') {
 4016:             $$where=join('.',@pwhere);
 4017:             $$trolecode=$$role.'.'.$$where;
 4018:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4019:             $$tstatus='is';
 4020:             if ($$tstart && $$tstart>$then) {
 4021:                 $$tstatus='future';
 4022:                 if ($$tstart<$now) {
 4023:                     if ($$tstart && $$tstart>$refresh) {
 4024:                         if (($$where ne '') && ($$role ne '')) {
 4025:                             my (%allroles,%allgroups,$group_privs);
 4026:                             my %userroles = (
 4027:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4028:                             );
 4029:                             my $spec=$$role.'.'.$$where;
 4030:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4031:                             if ($$role eq 'gr') {
 4032:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4033:                                                     $env{'user.name'})=@_;
 4034:                                 my ($trole) = split('_',$role,1);
 4035:                                 (undef,my $group_privs) = split(/\//,$trole);
 4036:                                 $group_privs = &unescape($group_privs);
 4037:                             }
 4038:                             if ($$role =~ /^cr\//) {
 4039:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4040:                             } elsif ($$role eq 'gr') {
 4041:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4042:                                                     $env{'user.name'});
 4043:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 4044:                                 (undef,my $group_privs) = split(/\//,$trole);
 4045:                                 $group_privs = &unescape($group_privs);
 4046:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4047:                             } else {
 4048:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4049:                             }
 4050:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4051:                             &appenv(\%userroles,[$$role,'cm']);
 4052:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4053:                         }
 4054:                     }
 4055:                     $$tstatus = 'is';
 4056:                 }
 4057:             }
 4058:             if ($$tend) {
 4059:                 if ($$tend<$then) {
 4060:                     $$tstatus='expired';
 4061:                 } elsif ($$tend<$now) {
 4062:                     $$tstatus='will_not';
 4063:                 }
 4064:             }
 4065:         }
 4066:     }
 4067: }
 4068: 
 4069: sub check_adhoc_privs {
 4070:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 4071:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4072:     if ($env{$cckey}) {
 4073:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4074:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4075:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4076:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4077:         }
 4078:     } else {
 4079:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4080:     }
 4081: }
 4082: 
 4083: sub set_adhoc_privileges {
 4084: # role can be cc or ca
 4085:     my ($dcdom,$pickedcourse,$role) = @_;
 4086:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4087:     my $spec = $role.'.'.$area;
 4088:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4089:                                   $env{'user.name'});
 4090:     my %ccrole = ();
 4091:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4092:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4093:     &appenv(\%userroles,[$role,'cm']);
 4094:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4095:     &appenv( {'request.role'        => $spec,
 4096:               'request.role.domain' => $dcdom,
 4097:               'request.course.sec'  => ''
 4098:              }
 4099:            );
 4100:     my $tadv=0;
 4101:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4102:     &appenv({'request.role.adv'    => $tadv});
 4103: }
 4104: 
 4105: # --------------------------------------------------------------- get interface
 4106: 
 4107: sub get {
 4108:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4109:    my $items='';
 4110:    foreach my $item (@$storearr) {
 4111:        $items.=&escape($item).'&';
 4112:    }
 4113:    $items=~s/\&$//;
 4114:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4115:    if (!$uname) { $uname=$env{'user.name'}; }
 4116:    my $uhome=&homeserver($uname,$udomain);
 4117: 
 4118:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4119:    my @pairs=split(/\&/,$rep);
 4120:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4121:      return @pairs;
 4122:    }
 4123:    my %returnhash=();
 4124:    my $i=0;
 4125:    foreach my $item (@$storearr) {
 4126:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4127:       $i++;
 4128:    }
 4129:    return %returnhash;
 4130: }
 4131: 
 4132: # --------------------------------------------------------------- del interface
 4133: 
 4134: sub del {
 4135:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4136:    my $items='';
 4137:    foreach my $item (@$storearr) {
 4138:        $items.=&escape($item).'&';
 4139:    }
 4140: 
 4141:    $items=~s/\&$//;
 4142:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4143:    if (!$uname) { $uname=$env{'user.name'}; }
 4144:    my $uhome=&homeserver($uname,$udomain);
 4145:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4146: }
 4147: 
 4148: # -------------------------------------------------------------- dump interface
 4149: 
 4150: sub dump {
 4151:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4152:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4153:     if (!$uname) { $uname=$env{'user.name'}; }
 4154:     my $uhome=&homeserver($uname,$udomain);
 4155:     if ($regexp) {
 4156: 	$regexp=&escape($regexp);
 4157:     } else {
 4158: 	$regexp='.';
 4159:     }
 4160:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4161:     my @pairs=split(/\&/,$rep);
 4162:     my %returnhash=();
 4163:     foreach my $item (@pairs) {
 4164: 	my ($key,$value)=split(/=/,$item,2);
 4165: 	$key = &unescape($key);
 4166: 	next if ($key =~ /^error: 2 /);
 4167: 	$returnhash{$key}=&thaw_unescape($value);
 4168:     }
 4169:     return %returnhash;
 4170: }
 4171: 
 4172: # --------------------------------------------------------- dumpstore interface
 4173: 
 4174: sub dumpstore {
 4175:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4176:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4177:    if (!$uname) { $uname=$env{'user.name'}; }
 4178:    my $uhome=&homeserver($uname,$udomain);
 4179:    if ($regexp) {
 4180:        $regexp=&escape($regexp);
 4181:    } else {
 4182:        $regexp='.';
 4183:    }
 4184:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4185:    my @pairs=split(/\&/,$rep);
 4186:    my %returnhash=();
 4187:    foreach my $item (@pairs) {
 4188:        my ($key,$value)=split(/=/,$item,2);
 4189:        next if ($key =~ /^error: 2 /);
 4190:        $returnhash{$key}=&thaw_unescape($value);
 4191:    }
 4192:    return %returnhash;
 4193: }
 4194: 
 4195: # -------------------------------------------------------------- keys interface
 4196: 
 4197: sub getkeys {
 4198:    my ($namespace,$udomain,$uname)=@_;
 4199:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4200:    if (!$uname) { $uname=$env{'user.name'}; }
 4201:    my $uhome=&homeserver($uname,$udomain);
 4202:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4203:    my @keyarray=();
 4204:    foreach my $key (split(/\&/,$rep)) {
 4205:       next if ($key =~ /^error: 2 /);
 4206:       push(@keyarray,&unescape($key));
 4207:    }
 4208:    return @keyarray;
 4209: }
 4210: 
 4211: # --------------------------------------------------------------- currentdump
 4212: sub currentdump {
 4213:    my ($courseid,$sdom,$sname)=@_;
 4214:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4215:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4216:    $sname    = $env{'user.name'}         if (! defined($sname));
 4217:    my $uhome = &homeserver($sname,$sdom);
 4218:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4219:    return if ($rep =~ /^(error:|no_such_host)/);
 4220:    #
 4221:    my %returnhash=();
 4222:    #
 4223:    if ($rep eq "unknown_cmd") { 
 4224:        # an old lond will not know currentdump
 4225:        # Do a dump and make it look like a currentdump
 4226:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4227:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4228:        my %hash = @tmp;
 4229:        @tmp=();
 4230:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4231:    } else {
 4232:        my @pairs=split(/\&/,$rep);
 4233:        foreach my $pair (@pairs) {
 4234:            my ($key,$value)=split(/=/,$pair,2);
 4235:            my ($symb,$param) = split(/:/,$key);
 4236:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4237:                                                         &thaw_unescape($value);
 4238:        }
 4239:    }
 4240:    return %returnhash;
 4241: }
 4242: 
 4243: sub convert_dump_to_currentdump{
 4244:     my %hash = %{shift()};
 4245:     my %returnhash;
 4246:     # Code ripped from lond, essentially.  The only difference
 4247:     # here is the unescaping done by lonnet::dump().  Conceivably
 4248:     # we might run in to problems with parameter names =~ /^v\./
 4249:     while (my ($key,$value) = each(%hash)) {
 4250:         my ($v,$symb,$param) = split(/:/,$key);
 4251: 	$symb  = &unescape($symb);
 4252: 	$param = &unescape($param);
 4253:         next if ($v eq 'version' || $symb eq 'keys');
 4254:         next if (exists($returnhash{$symb}) &&
 4255:                  exists($returnhash{$symb}->{$param}) &&
 4256:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4257:         $returnhash{$symb}->{$param}=$value;
 4258:         $returnhash{$symb}->{'v.'.$param}=$v;
 4259:     }
 4260:     #
 4261:     # Remove all of the keys in the hashes which keep track of
 4262:     # the version of the parameter.
 4263:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4264:         # use a foreach because we are going to delete from the hash.
 4265:         foreach my $key (keys(%$param_hash)) {
 4266:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4267:         }
 4268:     }
 4269:     return \%returnhash;
 4270: }
 4271: 
 4272: # ------------------------------------------------------ critical inc interface
 4273: 
 4274: sub cinc {
 4275:     return &inc(@_,'critical');
 4276: }
 4277: 
 4278: # --------------------------------------------------------------- inc interface
 4279: 
 4280: sub inc {
 4281:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4282:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4283:     if (!$uname) { $uname=$env{'user.name'}; }
 4284:     my $uhome=&homeserver($uname,$udomain);
 4285:     my $items='';
 4286:     if (! ref($store)) {
 4287:         # got a single value, so use that instead
 4288:         $items = &escape($store).'=&';
 4289:     } elsif (ref($store) eq 'SCALAR') {
 4290:         $items = &escape($$store).'=&';        
 4291:     } elsif (ref($store) eq 'ARRAY') {
 4292:         $items = join('=&',map {&escape($_);} @{$store});
 4293:     } elsif (ref($store) eq 'HASH') {
 4294:         while (my($key,$value) = each(%{$store})) {
 4295:             $items.= &escape($key).'='.&escape($value).'&';
 4296:         }
 4297:     }
 4298:     $items=~s/\&$//;
 4299:     if ($critical) {
 4300: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4301:     } else {
 4302: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4303:     }
 4304: }
 4305: 
 4306: # --------------------------------------------------------------- put interface
 4307: 
 4308: sub put {
 4309:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4310:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4311:    if (!$uname) { $uname=$env{'user.name'}; }
 4312:    my $uhome=&homeserver($uname,$udomain);
 4313:    my $items='';
 4314:    foreach my $item (keys(%$storehash)) {
 4315:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4316:    }
 4317:    $items=~s/\&$//;
 4318:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4319: }
 4320: 
 4321: # ------------------------------------------------------------ newput interface
 4322: 
 4323: sub newput {
 4324:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4325:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4326:    if (!$uname) { $uname=$env{'user.name'}; }
 4327:    my $uhome=&homeserver($uname,$udomain);
 4328:    my $items='';
 4329:    foreach my $key (keys(%$storehash)) {
 4330:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4331:    }
 4332:    $items=~s/\&$//;
 4333:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4334: }
 4335: 
 4336: # ---------------------------------------------------------  putstore interface
 4337: 
 4338: sub putstore {
 4339:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4340:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4341:    if (!$uname) { $uname=$env{'user.name'}; }
 4342:    my $uhome=&homeserver($uname,$udomain);
 4343:    my $items='';
 4344:    foreach my $key (keys(%$storehash)) {
 4345:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4346:    }
 4347:    $items=~s/\&$//;
 4348:    my $esc_symb=&escape($symb);
 4349:    my $esc_v=&escape($version);
 4350:    my $reply =
 4351:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4352: 	      $uhome);
 4353:    if ($reply eq 'unknown_cmd') {
 4354:        # gfall back to way things use to be done
 4355:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4356: 			    $uname);
 4357:    }
 4358:    return $reply;
 4359: }
 4360: 
 4361: sub old_putstore {
 4362:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4363:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4364:     if (!$uname) { $uname=$env{'user.name'}; }
 4365:     my $uhome=&homeserver($uname,$udomain);
 4366:     my %newstorehash;
 4367:     foreach my $item (keys(%$storehash)) {
 4368: 	my $key = $version.':'.&escape($symb).':'.$item;
 4369: 	$newstorehash{$key} = $storehash->{$item};
 4370:     }
 4371:     my $items='';
 4372:     my %allitems = ();
 4373:     foreach my $item (keys(%newstorehash)) {
 4374: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4375: 	    my $key = $1.':keys:'.$2;
 4376: 	    $allitems{$key} .= $3.':';
 4377: 	}
 4378: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4379:     }
 4380:     foreach my $item (keys(%allitems)) {
 4381: 	$allitems{$item} =~ s/\:$//;
 4382: 	$items.= $item.'='.$allitems{$item}.'&';
 4383:     }
 4384:     $items=~s/\&$//;
 4385:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4386: }
 4387: 
 4388: # ------------------------------------------------------ critical put interface
 4389: 
 4390: sub cput {
 4391:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4392:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4393:    if (!$uname) { $uname=$env{'user.name'}; }
 4394:    my $uhome=&homeserver($uname,$udomain);
 4395:    my $items='';
 4396:    foreach my $item (keys(%$storehash)) {
 4397:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4398:    }
 4399:    $items=~s/\&$//;
 4400:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4401: }
 4402: 
 4403: # -------------------------------------------------------------- eget interface
 4404: 
 4405: sub eget {
 4406:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4407:    my $items='';
 4408:    foreach my $item (@$storearr) {
 4409:        $items.=&escape($item).'&';
 4410:    }
 4411:    $items=~s/\&$//;
 4412:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4413:    if (!$uname) { $uname=$env{'user.name'}; }
 4414:    my $uhome=&homeserver($uname,$udomain);
 4415:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4416:    my @pairs=split(/\&/,$rep);
 4417:    my %returnhash=();
 4418:    my $i=0;
 4419:    foreach my $item (@$storearr) {
 4420:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4421:       $i++;
 4422:    }
 4423:    return %returnhash;
 4424: }
 4425: 
 4426: # ------------------------------------------------------------ tmpput interface
 4427: sub tmpput {
 4428:     my ($storehash,$server,$context)=@_;
 4429:     my $items='';
 4430:     foreach my $item (keys(%$storehash)) {
 4431: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4432:     }
 4433:     $items=~s/\&$//;
 4434:     if (defined($context)) {
 4435:         $items .= ':'.&escape($context);
 4436:     }
 4437:     return &reply("tmpput:$items",$server);
 4438: }
 4439: 
 4440: # ------------------------------------------------------------ tmpget interface
 4441: sub tmpget {
 4442:     my ($token,$server)=@_;
 4443:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4444:     my $rep=&reply("tmpget:$token",$server);
 4445:     my %returnhash;
 4446:     foreach my $item (split(/\&/,$rep)) {
 4447: 	my ($key,$value)=split(/=/,$item);
 4448:         next if ($key =~ /^error: 2 /);
 4449: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4450:     }
 4451:     return %returnhash;
 4452: }
 4453: 
 4454: # ------------------------------------------------------------ tmpget interface
 4455: sub tmpdel {
 4456:     my ($token,$server)=@_;
 4457:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4458:     return &reply("tmpdel:$token",$server);
 4459: }
 4460: 
 4461: # -------------------------------------------------- portfolio access checking
 4462: 
 4463: sub portfolio_access {
 4464:     my ($requrl) = @_;
 4465:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4466:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4467:     if ($result) {
 4468:         my %setters;
 4469:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4470:             my ($startblock,$endblock) =
 4471:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4472:             if ($startblock && $endblock) {
 4473:                 return 'B';
 4474:             }
 4475:         } else {
 4476:             my ($startblock,$endblock) =
 4477:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4478:             if ($startblock && $endblock) {
 4479:                 return 'B';
 4480:             }
 4481:         }
 4482:     }
 4483:     if ($result eq 'ok') {
 4484:        return 'F';
 4485:     } elsif ($result =~ /^[^:]+:guest_/) {
 4486:        return 'A';
 4487:     }
 4488:     return '';
 4489: }
 4490: 
 4491: sub get_portfolio_access {
 4492:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4493: 
 4494:     if (!ref($access_hash)) {
 4495: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4496: 	my %access_controls = &get_access_controls($current_perms,$group,
 4497: 						   $file_name);
 4498: 	$access_hash = $access_controls{$file_name};
 4499:     }
 4500: 
 4501:     my ($public,$guest,@domains,@users,@courses,@groups);
 4502:     my $now = time;
 4503:     if (ref($access_hash) eq 'HASH') {
 4504:         foreach my $key (keys(%{$access_hash})) {
 4505:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4506:             if ($start > $now) {
 4507:                 next;
 4508:             }
 4509:             if ($end && $end<$now) {
 4510:                 next;
 4511:             }
 4512:             if ($scope eq 'public') {
 4513:                 $public = $key;
 4514:                 last;
 4515:             } elsif ($scope eq 'guest') {
 4516:                 $guest = $key;
 4517:             } elsif ($scope eq 'domains') {
 4518:                 push(@domains,$key);
 4519:             } elsif ($scope eq 'users') {
 4520:                 push(@users,$key);
 4521:             } elsif ($scope eq 'course') {
 4522:                 push(@courses,$key);
 4523:             } elsif ($scope eq 'group') {
 4524:                 push(@groups,$key);
 4525:             }
 4526:         }
 4527:         if ($public) {
 4528:             return 'ok';
 4529:         }
 4530:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4531:             if ($guest) {
 4532:                 return $guest;
 4533:             }
 4534:         } else {
 4535:             if (@domains > 0) {
 4536:                 foreach my $domkey (@domains) {
 4537:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4538:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4539:                             return 'ok';
 4540:                         }
 4541:                     }
 4542:                 }
 4543:             }
 4544:             if (@users > 0) {
 4545:                 foreach my $userkey (@users) {
 4546:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4547:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4548:                             if (ref($item) eq 'HASH') {
 4549:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4550:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4551:                                     return 'ok';
 4552:                                 }
 4553:                             }
 4554:                         }
 4555:                     } 
 4556:                 }
 4557:             }
 4558:             my %roleshash;
 4559:             my @courses_and_groups = @courses;
 4560:             push(@courses_and_groups,@groups); 
 4561:             if (@courses_and_groups > 0) {
 4562:                 my (%allgroups,%allroles); 
 4563:                 my ($start,$end,$role,$sec,$group);
 4564:                 foreach my $envkey (%env) {
 4565:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4566:                         my $cid = $2.'_'.$3; 
 4567:                         if ($1 eq 'gr') {
 4568:                             $group = $4;
 4569:                             $allgroups{$cid}{$group} = $env{$envkey};
 4570:                         } else {
 4571:                             if ($4 eq '') {
 4572:                                 $sec = 'none';
 4573:                             } else {
 4574:                                 $sec = $4;
 4575:                             }
 4576:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4577:                         }
 4578:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4579:                         my $cid = $2.'_'.$3;
 4580:                         if ($4 eq '') {
 4581:                             $sec = 'none';
 4582:                         } else {
 4583:                             $sec = $4;
 4584:                         }
 4585:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4586:                     }
 4587:                 }
 4588:                 if (keys(%allroles) == 0) {
 4589:                     return;
 4590:                 }
 4591:                 foreach my $key (@courses_and_groups) {
 4592:                     my %content = %{$$access_hash{$key}};
 4593:                     my $cnum = $content{'number'};
 4594:                     my $cdom = $content{'domain'};
 4595:                     my $cid = $cdom.'_'.$cnum;
 4596:                     if (!exists($allroles{$cid})) {
 4597:                         next;
 4598:                     }    
 4599:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4600:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4601:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4602:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4603:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4604:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4605:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4606:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4607:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4608:                                         if (grep/^all$/,@sections) {
 4609:                                             return 'ok';
 4610:                                         } else {
 4611:                                             if (grep/^$sec$/,@sections) {
 4612:                                                 return 'ok';
 4613:                                             }
 4614:                                         }
 4615:                                     }
 4616:                                 }
 4617:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4618:                                     if (grep/^none$/,@groups) {
 4619:                                         return 'ok';
 4620:                                     }
 4621:                                 } else {
 4622:                                     if (grep/^all$/,@groups) {
 4623:                                         return 'ok';
 4624:                                     } 
 4625:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4626:                                         if (grep/^$group$/,@groups) {
 4627:                                             return 'ok';
 4628:                                         }
 4629:                                     }
 4630:                                 } 
 4631:                             }
 4632:                         }
 4633:                     }
 4634:                 }
 4635:             }
 4636:             if ($guest) {
 4637:                 return $guest;
 4638:             }
 4639:         }
 4640:     }
 4641:     return;
 4642: }
 4643: 
 4644: sub course_group_datechecker {
 4645:     my ($dates,$now,$status) = @_;
 4646:     my ($start,$end) = split(/\./,$dates);
 4647:     if (!$start && !$end) {
 4648:         return 'ok';
 4649:     }
 4650:     if (grep/^active$/,@{$status}) {
 4651:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4652:             return 'ok';
 4653:         }
 4654:     }
 4655:     if (grep/^previous$/,@{$status}) {
 4656:         if ($end > $now ) {
 4657:             return 'ok';
 4658:         }
 4659:     }
 4660:     if (grep/^future$/,@{$status}) {
 4661:         if ($start > $now) {
 4662:             return 'ok';
 4663:         }
 4664:     }
 4665:     return; 
 4666: }
 4667: 
 4668: sub parse_portfolio_url {
 4669:     my ($url) = @_;
 4670: 
 4671:     my ($type,$udom,$unum,$group,$file_name);
 4672:     
 4673:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4674: 	$type = 1;
 4675:         $udom = $1;
 4676:         $unum = $2;
 4677:         $file_name = $3;
 4678:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4679: 	$type = 2;
 4680:         $udom = $1;
 4681:         $unum = $2;
 4682:         $group = $3;
 4683:         $file_name = $3.'/'.$4;
 4684:     }
 4685:     if (wantarray) {
 4686: 	return ($type,$udom,$unum,$file_name,$group);
 4687:     }
 4688:     return $type;
 4689: }
 4690: 
 4691: sub is_portfolio_url {
 4692:     my ($url) = @_;
 4693:     return scalar(&parse_portfolio_url($url));
 4694: }
 4695: 
 4696: sub is_portfolio_file {
 4697:     my ($file) = @_;
 4698:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4699:         return 1;
 4700:     }
 4701:     return;
 4702: }
 4703: 
 4704: sub usertools_access {
 4705:     my ($uname,$udom,$tool,$action,$context) = @_;
 4706:     my ($access,%tools);
 4707:     if ($context eq '') {
 4708:         $context = 'tools';
 4709:     }
 4710:     if ($context eq 'requestcourses') {
 4711:         %tools = (
 4712:                       official   => 1,
 4713:                       unofficial => 1,
 4714:                       community  => 1,
 4715:                  );
 4716:     } else {
 4717:         %tools = (
 4718:                       aboutme   => 1,
 4719:                       blog      => 1,
 4720:                       portfolio => 1,
 4721:                  );
 4722:     }
 4723:     return if (!defined($tools{$tool}));
 4724: 
 4725:     if ((!defined($udom)) || (!defined($uname))) {
 4726:         $udom = $env{'user.domain'};
 4727:         $uname = $env{'user.name'};
 4728:     }
 4729: 
 4730:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4731:         if ($action ne 'reload') {
 4732:             if ($context eq 'requestcourses') {
 4733:                 return $env{'environment.canrequest.'.$tool};
 4734:             } else {
 4735:                 return $env{'environment.availabletools.'.$tool};
 4736:             }
 4737:         }
 4738:     }
 4739: 
 4740:     my ($toolstatus,$inststatus);
 4741: 
 4742:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4743:          ($action ne 'reload')) {
 4744:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4745:         $inststatus = $env{'environment.inststatus'};
 4746:     } else {
 4747:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 4748:         $toolstatus = $userenv{$context.'.'.$tool};
 4749:         $inststatus = $userenv{'inststatus'};
 4750:     }
 4751: 
 4752:     if ($toolstatus ne '') {
 4753:         if ($toolstatus) {
 4754:             $access = 1;
 4755:         } else {
 4756:             $access = 0;
 4757:         }
 4758:         return $access;
 4759:     }
 4760: 
 4761:     my $is_adv = &is_advanced_user($udom,$uname);
 4762:     my %domdef = &get_domain_defaults($udom);
 4763:     if (ref($domdef{$tool}) eq 'HASH') {
 4764:         if ($is_adv) {
 4765:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4766:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4767:                     $access = 1;
 4768:                 } else {
 4769:                     $access = 0;
 4770:                 }
 4771:                 return $access;
 4772:             }
 4773:         }
 4774:         if ($inststatus ne '') {
 4775:             my ($hasaccess,$hasnoaccess);
 4776:             foreach my $affiliation (split(/:/,$inststatus)) {
 4777:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4778:                     if ($domdef{$tool}{$affiliation}) {
 4779:                         $hasaccess = 1;
 4780:                     } else {
 4781:                         $hasnoaccess = 1;
 4782:                     }
 4783:                 }
 4784:             }
 4785:             if ($hasaccess || $hasnoaccess) {
 4786:                 if ($hasaccess) {
 4787:                     $access = 1;
 4788:                 } elsif ($hasnoaccess) {
 4789:                     $access = 0; 
 4790:                 }
 4791:                 return $access;
 4792:             }
 4793:         } else {
 4794:             if ($domdef{$tool}{'default'} ne '') {
 4795:                 if ($domdef{$tool}{'default'}) {
 4796:                     $access = 1;
 4797:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4798:                     $access = 0;
 4799:                 }
 4800:                 return $access;
 4801:             }
 4802:         }
 4803:     } else {
 4804:         if ($context eq 'tools') {
 4805:             $access = 1;
 4806:         } else {
 4807:             $access = 0;
 4808:         }
 4809:         return $access;
 4810:     }
 4811: }
 4812: 
 4813: sub is_advanced_user {
 4814:     my ($udom,$uname) = @_;
 4815:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4816:     my %allroles;
 4817:     my $is_adv;
 4818:     foreach my $role (keys(%roleshash)) {
 4819:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4820:         my $area = '/'.$tdomain.'/'.$trest;
 4821:         if ($sec ne '') {
 4822:             $area .= '/'.$sec;
 4823:         }
 4824:         if (($area ne '') && ($trole ne '')) {
 4825:             my $spec=$trole.'.'.$area;
 4826:             if ($trole =~ /^cr\//) {
 4827:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4828:             } elsif ($trole ne 'gr') {
 4829:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4830:             }
 4831:         }
 4832:     }
 4833:     foreach my $role (keys(%allroles)) {
 4834:         last if ($is_adv);
 4835:         foreach my $item (split(/:/,$allroles{$role})) {
 4836:             if ($item ne '') {
 4837:                 my ($privilege,$restrictions)=split(/&/,$item);
 4838:                 if ($privilege eq 'adv') {
 4839:                     $is_adv = 1;
 4840:                     last;
 4841:                 }
 4842:             }
 4843:         }
 4844:     }
 4845:     return $is_adv;
 4846: }
 4847: 
 4848: sub check_can_request {
 4849:     my ($dom,$can_request,$request_domains) = @_;
 4850:     my $canreq = 0;
 4851:     my ($types,$typename) = &Apache::loncommon::course_types();
 4852:     my @options = ('approval','validate','autolimit');
 4853:     my $optregex = join('|',@options);
 4854:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 4855:         foreach my $type (@{$types}) {
 4856:             if (&usertools_access($env{'user.name'},
 4857:                                   $env{'user.domain'},
 4858:                                   $type,undef,'requestcourses')) {
 4859:                 $canreq ++;
 4860:                 if (ref($request_domains) eq 'HASH') {
 4861:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 4862:                 }
 4863:                 if ($dom eq $env{'user.domain'}) {
 4864:                     $can_request->{$type} = 1;
 4865:                 }
 4866:             }
 4867:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 4868:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 4869:                 if (@curr > 0) {
 4870:                     foreach my $item (@curr) {
 4871:                         if (ref($request_domains) eq 'HASH') {
 4872:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 4873:                             if ($otherdom ne '') {
 4874:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 4875:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 4876:                                         push(@{$request_domains->{$type}},$otherdom);
 4877:                                     }
 4878:                                 } else {
 4879:                                     push(@{$request_domains->{$type}},$otherdom);
 4880:                                 }
 4881:                             }
 4882:                         }
 4883:                     }
 4884:                     unless($dom eq $env{'user.domain'}) {
 4885:                         $canreq ++;
 4886:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 4887:                             $can_request->{$type} = 1;
 4888:                         }
 4889:                     }
 4890:                 }
 4891:             }
 4892:         }
 4893:     }
 4894:     return $canreq;
 4895: }
 4896: 
 4897: # ---------------------------------------------- Custom access rule evaluation
 4898: 
 4899: sub customaccess {
 4900:     my ($priv,$uri)=@_;
 4901:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4902:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4903:     $udom = &LONCAPA::clean_domain($udom);
 4904:     $ucrs = &LONCAPA::clean_username($ucrs);
 4905:     my $access=0;
 4906:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4907: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4908: 	if ($type eq 'user') {
 4909: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4910: 		my ($tdom,$tuname)=split(m{/},$scope);
 4911: 		if ($tdom) {
 4912: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4913: 		}
 4914: 		if ($tuname) {
 4915: 		    if ($tuname ne $env{'user.name'}) { next; }
 4916: 		}
 4917: 		$access=($effect eq 'allow');
 4918: 		last;
 4919: 	    }
 4920: 	} else {
 4921: 	    if ($role) {
 4922: 		if ($role ne $urole) { next; }
 4923: 	    }
 4924: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4925: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4926: 		if ($tdom) {
 4927: 		    if ($tdom ne $udom) { next; }
 4928: 		}
 4929: 		if ($tcrs) {
 4930: 		    if ($tcrs ne $ucrs) { next; }
 4931: 		}
 4932: 		if ($tsec) {
 4933: 		    if ($tsec ne $usec) { next; }
 4934: 		}
 4935: 		$access=($effect eq 'allow');
 4936: 		last;
 4937: 	    }
 4938: 	    if ($realm eq '' && $role eq '') {
 4939: 		$access=($effect eq 'allow');
 4940: 	    }
 4941: 	}
 4942:     }
 4943:     return $access;
 4944: }
 4945: 
 4946: # ------------------------------------------------- Check for a user privilege
 4947: 
 4948: sub allowed {
 4949:     my ($priv,$uri,$symb,$role)=@_;
 4950:     my $ver_orguri=$uri;
 4951:     $uri=&deversion($uri);
 4952:     my $orguri=$uri;
 4953:     $uri=&declutter($uri);
 4954: 
 4955:     if ($priv eq 'evb') {
 4956: # Evade communication block restrictions for specified role in a course
 4957:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4958:             return $1;
 4959:         } else {
 4960:             return;
 4961:         }
 4962:     }
 4963: 
 4964:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4965: # Free bre access to adm and meta resources
 4966:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4967: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4968: 	&& ($priv eq 'bre')) {
 4969: 	return 'F';
 4970:     }
 4971: 
 4972: # Free bre access to user's own portfolio contents
 4973:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4974:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4975: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4976:         my %setters;
 4977:         my ($startblock,$endblock) = 
 4978:             &Apache::loncommon::blockcheck(\%setters,'port');
 4979:         if ($startblock && $endblock) {
 4980:             return 'B';
 4981:         } else {
 4982:             return 'F';
 4983:         }
 4984:     }
 4985: 
 4986: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4987:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4988:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4989:         if (exists($env{'request.course.id'})) {
 4990:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4991:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4992:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4993:                 my $courseprivid=$env{'request.course.id'};
 4994:                 $courseprivid=~s/\_/\//;
 4995:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4996:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4997:                     return $1; 
 4998:                 } else {
 4999:                     if ($env{'request.course.sec'}) {
 5000:                         $courseprivid.='/'.$env{'request.course.sec'};
 5001:                     }
 5002:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5003:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5004:                         return $2;
 5005:                     }
 5006:                 }
 5007:             }
 5008:         }
 5009:     }
 5010: 
 5011: # Free bre to public access
 5012: 
 5013:     if ($priv eq 'bre') {
 5014:         my $copyright=&metadata($uri,'copyright');
 5015: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5016:            return 'F'; 
 5017:         }
 5018:         if ($copyright eq 'priv') {
 5019:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5020: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5021: 		return '';
 5022:             }
 5023:         }
 5024:         if ($copyright eq 'domain') {
 5025:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5026: 	    unless (($env{'user.domain'} eq $1) ||
 5027:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5028: 		return '';
 5029:             }
 5030:         }
 5031:         if ($env{'request.role'}=~ /li\.\//) {
 5032:             # Library role, so allow browsing of resources in this domain.
 5033:             return 'F';
 5034:         }
 5035:         if ($copyright eq 'custom') {
 5036: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5037:         }
 5038:     }
 5039:     # Domain coordinator is trying to create a course
 5040:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5041:         # uri is the requested domain in this case.
 5042:         # comparison to 'request.role.domain' shows if the user has selected
 5043:         # a role of dc for the domain in question.
 5044:         return 'F' if ($uri eq $env{'request.role.domain'});
 5045:     }
 5046: 
 5047:     my $thisallowed='';
 5048:     my $statecond=0;
 5049:     my $courseprivid='';
 5050: 
 5051:     my $ownaccess;
 5052:     # Community Coordinator or Assistant Co-author browsing resource space.
 5053:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5054:         if ($uri eq '') {
 5055:             $ownaccess = 1;
 5056:         } else {
 5057:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5058:                 my $udom = $env{'user.domain'};
 5059:                 my $uname = $env{'user.name'};
 5060:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5061:                     $ownaccess = 1;
 5062:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5063:                     unless ($uri =~ m{\.\./}) {
 5064:                         $ownaccess = 1;
 5065:                     }
 5066:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5067:                     my $now = time;
 5068:                     if ($uri =~ m{^([^/]+)/?$}) {
 5069:                         my $adom = $1;
 5070:                         foreach my $key (keys(%env)) {
 5071:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5072:                                 my ($start,$end) = split('.',$env{$key});
 5073:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5074:                                     $ownaccess = 1;
 5075:                                     last;
 5076:                                 }
 5077:                             }
 5078:                         }
 5079:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5080:                         my $adom = $1;
 5081:                         my $aname = $2;
 5082:                         foreach my $role ('ca','aa') { 
 5083:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5084:                                 my ($start,$end) =
 5085:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5086:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5087:                                     $ownaccess = 1;
 5088:                                     last;
 5089:                                 }
 5090:                             }
 5091:                         }
 5092:                     }
 5093:                 }
 5094:             }
 5095:         }
 5096:     }
 5097: 
 5098: # Course
 5099: 
 5100:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5101:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5102:             $thisallowed.=$1;
 5103:         }
 5104:     }
 5105: 
 5106: # Domain
 5107: 
 5108:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5109:        =~/\Q$priv\E\&([^\:]*)/) {
 5110:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5111:             $thisallowed.=$1;
 5112:         }
 5113:     }
 5114: 
 5115: # Course: uri itself is a course
 5116:     my $courseuri=$uri;
 5117:     $courseuri=~s/\_(\d)/\/$1/;
 5118:     $courseuri=~s/^([^\/])/\/$1/;
 5119: 
 5120:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5121:        =~/\Q$priv\E\&([^\:]*)/) {
 5122:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5123:             $thisallowed.=$1;
 5124:         }
 5125:     }
 5126: 
 5127: # URI is an uploaded document for this course, default permissions don't matter
 5128: # not allowing 'edit' access (editupload) to uploaded course docs
 5129:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5130: 	$thisallowed='';
 5131:         my ($match)=&is_on_map($uri);
 5132:         if ($match) {
 5133:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5134:                   =~/\Q$priv\E\&([^\:]*)/) {
 5135:                 $thisallowed.=$1;
 5136:             }
 5137:         } else {
 5138:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5139:             if ($refuri) {
 5140:                 if ($refuri =~ m|^/adm/|) {
 5141:                     $thisallowed='F';
 5142:                 } else {
 5143:                     $refuri=&declutter($refuri);
 5144:                     my ($match) = &is_on_map($refuri);
 5145:                     if ($match) {
 5146:                         $thisallowed='F';
 5147:                     }
 5148:                 }
 5149:             }
 5150:         }
 5151:     }
 5152: 
 5153:     if ($priv eq 'bre'
 5154: 	&& $thisallowed ne 'F' 
 5155: 	&& $thisallowed ne '2'
 5156: 	&& &is_portfolio_url($uri)) {
 5157: 	$thisallowed = &portfolio_access($uri);
 5158:     }
 5159:     
 5160: # Full access at system, domain or course-wide level? Exit.
 5161:     if ($thisallowed=~/F/) {
 5162: 	return 'F';
 5163:     }
 5164: 
 5165: # If this is generating or modifying users, exit with special codes
 5166: 
 5167:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5168: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5169: 	    my ($audom,$auname)=split('/',$uri);
 5170: # no author name given, so this just checks on the general right to make a co-author in this domain
 5171: 	    unless ($auname) { return $thisallowed; }
 5172: # an author name is given, so we are about to actually make a co-author for a certain account
 5173: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5174: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5175: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5176: 	}
 5177: 	return $thisallowed;
 5178:     }
 5179: #
 5180: # Gathered so far: system, domain and course wide privileges
 5181: #
 5182: # Course: See if uri or referer is an individual resource that is part of 
 5183: # the course
 5184: 
 5185:     if ($env{'request.course.id'}) {
 5186: 
 5187:        $courseprivid=$env{'request.course.id'};
 5188:        if ($env{'request.course.sec'}) {
 5189:           $courseprivid.='/'.$env{'request.course.sec'};
 5190:        }
 5191:        $courseprivid=~s/\_/\//;
 5192:        my $checkreferer=1;
 5193:        my ($match,$cond)=&is_on_map($uri);
 5194:        if ($match) {
 5195:            $statecond=$cond;
 5196:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5197:                =~/\Q$priv\E\&([^\:]*)/) {
 5198:                $thisallowed.=$1;
 5199:                $checkreferer=0;
 5200:            }
 5201:        }
 5202:        
 5203:        if ($checkreferer) {
 5204: 	  my $refuri=$env{'httpref.'.$orguri};
 5205:             unless ($refuri) {
 5206:                 foreach my $key (keys(%env)) {
 5207: 		    if ($key=~/^httpref\..*\*/) {
 5208: 			my $pattern=$key;
 5209:                         $pattern=~s/^httpref\.\/res\///;
 5210:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5211:                         $pattern=~s/\//\\\//g;
 5212:                         if ($orguri=~/$pattern/) {
 5213: 			    $refuri=$env{$key};
 5214:                         }
 5215:                     }
 5216:                 }
 5217:             }
 5218: 
 5219:          if ($refuri) { 
 5220: 	  $refuri=&declutter($refuri);
 5221:           my ($match,$cond)=&is_on_map($refuri);
 5222:             if ($match) {
 5223:               my $refstatecond=$cond;
 5224:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5225:                   =~/\Q$priv\E\&([^\:]*)/) {
 5226:                   $thisallowed.=$1;
 5227:                   $uri=$refuri;
 5228:                   $statecond=$refstatecond;
 5229:               }
 5230:           }
 5231:         }
 5232:        }
 5233:    }
 5234: 
 5235: #
 5236: # Gathered now: all privileges that could apply, and condition number
 5237: # 
 5238: #
 5239: # Full or no access?
 5240: #
 5241: 
 5242:     if ($thisallowed=~/F/) {
 5243: 	return 'F';
 5244:     }
 5245: 
 5246:     unless ($thisallowed) {
 5247:         return '';
 5248:     }
 5249: 
 5250: # Restrictions exist, deal with them
 5251: #
 5252: #   C:according to course preferences
 5253: #   R:according to resource settings
 5254: #   L:unless locked
 5255: #   X:according to user session state
 5256: #
 5257: 
 5258: # Possibly locked functionality, check all courses
 5259: # Locks might take effect only after 10 minutes cache expiration for other
 5260: # courses, and 2 minutes for current course
 5261: 
 5262:     my $envkey;
 5263:     if ($thisallowed=~/L/) {
 5264:         foreach $envkey (keys(%env)) {
 5265:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5266:                my $courseid=$2;
 5267:                my $roleid=$1.'.'.$2;
 5268:                $courseid=~s/^\///;
 5269:                my $expiretime=600;
 5270:                if ($env{'request.role'} eq $roleid) {
 5271: 		  $expiretime=120;
 5272:                }
 5273: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5274:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5275:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5276: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5277:                }
 5278:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5279:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5280: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5281:                        &log($env{'user.domain'},$env{'user.name'},
 5282:                             $env{'user.home'},
 5283:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5284:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5285:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5286: 		       return '';
 5287:                    }
 5288:                }
 5289:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5290:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5291: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5292:                        &log($env{'user.domain'},$env{'user.name'},
 5293:                             $env{'user.home'},
 5294:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5295:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5296:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5297: 		       return '';
 5298:                    }
 5299:                }
 5300: 	   }
 5301:        }
 5302:     }
 5303:    
 5304: #
 5305: # Rest of the restrictions depend on selected course
 5306: #
 5307: 
 5308:     unless ($env{'request.course.id'}) {
 5309: 	if ($thisallowed eq 'A') {
 5310: 	    return 'A';
 5311:         } elsif ($thisallowed eq 'B') {
 5312:             return 'B';
 5313: 	} else {
 5314: 	    return '1';
 5315: 	}
 5316:     }
 5317: 
 5318: #
 5319: # Now user is definitely in a course
 5320: #
 5321: 
 5322: 
 5323: # Course preferences
 5324: 
 5325:    if ($thisallowed=~/C/) {
 5326:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5327:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5328:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5329: 	   =~/\Q$rolecode\E/) {
 5330: 	   if ($priv ne 'pch') { 
 5331: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5332: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5333: 			$env{'request.course.id'});
 5334: 	   }
 5335:            return '';
 5336:        }
 5337: 
 5338:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5339: 	   =~/\Q$unamedom\E/) {
 5340: 	   if ($priv ne 'pch') { 
 5341: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5342: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5343: 			$env{'request.course.id'});
 5344: 	   }
 5345:            return '';
 5346:        }
 5347:    }
 5348: 
 5349: # Resource preferences
 5350: 
 5351:    if ($thisallowed=~/R/) {
 5352:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5353:        if (&metadata($uri,'roledeny')=~/\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);
 5357: 	   }
 5358: 	   return '';
 5359:        }
 5360:    }
 5361: 
 5362: # Restricted by state or randomout?
 5363: 
 5364:    if ($thisallowed=~/X/) {
 5365:       if ($env{'acc.randomout'}) {
 5366: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5367:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5368:             return ''; 
 5369:          }
 5370:       }
 5371:       if (&condval($statecond)) {
 5372: 	 return '2';
 5373:       } else {
 5374:          return '';
 5375:       }
 5376:    }
 5377: 
 5378:     if ($thisallowed eq 'A') {
 5379: 	return 'A';
 5380:     } elsif ($thisallowed eq 'B') {
 5381:         return 'B';
 5382:     }
 5383:    return 'F';
 5384: }
 5385: 
 5386: sub split_uri_for_cond {
 5387:     my $uri=&deversion(&declutter(shift));
 5388:     my @uriparts=split(/\//,$uri);
 5389:     my $filename=pop(@uriparts);
 5390:     my $pathname=join('/',@uriparts);
 5391:     return ($pathname,$filename);
 5392: }
 5393: # --------------------------------------------------- Is a resource on the map?
 5394: 
 5395: sub is_on_map {
 5396:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5397:     #Trying to find the conditional for the file
 5398:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5399: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5400:     if ($match) {
 5401: 	return (1,$1);
 5402:     } else {
 5403: 	return (0,0);
 5404:     }
 5405: }
 5406: 
 5407: # --------------------------------------------------------- Get symb from alias
 5408: 
 5409: sub get_symb_from_alias {
 5410:     my $symb=shift;
 5411:     my ($map,$resid,$url)=&decode_symb($symb);
 5412: # Already is a symb
 5413:     if ($url) { return $symb; }
 5414: # Must be an alias
 5415:     my $aliassymb='';
 5416:     my %bighash;
 5417:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5418:                             &GDBM_READER(),0640)) {
 5419:         my $rid=$bighash{'mapalias_'.$symb};
 5420: 	if ($rid) {
 5421: 	    my ($mapid,$resid)=split(/\./,$rid);
 5422: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5423: 				    $resid,$bighash{'src_'.$rid});
 5424: 	}
 5425:         untie %bighash;
 5426:     }
 5427:     return $aliassymb;
 5428: }
 5429: 
 5430: # ----------------------------------------------------------------- Define Role
 5431: 
 5432: sub definerole {
 5433:   if (allowed('mcr','/')) {
 5434:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5435:     foreach my $role (split(':',$sysrole)) {
 5436: 	my ($crole,$cqual)=split(/\&/,$role);
 5437:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5438:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5439: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5440:                return "refused:s:$crole&$cqual"; 
 5441:             }
 5442:         }
 5443:     }
 5444:     foreach my $role (split(':',$domrole)) {
 5445: 	my ($crole,$cqual)=split(/\&/,$role);
 5446:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5447:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5448: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5449:                return "refused:d:$crole&$cqual"; 
 5450:             }
 5451:         }
 5452:     }
 5453:     foreach my $role (split(':',$courole)) {
 5454: 	my ($crole,$cqual)=split(/\&/,$role);
 5455:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5456:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5457: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5458:                return "refused:c:$crole&$cqual"; 
 5459:             }
 5460:         }
 5461:     }
 5462:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5463:                 "$env{'user.domain'}:$env{'user.name'}:".
 5464: 	        "rolesdef_$rolename=".
 5465:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5466:     return reply($command,$env{'user.home'});
 5467:   } else {
 5468:     return 'refused';
 5469:   }
 5470: }
 5471: 
 5472: # ---------------- Make a metadata query against the network of library servers
 5473: 
 5474: sub metadata_query {
 5475:     my ($query,$custom,$customshow,$server_array)=@_;
 5476:     my %rhash;
 5477:     my %libserv = &all_library();
 5478:     my @server_list = (defined($server_array) ? @$server_array
 5479:                                               : keys(%libserv) );
 5480:     for my $server (@server_list) {
 5481: 	unless ($custom or $customshow) {
 5482: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5483: 	    $rhash{$server}=$reply;
 5484: 	}
 5485: 	else {
 5486: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5487: 			     &escape($custom).':'.&escape($customshow),
 5488: 			     $server);
 5489: 	    $rhash{$server}=$reply;
 5490: 	}
 5491:     }
 5492:     return \%rhash;
 5493: }
 5494: 
 5495: # ----------------------------------------- Send log queries and wait for reply
 5496: 
 5497: sub log_query {
 5498:     my ($uname,$udom,$query,%filters)=@_;
 5499:     my $uhome=&homeserver($uname,$udom);
 5500:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5501:     my $uhost=&hostname($uhome);
 5502:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5503:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5504:                        $uhome);
 5505:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5506:     return get_query_reply($queryid);
 5507: }
 5508: 
 5509: # -------------------------- Update MySQL table for portfolio file
 5510: 
 5511: sub update_portfolio_table {
 5512:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5513:     if ($group ne '') {
 5514:         $file_name =~s /^\Q$group\E//;
 5515:     }
 5516:     my $homeserver = &homeserver($uname,$udom);
 5517:     my $queryid=
 5518:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5519:                ':'.&escape($file_name).':'.$action,$homeserver);
 5520:     my $reply = &get_query_reply($queryid);
 5521:     return $reply;
 5522: }
 5523: 
 5524: # -------------------------- Update MySQL allusers table
 5525: 
 5526: sub update_allusers_table {
 5527:     my ($uname,$udom,$names) = @_;
 5528:     my $homeserver = &homeserver($uname,$udom);
 5529:     my $queryid=
 5530:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5531:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5532:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5533:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5534:                'generation='.&escape($names->{'generation'}).'%%'.
 5535:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5536:                'id='.&escape($names->{'id'}),$homeserver);
 5537:     my $reply = &get_query_reply($queryid);
 5538:     return $reply;
 5539: }
 5540: 
 5541: # ------- Request retrieval of institutional classlists for course(s)
 5542: 
 5543: sub fetch_enrollment_query {
 5544:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5545:     my $homeserver;
 5546:     my $maxtries = 1;
 5547:     if ($context eq 'automated') {
 5548:         $homeserver = $perlvar{'lonHostID'};
 5549:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5550:     } else {
 5551:         $homeserver = &homeserver($cnum,$dom);
 5552:     }
 5553:     my $host=&hostname($homeserver);
 5554:     my $cmd = '';
 5555:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5556:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5557:     }
 5558:     $cmd =~ s/%%$//;
 5559:     $cmd = &escape($cmd);
 5560:     my $query = 'fetchenrollment';
 5561:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5562:     unless ($queryid=~/^\Q$host\E\_/) { 
 5563:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5564:         return 'error: '.$queryid;
 5565:     }
 5566:     my $reply = &get_query_reply($queryid);
 5567:     my $tries = 1;
 5568:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5569:         $reply = &get_query_reply($queryid);
 5570:         $tries ++;
 5571:     }
 5572:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5573:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5574:     } else {
 5575:         my @responses = split(/:/,$reply);
 5576:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5577:             foreach my $line (@responses) {
 5578:                 my ($key,$value) = split(/=/,$line,2);
 5579:                 $$replyref{$key} = $value;
 5580:             }
 5581:         } else {
 5582:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5583:             foreach my $line (@responses) {
 5584:                 my ($key,$value) = split(/=/,$line);
 5585:                 $$replyref{$key} = $value;
 5586:                 if ($value > 0) {
 5587:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5588:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5589:                         my $destname = $pathname.'/'.$filename;
 5590:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5591:                         if ($xml_classlist =~ /^error/) {
 5592:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5593:                         } else {
 5594:                             if ( open(FILE,">$destname") ) {
 5595:                                 print FILE &unescape($xml_classlist);
 5596:                                 close(FILE);
 5597:                             } else {
 5598:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5599:                             }
 5600:                         }
 5601:                     }
 5602:                 }
 5603:             }
 5604:         }
 5605:         return 'ok';
 5606:     }
 5607:     return 'error';
 5608: }
 5609: 
 5610: sub get_query_reply {
 5611:     my $queryid=shift;
 5612:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5613:     my $reply='';
 5614:     for (1..100) {
 5615: 	sleep 2;
 5616:         if (-e $replyfile.'.end') {
 5617: 	    if (open(my $fh,$replyfile)) {
 5618: 		$reply = join('',<$fh>);
 5619: 		close($fh);
 5620: 	   } else { return 'error: reply_file_error'; }
 5621:            return &unescape($reply);
 5622: 	}
 5623:     }
 5624:     return 'timeout:'.$queryid;
 5625: }
 5626: 
 5627: sub courselog_query {
 5628: #
 5629: # possible filters:
 5630: # url: url or symb
 5631: # username
 5632: # domain
 5633: # action: view, submit, grade
 5634: # start: timestamp
 5635: # end: timestamp
 5636: #
 5637:     my (%filters)=@_;
 5638:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5639:     if ($filters{'url'}) {
 5640: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5641:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5642:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5643:     }
 5644:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5645:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5646:     return &log_query($cname,$cdom,'courselog',%filters);
 5647: }
 5648: 
 5649: sub userlog_query {
 5650: #
 5651: # possible filters:
 5652: # action: log check role
 5653: # start: timestamp
 5654: # end: timestamp
 5655: #
 5656:     my ($uname,$udom,%filters)=@_;
 5657:     return &log_query($uname,$udom,'userlog',%filters);
 5658: }
 5659: 
 5660: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5661: 
 5662: sub auto_run {
 5663:     my ($cnum,$cdom) = @_;
 5664:     my $response = 0;
 5665:     my $settings;
 5666:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5667:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5668:         $settings = $domconfig{'autoenroll'};
 5669:         if ($settings->{'run'} eq '1') {
 5670:             $response = 1;
 5671:         }
 5672:     } else {
 5673:         my $homeserver;
 5674:         if (&is_course($cdom,$cnum)) {
 5675:             $homeserver = &homeserver($cnum,$cdom);
 5676:         } else {
 5677:             $homeserver = &domain($cdom,'primary');
 5678:         }
 5679:         if ($homeserver ne 'no_host') {
 5680:             $response = &reply('autorun:'.$cdom,$homeserver);
 5681:         }
 5682:     }
 5683:     return $response;
 5684: }
 5685: 
 5686: sub auto_get_sections {
 5687:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5688:     my $homeserver;
 5689:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5690:         $homeserver = &homeserver($cnum,$cdom);
 5691:     }
 5692:     if (!defined($homeserver)) { 
 5693:         if ($cdom =~ /^$match_domain$/) {
 5694:             $homeserver = &domain($cdom,'primary');
 5695:         }
 5696:     }
 5697:     my @secs;
 5698:     if (defined($homeserver)) {
 5699:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5700:         unless ($response eq 'refused') {
 5701:             @secs = split(/:/,$response);
 5702:         }
 5703:     }
 5704:     return @secs;
 5705: }
 5706: 
 5707: sub auto_new_course {
 5708:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5709:     my $homeserver = &homeserver($cnum,$cdom);
 5710:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5711:     return $response;
 5712: }
 5713: 
 5714: sub auto_validate_courseID {
 5715:     my ($cnum,$cdom,$inst_course_id) = @_;
 5716:     my $homeserver = &homeserver($cnum,$cdom);
 5717:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5718:     return $response;
 5719: }
 5720: 
 5721: sub auto_validate_instcode {
 5722:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5723:     my ($homeserver,$response);
 5724:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5725:         $homeserver = &homeserver($cnum,$cdom);
 5726:     }
 5727:     if (!defined($homeserver)) {
 5728:         if ($cdom =~ /^$match_domain$/) {
 5729:             $homeserver = &domain($cdom,'primary');
 5730:         }
 5731:     }
 5732:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5733:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5734:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 5735:     return ($outcome,$description);
 5736: }
 5737: 
 5738: sub auto_create_password {
 5739:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5740:     my ($homeserver,$response);
 5741:     my $create_passwd = 0;
 5742:     my $authchk = '';
 5743:     if ($udom =~ /^$match_domain$/) {
 5744:         $homeserver = &domain($udom,'primary');
 5745:     }
 5746:     if ($homeserver eq '') {
 5747:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5748:             $homeserver = &homeserver($cnum,$cdom);
 5749:         }
 5750:     }
 5751:     if ($homeserver eq '') {
 5752:         $authchk = 'nodomain';
 5753:     } else {
 5754:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5755:         if ($response eq 'refused') {
 5756:             $authchk = 'refused';
 5757:         } else {
 5758:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5759:         }
 5760:     }
 5761:     return ($authparam,$create_passwd,$authchk);
 5762: }
 5763: 
 5764: sub auto_photo_permission {
 5765:     my ($cnum,$cdom,$students) = @_;
 5766:     my $homeserver = &homeserver($cnum,$cdom);
 5767:     my ($outcome,$perm_reqd,$conditions) = 
 5768: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5769:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5770: 	return (undef,undef);
 5771:     }
 5772:     return ($outcome,$perm_reqd,$conditions);
 5773: }
 5774: 
 5775: sub auto_checkphotos {
 5776:     my ($uname,$udom,$pid) = @_;
 5777:     my $homeserver = &homeserver($uname,$udom);
 5778:     my ($result,$resulttype);
 5779:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5780: 				   &escape($uname).':'.&escape($pid),
 5781: 				   $homeserver));
 5782:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5783: 	return (undef,undef);
 5784:     }
 5785:     if ($outcome) {
 5786:         ($result,$resulttype) = split(/:/,$outcome);
 5787:     } 
 5788:     return ($result,$resulttype);
 5789: }
 5790: 
 5791: sub auto_photochoice {
 5792:     my ($cnum,$cdom) = @_;
 5793:     my $homeserver = &homeserver($cnum,$cdom);
 5794:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5795: 						       &escape($cdom),
 5796: 						       $homeserver)));
 5797:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5798: 	return (undef,undef);
 5799:     }
 5800:     return ($update,$comment);
 5801: }
 5802: 
 5803: sub auto_photoupdate {
 5804:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5805:     my $homeserver = &homeserver($cnum,$dom);
 5806:     my $host=&hostname($homeserver);
 5807:     my $cmd = '';
 5808:     my $maxtries = 1;
 5809:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5810:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5811:     }
 5812:     $cmd =~ s/%%$//;
 5813:     $cmd = &escape($cmd);
 5814:     my $query = 'institutionalphotos';
 5815:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5816:     unless ($queryid=~/^\Q$host\E\_/) {
 5817:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5818:         return 'error: '.$queryid;
 5819:     }
 5820:     my $reply = &get_query_reply($queryid);
 5821:     my $tries = 1;
 5822:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5823:         $reply = &get_query_reply($queryid);
 5824:         $tries ++;
 5825:     }
 5826:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5827:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5828:     } else {
 5829:         my @responses = split(/:/,$reply);
 5830:         my $outcome = shift(@responses); 
 5831:         foreach my $item (@responses) {
 5832:             my ($key,$value) = split(/=/,$item);
 5833:             $$photo{$key} = $value;
 5834:         }
 5835:         return $outcome;
 5836:     }
 5837:     return 'error';
 5838: }
 5839: 
 5840: sub auto_instcode_format {
 5841:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5842: 	$cat_order) = @_;
 5843:     my $courses = '';
 5844:     my @homeservers;
 5845:     if ($caller eq 'global') {
 5846: 	my %servers = &get_servers($codedom,'library');
 5847: 	foreach my $tryserver (keys(%servers)) {
 5848: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5849: 		push(@homeservers,$tryserver);
 5850: 	    }
 5851:         }
 5852:     } elsif ($caller eq 'requests') {
 5853:         if ($codedom =~ /^$match_domain$/) {
 5854:             my $chome = &domain($codedom,'primary');
 5855:             unless ($chome eq 'no_host') {
 5856:                 push(@homeservers,$chome);
 5857:             }
 5858:         }
 5859:     } else {
 5860:         push(@homeservers,&homeserver($caller,$codedom));
 5861:     }
 5862:     foreach my $code (keys(%{$instcodes})) {
 5863:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5864:     }
 5865:     chop($courses);
 5866:     my $ok_response = 0;
 5867:     my $response;
 5868:     while (@homeservers > 0 && $ok_response == 0) {
 5869:         my $server = shift(@homeservers); 
 5870:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5871:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5872:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5873: 		split(/:/,$response);
 5874:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5875:             push(@{$codetitles},&str2array($codetitles_str));
 5876:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5877:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5878:             $ok_response = 1;
 5879:         }
 5880:     }
 5881:     if ($ok_response) {
 5882:         return 'ok';
 5883:     } else {
 5884:         return $response;
 5885:     }
 5886: }
 5887: 
 5888: sub auto_instcode_defaults {
 5889:     my ($domain,$returnhash,$code_order) = @_;
 5890:     my @homeservers;
 5891: 
 5892:     my %servers = &get_servers($domain,'library');
 5893:     foreach my $tryserver (keys(%servers)) {
 5894: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5895: 	    push(@homeservers,$tryserver);
 5896: 	}
 5897:     }
 5898: 
 5899:     my $response;
 5900:     foreach my $server (@homeservers) {
 5901:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5902:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5903: 	
 5904: 	foreach my $pair (split(/\&/,$response)) {
 5905: 	    my ($name,$value)=split(/\=/,$pair);
 5906: 	    if ($name eq 'code_order') {
 5907: 		@{$code_order} = split(/\&/,&unescape($value));
 5908: 	    } else {
 5909: 		$returnhash->{&unescape($name)}=&unescape($value);
 5910: 	    }
 5911: 	}
 5912: 	return 'ok';
 5913:     }
 5914: 
 5915:     return $response;
 5916: }
 5917: 
 5918: sub auto_possible_instcodes {
 5919:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 5920:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 5921:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 5922:         return;
 5923:     }
 5924:     my (@homeservers,$uhome);
 5925:     if (defined(&domain($domain,'primary'))) {
 5926:         $uhome=&domain($domain,'primary');
 5927:         push(@homeservers,&domain($domain,'primary'));
 5928:     } else {
 5929:         my %servers = &get_servers($domain,'library');
 5930:         foreach my $tryserver (keys(%servers)) {
 5931:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5932:                 push(@homeservers,$tryserver);
 5933:             }
 5934:         }
 5935:     }
 5936:     my $response;
 5937:     foreach my $server (@homeservers) {
 5938:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 5939:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5940:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 5941:             split(':',$response);
 5942:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 5943:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 5944:         foreach my $item (split('&',$cat_title)) {   
 5945:             my ($name,$value)=split('=',$item);
 5946:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 5947:         }
 5948:         foreach my $item (split('&',$cat_order)) {
 5949:             my ($name,$value)=split('=',$item);
 5950:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 5951:         }
 5952:         return 'ok';
 5953:     }
 5954:     return $response;
 5955: }
 5956: 
 5957: sub auto_courserequest_checks {
 5958:     my ($dom) = @_;
 5959:     my ($homeserver,%validations);
 5960:     if ($dom =~ /^$match_domain$/) {
 5961:         $homeserver = &domain($dom,'primary');
 5962:     }
 5963:     unless ($homeserver eq 'no_host') {
 5964:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 5965:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 5966:             my @items = split(/&/,$response);
 5967:             foreach my $item (@items) {
 5968:                 my ($key,$value) = split('=',$item);
 5969:                 $validations{&unescape($key)} = &thaw_unescape($value);
 5970:             }
 5971:         }
 5972:     }
 5973:     return %validations; 
 5974: }
 5975: 
 5976: sub auto_courserequest_validation {
 5977:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 5978:     my ($homeserver,$response);
 5979:     if ($dom =~ /^$match_domain$/) {
 5980:         $homeserver = &domain($dom,'primary');
 5981:     }
 5982:     unless ($homeserver eq 'no_host') {  
 5983:           
 5984:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 5985:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 5986:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 5987:                                     $homeserver));
 5988:     }
 5989:     return $response;
 5990: }
 5991: 
 5992: sub auto_validate_class_sec {
 5993:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5994:     my $homeserver = &homeserver($cnum,$cdom);
 5995:     my $ownerlist;
 5996:     if (ref($owners) eq 'ARRAY') {
 5997:         $ownerlist = join(',',@{$owners});
 5998:     } else {
 5999:         $ownerlist = $owners;
 6000:     }
 6001:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6002:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6003:     return $response;
 6004: }
 6005: 
 6006: # ------------------------------------------------------- Course Group routines
 6007: 
 6008: sub get_coursegroups {
 6009:     my ($cdom,$cnum,$group,$namespace) = @_;
 6010:     return(&dump($namespace,$cdom,$cnum,$group));
 6011: }
 6012: 
 6013: sub modify_coursegroup {
 6014:     my ($cdom,$cnum,$groupsettings) = @_;
 6015:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6016: }
 6017: 
 6018: sub toggle_coursegroup_status {
 6019:     my ($cdom,$cnum,$group,$action) = @_;
 6020:     my ($from_namespace,$to_namespace);
 6021:     if ($action eq 'delete') {
 6022:         $from_namespace = 'coursegroups';
 6023:         $to_namespace = 'deleted_groups';
 6024:     } else {
 6025:         $from_namespace = 'deleted_groups';
 6026:         $to_namespace = 'coursegroups';
 6027:     }
 6028:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6029:     if (my $tmp = &error(%curr_group)) {
 6030:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6031:         return ('read error',$tmp);
 6032:     } else {
 6033:         my %savedsettings = %curr_group; 
 6034:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6035:         my $deloutcome;
 6036:         if ($result eq 'ok') {
 6037:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6038:         } else {
 6039:             return ('write error',$result);
 6040:         }
 6041:         if ($deloutcome eq 'ok') {
 6042:             return 'ok';
 6043:         } else {
 6044:             return ('delete error',$deloutcome);
 6045:         }
 6046:     }
 6047: }
 6048: 
 6049: sub modify_group_roles {
 6050:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6051:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6052:     my $role = 'gr/'.&escape($userprivs);
 6053:     my ($uname,$udom) = split(/:/,$user);
 6054:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6055:     if ($result eq 'ok') {
 6056:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6057:     }
 6058:     return $result;
 6059: }
 6060: 
 6061: sub modify_coursegroup_membership {
 6062:     my ($cdom,$cnum,$membership) = @_;
 6063:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6064:     return $result;
 6065: }
 6066: 
 6067: sub get_active_groups {
 6068:     my ($udom,$uname,$cdom,$cnum) = @_;
 6069:     my $now = time;
 6070:     my %groups = ();
 6071:     foreach my $key (keys(%env)) {
 6072:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6073:             my ($start,$end) = split(/\./,$env{$key});
 6074:             if (($end!=0) && ($end<$now)) { next; }
 6075:             if (($start!=0) && ($start>$now)) { next; }
 6076:             if ($1 eq $cdom && $2 eq $cnum) {
 6077:                 $groups{$3} = $env{$key} ;
 6078:             }
 6079:         }
 6080:     }
 6081:     return %groups;
 6082: }
 6083: 
 6084: sub get_group_membership {
 6085:     my ($cdom,$cnum,$group) = @_;
 6086:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6087: }
 6088: 
 6089: sub get_users_groups {
 6090:     my ($udom,$uname,$courseid) = @_;
 6091:     my @usersgroups;
 6092:     my $cachetime=1800;
 6093: 
 6094:     my $hashid="$udom:$uname:$courseid";
 6095:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6096:     if (defined($cached)) {
 6097:         @usersgroups = split(/:/,$grouplist);
 6098:     } else {  
 6099:         $grouplist = '';
 6100:         my $courseurl = &courseid_to_courseurl($courseid);
 6101:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 6102:         my $access_end = $env{'course.'.$courseid.
 6103:                               '.default_enrollment_end_date'};
 6104:         my $now = time;
 6105:         foreach my $key (keys(%roleshash)) {
 6106:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6107:                 my $group = $1;
 6108:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6109:                     my $start = $2;
 6110:                     my $end = $1;
 6111:                     if ($start == -1) { next; } # deleted from group
 6112:                     if (($start!=0) && ($start>$now)) { next; }
 6113:                     if (($end!=0) && ($end<$now)) {
 6114:                         if ($access_end && $access_end < $now) {
 6115:                             if ($access_end - $end < 86400) {
 6116:                                 push(@usersgroups,$group);
 6117:                             }
 6118:                         }
 6119:                         next;
 6120:                     }
 6121:                     push(@usersgroups,$group);
 6122:                 }
 6123:             }
 6124:         }
 6125:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6126:         $grouplist = join(':',@usersgroups);
 6127:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6128:     }
 6129:     return @usersgroups;
 6130: }
 6131: 
 6132: sub devalidate_getgroups_cache {
 6133:     my ($udom,$uname,$cdom,$cnum)=@_;
 6134:     my $courseid = $cdom.'_'.$cnum;
 6135: 
 6136:     my $hashid="$udom:$uname:$courseid";
 6137:     &devalidate_cache_new('getgroups',$hashid);
 6138: }
 6139: 
 6140: # ------------------------------------------------------------------ Plain Text
 6141: 
 6142: sub plaintext {
 6143:     my ($short,$type,$cid,$forcedefault) = @_;
 6144:     if ($short =~ /^cr/) {
 6145: 	return (split('/',$short))[-1];
 6146:     }
 6147:     if (!defined($cid)) {
 6148:         $cid = $env{'request.course.id'};
 6149:     }
 6150:     my %rolenames = (
 6151:                       Course    => 'std',
 6152:                       Community => 'alt1',
 6153:                     );
 6154:     if ($cid ne '') {
 6155:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6156:             unless ($forcedefault) {
 6157:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6158:                 &Apache::lonlocal::mt_escape(\$roletext);
 6159:                 return &Apache::lonlocal::mt($roletext);
 6160:             }
 6161:         }
 6162:     }
 6163:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6164:         (defined($rolenames{$type})) && 
 6165:         (defined($prp{$short}{$rolenames{$type}}))) {
 6166:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6167:     } elsif ($cid ne '') {
 6168:         my $crstype = $env{'course.'.$cid.'.type'};
 6169:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6170:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 6171:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 6172:         }
 6173:     }
 6174:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 6175: }
 6176: 
 6177: # ----------------------------------------------------------------- Assign Role
 6178: 
 6179: sub assignrole {
 6180:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6181:         $context)=@_;
 6182:     my $mrole;
 6183:     if ($role =~ /^cr\//) {
 6184:         my $cwosec=$url;
 6185:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6186: 	unless (&allowed('ccr',$cwosec)) {
 6187:            my $refused = 1;
 6188:            if ($context eq 'requestcourses') {
 6189:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 6190:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 6191:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 6192:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6193:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6194:                            if ($crsenv{'internal.courseowner'} eq
 6195:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 6196:                                $refused = '';
 6197:                            }
 6198:                        }
 6199:                    }
 6200:                }
 6201:            }
 6202:            if ($refused) {
 6203:                &logthis('Refused custom assignrole: '.
 6204:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 6205:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 6206:                return 'refused';
 6207:            }
 6208:         }
 6209:         $mrole='cr';
 6210:     } elsif ($role =~ /^gr\//) {
 6211:         my $cwogrp=$url;
 6212:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 6213:         unless (&allowed('mdg',$cwogrp)) {
 6214:             &logthis('Refused group assignrole: '.
 6215:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6216:                     $env{'user.name'}.' at '.$env{'user.domain'});
 6217:             return 'refused';
 6218:         }
 6219:         $mrole='gr';
 6220:     } else {
 6221:         my $cwosec=$url;
 6222:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6223:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 6224:             my $refused;
 6225:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 6226:                 if (!(&allowed('c'.$role,$url))) {
 6227:                     $refused = 1;
 6228:                 }
 6229:             } else {
 6230:                 $refused = 1;
 6231:             }
 6232:             if ($refused) {
 6233:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6234:                     $refused = '';
 6235:                 } elsif ($context eq 'requestcourses') {
 6236:                     my @possroles = ('st','ta','ep','in','cc','co');
 6237:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 6238:                         my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6239:                         my $wrongcc;
 6240:                         if ($cnum =~ /^$match_community$/) {
 6241:                             $wrongcc = 1 if ($role eq 'cc');
 6242:                         } else {
 6243:                             $wrongcc = 1 if ($role eq 'co');
 6244:                         }
 6245:                         unless ($wrongcc) {
 6246:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6247:                             if ($crsenv{'internal.courseowner'} eq 
 6248:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 6249:                                 $refused = '';
 6250:                             }
 6251:                         }
 6252:                     }
 6253:                 }
 6254:                 if ($refused) {
 6255:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6256:                              ' '.$role.' '.$end.' '.$start.' by '.
 6257: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6258:                     return 'refused';
 6259:                 }
 6260:             }
 6261:         }
 6262:         $mrole=$role;
 6263:     }
 6264:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6265:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6266:     if ($end) { $command.='_'.$end; }
 6267:     if ($start) {
 6268: 	if ($end) { 
 6269:            $command.='_'.$start; 
 6270:         } else {
 6271:            $command.='_0_'.$start;
 6272:         }
 6273:     }
 6274:     my $origstart = $start;
 6275:     my $origend = $end;
 6276:     my $delflag;
 6277: # actually delete
 6278:     if ($deleteflag) {
 6279: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6280: # modify command to delete the role
 6281:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6282:                 "$udom:$uname:$url".'_'."$mrole";
 6283: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6284: # set start and finish to negative values for userrolelog
 6285:            $start=-1;
 6286:            $end=-1;
 6287:            $delflag = 1;
 6288:         }
 6289:     }
 6290: # send command
 6291:     my $answer=&reply($command,&homeserver($uname,$udom));
 6292: # log new user role if status is ok
 6293:     if ($answer eq 'ok') {
 6294: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6295: # for course roles, perform group memberships changes triggered by role change.
 6296:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6297:         unless ($role =~ /^gr/) {
 6298:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6299:                                              $origstart,$selfenroll,$context);
 6300:         }
 6301:     }
 6302:     return $answer;
 6303: }
 6304: 
 6305: # -------------------------------------------------- Modify user authentication
 6306: # Overrides without validation
 6307: 
 6308: sub modifyuserauth {
 6309:     my ($udom,$uname,$umode,$upass)=@_;
 6310:     my $uhome=&homeserver($uname,$udom);
 6311:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6312:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6313:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6314:              ' in domain '.$env{'request.role.domain'});  
 6315:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6316: 		     &escape($upass),$uhome);
 6317:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6318:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6319:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6320:     &log($udom,,$uname,$uhome,
 6321:         'Authentication changed by '.$env{'user.domain'}.', '.
 6322:                                      $env{'user.name'}.', '.$umode.
 6323:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6324:     unless ($reply eq 'ok') {
 6325:         &logthis('Authentication mode error: '.$reply);
 6326: 	return 'error: '.$reply;
 6327:     }   
 6328:     return 'ok';
 6329: }
 6330: 
 6331: # --------------------------------------------------------------- Modify a user
 6332: 
 6333: sub modifyuser {
 6334:     my ($udom,    $uname, $uid,
 6335:         $umode,   $upass, $first,
 6336:         $middle,  $last,  $gene,
 6337:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6338:     $udom= &LONCAPA::clean_domain($udom);
 6339:     $uname=&LONCAPA::clean_username($uname);
 6340:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6341:              $umode.', '.$first.', '.$middle.', '.
 6342: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6343:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6344:                                      ' desiredhome not specified'). 
 6345:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6346:              ' in domain '.$env{'request.role.domain'});
 6347:     my $uhome=&homeserver($uname,$udom,'true');
 6348: # ----------------------------------------------------------------- Create User
 6349:     if (($uhome eq 'no_host') && 
 6350: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6351:         my $unhome='';
 6352:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6353:             $unhome = $desiredhome;
 6354: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6355: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6356:         } else { # load balancing routine for determining $unhome
 6357:             my $loadm=10000000;
 6358: 	    my %servers = &get_servers($udom,'library');
 6359: 	    foreach my $tryserver (keys(%servers)) {
 6360: 		my $answer=reply('load',$tryserver);
 6361: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6362: 		    $loadm=$answer;
 6363: 		    $unhome=$tryserver;
 6364: 		}
 6365: 	    }
 6366:         }
 6367:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6368: 	    return 'error: unable to find a home server for '.$uname.
 6369:                    ' in domain '.$udom;
 6370:         }
 6371:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6372:                          &escape($upass),$unhome);
 6373: 	unless ($reply eq 'ok') {
 6374:             return 'error: '.$reply;
 6375:         }   
 6376:         $uhome=&homeserver($uname,$udom,'true');
 6377:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6378: 	    return 'error: unable verify users home machine.';
 6379:         }
 6380:     }   # End of creation of new user
 6381: # ---------------------------------------------------------------------- Add ID
 6382:     if ($uid) {
 6383:        $uid=~tr/A-Z/a-z/;
 6384:        my %uidhash=&idrget($udom,$uname);
 6385:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6386:          && (!$forceid)) {
 6387: 	  unless ($uid eq $uidhash{$uname}) {
 6388: 	      return 'error: user id "'.$uid.'" does not match '.
 6389:                   'current user id "'.$uidhash{$uname}.'".';
 6390:           }
 6391:        } else {
 6392: 	  &idput($udom,($uname => $uid));
 6393:        }
 6394:     }
 6395: # -------------------------------------------------------------- Add names, etc
 6396:     my @tmp=&get('environment',
 6397: 		   ['firstname','middlename','lastname','generation','id',
 6398:                     'permanentemail','inststatus'],
 6399: 		   $udom,$uname);
 6400:     my %names;
 6401:     if ($tmp[0] =~ m/^error:.*/) { 
 6402:         %names=(); 
 6403:     } else {
 6404:         %names = @tmp;
 6405:     }
 6406: #
 6407: # Make sure to not trash student environment if instructor does not bother
 6408: # to supply name and email information
 6409: #
 6410:     if ($first)  { $names{'firstname'}  = $first; }
 6411:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6412:     if ($last)   { $names{'lastname'}   = $last; }
 6413:     if (defined($gene))   { $names{'generation'} = $gene; }
 6414:     if ($email) {
 6415:        $email=~s/[^\w\@\.\-\,]//gs;
 6416:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6417:     }
 6418:     if ($uid) { $names{'id'}  = $uid; }
 6419:     if (defined($inststatus)) {
 6420:         $names{'inststatus'} = '';
 6421:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6422:         if (ref($usertypes) eq 'HASH') {
 6423:             my @okstatuses; 
 6424:             foreach my $item (split(/:/,$inststatus)) {
 6425:                 if (defined($usertypes->{$item})) {
 6426:                     push(@okstatuses,$item);  
 6427:                 }
 6428:             }
 6429:             if (@okstatuses) {
 6430:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6431:             }
 6432:         }
 6433:     }
 6434:     my $reply = &put('environment', \%names, $udom,$uname);
 6435:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6436:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6437:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6438:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6439:                  $umode.', '.$first.', '.$middle.', '.
 6440: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6441:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6442:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6443:     } else {
 6444:         $logmsg .= ' during self creation';
 6445:     }
 6446:     &logthis($logmsg);
 6447:     return 'ok';
 6448: }
 6449: 
 6450: # -------------------------------------------------------------- Modify student
 6451: 
 6452: sub modifystudent {
 6453:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6454:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6455:         $selfenroll,$context,$inststatus)=@_;
 6456:     if (!$cid) {
 6457: 	unless ($cid=$env{'request.course.id'}) {
 6458: 	    return 'not_in_class';
 6459: 	}
 6460:     }
 6461: # --------------------------------------------------------------- Make the user
 6462:     my $reply=&modifyuser
 6463: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6464:          $desiredhome,$email,$inststatus);
 6465:     unless ($reply eq 'ok') { return $reply; }
 6466:     # This will cause &modify_student_enrollment to get the uid from the
 6467:     # students environment
 6468:     $uid = undef if (!$forceid);
 6469:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6470: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6471:     return $reply;
 6472: }
 6473: 
 6474: sub modify_student_enrollment {
 6475:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6476:     my ($cdom,$cnum,$chome);
 6477:     if (!$cid) {
 6478: 	unless ($cid=$env{'request.course.id'}) {
 6479: 	    return 'not_in_class';
 6480: 	}
 6481: 	$cdom=$env{'course.'.$cid.'.domain'};
 6482: 	$cnum=$env{'course.'.$cid.'.num'};
 6483:     } else {
 6484: 	($cdom,$cnum)=split(/_/,$cid);
 6485:     }
 6486:     $chome=$env{'course.'.$cid.'.home'};
 6487:     if (!$chome) {
 6488: 	$chome=&homeserver($cnum,$cdom);
 6489:     }
 6490:     if (!$chome) { return 'unknown_course'; }
 6491:     # Make sure the user exists
 6492:     my $uhome=&homeserver($uname,$udom);
 6493:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6494: 	return 'error: no such user';
 6495:     }
 6496:     # Get student data if we were not given enough information
 6497:     if (!defined($first)  || $first  eq '' || 
 6498:         !defined($last)   || $last   eq '' || 
 6499:         !defined($uid)    || $uid    eq '' || 
 6500:         !defined($middle) || $middle eq '' || 
 6501:         !defined($gene)   || $gene   eq '') {
 6502:         # They did not supply us with enough data to enroll the student, so
 6503:         # we need to pick up more information.
 6504:         my %tmp = &get('environment',
 6505:                        ['firstname','middlename','lastname', 'generation','id']
 6506:                        ,$udom,$uname);
 6507: 
 6508:         #foreach my $key (keys(%tmp)) {
 6509:         #    &logthis("key $key = ".$tmp{$key});
 6510:         #}
 6511:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6512:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6513:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6514:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6515:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6516:     }
 6517:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6518:     my $reply=cput('classlist',
 6519: 		   {"$uname:$udom" => 
 6520: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6521: 		   $cdom,$cnum);
 6522:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6523: 	return 'error: '.$reply;
 6524:     } else {
 6525: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6526:     }
 6527:     # Add student role to user
 6528:     my $uurl='/'.$cid;
 6529:     $uurl=~s/\_/\//g;
 6530:     if ($usec) {
 6531: 	$uurl.='/'.$usec;
 6532:     }
 6533:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6534: }
 6535: 
 6536: sub format_name {
 6537:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6538:     my $name;
 6539:     if ($first ne 'lastname') {
 6540: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6541:     } else {
 6542: 	if ($lastname=~/\S/) {
 6543: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6544: 	    $name=~s/\s+,/,/;
 6545: 	} else {
 6546: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6547: 	}
 6548:     }
 6549:     $name=~s/^\s+//;
 6550:     $name=~s/\s+$//;
 6551:     $name=~s/\s+/ /g;
 6552:     return $name;
 6553: }
 6554: 
 6555: # ------------------------------------------------- Write to course preferences
 6556: 
 6557: sub writecoursepref {
 6558:     my ($courseid,%prefs)=@_;
 6559:     $courseid=~s/^\///;
 6560:     $courseid=~s/\_/\//g;
 6561:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6562:     my $chome=homeserver($cnum,$cdomain);
 6563:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6564: 	return 'error: no such course';
 6565:     }
 6566:     my $cstring='';
 6567:     foreach my $pref (keys(%prefs)) {
 6568: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6569:     }
 6570:     $cstring=~s/\&$//;
 6571:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6572: }
 6573: 
 6574: # ---------------------------------------------------------- Make/modify course
 6575: 
 6576: sub createcourse {
 6577:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6578:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 6579:     $url=&declutter($url);
 6580:     my $cid='';
 6581:     if ($context eq 'requestcourses') {
 6582:         my $can_create = 0;
 6583:         my ($ownername,$ownerdom) = split(':',$course_owner);
 6584:         if ($udom eq $ownerdom) {
 6585:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 6586:                                   $context)) {
 6587:                 $can_create = 1;
 6588:             }
 6589:         } else {
 6590:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 6591:                                            $category);
 6592:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 6593:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 6594:                 if (@curr > 0) {
 6595:                     my @options = qw(approval validate autolimit);
 6596:                     my $optregex = join('|',@options);
 6597:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 6598:                         $can_create = 1;
 6599:                     }
 6600:                 }
 6601:             }
 6602:         }
 6603:         if ($can_create) {
 6604:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 6605:                 unless (&allowed('ccc',$udom)) {
 6606:                     return 'refused'; 
 6607:                 }
 6608:             }
 6609:         } else {
 6610:             return 'refused';
 6611:         }
 6612:     } elsif (!&allowed('ccc',$udom)) {
 6613:         return 'refused';
 6614:     }
 6615: # --------------------------------------------------------------- Get Unique ID
 6616:     my $uname;
 6617:     if ($cnum =~ /^$match_courseid$/) {
 6618:         my $chome=&homeserver($cnum,$udom,'true');
 6619:         if (($chome eq '') || ($chome eq 'no_host')) {
 6620:             $uname = $cnum;
 6621:         } else {
 6622:             $uname = &generate_coursenum($udom,$crstype);
 6623:         }
 6624:     } else {
 6625:         $uname = &generate_coursenum($udom,$crstype);
 6626:     }
 6627:     return $uname if ($uname =~ /^error/);
 6628: # -------------------------------------------------- Check supplied server name
 6629:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6630:     if (! &is_library($course_server)) {
 6631:         return 'error:bad server name '.$course_server;
 6632:     }
 6633: # ------------------------------------------------------------- Make the course
 6634:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6635:                       $course_server);
 6636:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6637:     my $uhome=&homeserver($uname,$udom,'true');
 6638:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6639: 	return 'error: no such course';
 6640:     }
 6641: # ----------------------------------------------------------------- Course made
 6642: # log existence
 6643:     my $now = time;
 6644:     my $newcourse = {
 6645:                     $udom.'_'.$uname => {
 6646:                                      description => $description,
 6647:                                      inst_code   => $inst_code,
 6648:                                      owner       => $course_owner,
 6649:                                      type        => $crstype,
 6650:                                      creator     => $env{'user.name'}.':'.
 6651:                                                     $env{'user.domain'},
 6652:                                      created     => $now,
 6653:                                      context     => $context,
 6654:                                                 },
 6655:                     };
 6656:     &courseidput($udom,$newcourse,$uhome,'notime');
 6657: # set toplevel url
 6658:     my $topurl=$url;
 6659:     unless ($nonstandard) {
 6660: # ------------------------------------------ For standard courses, make top url
 6661:         my $mapurl=&clutter($url);
 6662:         if ($mapurl eq '/res/') { $mapurl=''; }
 6663:         $env{'form.initmap'}=(<<ENDINITMAP);
 6664: <map>
 6665: <resource id="1" type="start"></resource>
 6666: <resource id="2" src="$mapurl"></resource>
 6667: <resource id="3" type="finish"></resource>
 6668: <link index="1" from="1" to="2"></link>
 6669: <link index="2" from="2" to="3"></link>
 6670: </map>
 6671: ENDINITMAP
 6672:         $topurl=&declutter(
 6673:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6674:                           );
 6675:     }
 6676: # ----------------------------------------------------------- Write preferences
 6677:     &writecoursepref($udom.'_'.$uname,
 6678:                      ('description' => $description,
 6679:                       'url'         => $topurl));
 6680:     return '/'.$udom.'/'.$uname;
 6681: }
 6682: 
 6683: # ------------------------------------------------------------------- Create ID
 6684: sub generate_coursenum {
 6685:     my ($udom,$crstype) = @_;
 6686:     my $domdesc = &domain($udom);
 6687:     return 'error: invalid domain' if ($domdesc eq '');
 6688:     my $first;
 6689:     if ($crstype eq 'Community') {
 6690:         $first = '0';
 6691:     } else {
 6692:         $first = int(1+rand(9)); 
 6693:     } 
 6694:     my $uname=$first.
 6695:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6696:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6697:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6698: # ----------------------------------------------- Make sure that does not exist
 6699:     my $uhome=&homeserver($uname,$udom,'true');
 6700:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6701:         if ($crstype eq 'Community') {
 6702:             $first = '0';
 6703:         } else {
 6704:             $first = int(1+rand(9));
 6705:         }
 6706:         $uname=$first.
 6707:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6708:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6709:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6710:         $uhome=&homeserver($uname,$udom,'true');
 6711:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6712:             return 'error: unable to generate unique course-ID';
 6713:         }
 6714:     }
 6715:     return $uname;
 6716: }
 6717: 
 6718: sub is_course {
 6719:     my ($cdom,$cnum) = @_;
 6720:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6721: 				undef,'.');
 6722:     if (exists($courses{$cdom.'_'.$cnum})) {
 6723:         return 1;
 6724:     }
 6725:     return 0;
 6726: }
 6727: 
 6728: sub store_userdata {
 6729:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 6730:     my $result;
 6731:     if ($datakey ne '') {
 6732:         if (ref($storehash) eq 'HASH') {
 6733:             if ($udom eq '' || $uname eq '') {
 6734:                 $udom = $env{'user.domain'};
 6735:                 $uname = $env{'user.name'};
 6736:             }
 6737:             my $uhome=&homeserver($uname,$udom);
 6738:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 6739:                 $result = 'error: no_host';
 6740:             } else {
 6741:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 6742:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 6743: 
 6744:                 my $namevalue='';
 6745:                 foreach my $key (keys(%{$storehash})) {
 6746:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6747:                 }
 6748:                 $namevalue=~s/\&$//;
 6749:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
 6750:                                   "$namespace:$datakey:$namevalue",$uhome);
 6751:             }
 6752:         } else {
 6753:             $result = 'error: data to store was not a hash reference'; 
 6754:         }
 6755:     } else {
 6756:         $result= 'error: invalid requestkey'; 
 6757:     }
 6758:     return $result;
 6759: }
 6760: 
 6761: # ---------------------------------------------------------- Assign Custom Role
 6762: 
 6763: sub assigncustomrole {
 6764:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6765:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6766:                        $end,$start,$deleteflag,$selfenroll,$context);
 6767: }
 6768: 
 6769: # ----------------------------------------------------------------- Revoke Role
 6770: 
 6771: sub revokerole {
 6772:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6773:     my $now=time;
 6774:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6775: }
 6776: 
 6777: # ---------------------------------------------------------- Revoke Custom Role
 6778: 
 6779: sub revokecustomrole {
 6780:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6781:     my $now=time;
 6782:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6783:            $deleteflag,$selfenroll,$context);
 6784: }
 6785: 
 6786: # ------------------------------------------------------------ Disk usage
 6787: sub diskusage {
 6788:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6789:     $directorypath =~ s/\/$//;
 6790:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6791:                        .&escape($getpropath).':'.&escape($uname).':'
 6792:                        .&escape($udom),homeserver($uname,$udom));
 6793:     if ($listing eq 'unknown_cmd') {
 6794:         if ($getpropath) {
 6795:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6796:         }
 6797:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6798:     }
 6799:     return $listing;
 6800: }
 6801: 
 6802: sub is_locked {
 6803:     my ($file_name, $domain, $user) = @_;
 6804:     my @check;
 6805:     my $is_locked;
 6806:     push @check, $file_name;
 6807:     my %locked = &get('file_permissions',\@check,
 6808: 		      $env{'user.domain'},$env{'user.name'});
 6809:     my ($tmp)=keys(%locked);
 6810:     if ($tmp=~/^error:/) { undef(%locked); }
 6811:     
 6812:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6813:         $is_locked = 'false';
 6814:         foreach my $entry (@{$locked{$file_name}}) {
 6815:            if (ref($entry) eq 'ARRAY') { 
 6816:                $is_locked = 'true';
 6817:                last;
 6818:            }
 6819:        }
 6820:     } else {
 6821:         $is_locked = 'false';
 6822:     }
 6823: }
 6824: 
 6825: sub declutter_portfile {
 6826:     my ($file) = @_;
 6827:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6828:     return $file;
 6829: }
 6830: 
 6831: # ------------------------------------------------------------- Mark as Read Only
 6832: 
 6833: sub mark_as_readonly {
 6834:     my ($domain,$user,$files,$what) = @_;
 6835:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6836:     my ($tmp)=keys(%current_permissions);
 6837:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6838:     foreach my $file (@{$files}) {
 6839: 	$file = &declutter_portfile($file);
 6840:         push(@{$current_permissions{$file}},$what);
 6841:     }
 6842:     &put('file_permissions',\%current_permissions,$domain,$user);
 6843:     return;
 6844: }
 6845: 
 6846: # ------------------------------------------------------------Save Selected Files
 6847: 
 6848: sub save_selected_files {
 6849:     my ($user, $path, @files) = @_;
 6850:     my $filename = $user."savedfiles";
 6851:     my @other_files = &files_not_in_path($user, $path);
 6852:     open (OUT, '>'.$tmpdir.$filename);
 6853:     foreach my $file (@files) {
 6854:         print (OUT $env{'form.currentpath'}.$file."\n");
 6855:     }
 6856:     foreach my $file (@other_files) {
 6857:         print (OUT $file."\n");
 6858:     }
 6859:     close (OUT);
 6860:     return 'ok';
 6861: }
 6862: 
 6863: sub clear_selected_files {
 6864:     my ($user) = @_;
 6865:     my $filename = $user."savedfiles";
 6866:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6867:     print (OUT undef);
 6868:     close (OUT);
 6869:     return ("ok");    
 6870: }
 6871: 
 6872: sub files_in_path {
 6873:     my ($user, $path) = @_;
 6874:     my $filename = $user."savedfiles";
 6875:     my %return_files;
 6876:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6877:     while (my $line_in = <IN>) {
 6878:         chomp ($line_in);
 6879:         my @paths_and_file = split (m!/!, $line_in);
 6880:         my $file_part = pop (@paths_and_file);
 6881:         my $path_part = join ('/', @paths_and_file);
 6882:         $path_part.='/';
 6883:         my $path_and_file = $path_part.$file_part;
 6884:         if ($path_part eq $path) {
 6885:             $return_files{$file_part}= 'selected';
 6886:         }
 6887:     }
 6888:     close (IN);
 6889:     return (\%return_files);
 6890: }
 6891: 
 6892: # called in portfolio select mode, to show files selected NOT in current directory
 6893: sub files_not_in_path {
 6894:     my ($user, $path) = @_;
 6895:     my $filename = $user."savedfiles";
 6896:     my @return_files;
 6897:     my $path_part;
 6898:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6899:     while (my $line = <IN>) {
 6900:         #ok, I know it's clunky, but I want it to work
 6901:         my @paths_and_file = split(m|/|, $line);
 6902:         my $file_part = pop(@paths_and_file);
 6903:         chomp($file_part);
 6904:         my $path_part = join('/', @paths_and_file);
 6905:         $path_part .= '/';
 6906:         my $path_and_file = $path_part.$file_part;
 6907:         if ($path_part ne $path) {
 6908:             push(@return_files, ($path_and_file));
 6909:         }
 6910:     }
 6911:     close(OUT);
 6912:     return (@return_files);
 6913: }
 6914: 
 6915: #----------------------------------------------Get portfolio file permissions
 6916: 
 6917: sub get_portfile_permissions {
 6918:     my ($domain,$user) = @_;
 6919:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6920:     my ($tmp)=keys(%current_permissions);
 6921:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6922:     return \%current_permissions;
 6923: }
 6924: 
 6925: #---------------------------------------------Get portfolio file access controls
 6926: 
 6927: sub get_access_controls {
 6928:     my ($current_permissions,$group,$file) = @_;
 6929:     my %access;
 6930:     my $real_file = $file;
 6931:     $file =~ s/\.meta$//;
 6932:     if (defined($file)) {
 6933:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6934:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6935:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6936:             }
 6937:         }
 6938:     } else {
 6939:         foreach my $key (keys(%{$current_permissions})) {
 6940:             if ($key =~ /\0accesscontrol$/) {
 6941:                 if (defined($group)) {
 6942:                     if ($key !~ m-^\Q$group\E/-) {
 6943:                         next;
 6944:                     }
 6945:                 }
 6946:                 my ($fullpath) = split(/\0/,$key);
 6947:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6948:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6949:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6950:                     }
 6951:                 }
 6952:             }
 6953:         }
 6954:     }
 6955:     return %access;
 6956: }
 6957: 
 6958: sub modify_access_controls {
 6959:     my ($file_name,$changes,$domain,$user)=@_;
 6960:     my ($outcome,$deloutcome);
 6961:     my %store_permissions;
 6962:     my %new_values;
 6963:     my %new_control;
 6964:     my %translation;
 6965:     my @deletions = ();
 6966:     my $now = time;
 6967:     if (exists($$changes{'activate'})) {
 6968:         if (ref($$changes{'activate'}) eq 'HASH') {
 6969:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6970:             my $numnew = scalar(@newitems);
 6971:             for (my $i=0; $i<$numnew; $i++) {
 6972:                 my $newkey = $newitems[$i];
 6973:                 my $newid = &Apache::loncommon::get_cgi_id();
 6974:                 if ($newkey =~ /^\d+:/) { 
 6975:                     $newkey =~ s/^(\d+)/$newid/;
 6976:                     $translation{$1} = $newid;
 6977:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6978:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6979:                     $translation{$1} = $newid;
 6980:                 }
 6981:                 $new_values{$file_name."\0".$newkey} = 
 6982:                                           $$changes{'activate'}{$newitems[$i]};
 6983:                 $new_control{$newkey} = $now;
 6984:             }
 6985:         }
 6986:     }
 6987:     my %todelete;
 6988:     my %changed_items;
 6989:     foreach my $action ('delete','update') {
 6990:         if (exists($$changes{$action})) {
 6991:             if (ref($$changes{$action}) eq 'HASH') {
 6992:                 foreach my $key (keys(%{$$changes{$action}})) {
 6993:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6994:                     if ($action eq 'delete') { 
 6995:                         $todelete{$itemnum} = 1;
 6996:                     } else {
 6997:                         $changed_items{$itemnum} = $key;
 6998:                     }
 6999:                 }
 7000:             }
 7001:         }
 7002:     }
 7003:     # get lock on access controls for file.
 7004:     my $lockhash = {
 7005:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 7006:                                                        ':'.$env{'user.domain'},
 7007:                    }; 
 7008:     my $tries = 0;
 7009:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7010:    
 7011:     while (($gotlock ne 'ok') && $tries <3) {
 7012:         $tries ++;
 7013:         sleep 1;
 7014:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7015:     }
 7016:     if ($gotlock eq 'ok') {
 7017:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 7018:         my ($tmp)=keys(%curr_permissions);
 7019:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 7020:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 7021:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 7022:             if (ref($curr_controls) eq 'HASH') {
 7023:                 foreach my $control_item (keys(%{$curr_controls})) {
 7024:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 7025:                     if (defined($todelete{$itemnum})) {
 7026:                         push(@deletions,$file_name."\0".$control_item);
 7027:                     } else {
 7028:                         if (defined($changed_items{$itemnum})) {
 7029:                             $new_control{$changed_items{$itemnum}} = $now;
 7030:                             push(@deletions,$file_name."\0".$control_item);
 7031:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 7032:                         } else {
 7033:                             $new_control{$control_item} = $$curr_controls{$control_item};
 7034:                         }
 7035:                     }
 7036:                 }
 7037:             }
 7038:         }
 7039:         my ($group);
 7040:         if (&is_course($domain,$user)) {
 7041:             ($group,my $file) = split(/\//,$file_name,2);
 7042:         }
 7043:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 7044:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 7045:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 7046:         #  remove lock
 7047:         my @del_lock = ($file_name."\0".'locked_access_records');
 7048:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 7049:         my $sqlresult =
 7050:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 7051:                                     $group);
 7052:     } else {
 7053:         $outcome = "error: could not obtain lockfile\n";  
 7054:     }
 7055:     return ($outcome,$deloutcome,\%new_values,\%translation);
 7056: }
 7057: 
 7058: sub make_public_indefinitely {
 7059:     my ($requrl) = @_;
 7060:     my $now = time;
 7061:     my $action = 'activate';
 7062:     my $aclnum = 0;
 7063:     if (&is_portfolio_url($requrl)) {
 7064:         my (undef,$udom,$unum,$file_name,$group) =
 7065:             &parse_portfolio_url($requrl);
 7066:         my $current_perms = &get_portfile_permissions($udom,$unum);
 7067:         my %access_controls = &get_access_controls($current_perms,
 7068:                                                    $group,$file_name);
 7069:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 7070:             my ($num,$scope,$end,$start) = 
 7071:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7072:             if ($scope eq 'public') {
 7073:                 if ($start <= $now && $end == 0) {
 7074:                     $action = 'none';
 7075:                 } else {
 7076:                     $action = 'update';
 7077:                     $aclnum = $num;
 7078:                 }
 7079:                 last;
 7080:             }
 7081:         }
 7082:         if ($action eq 'none') {
 7083:              return 'ok';
 7084:         } else {
 7085:             my %changes;
 7086:             my $newend = 0;
 7087:             my $newstart = $now;
 7088:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 7089:             $changes{$action}{$newkey} = {
 7090:                 type => 'public',
 7091:                 time => {
 7092:                     start => $newstart,
 7093:                     end   => $newend,
 7094:                 },
 7095:             };
 7096:             my ($outcome,$deloutcome,$new_values,$translation) =
 7097:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 7098:             return $outcome;
 7099:         }
 7100:     } else {
 7101:         return 'invalid';
 7102:     }
 7103: }
 7104: 
 7105: #------------------------------------------------------Get Marked as Read Only
 7106: 
 7107: sub get_marked_as_readonly {
 7108:     my ($domain,$user,$what,$group) = @_;
 7109:     my $current_permissions = &get_portfile_permissions($domain,$user);
 7110:     my @readonly_files;
 7111:     my $cmp1=$what;
 7112:     if (ref($what)) { $cmp1=join('',@{$what}) };
 7113:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7114:         if (defined($group)) {
 7115:             if ($file_name !~ m-^\Q$group\E/-) {
 7116:                 next;
 7117:             }
 7118:         }
 7119:         if (ref($value) eq "ARRAY"){
 7120:             foreach my $stored_what (@{$value}) {
 7121:                 my $cmp2=$stored_what;
 7122:                 if (ref($stored_what) eq 'ARRAY') {
 7123:                     $cmp2=join('',@{$stored_what});
 7124:                 }
 7125:                 if ($cmp1 eq $cmp2) {
 7126:                     push(@readonly_files, $file_name);
 7127:                     last;
 7128:                 } elsif (!defined($what)) {
 7129:                     push(@readonly_files, $file_name);
 7130:                     last;
 7131:                 }
 7132:             }
 7133:         }
 7134:     }
 7135:     return @readonly_files;
 7136: }
 7137: #-----------------------------------------------------------Get Marked as Read Only Hash
 7138: 
 7139: sub get_marked_as_readonly_hash {
 7140:     my ($current_permissions,$group,$what) = @_;
 7141:     my %readonly_files;
 7142:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7143:         if (defined($group)) {
 7144:             if ($file_name !~ m-^\Q$group\E/-) {
 7145:                 next;
 7146:             }
 7147:         }
 7148:         if (ref($value) eq "ARRAY"){
 7149:             foreach my $stored_what (@{$value}) {
 7150:                 if (ref($stored_what) eq 'ARRAY') {
 7151:                     foreach my $lock_descriptor(@{$stored_what}) {
 7152:                         if ($lock_descriptor eq 'graded') {
 7153:                             $readonly_files{$file_name} = 'graded';
 7154:                         } elsif ($lock_descriptor eq 'handback') {
 7155:                             $readonly_files{$file_name} = 'handback';
 7156:                         } else {
 7157:                             if (!exists($readonly_files{$file_name})) {
 7158:                                 $readonly_files{$file_name} = 'locked';
 7159:                             }
 7160:                         }
 7161:                     }
 7162:                 } 
 7163:             }
 7164:         } 
 7165:     }
 7166:     return %readonly_files;
 7167: }
 7168: # ------------------------------------------------------------ Unmark as Read Only
 7169: 
 7170: sub unmark_as_readonly {
 7171:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 7172:     # for portfolio submissions, $what contains [$symb,$crsid] 
 7173:     my ($domain,$user,$what,$file_name,$group) = @_;
 7174:     $file_name = &declutter_portfile($file_name);
 7175:     my $symb_crs = $what;
 7176:     if (ref($what)) { $symb_crs=join('',@$what); }
 7177:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 7178:     my ($tmp)=keys(%current_permissions);
 7179:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7180:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 7181:     foreach my $file (@readonly_files) {
 7182: 	my $clean_file = &declutter_portfile($file);
 7183: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 7184: 	my $current_locks = $current_permissions{$file};
 7185:         my @new_locks;
 7186:         my @del_keys;
 7187:         if (ref($current_locks) eq "ARRAY"){
 7188:             foreach my $locker (@{$current_locks}) {
 7189:                 my $compare=$locker;
 7190:                 if (ref($locker) eq 'ARRAY') {
 7191:                     $compare=join('',@{$locker});
 7192:                     if ($compare ne $symb_crs) {
 7193:                         push(@new_locks, $locker);
 7194:                     }
 7195:                 }
 7196:             }
 7197:             if (scalar(@new_locks) > 0) {
 7198:                 $current_permissions{$file} = \@new_locks;
 7199:             } else {
 7200:                 push(@del_keys, $file);
 7201:                 &del('file_permissions',\@del_keys, $domain, $user);
 7202:                 delete($current_permissions{$file});
 7203:             }
 7204:         }
 7205:     }
 7206:     &put('file_permissions',\%current_permissions,$domain,$user);
 7207:     return;
 7208: }
 7209: 
 7210: # ------------------------------------------------------------ Directory lister
 7211: 
 7212: sub dirlist {
 7213:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 7214:     $uri=~s/^\///;
 7215:     $uri=~s/\/$//;
 7216:     my ($udom, $uname);
 7217:     if ($getuserdir) {
 7218:         $udom = $userdomain;
 7219:         $uname = $username;
 7220:     } else {
 7221:         (undef,$udom,$uname)=split(/\//,$uri);
 7222:         if(defined($userdomain)) {
 7223:             $udom = $userdomain;
 7224:         }
 7225:         if(defined($username)) {
 7226:             $uname = $username;
 7227:         }
 7228:     }
 7229:     my ($dirRoot,$listing,@listing_results);
 7230: 
 7231:     $dirRoot = $perlvar{'lonDocRoot'};
 7232:     if (defined($getpropath)) {
 7233:         $dirRoot = &propath($udom,$uname);
 7234:         $dirRoot =~ s/\/$//;
 7235:     } elsif (defined($getuserdir)) {
 7236:         my $subdir=$uname.'__';
 7237:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 7238:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 7239:                    ."/$udom/$subdir/$uname";
 7240:     } elsif (defined($alternateRoot)) {
 7241:         $dirRoot = $alternateRoot;
 7242:     }
 7243: 
 7244:     if($udom) {
 7245:         if($uname) {
 7246:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 7247:                               .$getuserdir.':'.&escape($dirRoot)
 7248:                               .':'.&escape($uname).':'.&escape($udom),
 7249:                               &homeserver($uname,$udom));
 7250:             if ($listing eq 'unknown_cmd') {
 7251:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 7252:                                   &homeserver($uname,$udom));
 7253:             } else {
 7254:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7255:             }
 7256:             if ($listing eq 'unknown_cmd') {
 7257:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 7258: 				  &homeserver($uname,$udom));
 7259:                 @listing_results = split(/:/,$listing);
 7260:             } else {
 7261:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7262:             }
 7263:             return @listing_results;
 7264:         } elsif(!$alternateRoot) {
 7265:             my %allusers;
 7266: 	    my %servers = &get_servers($udom,'library');
 7267:  	    foreach my $tryserver (keys(%servers)) {
 7268:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 7269:                                   &escape($udom),$tryserver);
 7270:                 if ($listing eq 'unknown_cmd') {
 7271: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 7272: 				      $udom, $tryserver);
 7273:                 } else {
 7274:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 7275:                 }
 7276: 		if ($listing eq 'unknown_cmd') {
 7277: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 7278: 				      $udom, $tryserver);
 7279: 		    @listing_results = split(/:/,$listing);
 7280: 		} else {
 7281: 		    @listing_results =
 7282: 			map { &unescape($_); } split(/:/,$listing);
 7283: 		}
 7284: 		if ($listing_results[0] ne 'no_such_dir' && 
 7285: 		    $listing_results[0] ne 'empty'       &&
 7286: 		    $listing_results[0] ne 'con_lost') {
 7287: 		    foreach my $line (@listing_results) {
 7288: 			my ($entry) = split(/&/,$line,2);
 7289: 			$allusers{$entry} = 1;
 7290: 		    }
 7291: 		}
 7292:             }
 7293:             my $alluserstr='';
 7294:             foreach my $user (sort(keys(%allusers))) {
 7295:                 $alluserstr.=$user.'&user:';
 7296:             }
 7297:             $alluserstr=~s/:$//;
 7298:             return split(/:/,$alluserstr);
 7299:         } else {
 7300:             return ('missing user name');
 7301:         }
 7302:     } elsif(!defined($getpropath)) {
 7303:         my @all_domains = sort(&all_domains());
 7304:         foreach my $domain (@all_domains) {
 7305:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 7306:         }
 7307:         return @all_domains;
 7308:     } else {
 7309:         return ('missing domain');
 7310:     }
 7311: }
 7312: 
 7313: # --------------------------------------------- GetFileTimestamp
 7314: # This function utilizes dirlist and returns the date stamp for
 7315: # when it was last modified.  It will also return an error of -1
 7316: # if an error occurs
 7317: 
 7318: sub GetFileTimestamp {
 7319:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 7320:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 7321:     $studentName   = &LONCAPA::clean_username($studentName);
 7322:     my ($fileStat) = 
 7323:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 7324:                                  undef,$getuserdir);
 7325:     my @stats = split('&', $fileStat);
 7326:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7327:         # @stats contains first the filename, then the stat output
 7328:         return $stats[10]; # so this is 10 instead of 9.
 7329:     } else {
 7330:         return -1;
 7331:     }
 7332: }
 7333: 
 7334: sub stat_file {
 7335:     my ($uri) = @_;
 7336:     $uri = &clutter_with_no_wrapper($uri);
 7337: 
 7338:     my ($udom,$uname,$file);
 7339:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7340: 	($udom,$uname,$file) =
 7341: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7342: 	$file = 'userfiles/'.$file;
 7343:     }
 7344:     if ($uri =~ m-^/res/-) {
 7345: 	($udom,$uname) = 
 7346: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7347: 	$file = $uri;
 7348:     }
 7349: 
 7350:     if (!$udom || !$uname || !$file) {
 7351: 	# unable to handle the uri
 7352: 	return ();
 7353:     }
 7354:     my $getpropath;
 7355:     if ($file =~ /^userfiles\//) {
 7356:         $getpropath = 1;
 7357:     }
 7358:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7359:     my @stats = split('&', $result);
 7360:     
 7361:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7362: 	shift(@stats); #filename is first
 7363: 	return @stats;
 7364:     }
 7365:     return ();
 7366: }
 7367: 
 7368: # -------------------------------------------------------- Value of a Condition
 7369: 
 7370: # gets the value of a specific preevaluated condition
 7371: #    stored in the string  $env{user.state.<cid>}
 7372: # or looks up a condition reference in the bighash and if if hasn't
 7373: # already been evaluated recurses into docondval to get the value of
 7374: # the condition, then memoizing it to 
 7375: #   $env{user.state.<cid>.<condition>}
 7376: sub directcondval {
 7377:     my $number=shift;
 7378:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7379: 	&Apache::lonuserstate::evalstate();
 7380:     }
 7381:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7382: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7383:     } elsif ($number =~ /^_/) {
 7384: 	my $sub_condition;
 7385: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7386: 		&GDBM_READER(),0640)) {
 7387: 	    $sub_condition=$bighash{'conditions'.$number};
 7388: 	    untie(%bighash);
 7389: 	}
 7390: 	my $value = &docondval($sub_condition);
 7391: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7392: 	return $value;
 7393:     }
 7394:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7395:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7396:     } else {
 7397:        return 2;
 7398:     }
 7399: }
 7400: 
 7401: # get the collection of conditions for this resource
 7402: sub condval {
 7403:     my $condidx=shift;
 7404:     my $allpathcond='';
 7405:     foreach my $cond (split(/\|/,$condidx)) {
 7406: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7407: 	    $allpathcond.=
 7408: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7409: 	}
 7410:     }
 7411:     $allpathcond=~s/\|$//;
 7412:     return &docondval($allpathcond);
 7413: }
 7414: 
 7415: #evaluates an expression of conditions
 7416: sub docondval {
 7417:     my ($allpathcond) = @_;
 7418:     my $result=0;
 7419:     if ($env{'request.course.id'}
 7420: 	&& defined($allpathcond)) {
 7421: 	my $operand='|';
 7422: 	my @stack;
 7423: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7424: 	    if ($chunk eq '(') {
 7425: 		push @stack,($operand,$result);
 7426: 	    } elsif ($chunk eq ')') {
 7427: 		my $before=pop @stack;
 7428: 		if (pop @stack eq '&') {
 7429: 		    $result=$result>$before?$before:$result;
 7430: 		} else {
 7431: 		    $result=$result>$before?$result:$before;
 7432: 		}
 7433: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7434: 		$operand=$chunk;
 7435: 	    } else {
 7436: 		my $new=directcondval($chunk);
 7437: 		if ($operand eq '&') {
 7438: 		    $result=$result>$new?$new:$result;
 7439: 		} else {
 7440: 		    $result=$result>$new?$result:$new;
 7441: 		}
 7442: 	    }
 7443: 	}
 7444:     }
 7445:     return $result;
 7446: }
 7447: 
 7448: # ---------------------------------------------------- Devalidate courseresdata
 7449: 
 7450: sub devalidatecourseresdata {
 7451:     my ($coursenum,$coursedomain)=@_;
 7452:     my $hashid=$coursenum.':'.$coursedomain;
 7453:     &devalidate_cache_new('courseres',$hashid);
 7454: }
 7455: 
 7456: 
 7457: # --------------------------------------------------- Course Resourcedata Query
 7458: #
 7459: #  Parameters:
 7460: #      $coursenum    - Number of the course.
 7461: #      $coursedomain - Domain at which the course was created.
 7462: #  Returns:
 7463: #     A hash of the course parameters along (I think) with timestamps
 7464: #     and version info.
 7465: 
 7466: sub get_courseresdata {
 7467:     my ($coursenum,$coursedomain)=@_;
 7468:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7469:     my $hashid=$coursenum.':'.$coursedomain;
 7470:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7471:     my %dumpreply;
 7472:     unless (defined($cached)) {
 7473: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7474: 	$result=\%dumpreply;
 7475: 	my ($tmp) = keys(%dumpreply);
 7476: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7477: 	    &do_cache_new('courseres',$hashid,$result,600);
 7478: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7479: 	    return $tmp;
 7480: 	} elsif ($tmp =~ /^(error)/) {
 7481: 	    $result=undef;
 7482: 	    &do_cache_new('courseres',$hashid,$result,600);
 7483: 	}
 7484:     }
 7485:     return $result;
 7486: }
 7487: 
 7488: sub devalidateuserresdata {
 7489:     my ($uname,$udom)=@_;
 7490:     my $hashid="$udom:$uname";
 7491:     &devalidate_cache_new('userres',$hashid);
 7492: }
 7493: 
 7494: sub get_userresdata {
 7495:     my ($uname,$udom)=@_;
 7496:     #most student don\'t have any data set, check if there is some data
 7497:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7498: 
 7499:     my $hashid="$udom:$uname";
 7500:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7501:     if (!defined($cached)) {
 7502: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7503: 	$result=\%resourcedata;
 7504: 	&do_cache_new('userres',$hashid,$result,600);
 7505:     }
 7506:     my ($tmp)=keys(%$result);
 7507:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7508: 	return $result;
 7509:     }
 7510:     #error 2 occurs when the .db doesn't exist
 7511:     if ($tmp!~/error: 2 /) {
 7512: 	&logthis("<font color=\"blue\">WARNING:".
 7513: 		 " Trying to get resource data for ".
 7514: 		 $uname." at ".$udom.": ".
 7515: 		 $tmp."</font>");
 7516:     } elsif ($tmp=~/error: 2 /) {
 7517: 	#&EXT_cache_set($udom,$uname);
 7518: 	&do_cache_new('userres',$hashid,undef,600);
 7519: 	undef($tmp); # not really an error so don't send it back
 7520:     }
 7521:     return $tmp;
 7522: }
 7523: #----------------------------------------------- resdata - return resource data
 7524: #  Purpose:
 7525: #    Return resource data for either users or for a course.
 7526: #  Parameters:
 7527: #     $name      - Course/user name.
 7528: #     $domain    - Name of the domain the user/course is registered on.
 7529: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7530: #     @which     - Array of names of resources desired.
 7531: #  Returns:
 7532: #     The value of the first reasource in @which that is found in the
 7533: #     resource hash.
 7534: #  Exceptional Conditions:
 7535: #     If the $type passed in is not valid (not the string 'course' or 
 7536: #     'user', an undefined  reference is returned.
 7537: #     If none of the resources are found, an undef is returned
 7538: sub resdata {
 7539:     my ($name,$domain,$type,@which)=@_;
 7540:     my $result;
 7541:     if ($type eq 'course') {
 7542: 	$result=&get_courseresdata($name,$domain);
 7543:     } elsif ($type eq 'user') {
 7544: 	$result=&get_userresdata($name,$domain);
 7545:     }
 7546:     if (!ref($result)) { return $result; }    
 7547:     foreach my $item (@which) {
 7548: 	if (defined($result->{$item->[0]})) {
 7549: 	    return [$result->{$item->[0]},$item->[1]];
 7550: 	}
 7551:     }
 7552:     return undef;
 7553: }
 7554: 
 7555: #
 7556: # EXT resource caching routines
 7557: #
 7558: 
 7559: sub clear_EXT_cache_status {
 7560:     &delenv('cache.EXT.');
 7561: }
 7562: 
 7563: sub EXT_cache_status {
 7564:     my ($target_domain,$target_user) = @_;
 7565:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7566:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7567:         # We know already the user has no data
 7568:         return 1;
 7569:     } else {
 7570:         return 0;
 7571:     }
 7572: }
 7573: 
 7574: sub EXT_cache_set {
 7575:     my ($target_domain,$target_user) = @_;
 7576:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7577:     #&appenv({$cachename => time});
 7578: }
 7579: 
 7580: # --------------------------------------------------------- Value of a Variable
 7581: sub EXT {
 7582: 
 7583:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7584:     unless ($varname) { return ''; }
 7585:     #get real user name/domain, courseid and symb
 7586:     my $courseid;
 7587:     my $publicuser;
 7588:     if ($symbparm) {
 7589: 	$symbparm=&get_symb_from_alias($symbparm);
 7590:     }
 7591:     if (!($uname && $udom)) {
 7592:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7593:       if (!$symbparm) {	$symbparm=$cursymb; }
 7594:     } else {
 7595: 	$courseid=$env{'request.course.id'};
 7596:     }
 7597:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7598:     my $rest;
 7599:     if (defined($therest[0])) {
 7600:        $rest=join('.',@therest);
 7601:     } else {
 7602:        $rest='';
 7603:     }
 7604: 
 7605:     my $qualifierrest=$qualifier;
 7606:     if ($rest) { $qualifierrest.='.'.$rest; }
 7607:     my $spacequalifierrest=$space;
 7608:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7609:     if ($realm eq 'user') {
 7610: # --------------------------------------------------------------- user.resource
 7611: 	if ($space eq 'resource') {
 7612: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7613: 		  || defined($Apache::lonhomework::parsing_a_task))
 7614: 		 &&
 7615: 		 ($symbparm eq &symbread()) ) {	
 7616: 		# if we are in the middle of processing the resource the
 7617: 		# get the value we are planning on committing
 7618:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7619:                     return $Apache::lonhomework::results{$qualifierrest};
 7620:                 } else {
 7621:                     return $Apache::lonhomework::history{$qualifierrest};
 7622:                 }
 7623: 	    } else {
 7624: 		my %restored;
 7625: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7626: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7627: 		} else {
 7628: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7629: 		}
 7630: 		return $restored{$qualifierrest};
 7631: 	    }
 7632: # ----------------------------------------------------------------- user.access
 7633:         } elsif ($space eq 'access') {
 7634: 	    # FIXME - not supporting calls for a specific user
 7635:             return &allowed($qualifier,$rest);
 7636: # ------------------------------------------ user.preferences, user.environment
 7637:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7638: 	    if (($uname eq $env{'user.name'}) &&
 7639: 		($udom eq $env{'user.domain'})) {
 7640: 		return $env{join('.',('environment',$qualifierrest))};
 7641: 	    } else {
 7642: 		my %returnhash;
 7643: 		if (!$publicuser) {
 7644: 		    %returnhash=&userenvironment($udom,$uname,
 7645: 						 $qualifierrest);
 7646: 		}
 7647: 		return $returnhash{$qualifierrest};
 7648: 	    }
 7649: # ----------------------------------------------------------------- user.course
 7650:         } elsif ($space eq 'course') {
 7651: 	    # FIXME - not supporting calls for a specific user
 7652:             return $env{join('.',('request.course',$qualifier))};
 7653: # ------------------------------------------------------------------- user.role
 7654:         } elsif ($space eq 'role') {
 7655: 	    # FIXME - not supporting calls for a specific user
 7656:             my ($role,$where)=split(/\./,$env{'request.role'});
 7657:             if ($qualifier eq 'value') {
 7658: 		return $role;
 7659:             } elsif ($qualifier eq 'extent') {
 7660:                 return $where;
 7661:             }
 7662: # ----------------------------------------------------------------- user.domain
 7663:         } elsif ($space eq 'domain') {
 7664:             return $udom;
 7665: # ------------------------------------------------------------------- user.name
 7666:         } elsif ($space eq 'name') {
 7667:             return $uname;
 7668: # ---------------------------------------------------- Any other user namespace
 7669:         } else {
 7670: 	    my %reply;
 7671: 	    if (!$publicuser) {
 7672: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7673: 	    }
 7674: 	    return $reply{$qualifierrest};
 7675:         }
 7676:     } elsif ($realm eq 'query') {
 7677: # ---------------------------------------------- pull stuff out of query string
 7678:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7679: 						[$spacequalifierrest]);
 7680: 	return $env{'form.'.$spacequalifierrest}; 
 7681:    } elsif ($realm eq 'request') {
 7682: # ------------------------------------------------------------- request.browser
 7683:         if ($space eq 'browser') {
 7684: 	    if ($qualifier eq 'textremote') {
 7685: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7686: 		    return 1;
 7687: 		} else {
 7688: 		    return 0;
 7689: 		}
 7690: 	    } else {
 7691: 		return $env{'browser.'.$qualifier};
 7692: 	    }
 7693: # ------------------------------------------------------------ request.filename
 7694:         } else {
 7695:             return $env{'request.'.$spacequalifierrest};
 7696:         }
 7697:     } elsif ($realm eq 'course') {
 7698: # ---------------------------------------------------------- course.description
 7699:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7700:     } elsif ($realm eq 'resource') {
 7701: 
 7702: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7703: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7704: 	}
 7705: 
 7706: 	if ($space eq 'title') {
 7707: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7708: 	    return &gettitle($symbparm);
 7709: 	}
 7710: 	
 7711: 	if ($space eq 'map') {
 7712: 	    my ($map) = &decode_symb($symbparm);
 7713: 	    return &symbread($map);
 7714: 	}
 7715: 	if ($space eq 'filename') {
 7716: 	    if ($symbparm) {
 7717: 		return &clutter((&decode_symb($symbparm))[2]);
 7718: 	    }
 7719: 	    return &hreflocation('',$env{'request.filename'});
 7720: 	}
 7721: 
 7722: 	my ($section, $group, @groups);
 7723: 	my ($courselevelm,$courselevel);
 7724: 	if ($symbparm && defined($courseid) && 
 7725: 	    $courseid eq $env{'request.course.id'}) {
 7726: 
 7727: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7728: 
 7729: # ----------------------------------------------------- Cascading lookup scheme
 7730: 	    my $symbp=$symbparm;
 7731: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7732: 
 7733: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7734: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7735: 
 7736: 	    if (($env{'user.name'} eq $uname) &&
 7737: 		($env{'user.domain'} eq $udom)) {
 7738: 		$section=$env{'request.course.sec'};
 7739:                 @groups = split(/:/,$env{'request.course.groups'});  
 7740:                 @groups=&sort_course_groups($courseid,@groups); 
 7741: 	    } else {
 7742: 		if (! defined($usection)) {
 7743: 		    $section=&getsection($udom,$uname,$courseid);
 7744: 		} else {
 7745: 		    $section = $usection;
 7746: 		}
 7747:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7748: 	    }
 7749: 
 7750: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7751: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7752: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7753: 
 7754: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7755: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7756: 	    $courselevelm=$courseid.'.'.$mapparm;
 7757: 
 7758: # ----------------------------------------------------------- first, check user
 7759: 
 7760: 	    my $userreply=&resdata($uname,$udom,'user',
 7761: 				       ([$courselevelr,'resource'],
 7762: 					[$courselevelm,'map'     ],
 7763: 					[$courselevel, 'course'  ]));
 7764: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7765: 
 7766: # ------------------------------------------------ second, check some of course
 7767:             my $coursereply;
 7768:             if (@groups > 0) {
 7769:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7770:                                        $mapparm,$spacequalifierrest);
 7771:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7772:             }
 7773: 
 7774: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7775: 				  $env{'course.'.$courseid.'.domain'},
 7776: 				  'course',
 7777: 				  ([$seclevelr,   'resource'],
 7778: 				   [$seclevelm,   'map'     ],
 7779: 				   [$seclevel,    'course'  ],
 7780: 				   [$courselevelr,'resource']));
 7781: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7782: 
 7783: # ------------------------------------------------------ third, check map parms
 7784: 	    my %parmhash=();
 7785: 	    my $thisparm='';
 7786: 	    if (tie(%parmhash,'GDBM_File',
 7787: 		    $env{'request.course.fn'}.'_parms.db',
 7788: 		    &GDBM_READER(),0640)) {
 7789: 		$thisparm=$parmhash{$symbparm};
 7790: 		untie(%parmhash);
 7791: 	    }
 7792: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7793: 	}
 7794: # ------------------------------------------ fourth, look in resource metadata
 7795: 
 7796: 	$spacequalifierrest=~s/\./\_/;
 7797: 	my $filename;
 7798: 	if (!$symbparm) { $symbparm=&symbread(); }
 7799: 	if ($symbparm) {
 7800: 	    $filename=(&decode_symb($symbparm))[2];
 7801: 	} else {
 7802: 	    $filename=$env{'request.filename'};
 7803: 	}
 7804: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7805: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7806: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7807: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7808: 
 7809: # ---------------------------------------------- fourth, look in rest of course
 7810: 	if ($symbparm && defined($courseid) && 
 7811: 	    $courseid eq $env{'request.course.id'}) {
 7812: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7813: 				     $env{'course.'.$courseid.'.domain'},
 7814: 				     'course',
 7815: 				     ([$courselevelm,'map'   ],
 7816: 				      [$courselevel, 'course']));
 7817: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7818: 	}
 7819: # ------------------------------------------------------------------ Cascade up
 7820: 	unless ($space eq '0') {
 7821: 	    my @parts=split(/_/,$space);
 7822: 	    my $id=pop(@parts);
 7823: 	    my $part=join('_',@parts);
 7824: 	    if ($part eq '') { $part='0'; }
 7825: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7826: 				 $symbparm,$udom,$uname,$section,1);
 7827: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7828: 	}
 7829: 	if ($recurse) { return undef; }
 7830: 	my $pack_def=&packages_tab_default($filename,$varname);
 7831: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7832: # ---------------------------------------------------- Any other user namespace
 7833:     } elsif ($realm eq 'environment') {
 7834: # ----------------------------------------------------------------- environment
 7835: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7836: 	    return $env{'environment.'.$spacequalifierrest};
 7837: 	} else {
 7838: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7839: 		return '';
 7840: 	    }
 7841: 	    my %returnhash=&userenvironment($udom,$uname,
 7842: 					    $spacequalifierrest);
 7843: 	    return $returnhash{$spacequalifierrest};
 7844: 	}
 7845:     } elsif ($realm eq 'system') {
 7846: # ----------------------------------------------------------------- system.time
 7847: 	if ($space eq 'time') {
 7848: 	    return time;
 7849:         }
 7850:     } elsif ($realm eq 'server') {
 7851: # ----------------------------------------------------------------- system.time
 7852: 	if ($space eq 'name') {
 7853: 	    return $ENV{'SERVER_NAME'};
 7854:         }
 7855:     }
 7856:     return '';
 7857: }
 7858: 
 7859: sub get_reply {
 7860:     my ($reply_value) = @_;
 7861:     if (ref($reply_value) eq 'ARRAY') {
 7862:         if (wantarray) {
 7863: 	    return @$reply_value;
 7864:         }
 7865:         return $reply_value->[0];
 7866:     } else {
 7867:         return $reply_value;
 7868:     }
 7869: }
 7870: 
 7871: sub check_group_parms {
 7872:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7873:     my @groupitems = ();
 7874:     my $resultitem;
 7875:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7876:     foreach my $group (@{$groups}) {
 7877:         foreach my $level (@levels) {
 7878:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7879:              push(@groupitems,[$item,$level->[1]]);
 7880:         }
 7881:     }
 7882:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7883:                             $env{'course.'.$courseid.'.domain'},
 7884:                                      'course',@groupitems);
 7885:     return $coursereply;
 7886: }
 7887: 
 7888: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7889:     my ($courseid,@groups) = @_;
 7890:     @groups = sort(@groups);
 7891:     return @groups;
 7892: }
 7893: 
 7894: sub packages_tab_default {
 7895:     my ($uri,$varname)=@_;
 7896:     my (undef,$part,$name)=split(/\./,$varname);
 7897: 
 7898:     my (@extension,@specifics,$do_default);
 7899:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7900: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7901: 	if ($pack_type eq 'default') {
 7902: 	    $do_default=1;
 7903: 	} elsif ($pack_type eq 'extension') {
 7904: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7905: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7906: 	    # only look at packages defaults for packages that this id is
 7907: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7908: 	}
 7909:     }
 7910:     # first look for a package that matches the requested part id
 7911:     foreach my $package (@specifics) {
 7912: 	my (undef,$pack_type,$pack_part)=@{$package};
 7913: 	next if ($pack_part ne $part);
 7914: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7915: 	    return $packagetab{"$pack_type&$name&default"};
 7916: 	}
 7917:     }
 7918:     # look for any possible matching non extension_ package
 7919:     foreach my $package (@specifics) {
 7920: 	my (undef,$pack_type,$pack_part)=@{$package};
 7921: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7922: 	    return $packagetab{"$pack_type&$name&default"};
 7923: 	}
 7924: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7925: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7926: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7927: 	}
 7928:     }
 7929:     # look for any posible extension_ match
 7930:     foreach my $package (@extension) {
 7931: 	my ($package,$pack_type)=@{$package};
 7932: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7933: 	    return $packagetab{"$pack_type&$name&default"};
 7934: 	}
 7935: 	if (defined($packagetab{$package."&$name&default"})) {
 7936: 	    return $packagetab{$package."&$name&default"};
 7937: 	}
 7938:     }
 7939:     # look for a global default setting
 7940:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7941: 	return $packagetab{"default&$name&default"};
 7942:     }
 7943:     return undef;
 7944: }
 7945: 
 7946: sub add_prefix_and_part {
 7947:     my ($prefix,$part)=@_;
 7948:     my $keyroot;
 7949:     if (defined($prefix) && $prefix !~ /^__/) {
 7950: 	# prefix that has a part already
 7951: 	$keyroot=$prefix;
 7952:     } elsif (defined($prefix)) {
 7953: 	# prefix that is missing a part
 7954: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7955:     } else {
 7956: 	# no prefix at all
 7957: 	if (defined($part)) { $keyroot='_'.$part; }
 7958:     }
 7959:     return $keyroot;
 7960: }
 7961: 
 7962: # ---------------------------------------------------------------- Get metadata
 7963: 
 7964: my %metaentry;
 7965: sub metadata {
 7966:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7967:     $uri=&declutter($uri);
 7968:     # if it is a non metadata possible uri return quickly
 7969:     if (($uri eq '') || 
 7970: 	(($uri =~ m|^/*adm/|) && 
 7971: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7972:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7973: 	return undef;
 7974:     }
 7975:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7976: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7977: 	return undef;
 7978:     }
 7979:     my $filename=$uri;
 7980:     $uri=~s/\.meta$//;
 7981: #
 7982: # Is the metadata already cached?
 7983: # Look at timestamp of caching
 7984: # Everything is cached by the main uri, libraries are never directly cached
 7985: #
 7986:     if (!defined($liburi)) {
 7987: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7988: 	if (defined($cached)) { return $result->{':'.$what}; }
 7989:     }
 7990:     {
 7991: #
 7992: # Is this a recursive call for a library?
 7993: #
 7994: #	if (! exists($metacache{$uri})) {
 7995: #	    $metacache{$uri}={};
 7996: #	}
 7997: 	my $cachetime = 60*60;
 7998:         if ($liburi) {
 7999: 	    $liburi=&declutter($liburi);
 8000:             $filename=$liburi;
 8001:         } else {
 8002: 	    &devalidate_cache_new('meta',$uri);
 8003: 	    undef(%metaentry);
 8004: 	}
 8005:         my %metathesekeys=();
 8006:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 8007: 	my $metastring;
 8008: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 8009: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 8010: 	    $metastring = 
 8011: 		&Apache::lonnet::ssi_body($which,
 8012: 					  ('grade_target' => 'meta'));
 8013: 	    $cachetime = 1; # only want this cached in the child not long term
 8014: 	} elsif ($uri !~ m -^(editupload)/-) {
 8015: 	    my $file=&filelocation('',&clutter($filename));
 8016: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 8017: 	    $metastring=&getfile($file);
 8018: 	}
 8019:         my $parser=HTML::LCParser->new(\$metastring);
 8020:         my $token;
 8021:         undef %metathesekeys;
 8022:         while ($token=$parser->get_token) {
 8023: 	    if ($token->[0] eq 'S') {
 8024: 		if (defined($token->[2]->{'package'})) {
 8025: #
 8026: # This is a package - get package info
 8027: #
 8028: 		    my $package=$token->[2]->{'package'};
 8029: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8030: 		    if (defined($token->[2]->{'id'})) { 
 8031: 			$keyroot.='_'.$token->[2]->{'id'}; 
 8032: 		    }
 8033: 		    if ($metaentry{':packages'}) {
 8034: 			$metaentry{':packages'}.=','.$package.$keyroot;
 8035: 		    } else {
 8036: 			$metaentry{':packages'}=$package.$keyroot;
 8037: 		    }
 8038: 		    foreach my $pack_entry (keys(%packagetab)) {
 8039: 			my $part=$keyroot;
 8040: 			$part=~s/^\_//;
 8041: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 8042: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 8043: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 8044: 			    # ignore package.tab specified default values
 8045:                             # here &package_tab_default() will fetch those
 8046: 			    if ($subp eq 'default') { next; }
 8047: 			    my $value=$packagetab{$pack_entry};
 8048: 			    my $unikey;
 8049: 			    if ($pack =~ /_0$/) {
 8050: 				$unikey='parameter_0_'.$name;
 8051: 				$part=0;
 8052: 			    } else {
 8053: 				$unikey='parameter'.$keyroot.'_'.$name;
 8054: 			    }
 8055: 			    if ($subp eq 'display') {
 8056: 				$value.=' [Part: '.$part.']';
 8057: 			    }
 8058: 			    $metaentry{':'.$unikey.'.part'}=$part;
 8059: 			    $metathesekeys{$unikey}=1;
 8060: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8061: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 8062: 			    }
 8063: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 8064: 				$metaentry{':'.$unikey}=
 8065: 				    $metaentry{':'.$unikey.'.default'};
 8066: 			    }
 8067: 			}
 8068: 		    }
 8069: 		} else {
 8070: #
 8071: # This is not a package - some other kind of start tag
 8072: #
 8073: 		    my $entry=$token->[1];
 8074: 		    my $unikey;
 8075: 		    if ($entry eq 'import') {
 8076: 			$unikey='';
 8077: 		    } else {
 8078: 			$unikey=$entry;
 8079: 		    }
 8080: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8081: 
 8082: 		    if (defined($token->[2]->{'id'})) { 
 8083: 			$unikey.='_'.$token->[2]->{'id'}; 
 8084: 		    }
 8085: 
 8086: 		    if ($entry eq 'import') {
 8087: #
 8088: # Importing a library here
 8089: #
 8090: 			if ($depthcount<20) {
 8091: 			    my $location=$parser->get_text('/import');
 8092: 			    my $dir=$filename;
 8093: 			    $dir=~s|[^/]*$||;
 8094: 			    $location=&filelocation($dir,$location);
 8095: 			    my $metadata = 
 8096: 				&metadata($uri,'keys', $location,$unikey,
 8097: 					  $depthcount+1);
 8098: 			    foreach my $meta (split(',',$metadata)) {
 8099: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 8100: 				$metathesekeys{$meta}=1;
 8101: 			    }
 8102: 			}
 8103: 		    } else { 
 8104: 			
 8105: 			if (defined($token->[2]->{'name'})) { 
 8106: 			    $unikey.='_'.$token->[2]->{'name'}; 
 8107: 			}
 8108: 			$metathesekeys{$unikey}=1;
 8109: 			foreach my $param (@{$token->[3]}) {
 8110: 			    $metaentry{':'.$unikey.'.'.$param} =
 8111: 				$token->[2]->{$param};
 8112: 			}
 8113: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 8114: 			my $default=$metaentry{':'.$unikey.'.default'};
 8115: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 8116: 		 # only ws inside the tag, and not in default, so use default
 8117: 		 # as value
 8118: 			    $metaentry{':'.$unikey}=$default;
 8119: 			} elsif ( $internaltext =~ /\S/ ) {
 8120: 		  # something interesting inside the tag
 8121: 			    $metaentry{':'.$unikey}=$internaltext;
 8122: 			} else {
 8123: 		  # no interesting values, don't set a default
 8124: 			}
 8125: # end of not-a-package not-a-library import
 8126: 		    }
 8127: # end of not-a-package start tag
 8128: 		}
 8129: # the next is the end of "start tag"
 8130: 	    }
 8131: 	}
 8132: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 8133: 	$extension = lc($extension);
 8134: 	if ($extension eq 'htm') { $extension='html'; }
 8135: 
 8136: 	foreach my $key (keys(%packagetab)) {
 8137: 	    #no specific packages #how's our extension
 8138: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 8139: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 8140: 					 \%metathesekeys);
 8141: 	}
 8142: 
 8143: 	if (!exists($metaentry{':packages'})
 8144: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 8145: 	    foreach my $key (keys(%packagetab)) {
 8146: 		#no specific packages well let's get default then
 8147: 		if ($key!~/^default&/) { next; }
 8148: 		&metadata_create_package_def($uri,$key,'default',
 8149: 					     \%metathesekeys);
 8150: 	    }
 8151: 	}
 8152: # are there custom rights to evaluate
 8153: 	if ($metaentry{':copyright'} eq 'custom') {
 8154: 
 8155:     #
 8156:     # Importing a rights file here
 8157:     #
 8158: 	    unless ($depthcount) {
 8159: 		my $location=$metaentry{':customdistributionfile'};
 8160: 		my $dir=$filename;
 8161: 		$dir=~s|[^/]*$||;
 8162: 		$location=&filelocation($dir,$location);
 8163: 		my $rights_metadata =
 8164: 		    &metadata($uri,'keys',$location,'_rights',
 8165: 			      $depthcount+1);
 8166: 		foreach my $rights (split(',',$rights_metadata)) {
 8167: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 8168: 		    $metathesekeys{$rights}=1;
 8169: 		}
 8170: 	    }
 8171: 	}
 8172: 	# uniqifiy package listing
 8173: 	my %seen;
 8174: 	my @uniq_packages =
 8175: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 8176: 	$metaentry{':packages'} = join(',',@uniq_packages);
 8177: 
 8178: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 8179: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 8180: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 8181: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 8182: # this is the end of "was not already recently cached
 8183:     }
 8184:     return $metaentry{':'.$what};
 8185: }
 8186: 
 8187: sub metadata_create_package_def {
 8188:     my ($uri,$key,$package,$metathesekeys)=@_;
 8189:     my ($pack,$name,$subp)=split(/\&/,$key);
 8190:     if ($subp eq 'default') { next; }
 8191:     
 8192:     if (defined($metaentry{':packages'})) {
 8193: 	$metaentry{':packages'}.=','.$package;
 8194:     } else {
 8195: 	$metaentry{':packages'}=$package;
 8196:     }
 8197:     my $value=$packagetab{$key};
 8198:     my $unikey;
 8199:     $unikey='parameter_0_'.$name;
 8200:     $metaentry{':'.$unikey.'.part'}=0;
 8201:     $$metathesekeys{$unikey}=1;
 8202:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8203: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 8204:     }
 8205:     if (defined($metaentry{':'.$unikey.'.default'})) {
 8206: 	$metaentry{':'.$unikey}=
 8207: 	    $metaentry{':'.$unikey.'.default'};
 8208:     }
 8209: }
 8210: 
 8211: sub metadata_generate_part0 {
 8212:     my ($metadata,$metacache,$uri) = @_;
 8213:     my %allnames;
 8214:     foreach my $metakey (keys(%$metadata)) {
 8215: 	if ($metakey=~/^parameter\_(.*)/) {
 8216: 	  my $part=$$metacache{':'.$metakey.'.part'};
 8217: 	  my $name=$$metacache{':'.$metakey.'.name'};
 8218: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 8219: 	    $allnames{$name}=$part;
 8220: 	  }
 8221: 	}
 8222:     }
 8223:     foreach my $name (keys(%allnames)) {
 8224:       $$metadata{"parameter_0_$name"}=1;
 8225:       my $key=":parameter_0_$name";
 8226:       $$metacache{"$key.part"}='0';
 8227:       $$metacache{"$key.name"}=$name;
 8228:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 8229: 					   $allnames{$name}.'_'.$name.
 8230: 					   '.type'};
 8231:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 8232: 			     '.display'};
 8233:       my $expr='[Part: '.$allnames{$name}.']';
 8234:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 8235:       $$metacache{"$key.display"}=$olddis;
 8236:     }
 8237: }
 8238: 
 8239: # ------------------------------------------------------ Devalidate title cache
 8240: 
 8241: sub devalidate_title_cache {
 8242:     my ($url)=@_;
 8243:     if (!$env{'request.course.id'}) { return; }
 8244:     my $symb=&symbread($url);
 8245:     if (!$symb) { return; }
 8246:     my $key=$env{'request.course.id'}."\0".$symb;
 8247:     &devalidate_cache_new('title',$key);
 8248: }
 8249: 
 8250: # ------------------------------------------------- Get the title of a course
 8251: 
 8252: sub current_course_title {
 8253:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 8254: }
 8255: # ------------------------------------------------- Get the title of a resource
 8256: 
 8257: sub gettitle {
 8258:     my $urlsymb=shift;
 8259:     my $symb=&symbread($urlsymb);
 8260:     if ($symb) {
 8261: 	my $key=$env{'request.course.id'}."\0".$symb;
 8262: 	my ($result,$cached)=&is_cached_new('title',$key);
 8263: 	if (defined($cached)) { 
 8264: 	    return $result;
 8265: 	}
 8266: 	my ($map,$resid,$url)=&decode_symb($symb);
 8267: 	my $title='';
 8268: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 8269: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 8270: 	} else {
 8271: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8272: 		    &GDBM_READER(),0640)) {
 8273: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 8274: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 8275: 		untie(%bighash);
 8276: 	    }
 8277: 	}
 8278: 	$title=~s/\&colon\;/\:/gs;
 8279: 	if ($title) {
 8280: 	    return &do_cache_new('title',$key,$title,600);
 8281: 	}
 8282: 	$urlsymb=$url;
 8283:     }
 8284:     my $title=&metadata($urlsymb,'title');
 8285:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 8286:     return $title;
 8287: }
 8288: 
 8289: sub get_slot {
 8290:     my ($which,$cnum,$cdom)=@_;
 8291:     if (!$cnum || !$cdom) {
 8292: 	(undef,my $courseid)=&whichuser();
 8293: 	$cdom=$env{'course.'.$courseid.'.domain'};
 8294: 	$cnum=$env{'course.'.$courseid.'.num'};
 8295:     }
 8296:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 8297:     my %slotinfo;
 8298:     if (exists($remembered{$key})) {
 8299: 	$slotinfo{$which} = $remembered{$key};
 8300:     } else {
 8301: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 8302: 	&Apache::lonhomework::showhash(%slotinfo);
 8303: 	my ($tmp)=keys(%slotinfo);
 8304: 	if ($tmp=~/^error:/) { return (); }
 8305: 	$remembered{$key} = $slotinfo{$which};
 8306:     }
 8307:     if (ref($slotinfo{$which}) eq 'HASH') {
 8308: 	return %{$slotinfo{$which}};
 8309:     }
 8310:     return $slotinfo{$which};
 8311: }
 8312: # ------------------------------------------------- Update symbolic store links
 8313: 
 8314: sub symblist {
 8315:     my ($mapname,%newhash)=@_;
 8316:     $mapname=&deversion(&declutter($mapname));
 8317:     my %hash;
 8318:     if (($env{'request.course.fn'}) && (%newhash)) {
 8319:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8320:                       &GDBM_WRCREAT(),0640)) {
 8321: 	    foreach my $url (keys(%newhash)) {
 8322: 		next if ($url eq 'last_known'
 8323: 			 && $env{'form.no_update_last_known'});
 8324: 		$hash{declutter($url)}=&encode_symb($mapname,
 8325: 						    $newhash{$url}->[1],
 8326: 						    $newhash{$url}->[0]);
 8327:             }
 8328:             if (untie(%hash)) {
 8329: 		return 'ok';
 8330:             }
 8331:         }
 8332:     }
 8333:     return 'error';
 8334: }
 8335: 
 8336: # --------------------------------------------------------------- Verify a symb
 8337: 
 8338: sub symbverify {
 8339:     my ($symb,$thisurl)=@_;
 8340:     my $thisfn=$thisurl;
 8341:     $thisfn=&declutter($thisfn);
 8342: # direct jump to resource in page or to a sequence - will construct own symbs
 8343:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8344: # check URL part
 8345:     my ($map,$resid,$url)=&decode_symb($symb);
 8346: 
 8347:     unless ($url eq $thisfn) { return 0; }
 8348: 
 8349:     $symb=&symbclean($symb);
 8350:     $thisurl=&deversion($thisurl);
 8351:     $thisfn=&deversion($thisfn);
 8352: 
 8353:     my %bighash;
 8354:     my $okay=0;
 8355: 
 8356:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8357:                             &GDBM_READER(),0640)) {
 8358:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 8359:             $thisurl =~ s/\?.+$//;
 8360:         }
 8361:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8362:         unless ($ids) { 
 8363:            $ids=$bighash{'ids_/'.$thisurl};
 8364:         }
 8365:         if ($ids) {
 8366: # ------------------------------------------------------------------- Has ID(s)
 8367: 	    foreach my $id (split(/\,/,$ids)) {
 8368: 	       my ($mapid,$resid)=split(/\./,$id);
 8369:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 8370:                    $symb =~ s/\?.+$//;
 8371:                }
 8372:                if (
 8373:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8374:    eq $symb) { 
 8375: 		   if (($env{'request.role.adv'}) ||
 8376: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8377: 		       $okay=1; 
 8378: 		   }
 8379: 	       }
 8380: 	   }
 8381:         }
 8382: 	untie(%bighash);
 8383:     }
 8384:     return $okay;
 8385: }
 8386: 
 8387: # --------------------------------------------------------------- Clean-up symb
 8388: 
 8389: sub symbclean {
 8390:     my $symb=shift;
 8391:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8392: # remove version from map
 8393:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8394: 
 8395: # remove version from URL
 8396:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8397: 
 8398: # remove wrapper
 8399: 
 8400:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8401:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8402:     return $symb;
 8403: }
 8404: 
 8405: # ---------------------------------------------- Split symb to find map and url
 8406: 
 8407: sub encode_symb {
 8408:     my ($map,$resid,$url)=@_;
 8409:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8410: }
 8411: 
 8412: sub decode_symb {
 8413:     my $symb=shift;
 8414:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8415:     my ($map,$resid,$url)=split(/___/,$symb);
 8416:     return (&fixversion($map),$resid,&fixversion($url));
 8417: }
 8418: 
 8419: sub fixversion {
 8420:     my $fn=shift;
 8421:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8422:     my %bighash;
 8423:     my $uri=&clutter($fn);
 8424:     my $key=$env{'request.course.id'}.'_'.$uri;
 8425: # is this cached?
 8426:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8427:     if (defined($cached)) { return $result; }
 8428: # unfortunately not cached, or expired
 8429:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8430: 	    &GDBM_READER(),0640)) {
 8431:  	if ($bighash{'version_'.$uri}) {
 8432:  	    my $version=$bighash{'version_'.$uri};
 8433:  	    unless (($version eq 'mostrecent') || 
 8434: 		    ($version==&getversion($uri))) {
 8435:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8436:  	    }
 8437:  	}
 8438:  	untie %bighash;
 8439:     }
 8440:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8441: }
 8442: 
 8443: sub deversion {
 8444:     my $url=shift;
 8445:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8446:     return $url;
 8447: }
 8448: 
 8449: # ------------------------------------------------------ Return symb list entry
 8450: 
 8451: sub symbread {
 8452:     my ($thisfn,$donotrecurse)=@_;
 8453:     my $cache_str='request.symbread.cached.'.$thisfn;
 8454:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8455: # no filename provided? try from environment
 8456:     unless ($thisfn) {
 8457:         if ($env{'request.symb'}) {
 8458: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8459: 	}
 8460: 	$thisfn=$env{'request.filename'};
 8461:     }
 8462:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8463: # is that filename actually a symb? Verify, clean, and return
 8464:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8465: 	if (&symbverify($thisfn,$1)) {
 8466: 	    return $env{$cache_str}=&symbclean($thisfn);
 8467: 	}
 8468:     }
 8469:     $thisfn=declutter($thisfn);
 8470:     my %hash;
 8471:     my %bighash;
 8472:     my $syval='';
 8473:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8474:         my $targetfn = $thisfn;
 8475:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8476:             $targetfn = 'adm/wrapper/'.$thisfn;
 8477:         }
 8478: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8479: 	    $targetfn=$1;
 8480: 	}
 8481:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8482:                       &GDBM_READER(),0640)) {
 8483: 	    $syval=$hash{$targetfn};
 8484:             untie(%hash);
 8485:         }
 8486: # ---------------------------------------------------------- There was an entry
 8487:         if ($syval) {
 8488: 	    #unless ($syval=~/\_\d+$/) {
 8489: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8490: 		    #&appenv({'request.ambiguous' => $thisfn});
 8491: 		    #return $env{$cache_str}='';
 8492: 		#}    
 8493: 		#$syval.=$1;
 8494: 	    #}
 8495:         } else {
 8496: # ------------------------------------------------------- Was not in symb table
 8497:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8498:                             &GDBM_READER(),0640)) {
 8499: # ---------------------------------------------- Get ID(s) for current resource
 8500:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8501:               unless ($ids) { 
 8502:                  $ids=$bighash{'ids_/'.$thisfn};
 8503:               }
 8504:               unless ($ids) {
 8505: # alias?
 8506: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8507:               }
 8508:               if ($ids) {
 8509: # ------------------------------------------------------------------- Has ID(s)
 8510:                  my @possibilities=split(/\,/,$ids);
 8511:                  if ($#possibilities==0) {
 8512: # ----------------------------------------------- There is only one possibility
 8513: 		     my ($mapid,$resid)=split(/\./,$ids);
 8514: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8515: 						    $resid,$thisfn);
 8516:                  } elsif (!$donotrecurse) {
 8517: # ------------------------------------------ There is more than one possibility
 8518:                      my $realpossible=0;
 8519:                      foreach my $id (@possibilities) {
 8520: 			 my $file=$bighash{'src_'.$id};
 8521:                          if (&allowed('bre',$file)) {
 8522:          		    my ($mapid,$resid)=split(/\./,$id);
 8523:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8524: 				$realpossible++;
 8525:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8526: 						    $resid,$thisfn);
 8527:                             }
 8528: 			 }
 8529:                      }
 8530: 		     if ($realpossible!=1) { $syval=''; }
 8531:                  } else {
 8532:                      $syval='';
 8533:                  }
 8534: 	      }
 8535:               untie(%bighash)
 8536:            }
 8537:         }
 8538:         if ($syval) {
 8539: 	    return $env{$cache_str}=$syval;
 8540:         }
 8541:     }
 8542:     &appenv({'request.ambiguous' => $thisfn});
 8543:     return $env{$cache_str}='';
 8544: }
 8545: 
 8546: # ---------------------------------------------------------- Return random seed
 8547: 
 8548: sub numval {
 8549:     my $txt=shift;
 8550:     $txt=~tr/A-J/0-9/;
 8551:     $txt=~tr/a-j/0-9/;
 8552:     $txt=~tr/K-T/0-9/;
 8553:     $txt=~tr/k-t/0-9/;
 8554:     $txt=~tr/U-Z/0-5/;
 8555:     $txt=~tr/u-z/0-5/;
 8556:     $txt=~s/\D//g;
 8557:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8558:     return int($txt);
 8559: }
 8560: 
 8561: sub numval2 {
 8562:     my $txt=shift;
 8563:     $txt=~tr/A-J/0-9/;
 8564:     $txt=~tr/a-j/0-9/;
 8565:     $txt=~tr/K-T/0-9/;
 8566:     $txt=~tr/k-t/0-9/;
 8567:     $txt=~tr/U-Z/0-5/;
 8568:     $txt=~tr/u-z/0-5/;
 8569:     $txt=~s/\D//g;
 8570:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8571:     my $total;
 8572:     foreach my $val (@txts) { $total+=$val; }
 8573:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8574:     return int($total);
 8575: }
 8576: 
 8577: sub numval3 {
 8578:     use integer;
 8579:     my $txt=shift;
 8580:     $txt=~tr/A-J/0-9/;
 8581:     $txt=~tr/a-j/0-9/;
 8582:     $txt=~tr/K-T/0-9/;
 8583:     $txt=~tr/k-t/0-9/;
 8584:     $txt=~tr/U-Z/0-5/;
 8585:     $txt=~tr/u-z/0-5/;
 8586:     $txt=~s/\D//g;
 8587:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8588:     my $total;
 8589:     foreach my $val (@txts) { $total+=$val; }
 8590:     if ($_64bit) { $total=(($total<<32)>>32); }
 8591:     return $total;
 8592: }
 8593: 
 8594: sub digest {
 8595:     my ($data)=@_;
 8596:     my $digest=&Digest::MD5::md5($data);
 8597:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8598:     my ($e,$f);
 8599:     {
 8600:         use integer;
 8601:         $e=($a+$b);
 8602:         $f=($c+$d);
 8603:         if ($_64bit) {
 8604:             $e=(($e<<32)>>32);
 8605:             $f=(($f<<32)>>32);
 8606:         }
 8607:     }
 8608:     if (wantarray) {
 8609: 	return ($e,$f);
 8610:     } else {
 8611: 	my $g;
 8612: 	{
 8613: 	    use integer;
 8614: 	    $g=($e+$f);
 8615: 	    if ($_64bit) {
 8616: 		$g=(($g<<32)>>32);
 8617: 	    }
 8618: 	}
 8619: 	return $g;
 8620:     }
 8621: }
 8622: 
 8623: sub latest_rnd_algorithm_id {
 8624:     return '64bit5';
 8625: }
 8626: 
 8627: sub get_rand_alg {
 8628:     my ($courseid)=@_;
 8629:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8630:     if ($courseid) {
 8631: 	return $env{"course.$courseid.rndseed"};
 8632:     }
 8633:     return &latest_rnd_algorithm_id();
 8634: }
 8635: 
 8636: sub validCODE {
 8637:     my ($CODE)=@_;
 8638:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8639:     return 0;
 8640: }
 8641: 
 8642: sub getCODE {
 8643:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8644:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8645: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8646: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8647: 	return $Apache::lonhomework::history{'resource.CODE'};
 8648:     }
 8649:     return undef;
 8650: }
 8651: 
 8652: sub rndseed {
 8653:     my ($symb,$courseid,$domain,$username)=@_;
 8654:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8655:     if (!defined($symb)) {
 8656: 	unless ($symb=$wsymb) { return time; }
 8657:     }
 8658:     if (!$courseid) { $courseid=$wcourseid; }
 8659:     if (!$domain) { $domain=$wdomain; }
 8660:     if (!$username) { $username=$wusername }
 8661:     my $which=&get_rand_alg();
 8662: 
 8663:     if (defined(&getCODE())) {
 8664: 	if ($which eq '64bit5') {
 8665: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8666: 	} elsif ($which eq '64bit4') {
 8667: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8668: 	} else {
 8669: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8670: 	}
 8671:     } elsif ($which eq '64bit5') {
 8672: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8673:     } elsif ($which eq '64bit4') {
 8674: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8675:     } elsif ($which eq '64bit3') {
 8676: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8677:     } elsif ($which eq '64bit2') {
 8678: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8679:     } elsif ($which eq '64bit') {
 8680: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8681:     }
 8682:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8683: }
 8684: 
 8685: sub rndseed_32bit {
 8686:     my ($symb,$courseid,$domain,$username)=@_;
 8687:     {
 8688: 	use integer;
 8689: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8690: 	my $symbseed=numval($symb) << 22;
 8691: 	my $namechck=unpack("%32C*",$username) << 17;
 8692: 	my $nameseed=numval($username) << 12;
 8693: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8694: 	my $courseseed=unpack("%32C*",$courseid);
 8695: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8696: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8697: 	#&logthis("rndseed :$num:$symb");
 8698: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8699: 	return $num;
 8700:     }
 8701: }
 8702: 
 8703: sub rndseed_64bit {
 8704:     my ($symb,$courseid,$domain,$username)=@_;
 8705:     {
 8706: 	use integer;
 8707: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8708: 	my $symbseed=numval($symb) << 10;
 8709: 	my $namechck=unpack("%32S*",$username);
 8710: 	
 8711: 	my $nameseed=numval($username) << 21;
 8712: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8713: 	my $courseseed=unpack("%32S*",$courseid);
 8714: 	
 8715: 	my $num1=$symbchck+$symbseed+$namechck;
 8716: 	my $num2=$nameseed+$domainseed+$courseseed;
 8717: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8718: 	#&logthis("rndseed :$num:$symb");
 8719: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8720: 	return "$num1,$num2";
 8721:     }
 8722: }
 8723: 
 8724: sub rndseed_64bit2 {
 8725:     my ($symb,$courseid,$domain,$username)=@_;
 8726:     {
 8727: 	use integer;
 8728: 	# strings need to be an even # of cahracters long, it it is odd the
 8729:         # last characters gets thrown away
 8730: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8731: 	my $symbseed=numval($symb) << 10;
 8732: 	my $namechck=unpack("%32S*",$username.' ');
 8733: 	
 8734: 	my $nameseed=numval($username) << 21;
 8735: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8736: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8737: 	
 8738: 	my $num1=$symbchck+$symbseed+$namechck;
 8739: 	my $num2=$nameseed+$domainseed+$courseseed;
 8740: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8741: 	#&logthis("rndseed :$num:$symb");
 8742: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8743: 	return "$num1,$num2";
 8744:     }
 8745: }
 8746: 
 8747: sub rndseed_64bit3 {
 8748:     my ($symb,$courseid,$domain,$username)=@_;
 8749:     {
 8750: 	use integer;
 8751: 	# strings need to be an even # of cahracters long, it it is odd the
 8752:         # last characters gets thrown away
 8753: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8754: 	my $symbseed=numval2($symb) << 10;
 8755: 	my $namechck=unpack("%32S*",$username.' ');
 8756: 	
 8757: 	my $nameseed=numval2($username) << 21;
 8758: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8759: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8760: 	
 8761: 	my $num1=$symbchck+$symbseed+$namechck;
 8762: 	my $num2=$nameseed+$domainseed+$courseseed;
 8763: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8764: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8765: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8766: 	
 8767: 	return "$num1:$num2";
 8768:     }
 8769: }
 8770: 
 8771: sub rndseed_64bit4 {
 8772:     my ($symb,$courseid,$domain,$username)=@_;
 8773:     {
 8774: 	use integer;
 8775: 	# strings need to be an even # of cahracters long, it it is odd the
 8776:         # last characters gets thrown away
 8777: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8778: 	my $symbseed=numval3($symb) << 10;
 8779: 	my $namechck=unpack("%32S*",$username.' ');
 8780: 	
 8781: 	my $nameseed=numval3($username) << 21;
 8782: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8783: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8784: 	
 8785: 	my $num1=$symbchck+$symbseed+$namechck;
 8786: 	my $num2=$nameseed+$domainseed+$courseseed;
 8787: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8788: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8789: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8790: 	
 8791: 	return "$num1:$num2";
 8792:     }
 8793: }
 8794: 
 8795: sub rndseed_64bit5 {
 8796:     my ($symb,$courseid,$domain,$username)=@_;
 8797:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8798:     return "$num1:$num2";
 8799: }
 8800: 
 8801: sub rndseed_CODE_64bit {
 8802:     my ($symb,$courseid,$domain,$username)=@_;
 8803:     {
 8804: 	use integer;
 8805: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8806: 	my $symbseed=numval2($symb);
 8807: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8808: 	my $CODEseed=numval(&getCODE());
 8809: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8810: 	my $num1=$symbseed+$CODEchck;
 8811: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8812: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8813: 	#&logthis("rndseed :$num1:$num2:$symb");
 8814: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8815: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8816: 	return "$num1:$num2";
 8817:     }
 8818: }
 8819: 
 8820: sub rndseed_CODE_64bit4 {
 8821:     my ($symb,$courseid,$domain,$username)=@_;
 8822:     {
 8823: 	use integer;
 8824: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8825: 	my $symbseed=numval3($symb);
 8826: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8827: 	my $CODEseed=numval3(&getCODE());
 8828: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8829: 	my $num1=$symbseed+$CODEchck;
 8830: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8831: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8832: 	#&logthis("rndseed :$num1:$num2:$symb");
 8833: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8834: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8835: 	return "$num1:$num2";
 8836:     }
 8837: }
 8838: 
 8839: sub rndseed_CODE_64bit5 {
 8840:     my ($symb,$courseid,$domain,$username)=@_;
 8841:     my $code = &getCODE();
 8842:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8843:     return "$num1:$num2";
 8844: }
 8845: 
 8846: sub setup_random_from_rndseed {
 8847:     my ($rndseed)=@_;
 8848:     if ($rndseed =~/([,:])/) {
 8849: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8850: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8851:     } else {
 8852: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8853:     }
 8854: }
 8855: 
 8856: sub latest_receipt_algorithm_id {
 8857:     return 'receipt3';
 8858: }
 8859: 
 8860: sub recunique {
 8861:     my $fucourseid=shift;
 8862:     my $unique;
 8863:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8864: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8865: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8866:     } else {
 8867: 	$unique=$perlvar{'lonReceipt'};
 8868:     }
 8869:     return unpack("%32C*",$unique);
 8870: }
 8871: 
 8872: sub recprefix {
 8873:     my $fucourseid=shift;
 8874:     my $prefix;
 8875:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8876: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8877: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8878:     } else {
 8879: 	$prefix=$perlvar{'lonHostID'};
 8880:     }
 8881:     return unpack("%32C*",$prefix);
 8882: }
 8883: 
 8884: sub ireceipt {
 8885:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8886: 
 8887:     my $return =&recprefix($fucourseid).'-';
 8888: 
 8889:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8890: 	$env{'request.state'} eq 'construct') {
 8891: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8892: 	return $return;
 8893:     }
 8894: 
 8895:     my $cuname=unpack("%32C*",$funame);
 8896:     my $cudom=unpack("%32C*",$fudom);
 8897:     my $cucourseid=unpack("%32C*",$fucourseid);
 8898:     my $cusymb=unpack("%32C*",$fusymb);
 8899:     my $cunique=&recunique($fucourseid);
 8900:     my $cpart=unpack("%32S*",$part);
 8901:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8902: 
 8903: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8904: 			       
 8905: 	$return.= ($cunique%$cuname+
 8906: 		   $cunique%$cudom+
 8907: 		   $cusymb%$cuname+
 8908: 		   $cusymb%$cudom+
 8909: 		   $cucourseid%$cuname+
 8910: 		   $cucourseid%$cudom+
 8911: 		   $cpart%$cuname+
 8912: 		   $cpart%$cudom);
 8913:     } else {
 8914: 	$return.= ($cunique%$cuname+
 8915: 		   $cunique%$cudom+
 8916: 		   $cusymb%$cuname+
 8917: 		   $cusymb%$cudom+
 8918: 		   $cucourseid%$cuname+
 8919: 		   $cucourseid%$cudom);
 8920:     }
 8921:     return $return;
 8922: }
 8923: 
 8924: sub receipt {
 8925:     my ($part)=@_;
 8926:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8927:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8928: }
 8929: 
 8930: sub whichuser {
 8931:     my ($passedsymb)=@_;
 8932:     my ($symb,$courseid,$domain,$name,$publicuser);
 8933:     if (defined($env{'form.grade_symb'})) {
 8934: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8935: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8936: 	if (!$allowed &&
 8937: 	    exists($env{'request.course.sec'}) &&
 8938: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8939: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8940: 			      '/'.$env{'request.course.sec'});
 8941: 	}
 8942: 	if ($allowed) {
 8943: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8944: 	    $courseid=$tmp_courseid;
 8945: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8946: 	    ($name)=&get_env_multiple('form.grade_username');
 8947: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8948: 	}
 8949:     }
 8950:     if (!$passedsymb) {
 8951: 	$symb=&symbread();
 8952:     } else {
 8953: 	$symb=$passedsymb;
 8954:     }
 8955:     $courseid=$env{'request.course.id'};
 8956:     $domain=$env{'user.domain'};
 8957:     $name=$env{'user.name'};
 8958:     if ($name eq 'public' && $domain eq 'public') {
 8959: 	if (!defined($env{'form.username'})) {
 8960: 	    $env{'form.username'}.=time.rand(10000000);
 8961: 	}
 8962: 	$name.=$env{'form.username'};
 8963:     }
 8964:     return ($symb,$courseid,$domain,$name,$publicuser);
 8965: 
 8966: }
 8967: 
 8968: # ------------------------------------------------------------ Serves up a file
 8969: # returns either the contents of the file or 
 8970: # -1 if the file doesn't exist
 8971: #
 8972: # if the target is a file that was uploaded via DOCS, 
 8973: # a check will be made to see if a current copy exists on the local server,
 8974: # if it does this will be served, otherwise a copy will be retrieved from
 8975: # the home server for the course and stored in /home/httpd/html/userfiles on
 8976: # the local server.   
 8977: 
 8978: sub getfile {
 8979:     my ($file) = @_;
 8980:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8981:     &repcopy($file);
 8982:     return &readfile($file);
 8983: }
 8984: 
 8985: sub repcopy_userfile {
 8986:     my ($file)=@_;
 8987:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8988:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8989:     my ($cdom,$cnum,$filename) = 
 8990: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8991:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8992:     if (-e "$file") {
 8993: # we already have a local copy, check it out
 8994: 	my @fileinfo = stat($file);
 8995: 	my $rtncode;
 8996: 	my $info;
 8997: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8998: 	if ($lwpresp ne 'ok') {
 8999: # there is no such file anymore, even though we had a local copy
 9000: 	    if ($rtncode eq '404') {
 9001: 		unlink($file);
 9002: 	    }
 9003: 	    return -1;
 9004: 	}
 9005: 	if ($info < $fileinfo[9]) {
 9006: # nice, the file we have is up-to-date, just say okay
 9007: 	    return 'ok';
 9008: 	} else {
 9009: # the file is outdated, get rid of it
 9010: 	    unlink($file);
 9011: 	}
 9012:     }
 9013: # one way or the other, at this point, we don't have the file
 9014: # construct the correct path for the file
 9015:     my @parts = ($cdom,$cnum); 
 9016:     if ($filename =~ m|^(.+)/[^/]+$|) {
 9017: 	push @parts, split(/\//,$1);
 9018:     }
 9019:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 9020:     foreach my $part (@parts) {
 9021: 	$path .= '/'.$part;
 9022: 	if (!-e $path) {
 9023: 	    mkdir($path,0770);
 9024: 	}
 9025:     }
 9026: # now the path exists for sure
 9027: # get a user agent
 9028:     my $ua=new LWP::UserAgent;
 9029:     my $transferfile=$file.'.in.transfer';
 9030: # FIXME: this should flock
 9031:     if (-e $transferfile) { return 'ok'; }
 9032:     my $request;
 9033:     $uri=~s/^\///;
 9034:     my $homeserver = &homeserver($cnum,$cdom);
 9035:     my $protocol = $protocol{$homeserver};
 9036:     $protocol = 'http' if ($protocol ne 'https');
 9037:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 9038:     my $response=$ua->request($request,$transferfile);
 9039: # did it work?
 9040:     if ($response->is_error()) {
 9041: 	unlink($transferfile);
 9042: 	&logthis("Userfile repcopy failed for $uri");
 9043: 	return -1;
 9044:     }
 9045: # worked, rename the transfer file
 9046:     rename($transferfile,$file);
 9047:     return 'ok';
 9048: }
 9049: 
 9050: sub tokenwrapper {
 9051:     my $uri=shift;
 9052:     $uri=~s|^https?\://([^/]+)||;
 9053:     $uri=~s|^/||;
 9054:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 9055:     my $token=$1;
 9056:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 9057:     if ($udom && $uname && $file) {
 9058: 	$file=~s|(\?\.*)*$||;
 9059:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 9060:         my $homeserver = &homeserver($uname,$udom);
 9061:         my $protocol = $protocol{$homeserver};
 9062:         $protocol = 'http' if ($protocol ne 'https');
 9063:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 9064:                (($uri=~/\?/)?'&':'?').'token='.$token.
 9065:                                '&tokenissued='.$perlvar{'lonHostID'};
 9066:     } else {
 9067:         return '/adm/notfound.html';
 9068:     }
 9069: }
 9070: 
 9071: # call with reqtype HEAD: get last modification time
 9072: # call with reqtype GET: get the file contents
 9073: # Do not call this with reqtype GET for large files! It loads everything into memory
 9074: #
 9075: sub getuploaded {
 9076:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 9077:     $uri=~s/^\///;
 9078:     my $homeserver = &homeserver($cnum,$cdom);
 9079:     my $protocol = $protocol{$homeserver};
 9080:     $protocol = 'http' if ($protocol ne 'https');
 9081:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 9082:     my $ua=new LWP::UserAgent;
 9083:     my $request=new HTTP::Request($reqtype,$uri);
 9084:     my $response=$ua->request($request);
 9085:     $$rtncode = $response->code;
 9086:     if (! $response->is_success()) {
 9087: 	return 'failed';
 9088:     }      
 9089:     if ($reqtype eq 'HEAD') {
 9090: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 9091:     } elsif ($reqtype eq 'GET') {
 9092: 	$$info = $response->content;
 9093:     }
 9094:     return 'ok';
 9095: }
 9096: 
 9097: sub readfile {
 9098:     my $file = shift;
 9099:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 9100:     my $fh;
 9101:     open($fh,"<$file");
 9102:     my $a='';
 9103:     while (my $line = <$fh>) { $a .= $line; }
 9104:     return $a;
 9105: }
 9106: 
 9107: sub filelocation {
 9108:     my ($dir,$file) = @_;
 9109:     my $location;
 9110:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 9111: 
 9112:     if ($file =~ m-^/adm/-) {
 9113: 	$file=~s-^/adm/wrapper/-/-;
 9114: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9115:     }
 9116: 
 9117:     if ($file=~m:^/~:) { # is a contruction space reference
 9118:         $location = $file;
 9119:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 9120:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 9121: 	# is a correct contruction space reference
 9122:         $location = $file;
 9123:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 9124:         $location = $file;
 9125:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 9126:         my ($udom,$uname,$filename)=
 9127:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 9128:         my $home=&homeserver($uname,$udom);
 9129:         my $is_me=0;
 9130:         my @ids=&current_machine_ids();
 9131:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 9132:         if ($is_me) {
 9133:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 9134:         } else {
 9135:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 9136:   	      $udom.'/'.$uname.'/'.$filename;
 9137:         }
 9138:     } elsif ($file =~ m-^/adm/-) {
 9139: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 9140:     } else {
 9141:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9142:         $file=~s:^/res/:/:;
 9143:         if ( !( $file =~ m:^/:) ) {
 9144:             $location = $dir. '/'.$file;
 9145:         } else {
 9146:             $location = '/home/httpd/html/res'.$file;
 9147:         }
 9148:     }
 9149:     $location=~s://+:/:g; # remove duplicate /
 9150:     while ($location=~m{/\.\./}) {
 9151: 	if ($location =~ m{/[^/]+/\.\./}) {
 9152: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 9153: 	} else {
 9154: 	    $location=~ s{/\.\./}{/}g;
 9155: 	}
 9156:     } #remove dir/..
 9157:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 9158:     return $location;
 9159: }
 9160: 
 9161: sub hreflocation {
 9162:     my ($dir,$file)=@_;
 9163:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 9164: 	$file=filelocation($dir,$file);
 9165:     } elsif ($file=~m-^/adm/-) {
 9166: 	$file=~s-^/adm/wrapper/-/-;
 9167: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9168:     }
 9169:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 9170: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 9171:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 9172: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 9173:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 9174: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 9175: 	    -/uploaded/$1/$2/-x;
 9176:     }
 9177:     if ($file=~ m{^/userfiles/}) {
 9178: 	$file =~ s{^/userfiles/}{/uploaded/};
 9179:     }
 9180:     return $file;
 9181: }
 9182: 
 9183: sub current_machine_domains {
 9184:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 9185: }
 9186: 
 9187: sub machine_domains {
 9188:     my ($hostname) = @_;
 9189:     my @domains;
 9190:     my %hostname = &all_hostnames();
 9191:     while( my($id, $name) = each(%hostname)) {
 9192: #	&logthis("-$id-$name-$hostname-");
 9193: 	if ($hostname eq $name) {
 9194: 	    push(@domains,&host_domain($id));
 9195: 	}
 9196:     }
 9197:     return @domains;
 9198: }
 9199: 
 9200: sub current_machine_ids {
 9201:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 9202: }
 9203: 
 9204: sub machine_ids {
 9205:     my ($hostname) = @_;
 9206:     $hostname ||= &hostname($perlvar{'lonHostID'});
 9207:     my @ids;
 9208:     my %name_to_host = &all_names();
 9209:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 9210: 	return @{ $name_to_host{$hostname} };
 9211:     }
 9212:     return;
 9213: }
 9214: 
 9215: sub additional_machine_domains {
 9216:     my @domains;
 9217:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 9218:     while( my $line = <$fh>) {
 9219:         $line =~ s/\s//g;
 9220:         push(@domains,$line);
 9221:     }
 9222:     return @domains;
 9223: }
 9224: 
 9225: sub default_login_domain {
 9226:     my $domain = $perlvar{'lonDefDomain'};
 9227:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 9228:     foreach my $posdom (&current_machine_domains(),
 9229:                         &additional_machine_domains()) {
 9230:         if (lc($posdom) eq lc($testdomain)) {
 9231:             $domain=$posdom;
 9232:             last;
 9233:         }
 9234:     }
 9235:     return $domain;
 9236: }
 9237: 
 9238: # ------------------------------------------------------------- Declutters URLs
 9239: 
 9240: sub declutter {
 9241:     my $thisfn=shift;
 9242:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9243:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9244:     $thisfn=~s/^\///;
 9245:     $thisfn=~s|^adm/wrapper/||;
 9246:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 9247:     $thisfn=~s/^res\///;
 9248:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
 9249:         $thisfn=~s/\?.+$//;
 9250:     }
 9251:     return $thisfn;
 9252: }
 9253: 
 9254: # ------------------------------------------------------------- Clutter up URLs
 9255: 
 9256: sub clutter {
 9257:     my $thisfn='/'.&declutter(shift);
 9258:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 9259: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 9260:        $thisfn='/res'.$thisfn; 
 9261:     }
 9262:     if ($thisfn !~m|^/adm|) {
 9263: 	if ($thisfn =~ m|^/ext/|) {
 9264: 	    $thisfn='/adm/wrapper'.$thisfn;
 9265: 	} else {
 9266: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 9267: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 9268: 	    if ($embstyle eq 'ssi'
 9269: 		|| ($embstyle eq 'hdn')
 9270: 		|| ($embstyle eq 'rat')
 9271: 		|| ($embstyle eq 'prv')
 9272: 		|| ($embstyle eq 'ign')) {
 9273: 		#do nothing with these
 9274: 	    } elsif (($embstyle eq 'img') 
 9275: 		|| ($embstyle eq 'emb')
 9276: 		|| ($embstyle eq 'wrp')) {
 9277: 		$thisfn='/adm/wrapper'.$thisfn;
 9278: 	    } elsif ($embstyle eq 'unk'
 9279: 		     && $thisfn!~/\.(sequence|page)$/) {
 9280: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 9281: 	    } else {
 9282: #		&logthis("Got a blank emb style");
 9283: 	    }
 9284: 	}
 9285:     }
 9286:     return $thisfn;
 9287: }
 9288: 
 9289: sub clutter_with_no_wrapper {
 9290:     my $uri = &clutter(shift);
 9291:     if ($uri =~ m-^/adm/-) {
 9292: 	$uri =~ s-^/adm/wrapper/-/-;
 9293: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 9294:     }
 9295:     return $uri;
 9296: }
 9297: 
 9298: sub freeze_escape {
 9299:     my ($value)=@_;
 9300:     if (ref($value)) {
 9301: 	$value=&nfreeze($value);
 9302: 	return '__FROZEN__'.&escape($value);
 9303:     }
 9304:     return &escape($value);
 9305: }
 9306: 
 9307: 
 9308: sub thaw_unescape {
 9309:     my ($value)=@_;
 9310:     if ($value =~ /^__FROZEN__/) {
 9311: 	substr($value,0,10,undef);
 9312: 	$value=&unescape($value);
 9313: 	return &thaw($value);
 9314:     }
 9315:     return &unescape($value);
 9316: }
 9317: 
 9318: sub correct_line_ends {
 9319:     my ($result)=@_;
 9320:     $$result =~s/\r\n/\n/mg;
 9321:     $$result =~s/\r/\n/mg;
 9322: }
 9323: # ================================================================ Main Program
 9324: 
 9325: sub goodbye {
 9326:    &logthis("Starting Shut down");
 9327: #not converted to using infrastruture and probably shouldn't be
 9328:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 9329: #converted
 9330: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 9331:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 9332: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 9333: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 9334: #1.1 only
 9335: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 9336: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 9337: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 9338: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 9339:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 9340:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 9341:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 9342:    &flushcourselogs();
 9343:    &logthis("Shutting down");
 9344: }
 9345: 
 9346: sub get_dns {
 9347:     my ($url,$func,$ignore_cache) = @_;
 9348:     if (!$ignore_cache) {
 9349: 	my ($content,$cached)=
 9350: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9351: 	if ($cached) {
 9352: 	    &$func($content);
 9353: 	    return;
 9354: 	}
 9355:     }
 9356: 
 9357:     my %alldns;
 9358:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9359:     foreach my $dns (<$config>) {
 9360: 	next if ($dns !~ /^\^(\S*)/x);
 9361:         my $line = $1;
 9362:         my ($host,$protocol) = split(/:/,$line);
 9363:         if ($protocol ne 'https') {
 9364:             $protocol = 'http';
 9365:         }
 9366: 	$alldns{$host} = $protocol;
 9367:     }
 9368:     while (%alldns) {
 9369: 	my ($dns) = keys(%alldns);
 9370: 	my $ua=new LWP::UserAgent;
 9371: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9372: 	my $response=$ua->request($request);
 9373:         delete($alldns{$dns});
 9374: 	next if ($response->is_error());
 9375: 	my @content = split("\n",$response->content);
 9376: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9377: 	&$func(\@content);
 9378: 	return;
 9379:     }
 9380:     close($config);
 9381:     my $which = (split('/',$url))[3];
 9382:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9383:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9384:     my @content = <$config>;
 9385:     &$func(\@content);
 9386:     return;
 9387: }
 9388: # ------------------------------------------------------------ Read domain file
 9389: {
 9390:     my $loaded;
 9391:     my %domain;
 9392: 
 9393:     sub parse_domain_tab {
 9394: 	my ($lines) = @_;
 9395: 	foreach my $line (@$lines) {
 9396: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9397: 
 9398: 	    chomp($line);
 9399: 	    my ($name,@elements) = split(/:/,$line,9);
 9400: 	    my %this_domain;
 9401: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9402: 			       'lang_def', 'city', 'longi', 'lati',
 9403: 			       'primary') {
 9404: 		$this_domain{$field} = shift(@elements);
 9405: 	    }
 9406: 	    $domain{$name} = \%this_domain;
 9407: 	}
 9408:     }
 9409: 
 9410:     sub reset_domain_info {
 9411: 	undef($loaded);
 9412: 	undef(%domain);
 9413:     }
 9414: 
 9415:     sub load_domain_tab {
 9416: 	my ($ignore_cache) = @_;
 9417: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9418: 	my $fh;
 9419: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9420: 	    my @lines = <$fh>;
 9421: 	    &parse_domain_tab(\@lines);
 9422: 	}
 9423: 	close($fh);
 9424: 	$loaded = 1;
 9425:     }
 9426: 
 9427:     sub domain {
 9428: 	&load_domain_tab() if (!$loaded);
 9429: 
 9430: 	my ($name,$what) = @_;
 9431: 	return if ( !exists($domain{$name}) );
 9432: 
 9433: 	if (!$what) {
 9434: 	    return $domain{$name}{'description'};
 9435: 	}
 9436: 	return $domain{$name}{$what};
 9437:     }
 9438: 
 9439:     sub domain_info {
 9440:         &load_domain_tab() if (!$loaded);
 9441:         return %domain;
 9442:     }
 9443: 
 9444: }
 9445: 
 9446: 
 9447: # ------------------------------------------------------------- Read hosts file
 9448: {
 9449:     my %hostname;
 9450:     my %hostdom;
 9451:     my %libserv;
 9452:     my $loaded;
 9453:     my %name_to_host;
 9454: 
 9455:     sub parse_hosts_tab {
 9456: 	my ($file) = @_;
 9457: 	foreach my $configline (@$file) {
 9458: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9459: 	    next if ($configline =~ /^\^/);
 9460: 	    chomp($configline);
 9461: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9462: 	    $name=~s/\s//g;
 9463: 	    if ($id && $domain && $role && $name) {
 9464: 		$hostname{$id}=$name;
 9465: 		push(@{$name_to_host{$name}}, $id);
 9466: 		$hostdom{$id}=$domain;
 9467: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9468:                 if (defined($protocol)) {
 9469:                     if ($protocol eq 'https') {
 9470:                         $protocol{$id} = $protocol;
 9471:                     } else {
 9472:                         $protocol{$id} = 'http'; 
 9473:                     }
 9474:                 } else {
 9475:                     $protocol{$id} = 'http';
 9476:                 }
 9477: 	    }
 9478: 	}
 9479:     }
 9480:     
 9481:     sub reset_hosts_info {
 9482: 	&purge_remembered();
 9483: 	&reset_domain_info();
 9484: 	&reset_hosts_ip_info();
 9485: 	undef(%name_to_host);
 9486: 	undef(%hostname);
 9487: 	undef(%hostdom);
 9488: 	undef(%libserv);
 9489: 	undef($loaded);
 9490:     }
 9491: 
 9492:     sub load_hosts_tab {
 9493: 	my ($ignore_cache) = @_;
 9494: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9495: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9496: 	my @config = <$config>;
 9497: 	&parse_hosts_tab(\@config);
 9498: 	close($config);
 9499: 	$loaded=1;
 9500:     }
 9501: 
 9502:     sub hostname {
 9503: 	&load_hosts_tab() if (!$loaded);
 9504: 
 9505: 	my ($lonid) = @_;
 9506: 	return $hostname{$lonid};
 9507:     }
 9508: 
 9509:     sub all_hostnames {
 9510: 	&load_hosts_tab() if (!$loaded);
 9511: 
 9512: 	return %hostname;
 9513:     }
 9514: 
 9515:     sub all_names {
 9516: 	&load_hosts_tab() if (!$loaded);
 9517: 
 9518: 	return %name_to_host;
 9519:     }
 9520: 
 9521:     sub all_host_domain {
 9522:         &load_hosts_tab() if (!$loaded);
 9523:         return %hostdom;
 9524:     }
 9525: 
 9526:     sub is_library {
 9527: 	&load_hosts_tab() if (!$loaded);
 9528: 
 9529: 	return exists($libserv{$_[0]});
 9530:     }
 9531: 
 9532:     sub all_library {
 9533: 	&load_hosts_tab() if (!$loaded);
 9534: 
 9535: 	return %libserv;
 9536:     }
 9537: 
 9538:     sub get_servers {
 9539: 	&load_hosts_tab() if (!$loaded);
 9540: 
 9541: 	my ($domain,$type) = @_;
 9542: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9543: 	                                          : %hostname;
 9544: 	my %result;
 9545: 	if (ref($domain) eq 'ARRAY') {
 9546: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9547: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9548: 		    $result{$host} = $hostname;
 9549: 		}
 9550: 	    }
 9551: 	} else {
 9552: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9553: 		if ($hostdom{$host} eq $domain) {
 9554: 		    $result{$host} = $hostname;
 9555: 		}
 9556: 	    }
 9557: 	}
 9558: 	return %result;
 9559:     }
 9560: 
 9561:     sub host_domain {
 9562: 	&load_hosts_tab() if (!$loaded);
 9563: 
 9564: 	my ($lonid) = @_;
 9565: 	return $hostdom{$lonid};
 9566:     }
 9567: 
 9568:     sub all_domains {
 9569: 	&load_hosts_tab() if (!$loaded);
 9570: 
 9571: 	my %seen;
 9572: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9573: 	return @uniq;
 9574:     }
 9575: }
 9576: 
 9577: { 
 9578:     my %iphost;
 9579:     my %name_to_ip;
 9580:     my %lonid_to_ip;
 9581: 
 9582:     sub get_hosts_from_ip {
 9583: 	my ($ip) = @_;
 9584: 	my %iphosts = &get_iphost();
 9585: 	if (ref($iphosts{$ip})) {
 9586: 	    return @{$iphosts{$ip}};
 9587: 	}
 9588: 	return;
 9589:     }
 9590:     
 9591:     sub reset_hosts_ip_info {
 9592: 	undef(%iphost);
 9593: 	undef(%name_to_ip);
 9594: 	undef(%lonid_to_ip);
 9595:     }
 9596: 
 9597:     sub get_host_ip {
 9598: 	my ($lonid) = @_;
 9599: 	if (exists($lonid_to_ip{$lonid})) {
 9600: 	    return $lonid_to_ip{$lonid};
 9601: 	}
 9602: 	my $name=&hostname($lonid);
 9603:    	my $ip = gethostbyname($name);
 9604: 	return if (!$ip || length($ip) ne 4);
 9605: 	$ip=inet_ntoa($ip);
 9606: 	$name_to_ip{$name}   = $ip;
 9607: 	$lonid_to_ip{$lonid} = $ip;
 9608: 	return $ip;
 9609:     }
 9610:     
 9611:     sub get_iphost {
 9612: 	my ($ignore_cache) = @_;
 9613: 
 9614: 	if (!$ignore_cache) {
 9615: 	    if (%iphost) {
 9616: 		return %iphost;
 9617: 	    }
 9618: 	    my ($ip_info,$cached)=
 9619: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9620: 	    if ($cached) {
 9621: 		%iphost      = %{$ip_info->[0]};
 9622: 		%name_to_ip  = %{$ip_info->[1]};
 9623: 		%lonid_to_ip = %{$ip_info->[2]};
 9624: 		return %iphost;
 9625: 	    }
 9626: 	}
 9627: 
 9628: 	# get yesterday's info for fallback
 9629: 	my %old_name_to_ip;
 9630: 	my ($ip_info,$cached)=
 9631: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9632: 	if ($cached) {
 9633: 	    %old_name_to_ip = %{$ip_info->[1]};
 9634: 	}
 9635: 
 9636: 	my %name_to_host = &all_names();
 9637: 	foreach my $name (keys(%name_to_host)) {
 9638: 	    my $ip;
 9639: 	    if (!exists($name_to_ip{$name})) {
 9640: 		$ip = gethostbyname($name);
 9641: 		if (!$ip || length($ip) ne 4) {
 9642: 		    if (defined($old_name_to_ip{$name})) {
 9643: 			$ip = $old_name_to_ip{$name};
 9644: 			&logthis("Can't find $name defaulting to old $ip");
 9645: 		    } else {
 9646: 			&logthis("Name $name no IP found");
 9647: 			next;
 9648: 		    }
 9649: 		} else {
 9650: 		    $ip=inet_ntoa($ip);
 9651: 		}
 9652: 		$name_to_ip{$name} = $ip;
 9653: 	    } else {
 9654: 		$ip = $name_to_ip{$name};
 9655: 	    }
 9656: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9657: 		$lonid_to_ip{$id} = $ip;
 9658: 	    }
 9659: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9660: 	}
 9661: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9662: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9663: 				      48*60*60);
 9664: 
 9665: 	return %iphost;
 9666:     }
 9667: 
 9668:     #
 9669:     #  Given a DNS returns the loncapa host name for that DNS 
 9670:     # 
 9671:     sub host_from_dns {
 9672:         my ($dns) = @_;
 9673:         my @hosts;
 9674:         my $ip;
 9675: 
 9676:         if (exists($name_to_ip{$dns})) {
 9677:             $ip = $name_to_ip{$dns};
 9678:         }
 9679:         if (!$ip) {
 9680:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9681:             if (length($ip) == 4) { 
 9682: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9683:             }
 9684:         }
 9685:         if ($ip) {
 9686: 	    @hosts = get_hosts_from_ip($ip);
 9687: 	    return $hosts[0];
 9688:         }
 9689:         return undef;
 9690:     }
 9691: 
 9692: }
 9693: 
 9694: BEGIN {
 9695: 
 9696: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9697:     unless ($readit) {
 9698: {
 9699:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9700:     %perlvar = (%perlvar,%{$configvars});
 9701: }
 9702: 
 9703: 
 9704: # ------------------------------------------------------ Read spare server file
 9705: {
 9706:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9707: 
 9708:     while (my $configline=<$config>) {
 9709:        chomp($configline);
 9710:        if ($configline) {
 9711: 	   my ($host,$type) = split(':',$configline,2);
 9712: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9713: 	   push(@{ $spareid{$type} }, $host);
 9714:        }
 9715:     }
 9716:     close($config);
 9717: }
 9718: # ------------------------------------------------------------ Read permissions
 9719: {
 9720:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9721: 
 9722:     while (my $configline=<$config>) {
 9723: 	chomp($configline);
 9724: 	if ($configline) {
 9725: 	    my ($role,$perm)=split(/ /,$configline);
 9726: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9727: 	}
 9728:     }
 9729:     close($config);
 9730: }
 9731: 
 9732: # -------------------------------------------- Read plain texts for permissions
 9733: {
 9734:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9735: 
 9736:     while (my $configline=<$config>) {
 9737: 	chomp($configline);
 9738: 	if ($configline) {
 9739: 	    my ($short,@plain)=split(/:/,$configline);
 9740:             %{$prp{$short}} = ();
 9741: 	    if (@plain > 0) {
 9742:                 $prp{$short}{'std'} = $plain[0];
 9743:                 for (my $i=1; $i<@plain; $i++) {
 9744:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9745:                 }
 9746:             }
 9747: 	}
 9748:     }
 9749:     close($config);
 9750: }
 9751: 
 9752: # ---------------------------------------------------------- Read package table
 9753: {
 9754:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9755: 
 9756:     while (my $configline=<$config>) {
 9757: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9758: 	chomp($configline);
 9759: 	my ($short,$plain)=split(/:/,$configline);
 9760: 	my ($pack,$name)=split(/\&/,$short);
 9761: 	if ($plain ne '') {
 9762: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9763: 	    $packagetab{$short}=$plain; 
 9764: 	}
 9765:     }
 9766:     close($config);
 9767: }
 9768: 
 9769: # ------------- set up temporary directory
 9770: {
 9771:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9772: 
 9773: }
 9774: 
 9775: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9776: 				'compress_threshold'=> 20_000,
 9777:  			        });
 9778: 
 9779: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9780: $dumpcount=0;
 9781: $locknum=0;
 9782: 
 9783: &logtouch();
 9784: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9785: $readit=1;
 9786:     {
 9787: 	use integer;
 9788: 	my $test=(2**32)+1;
 9789: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9790: 	&logthis(" Detected 64bit platform ($_64bit)");
 9791:     }
 9792: }
 9793: }
 9794: 
 9795: 1;
 9796: __END__
 9797: 
 9798: =pod
 9799: 
 9800: =head1 NAME
 9801: 
 9802: Apache::lonnet - Subroutines to ask questions about things in the network.
 9803: 
 9804: =head1 SYNOPSIS
 9805: 
 9806: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9807: 
 9808:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9809: 
 9810: Common parameters:
 9811: 
 9812: =over 4
 9813: 
 9814: =item *
 9815: 
 9816: $uname : an internal username (if $cname expecting a course Id specifically)
 9817: 
 9818: =item *
 9819: 
 9820: $udom : a domain (if $cdom expecting a course's domain specifically)
 9821: 
 9822: =item *
 9823: 
 9824: $symb : a resource instance identifier
 9825: 
 9826: =item *
 9827: 
 9828: $namespace : the name of a .db file that contains the data needed or
 9829: being set.
 9830: 
 9831: =back
 9832: 
 9833: =head1 OVERVIEW
 9834: 
 9835: lonnet provides subroutines which interact with the
 9836: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9837: about classes, users, and resources.
 9838: 
 9839: For many of these objects you can also use this to store data about
 9840: them or modify them in various ways.
 9841: 
 9842: =head2 Symbs
 9843: 
 9844: To identify a specific instance of a resource, LON-CAPA uses symbols
 9845: or "symbs"X<symb>. These identifiers are built from the URL of the
 9846: map, the resource number of the resource in the map, and the URL of
 9847: the resource itself. The latter is somewhat redundant, but might help
 9848: if maps change.
 9849: 
 9850: An example is
 9851: 
 9852:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9853: 
 9854: The respective map entry is
 9855: 
 9856:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9857:   title="Problem 2">
 9858:  </resource>
 9859: 
 9860: Symbs are used by the random number generator, as well as to store and
 9861: restore data specific to a certain instance of for example a problem.
 9862: 
 9863: =head2 Storing And Retrieving Data
 9864: 
 9865: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9866: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9867: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9868: is is the non-critical message twin of cstore. These functions are for
 9869: handlers to store a perl hash to a user's permanent data space in an
 9870: easy manner, and to retrieve it again on another call. It is expected
 9871: that a handler would use this once at the beginning to retrieve data,
 9872: and then again once at the end to send only the new data back.
 9873: 
 9874: The data is stored in the user's data directory on the user's
 9875: homeserver under the ID of the course.
 9876: 
 9877: The hash that is returned by restore will have all of the previous
 9878: value for all of the elements of the hash.
 9879: 
 9880: Example:
 9881: 
 9882:  #creating a hash
 9883:  my %hash;
 9884:  $hash{'foo'}='bar';
 9885: 
 9886:  #storing it
 9887:  &Apache::lonnet::cstore(\%hash);
 9888: 
 9889:  #changing a value
 9890:  $hash{'foo'}='notbar';
 9891: 
 9892:  #adding a new value
 9893:  $hash{'bar'}='foo';
 9894:  &Apache::lonnet::cstore(\%hash);
 9895: 
 9896:  #retrieving the hash
 9897:  my %history=&Apache::lonnet::restore();
 9898: 
 9899:  #print the hash
 9900:  foreach my $key (sort(keys(%history))) {
 9901:    print("\%history{$key} = $history{$key}");
 9902:  }
 9903: 
 9904: Will print out:
 9905: 
 9906:  %history{1:foo} = bar
 9907:  %history{1:keys} = foo:timestamp
 9908:  %history{1:timestamp} = 990455579
 9909:  %history{2:bar} = foo
 9910:  %history{2:foo} = notbar
 9911:  %history{2:keys} = foo:bar:timestamp
 9912:  %history{2:timestamp} = 990455580
 9913:  %history{bar} = foo
 9914:  %history{foo} = notbar
 9915:  %history{timestamp} = 990455580
 9916:  %history{version} = 2
 9917: 
 9918: Note that the special hash entries C<keys>, C<version> and
 9919: C<timestamp> were added to the hash. C<version> will be equal to the
 9920: total number of versions of the data that have been stored. The
 9921: C<timestamp> attribute will be the UNIX time the hash was
 9922: stored. C<keys> is available in every historical section to list which
 9923: keys were added or changed at a specific historical revision of a
 9924: hash.
 9925: 
 9926: B<Warning>: do not store the hash that restore returns directly. This
 9927: will cause a mess since it will restore the historical keys as if the
 9928: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9929: 
 9930: Calling convention:
 9931: 
 9932:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9933:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9934: 
 9935: For more detailed information, see lonnet specific documentation.
 9936: 
 9937: =head1 RETURN MESSAGES
 9938: 
 9939: =over 4
 9940: 
 9941: =item * B<con_lost>: unable to contact remote host
 9942: 
 9943: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9944: when the connection is brought back up
 9945: 
 9946: =item * B<con_failed>: unable to contact remote host and unable to save message
 9947: for later delivery
 9948: 
 9949: =item * B<error:>: an error a occurred, a description of the error follows the :
 9950: 
 9951: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9952: that was requested
 9953: 
 9954: =back
 9955: 
 9956: =head1 PUBLIC SUBROUTINES
 9957: 
 9958: =head2 Session Environment Functions
 9959: 
 9960: =over 4
 9961: 
 9962: =item * 
 9963: X<appenv()>
 9964: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9965: the user envirnoment file, and will be restored for each access this
 9966: user makes during this session, also modifies the %env for the current
 9967: process. Optional rolesarrayref - if defined contains a reference to an array
 9968: of roles which are exempt from the restriction on modifying user.role entries 
 9969: in the user's environment.db and in %env.    
 9970: 
 9971: =item *
 9972: X<delenv()>
 9973: B<delenv($delthis,$regexp)>: removes all items from the session
 9974: environment file that begin with $delthis. If the 
 9975: optional second arg - $regexp - is true, $delthis is treated as a 
 9976: regular expression, otherwise \Q$delthis\E is used. 
 9977: The values are also deleted from the current processes %env.
 9978: 
 9979: =item * get_env_multiple($name) 
 9980: 
 9981: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9982: values may be defined and end up as an array ref.
 9983: 
 9984: returns an array of values
 9985: 
 9986: =back
 9987: 
 9988: =head2 User Information
 9989: 
 9990: =over 4
 9991: 
 9992: =item *
 9993: X<queryauthenticate()>
 9994: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9995: authentication scheme
 9996: 
 9997: =item *
 9998: X<authenticate()>
 9999: B<authenticate($uname,$upass,$udom)>: try to
10000: authenticate user from domain's lib servers (first use the current
10001: one). C<$upass> should be the users password.
10002: 
10003: =item *
10004: X<homeserver()>
10005: B<homeserver($uname,$udom)>: find the server which has
10006: the user's directory and files (there must be only one), this caches
10007: the answer, and also caches if there is a borken connection.
10008: 
10009: =item *
10010: X<idget()>
10011: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10012: (IDs are a unique resource in a domain, there must be only 1 ID per
10013: username, and only 1 username per ID in a specific domain) (returns
10014: hash: id=>name,id=>name)
10015: 
10016: =item *
10017: X<idrget()>
10018: B<idrget($udom,@unames)>: find the IDs behind a list of
10019: usernames (returns hash: name=>id,name=>id)
10020: 
10021: =item *
10022: X<idput()>
10023: B<idput($udom,%ids)>: store away a list of names and associated IDs
10024: 
10025: =item *
10026: X<rolesinit()>
10027: B<rolesinit($udom,$username,$authhost)>: get user privileges
10028: 
10029: =item *
10030: X<getsection()>
10031: B<getsection($udom,$uname,$cname)>: finds the section of student in the
10032: course $cname, return section name/number or '' for "not in course"
10033: and '-1' for "no section"
10034: 
10035: =item *
10036: X<userenvironment()>
10037: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
10038: passed in @what from the requested user's environment, returns a hash
10039: 
10040: =item * 
10041: X<userlog_query()>
10042: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10043: activity.log file. %filters defines filters applied when parsing the
10044: log file. These can be start or end timestamps, or the type of action
10045: - log to look for Login or Logout events, check for Checkin or
10046: Checkout, role for role selection. The response is in the form
10047: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
10048: escaped strings of the action recorded in the activity.log file.
10049: 
10050: =back
10051: 
10052: =head2 User Roles
10053: 
10054: =over 4
10055: 
10056: =item *
10057: 
10058: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
10059:  F: full access
10060:  U,I,K: authentication modes (cxx only)
10061:  '': forbidden
10062:  1: user needs to choose course
10063:  2: browse allowed
10064:  A: passphrase authentication needed
10065: 
10066: =item *
10067: 
10068: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10069: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10070: and course level
10071: 
10072: =item *
10073: 
10074: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
10075: (rolesplain.tab); plain text explanation of a user role term.
10076: $type is Course (default) or Community.
10077: If $forcedefault evaluates to true, text returned will be default 
10078: text for $type. Otherwise, if this is a course, the text returned 
10079: will be a custom name for the role (if defined in the course's 
10080: environment).  If no custom name is defined the default is returned.
10081:    
10082: =item *
10083: 
10084: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
10085: All arguments are optional. Returns a hash of a roles, either for
10086: co-author/assistant author roles for a user's Construction Space
10087: (default), or if $context is 'userroles', roles for the user himself,
10088: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10089: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10090: For each key, value is set to colon-separated start and end times for
10091: the role.  If no username and domain are specified, will default to
10092: current user/domain. Types, roles, and roledoms are references to arrays
10093: of role statuses (active, future or previous), roles 
10094: (e.g., cc,in, st etc.) and domains of the roles which can be used
10095: to restrict the list of roles reported. If no array ref is 
10096: provided for types, will default to return only active roles.
10097: 
10098: =back
10099: 
10100: =head2 User Modification
10101: 
10102: =over 4
10103: 
10104: =item *
10105: 
10106: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10107: user for the level given by URL.  Optional start and end dates (leave empty
10108: string or zero for "no date")
10109: 
10110: =item *
10111: 
10112: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10113: change a users, password, possible return values are: ok,
10114: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10115: refused
10116: 
10117: =item *
10118: 
10119: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10120: 
10121: =item *
10122: 
10123: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
10124:            $forceid,$desiredhome,$email,$inststatus) : 
10125: modify user
10126: 
10127: =item *
10128: 
10129: modifystudent
10130: 
10131: modify a student's enrollment and identification information.
10132: The course id is resolved based on the current users environment.  
10133: This means the envoking user must be a course coordinator or otherwise
10134: associated with a course.
10135: 
10136: This call is essentially a wrapper for lonnet::modifyuser and
10137: lonnet::modify_student_enrollment
10138: 
10139: Inputs: 
10140: 
10141: =over 4
10142: 
10143: =item B<$udom> Student's loncapa domain
10144: 
10145: =item B<$uname> Student's loncapa login name
10146: 
10147: =item B<$uid> Student/Employee ID
10148: 
10149: =item B<$umode> Student's authentication mode
10150: 
10151: =item B<$upass> Student's password
10152: 
10153: =item B<$first> Student's first name
10154: 
10155: =item B<$middle> Student's middle name
10156: 
10157: =item B<$last> Student's last name
10158: 
10159: =item B<$gene> Student's generation
10160: 
10161: =item B<$usec> Student's section in course
10162: 
10163: =item B<$end> Unix time of the roles expiration
10164: 
10165: =item B<$start> Unix time of the roles start date
10166: 
10167: =item B<$forceid> If defined, allow $uid to be changed
10168: 
10169: =item B<$desiredhome> server to use as home server for student
10170: 
10171: =item B<$email> Student's permanent e-mail address
10172: 
10173: =item B<$type> Type of enrollment (auto or manual)
10174: 
10175: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
10176: 
10177: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10178: 
10179: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10180: 
10181: =item B<$context> role change context (shown in User Management Logs display in a course)
10182: 
10183: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
10184: 
10185: =back
10186: 
10187: =item *
10188: 
10189: modify_student_enrollment
10190: 
10191: Change a students enrollment status in a class.  The environment variable
10192: 'role.request.course' must be defined for this function to proceed.
10193: 
10194: Inputs:
10195: 
10196: =over 4
10197: 
10198: =item $udom, students domain
10199: 
10200: =item $uname, students name
10201: 
10202: =item $uid, students user id
10203: 
10204: =item $first, students first name
10205: 
10206: =item $middle
10207: 
10208: =item $last
10209: 
10210: =item $gene
10211: 
10212: =item $usec
10213: 
10214: =item $end
10215: 
10216: =item $start
10217: 
10218: =item $type
10219: 
10220: =item $locktype
10221: 
10222: =item $cid
10223: 
10224: =item $selfenroll
10225: 
10226: =item $context
10227: 
10228: =back
10229: 
10230: 
10231: =item *
10232: 
10233: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10234: custom role; give a custom role to a user for the level given by URL.  Specify
10235: name and domain of role author, and role name
10236: 
10237: =item *
10238: 
10239: revokerole($udom,$uname,$url,$role) : revoke a role for url
10240: 
10241: =item *
10242: 
10243: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10244: 
10245: =back
10246: 
10247: =head2 Course Infomation
10248: 
10249: =over 4
10250: 
10251: =item *
10252: 
10253: coursedescription($courseid) : returns a hash of information about the
10254: specified course id, including all environment settings for the
10255: course, the description of the course will be in the hash under the
10256: key 'description'
10257: 
10258: =item *
10259: 
10260: resdata($name,$domain,$type,@which) : request for current parameter
10261: setting for a specific $type, where $type is either 'course' or 'user',
10262: @what should be a list of parameters to ask about. This routine caches
10263: answers for 5 minutes.
10264: 
10265: =item *
10266: 
10267: get_courseresdata($courseid, $domain) : dump the entire course resource
10268: data base, returning a hash that is keyed by the resource name and has
10269: values that are the resource value.  I believe that the timestamps and
10270: versions are also returned.
10271: 
10272: 
10273: =back
10274: 
10275: =head2 Course Modification
10276: 
10277: =over 4
10278: 
10279: =item *
10280: 
10281: writecoursepref($courseid,%prefs) : write preferences (environment
10282: database) for a course
10283: 
10284: =item *
10285: 
10286: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10287: 
10288: =item *
10289: 
10290: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
10291: 
10292: =back
10293: 
10294: =head2 Resource Subroutines
10295: 
10296: =over 4
10297: 
10298: =item *
10299: 
10300: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10301: 
10302: =item *
10303: 
10304: repcopy($filename) : subscribes to the requested file, and attempts to
10305: replicate from the owning library server, Might return
10306: 'unavailable', 'not_found', 'forbidden', 'ok', or
10307: 'bad_request', also attempts to grab the metadata for the
10308: resource. Expects the local filesystem pathname
10309: (/home/httpd/html/res/....)
10310: 
10311: =back
10312: 
10313: =head2 Resource Information
10314: 
10315: =over 4
10316: 
10317: =item *
10318: 
10319: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10320: a vairety of different possible values, $varname should be a request
10321: string, and the other parameters can be used to specify who and what
10322: one is asking about.
10323: 
10324: Possible values for $varname are environment.lastname (or other item
10325: from the envirnment hash), user.name (or someother aspect about the
10326: user), resource.0.maxtries (or some other part and parameter of a
10327: resource)
10328: 
10329: =item *
10330: 
10331: directcondval($number) : get current value of a condition; reads from a state
10332: string
10333: 
10334: =item *
10335: 
10336: condval($condidx) : value of condition index based on state
10337: 
10338: =item *
10339: 
10340: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10341: resource's metadata, $what should be either a specific key, or either
10342: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10343: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10344: 
10345: this function automatically caches all requests
10346: 
10347: =item *
10348: 
10349: metadata_query($query,$custom,$customshow) : make a metadata query against the
10350: network of library servers; returns file handle of where SQL and regex results
10351: will be stored for query
10352: 
10353: =item *
10354: 
10355: symbread($filename) : return symbolic list entry (filename argument optional);
10356: returns the data handle
10357: 
10358: =item *
10359: 
10360: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10361: a possible symb for the URL in $thisfn, and if is an encryypted
10362: resource that the user accessed using /enc/ returns a 1 on success, 0
10363: on failure, user must be in a course, as it assumes the existance of
10364: the course initial hash, and uses $env('request.course.id'}
10365: 
10366: 
10367: =item *
10368: 
10369: symbclean($symb) : removes versions numbers from a symb, returns the
10370: cleaned symb
10371: 
10372: =item *
10373: 
10374: is_on_map($uri) : checks if the $uri is somewhere on the current
10375: course map, user must be in a course for it to work.
10376: 
10377: =item *
10378: 
10379: numval($salt) : return random seed value (addend for rndseed)
10380: 
10381: =item *
10382: 
10383: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10384: a random seed, all arguments are optional, if they aren't sent it uses the
10385: environment to derive them. Note: if symb isn't sent and it can't get one
10386: from &symbread it will use the current time as its return value
10387: 
10388: =item *
10389: 
10390: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10391: unfakeable, receipt
10392: 
10393: =item *
10394: 
10395: receipt() : API to ireceipt working off of env values; given out to users
10396: 
10397: =item *
10398: 
10399: countacc($url) : count the number of accesses to a given URL
10400: 
10401: =item *
10402: 
10403: 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
10404: 
10405: =item *
10406: 
10407: 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)
10408: 
10409: =item *
10410: 
10411: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10412: 
10413: =item *
10414: 
10415: devalidate($symb) : devalidate temporary spreadsheet calculations,
10416: forcing spreadsheet to reevaluate the resource scores next time.
10417: 
10418: =back
10419: 
10420: =head2 Storing/Retreiving Data
10421: 
10422: =over 4
10423: 
10424: =item *
10425: 
10426: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10427: for this url; hashref needs to be given and should be a \%hashname; the
10428: remaining args aren't required and if they aren't passed or are '' they will
10429: be derived from the env
10430: 
10431: =item *
10432: 
10433: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10434: uses critical subroutine
10435: 
10436: =item *
10437: 
10438: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10439: all args are optional
10440: 
10441: =item *
10442: 
10443: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10444: dumps the complete (or key matching regexp) namespace into a hash
10445: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10446: normally &store()ed into
10447: 
10448: $range should be either an integer '100' (give me the first 100
10449:                                            matching records)
10450:               or be  two integers sperated by a - with no spaces
10451:                  '30-50' (give me the 30th through the 50th matching
10452:                           records)
10453: 
10454: 
10455: =item *
10456: 
10457: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10458: replaces a &store() version of data with a replacement set of data
10459: for a particular resource in a namespace passed in the $storehash hash 
10460: reference
10461: 
10462: =item *
10463: 
10464: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10465: works very similar to store/cstore, but all data is stored in a
10466: temporary location and can be reset using tmpreset, $storehash should
10467: be a hash reference, returns nothing on success
10468: 
10469: =item *
10470: 
10471: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10472: similar to restore, but all data is stored in a temporary location and
10473: can be reset using tmpreset. Returns a hash of values on success,
10474: error string otherwise.
10475: 
10476: =item *
10477: 
10478: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10479: deltes all keys for $symb form the temporary storage hash.
10480: 
10481: =item *
10482: 
10483: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10484: reference filled in from namesp ($udom and $uname are optional)
10485: 
10486: =item *
10487: 
10488: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10489: namesp ($udom and $uname are optional)
10490: 
10491: =item *
10492: 
10493: dump($namespace,$udom,$uname,$regexp,$range) : 
10494: dumps the complete (or key matching regexp) namespace into a hash
10495: ($udom, $uname, $regexp, $range are optional)
10496: 
10497: $range should be either an integer '100' (give me the first 100
10498:                                            matching records)
10499:               or be  two integers sperated by a - with no spaces
10500:                  '30-50' (give me the 30th through the 50th matching
10501:                           records)
10502: =item *
10503: 
10504: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10505: $store can be a scalar, an array reference, or if the amount to be 
10506: incremented is > 1, a hash reference.
10507: 
10508: ($udom and $uname are optional)
10509: 
10510: =item *
10511: 
10512: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10513: ($udom and $uname are optional)
10514: 
10515: =item *
10516: 
10517: cput($namespace,$storehash,$udom,$uname) : critical put
10518: ($udom and $uname are optional)
10519: 
10520: =item *
10521: 
10522: newput($namespace,$storehash,$udom,$uname) :
10523: 
10524: Attempts to store the items in the $storehash, but only if they don't
10525: currently exist, if this succeeds you can be certain that you have 
10526: successfully created a new key value pair in the $namespace db.
10527: 
10528: 
10529: Args:
10530:  $namespace: name of database to store values to
10531:  $storehash: hashref to store to the db
10532:  $udom: (optional) domain of user containing the db
10533:  $uname: (optional) name of user caontaining the db
10534: 
10535: Returns:
10536:  'ok' -> succeeded in storing all keys of $storehash
10537:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10538:                         least <key> already existed in the db (other
10539:                         requested keys may also already exist)
10540:  'error: <msg>' -> unable to tie the DB or other error occurred
10541:  'con_lost' -> unable to contact request server
10542:  'refused' -> action was not allowed by remote machine
10543: 
10544: 
10545: =item *
10546: 
10547: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10548: reference filled in from namesp (encrypts the return communication)
10549: ($udom and $uname are optional)
10550: 
10551: =item *
10552: 
10553: log($udom,$name,$home,$message) : write to permanent log for user; use
10554: critical subroutine
10555: 
10556: =item *
10557: 
10558: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10559: array reference filled in from namespace found in domain level on either
10560: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10561: 
10562: =item *
10563: 
10564: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10565: domain level either on specified domain server ($uhome) or primary domain 
10566: server ($udom and $uhome are optional)
10567: 
10568: =item * 
10569: 
10570: get_domain_defaults($target_domain) : returns hash with defaults for
10571: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10572: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10573: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10574: Values are retrieved from cache (if current), or from domain's configuration.db
10575: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10576: or lonTabs/domain.tab. 
10577: 
10578: %domdefaults = &get_auth_defaults($target_domain);
10579: 
10580: =back
10581: 
10582: =head2 Network Status Functions
10583: 
10584: =over 4
10585: 
10586: =item *
10587: 
10588: dirlist($uri) : return directory list based on URI
10589: 
10590: =item *
10591: 
10592: spareserver() : find server with least workload from spare.tab
10593: 
10594: 
10595: =item *
10596: 
10597: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10598: if there is no corresponding loncapa host.
10599: 
10600: =back
10601: 
10602: 
10603: =head2 Apache Request
10604: 
10605: =over 4
10606: 
10607: =item *
10608: 
10609: ssi($url,%hash) : server side include, does a complete request cycle on url to
10610: localhost, posts hash
10611: 
10612: =back
10613: 
10614: =head2 Data to String to Data
10615: 
10616: =over 4
10617: 
10618: =item *
10619: 
10620: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10621: and '&' separators, supports elements that are arrayrefs and hashrefs
10622: 
10623: =item *
10624: 
10625: hashref2str($hashref) : convert a hashref into a string complete with
10626: escaping and '=' and '&' separators, supports elements that are
10627: arrayrefs and hashrefs
10628: 
10629: =item *
10630: 
10631: arrayref2str($arrayref) : convert an arrayref into a string complete
10632: with escaping and '&' separators, supports elements that are arrayrefs
10633: and hashrefs
10634: 
10635: =item *
10636: 
10637: str2hash($string) : convert string to hash using unescaping and
10638: splitting on '=' and '&', supports elements that are arrayrefs and
10639: hashrefs
10640: 
10641: =item *
10642: 
10643: str2array($string) : convert string to hash using unescaping and
10644: splitting on '&', supports elements that are arrayrefs and hashrefs
10645: 
10646: =back
10647: 
10648: =head2 Logging Routines
10649: 
10650: =over 4
10651: 
10652: These routines allow one to make log messages in the lonnet.log and
10653: lonnet.perm logfiles.
10654: 
10655: =item *
10656: 
10657: logtouch() : make sure the logfile, lonnet.log, exists
10658: 
10659: =item *
10660: 
10661: logthis() : append message to the normal lonnet.log file, it gets
10662: preiodically rolled over and deleted.
10663: 
10664: =item *
10665: 
10666: logperm() : append a permanent message to lonnet.perm.log, this log
10667: file never gets deleted by any automated portion of the system, only
10668: messages of critical importance should go in here.
10669: 
10670: =back
10671: 
10672: =head2 General File Helper Routines
10673: 
10674: =over 4
10675: 
10676: =item *
10677: 
10678: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10679: (a) files in /uploaded
10680:   (i) If a local copy of the file exists - 
10681:       compares modification date of local copy with last-modified date for 
10682:       definitive version stored on home server for course. If local copy is 
10683:       stale, requests a new version from the home server and stores it. 
10684:       If the original has been removed from the home server, then local copy 
10685:       is unlinked.
10686:   (ii) If local copy does not exist -
10687:       requests the file from the home server and stores it. 
10688:   
10689:   If $caller is 'uploadrep':  
10690:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10691:     for request for files originally uploaded via DOCS. 
10692:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10693:   
10694:   Otherwise:
10695:      This indicates a call from the content generation phase of the request.
10696:      -  returns the entire contents of the file or -1.
10697:      
10698: (b) files in /res
10699:    - returns the entire contents of a file or -1; 
10700:    it properly subscribes to and replicates the file if neccessary.
10701: 
10702: 
10703: =item *
10704: 
10705: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10706:                   reference
10707: 
10708: returns either a stat() list of data about the file or an empty list
10709: if the file doesn't exist or couldn't find out about it (connection
10710: problems or user unknown)
10711: 
10712: =item *
10713: 
10714: filelocation($dir,$file) : returns file system location of a file
10715: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10716: directory that relative $file lookups are to looked in ($dir of /a/dir
10717: and a file of ../bob will become /a/bob)
10718: 
10719: =item *
10720: 
10721: hreflocation($dir,$file) : returns file system location or a URL; same as
10722: filelocation except for hrefs
10723: 
10724: =item *
10725: 
10726: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10727: 
10728: =back
10729: 
10730: =head2 Usererfile file routines (/uploaded*)
10731: 
10732: =over 4
10733: 
10734: =item *
10735: 
10736: userfileupload(): main rotine for putting a file in a user or course's
10737:                   filespace, arguments are,
10738: 
10739:  formname - required - this is the name of the element in $env where the
10740:            filename, and the contents of the file to create/modifed exist
10741:            the filename is in $env{'form.'.$formname.'.filename'} and the
10742:            contents of the file is located in $env{'form.'.$formname}
10743:  coursedoc - if true, store the file in the course of the active role
10744:              of the current user
10745:  subdir - required - subdirectory to put the file in under ../userfiles/
10746:          if undefined, it will be placed in "unknown"
10747: 
10748:  (This routine calls clean_filename() to remove any dangerous
10749:  characters from the filename, and then calls finuserfileupload() to
10750:  complete the transaction)
10751: 
10752:  returns either the url of the uploaded file (/uploaded/....) if successful
10753:  and /adm/notfound.html if unsuccessful
10754: 
10755: =item *
10756: 
10757: clean_filename(): routine for cleaing a filename up for storage in
10758:                  userfile space, argument is:
10759: 
10760:  filename - proposed filename
10761: 
10762: returns: the new clean filename
10763: 
10764: =item *
10765: 
10766: finishuserfileupload(): routine that creaes and sends the file to
10767: userspace, probably shouldn't be called directly
10768: 
10769:   docuname: username or courseid of destination for the file
10770:   docudom: domain of user/course of destination for the file
10771:   formname: same as for userfileupload()
10772:   fname: filename (inculding subdirectories) for the file
10773: 
10774:  returns either the url of the uploaded file (/uploaded/....) if successful
10775:  and /adm/notfound.html if unsuccessful
10776: 
10777: =item *
10778: 
10779: renameuserfile(): renames an existing userfile to a new name
10780: 
10781:   Args:
10782:    docuname: username or courseid of destination for the file
10783:    docudom: domain of user/course of destination for the file
10784:    old: current file name (including any subdirs under userfiles)
10785:    new: desired file name (including any subdirs under userfiles)
10786: 
10787: =item *
10788: 
10789: mkdiruserfile(): creates a directory is a userfiles dir
10790: 
10791:   Args:
10792:    docuname: username or courseid of destination for the file
10793:    docudom: domain of user/course of destination for the file
10794:    dir: dir to create (including any subdirs under userfiles)
10795: 
10796: =item *
10797: 
10798: removeuserfile(): removes a file that exists in userfiles
10799: 
10800:   Args:
10801:    docuname: username or courseid of destination for the file
10802:    docudom: domain of user/course of destination for the file
10803:    fname: filname to delete (including any subdirs under userfiles)
10804: 
10805: =item *
10806: 
10807: removeuploadedurl(): convience function for removeuserfile()
10808: 
10809:   Args:
10810:    url:  a full /uploaded/... url to delete
10811: 
10812: =item * 
10813: 
10814: get_portfile_permissions():
10815:   Args:
10816:     domain: domain of user or course contain the portfolio files
10817:     user: name of user or num of course contain the portfolio files
10818:   Returns:
10819:     hashref of a dump of the proper file_permissions.db
10820:    
10821: 
10822: =item * 
10823: 
10824: get_access_controls():
10825: 
10826: Args:
10827:   current_permissions: the hash ref returned from get_portfile_permissions()
10828:   group: (optional) the group you want the files associated with
10829:   file: (optional) the file you want access info on
10830: 
10831: Returns:
10832:     a hash (keys are file names) of hashes containing
10833:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10834:         values are XML containing access control settings (see below) 
10835: 
10836: Internal notes:
10837: 
10838:  access controls are stored in file_permissions.db as key=value pairs.
10839:     key -> path to file/file_name\0uniqueID:scope_end_start
10840:         where scope -> public,guest,course,group,domains or users.
10841:               end -> UNIX time for end of access (0 -> no end date)
10842:               start -> UNIX time for start of access
10843: 
10844:     value -> XML description of access control
10845:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10846:             <start></start>
10847:             <end></end>
10848: 
10849:             <password></password>  for scope type = guest
10850: 
10851:             <domain></domain>     for scope type = course or group
10852:             <number></number>
10853:             <roles id="">
10854:              <role></role>
10855:              <access></access>
10856:              <section></section>
10857:              <group></group>
10858:             </roles>
10859: 
10860:             <dom></dom>         for scope type = domains
10861: 
10862:             <users>             for scope type = users
10863:              <user>
10864:               <uname></uname>
10865:               <udom></udom>
10866:              </user>
10867:             </users>
10868:            </scope> 
10869:               
10870:  Access data is also aggregated for each file in an additional key=value pair:
10871:  key -> path to file/file_name\0accesscontrol 
10872:  value -> reference to hash
10873:           hash contains key = value pairs
10874:           where key = uniqueID:scope_end_start
10875:                 value = UNIX time record was last updated
10876: 
10877:           Used to improve speed of look-ups of access controls for each file.  
10878:  
10879:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10880: 
10881: modify_access_controls():
10882: 
10883: Modifies access controls for a portfolio file
10884: Args
10885: 1. file name
10886: 2. reference to hash of required changes,
10887: 3. domain
10888: 4. username
10889:   where domain,username are the domain of the portfolio owner 
10890:   (either a user or a course) 
10891: 
10892: Returns:
10893: 1. result of additions or updates ('ok' or 'error', with error message). 
10894: 2. result of deletions ('ok' or 'error', with error message).
10895: 3. reference to hash of any new or updated access controls.
10896: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10897:    key = integer (inbound ID)
10898:    value = uniqueID  
10899: 
10900: =back
10901: 
10902: =head2 HTTP Helper Routines
10903: 
10904: =over 4
10905: 
10906: =item *
10907: 
10908: escape() : unpack non-word characters into CGI-compatible hex codes
10909: 
10910: =item *
10911: 
10912: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10913: 
10914: =back
10915: 
10916: =head1 PRIVATE SUBROUTINES
10917: 
10918: =head2 Underlying communication routines (Shouldn't call)
10919: 
10920: =over 4
10921: 
10922: =item *
10923: 
10924: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10925: 
10926: =item *
10927: 
10928: reply() : uses subreply to send a message to remote machine, logs all failures
10929: 
10930: =item *
10931: 
10932: critical() : passes a critical message to another server; if cannot
10933: get through then place message in connection buffer directory and
10934: returns con_delayed, if incapable of saving message, returns
10935: con_failed
10936: 
10937: =item *
10938: 
10939: reconlonc() : tries to reconnect lonc client processes.
10940: 
10941: =back
10942: 
10943: =head2 Resource Access Logging
10944: 
10945: =over 4
10946: 
10947: =item *
10948: 
10949: flushcourselogs() : flush (save) buffer logs and access logs
10950: 
10951: =item *
10952: 
10953: courselog($what) : save message for course in hash
10954: 
10955: =item *
10956: 
10957: courseacclog($what) : save message for course using &courselog().  Perform
10958: special processing for specific resource types (problems, exams, quizzes, etc).
10959: 
10960: =item *
10961: 
10962: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10963: as a PerlChildExitHandler
10964: 
10965: =back
10966: 
10967: =head2 Other
10968: 
10969: =over 4
10970: 
10971: =item *
10972: 
10973: symblist($mapname,%newhash) : update symbolic storage links
10974: 
10975: =back
10976: 
10977: =cut
10978: 

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