File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1044: download - view: text, annotated - select for diffs
Sat Nov 28 19:03:36 2009 UTC (14 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Record role changes for 'co' role in Community in nohist_rolelog.db

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1044 2009/11/28 19:03:36 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:         ($trole eq 'co')) {
 2765:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2766:             my $cdom = $1;
 2767:             my $cnum = $2;
 2768:             my $sec = $3;
 2769:             my $namespace = 'rolelog';
 2770:             my %storehash = (
 2771:                                role    => $trole,
 2772:                                start   => $tstart,
 2773:                                end     => $tend,
 2774:                                selfenroll => $selfenroll,
 2775:                                context    => $context,
 2776:                             );
 2777:             if ($trole eq 'gr') {
 2778:                 $namespace = 'groupslog';
 2779:                 $storehash{'group'} = $sec;
 2780:             } else {
 2781:                 $storehash{'section'} = $sec;
 2782:             }
 2783:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2784:             if (($trole ne 'st') || ($sec ne '')) {
 2785:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2786:             }
 2787:         }
 2788:     }
 2789:     return;
 2790: }
 2791: 
 2792: sub get_course_adv_roles {
 2793:     my ($cid,$codes) = @_;
 2794:     $cid=$env{'request.course.id'} unless (defined($cid));
 2795:     my %coursehash=&coursedescription($cid);
 2796:     my $crstype = &Apache::loncommon::course_type($cid);
 2797:     my %nothide=();
 2798:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2799:         if ($user !~ /:/) {
 2800: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2801:         } else {
 2802:             $nothide{$user}=1;
 2803:         }
 2804:     }
 2805:     my %returnhash=();
 2806:     my %dumphash=
 2807:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2808:     my $now=time;
 2809:     my %privileged;
 2810:     foreach my $entry (keys(%dumphash)) {
 2811: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2812:         if (($tstart) && ($tstart<0)) { next; }
 2813:         if (($tend) && ($tend<$now)) { next; }
 2814:         if (($tstart) && ($now<$tstart)) { next; }
 2815:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2816: 	if ($username eq '' || $domain eq '') { next; }
 2817:         unless (ref($privileged{$domain}) eq 'HASH') {
 2818:             my %dompersonnel =
 2819:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2820:             $privileged{$domain} = {};
 2821:             foreach my $server (keys(%dompersonnel)) {
 2822:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2823:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2824:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2825:                         $privileged{$udom}{$uname} = 1;
 2826:                     }
 2827:                 }
 2828:             }
 2829:         }
 2830:         if ((exists($privileged{$domain}{$username})) && 
 2831:             (!$nothide{$username.':'.$domain})) { next; }
 2832: 	if ($role eq 'cr') { next; }
 2833:         if ($codes) {
 2834:             if ($section) { $role .= ':'.$section; }
 2835:             if ($returnhash{$role}) {
 2836:                 $returnhash{$role}.=','.$username.':'.$domain;
 2837:             } else {
 2838:                 $returnhash{$role}=$username.':'.$domain;
 2839:             }
 2840:         } else {
 2841:             my $key=&plaintext($role,$crstype);
 2842:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2843:             if ($returnhash{$key}) {
 2844: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2845:             } else {
 2846:                 $returnhash{$key}=$username.':'.$domain;
 2847:             }
 2848:         }
 2849:     }
 2850:     return %returnhash;
 2851: }
 2852: 
 2853: sub get_my_roles {
 2854:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2855:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2856:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2857:     my (%dumphash,%nothide);
 2858:     if ($context eq 'userroles') { 
 2859:         %dumphash = &dump('roles',$udom,$uname);
 2860:     } else {
 2861:         %dumphash=
 2862:             &dump('nohist_userroles',$udom,$uname);
 2863:         if ($hidepriv) {
 2864:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2865:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2866:                 if ($user !~ /:/) {
 2867:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2868:                 } else {
 2869:                     $nothide{$user} = 1;
 2870:                 }
 2871:             }
 2872:         }
 2873:     }
 2874:     my %returnhash=();
 2875:     my $now=time;
 2876:     my %privileged;
 2877:     foreach my $entry (keys(%dumphash)) {
 2878:         my ($role,$tend,$tstart);
 2879:         if ($context eq 'userroles') {
 2880: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2881:         } else {
 2882:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2883:         }
 2884:         if (($tstart) && ($tstart<0)) { next; }
 2885:         my $status = 'active';
 2886:         if (($tend) && ($tend<=$now)) {
 2887:             $status = 'previous';
 2888:         } 
 2889:         if (($tstart) && ($now<$tstart)) {
 2890:             $status = 'future';
 2891:         }
 2892:         if (ref($types) eq 'ARRAY') {
 2893:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2894:                 next;
 2895:             } 
 2896:         } else {
 2897:             if ($status ne 'active') {
 2898:                 next;
 2899:             }
 2900:         }
 2901:         my ($rolecode,$username,$domain,$section,$area);
 2902:         if ($context eq 'userroles') {
 2903:             ($area,$rolecode) = split(/_/,$entry);
 2904:             (undef,$domain,$username,$section) = split(/\//,$area);
 2905:         } else {
 2906:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2907:         }
 2908:         if (ref($roledoms) eq 'ARRAY') {
 2909:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2910:                 next;
 2911:             }
 2912:         }
 2913:         if (ref($roles) eq 'ARRAY') {
 2914:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2915:                 if ($role =~ /^cr\//) {
 2916:                     if (!grep(/^cr$/,@{$roles})) {
 2917:                         next;
 2918:                     }
 2919:                 } else {
 2920:                     next;
 2921:                 }
 2922:             }
 2923:         }
 2924:         if ($hidepriv) {
 2925:             if ($context eq 'userroles') {
 2926:                 if ((&privileged($username,$domain)) &&
 2927:                     (!$nothide{$username.':'.$domain})) {
 2928:                     next;
 2929:                 }
 2930:             } else {
 2931:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2932:                     my %dompersonnel =
 2933:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2934:                     $privileged{$domain} = {};
 2935:                     if (keys(%dompersonnel)) {
 2936:                         foreach my $server (keys(%dompersonnel)) {
 2937:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2938:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2939:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2940:                                     $privileged{$udom}{$uname} = $trole;
 2941:                                 }
 2942:                             }
 2943:                         }
 2944:                     }
 2945:                 }
 2946:                 if (exists($privileged{$domain}{$username})) {
 2947:                     if (!$nothide{$username.':'.$domain}) {
 2948:                         next;
 2949:                     }
 2950:                 }
 2951:             }
 2952:         }
 2953:         if ($withsec) {
 2954:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2955:                 $tstart.':'.$tend;
 2956:         } else {
 2957:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2958:         }
 2959:     }
 2960:     return %returnhash;
 2961: }
 2962: 
 2963: # ----------------------------------------------------- Frontpage Announcements
 2964: #
 2965: #
 2966: 
 2967: sub postannounce {
 2968:     my ($server,$text)=@_;
 2969:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2970:     unless ($text=~/\w/) { $text=''; }
 2971:     return &reply('setannounce:'.&escape($text),$server);
 2972: }
 2973: 
 2974: sub getannounce {
 2975: 
 2976:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2977: 	my $announcement='';
 2978: 	while (my $line = <$fh>) { $announcement .= $line; }
 2979: 	close($fh);
 2980: 	if ($announcement=~/\w/) { 
 2981: 	    return 
 2982:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2983:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2984: 	} else {
 2985: 	    return '';
 2986: 	}
 2987:     } else {
 2988: 	return '';
 2989:     }
 2990: }
 2991: 
 2992: # ---------------------------------------------------------- Course ID routines
 2993: # Deal with domain's nohist_courseid.db files
 2994: #
 2995: 
 2996: sub courseidput {
 2997:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2998:     my $outcome;
 2999:     if ($caller eq 'timeonly') {
 3000:         my $cids = '';
 3001:         foreach my $item (keys(%$storehash)) {
 3002:             $cids.=&escape($item).'&';
 3003:         }
 3004:         $cids=~s/\&$//;
 3005:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3006:                           $coursehome);       
 3007:     } else {
 3008:         my $items = '';
 3009:         foreach my $item (keys(%$storehash)) {
 3010:             $items.= &escape($item).'='.
 3011:                      &freeze_escape($$storehash{$item}).'&';
 3012:         }
 3013:         $items=~s/\&$//;
 3014:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3015:                           $coursehome);
 3016:     }
 3017:     if ($outcome eq 'unknown_cmd') {
 3018:         my $what;
 3019:         foreach my $cid (keys(%$storehash)) {
 3020:             $what .= &escape($cid).'=';
 3021:             foreach my $item ('description','inst_code','owner','type') {
 3022:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3023:             }
 3024:             $what =~ s/\:$/&/;
 3025:         }
 3026:         $what =~ s/\&$//;  
 3027:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3028:     } else {
 3029:         return $outcome;
 3030:     }
 3031: }
 3032: 
 3033: sub courseiddump {
 3034:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3035:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3036:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3037:         $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
 3038:     my $as_hash = 1;
 3039:     my %returnhash;
 3040:     if (!$domfilter) { $domfilter=''; }
 3041:     my %libserv = &all_library();
 3042:     foreach my $tryserver (keys(%libserv)) {
 3043:         if ( (  $hostidflag == 1 
 3044: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3045: 	     || (!defined($hostidflag)) ) {
 3046: 
 3047: 	    if (($domfilter eq '') ||
 3048: 		(&host_domain($tryserver) eq $domfilter)) {
 3049:                 my $rep = 
 3050:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3051:                          $sincefilter.':'.&escape($descfilter).':'.
 3052:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3053:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3054:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3055:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3056:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3057:                          &escape($cc_clone).':'.$cloneonly.':'.
 3058:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3059:                          &escape($creationcontext),$tryserver);
 3060:                 my @pairs=split(/\&/,$rep);
 3061:                 foreach my $item (@pairs) {
 3062:                     my ($key,$value)=split(/\=/,$item,2);
 3063:                     $key = &unescape($key);
 3064:                     next if ($key =~ /^error: 2 /);
 3065:                     my $result = &thaw_unescape($value);
 3066:                     if (ref($result) eq 'HASH') {
 3067:                         $returnhash{$key}=$result;
 3068:                     } else {
 3069:                         my @responses = split(/:/,$value);
 3070:                         my @items = ('description','inst_code','owner','type');
 3071:                         for (my $i=0; $i<@responses; $i++) {
 3072:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3073:                         }
 3074:                     }
 3075:                 }
 3076:             }
 3077:         }
 3078:     }
 3079:     return %returnhash;
 3080: }
 3081: 
 3082: # ---------------------------------------------------------- DC e-mail
 3083: 
 3084: sub dcmailput {
 3085:     my ($domain,$msgid,$message,$server)=@_;
 3086:     my $status = &Apache::lonnet::critical(
 3087:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3088:        &escape($message),$server);
 3089:     return $status;
 3090: }
 3091: 
 3092: sub dcmaildump {
 3093:     my ($dom,$startdate,$enddate,$senders) = @_;
 3094:     my %returnhash=();
 3095: 
 3096:     if (defined(&domain($dom,'primary'))) {
 3097:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3098:                                                          &escape($enddate).':';
 3099: 	my @esc_senders=map { &escape($_)} @$senders;
 3100: 	$cmd.=&escape(join('&',@esc_senders));
 3101: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3102:             my ($key,$value) = split(/\=/,$line,2);
 3103:             if (($key) && ($value)) {
 3104:                 $returnhash{&unescape($key)} = &unescape($value);
 3105:             }
 3106:         }
 3107:     }
 3108:     return %returnhash;
 3109: }
 3110: # ---------------------------------------------------------- Domain roles
 3111: 
 3112: sub get_domain_roles {
 3113:     my ($dom,$roles,$startdate,$enddate)=@_;
 3114:     if ((!defined($startdate)) || ($startdate eq '')) {
 3115:         $startdate = '.';
 3116:     }
 3117:     if ((!defined($enddate)) || ($enddate eq '')) {
 3118:         $enddate = '.';
 3119:     }
 3120:     my $rolelist;
 3121:     if (ref($roles) eq 'ARRAY') {
 3122:         $rolelist = join(':',@{$roles});
 3123:     }
 3124:     my %personnel = ();
 3125: 
 3126:     my %servers = &get_servers($dom,'library');
 3127:     foreach my $tryserver (keys(%servers)) {
 3128: 	%{$personnel{$tryserver}}=();
 3129: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3130: 					    &escape($startdate).':'.
 3131: 					    &escape($enddate).':'.
 3132: 					    &escape($rolelist), $tryserver))) {
 3133: 	    my ($key,$value) = split(/\=/,$line,2);
 3134: 	    if (($key) && ($value)) {
 3135: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3136: 	    }
 3137: 	}
 3138:     }
 3139:     return %personnel;
 3140: }
 3141: 
 3142: # ----------------------------------------------------------- Check out an item
 3143: 
 3144: sub get_first_access {
 3145:     my ($type,$argsymb)=@_;
 3146:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3147:     if ($argsymb) { $symb=$argsymb; }
 3148:     my ($map,$id,$res)=&decode_symb($symb);
 3149:     if ($type eq 'course') {
 3150: 	$res='course';
 3151:     } elsif ($type eq 'map') {
 3152: 	$res=&symbread($map);
 3153:     } else {
 3154: 	$res=$symb;
 3155:     }
 3156:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3157:     return $times{"$courseid\0$res"};
 3158: }
 3159: 
 3160: sub set_first_access {
 3161:     my ($type)=@_;
 3162:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3163:     my ($map,$id,$res)=&decode_symb($symb);
 3164:     if ($type eq 'course') {
 3165: 	$res='course';
 3166:     } elsif ($type eq 'map') {
 3167: 	$res=&symbread($map);
 3168:     } else {
 3169: 	$res=$symb;
 3170:     }
 3171:     my $firstaccess=&get_first_access($type,$symb);
 3172:     if (!$firstaccess) {
 3173: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3174:     }
 3175:     return 'already_set';
 3176: }
 3177: 
 3178: sub checkout {
 3179:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3180:     my $now=time;
 3181:     my $lonhost=$perlvar{'lonHostID'};
 3182:     my $infostr=&escape(
 3183:                  'CHECKOUTTOKEN&'.
 3184:                  $tuname.'&'.
 3185:                  $tudom.'&'.
 3186:                  $tcrsid.'&'.
 3187:                  $symb.'&'.
 3188: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3189:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3190:     if ($token=~/^error\:/) { 
 3191:         &logthis("<font color=\"blue\">WARNING: ".
 3192:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3193:                  "</font>");
 3194:         return ''; 
 3195:     }
 3196: 
 3197:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3198:     $token=~tr/a-z/A-Z/;
 3199: 
 3200:     my %infohash=('resource.0.outtoken' => $token,
 3201:                   'resource.0.checkouttime' => $now,
 3202:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3203: 
 3204:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3205:        return '';
 3206:     } else {
 3207:         &logthis("<font color=\"blue\">WARNING: ".
 3208:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3209:                  "</font>");
 3210:     }    
 3211: 
 3212:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3213:                          &escape('Checkout '.$infostr.' - '.
 3214:                                                  $token)) ne 'ok') {
 3215: 	return '';
 3216:     } else {
 3217:         &logthis("<font color=\"blue\">WARNING: ".
 3218:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3219:                  "</font>");
 3220:     }
 3221:     return $token;
 3222: }
 3223: 
 3224: # ------------------------------------------------------------ Check in an item
 3225: 
 3226: sub checkin {
 3227:     my $token=shift;
 3228:     my $now=time;
 3229:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3230:     $lonhost=~tr/A-Z/a-z/;
 3231:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3232:     $dtoken=~s/\W/\_/g;
 3233:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3234:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3235: 
 3236:     unless (($tuname) && ($tudom)) {
 3237:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3238:         return '';
 3239:     }
 3240:     
 3241:     unless (&allowed('mgr',$tcrsid)) {
 3242:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3243:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3244:         return '';
 3245:     }
 3246: 
 3247:     my %infohash=('resource.0.intoken' => $token,
 3248:                   'resource.0.checkintime' => $now,
 3249:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3250: 
 3251:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3252:        return '';
 3253:     }    
 3254: 
 3255:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3256:                          &escape('Checkin - '.$token)) ne 'ok') {
 3257: 	return '';
 3258:     }
 3259: 
 3260:     return ($symb,$tuname,$tudom,$tcrsid);    
 3261: }
 3262: 
 3263: # --------------------------------------------- Set Expire Date for Spreadsheet
 3264: 
 3265: sub expirespread {
 3266:     my ($uname,$udom,$stype,$usymb)=@_;
 3267:     my $cid=$env{'request.course.id'}; 
 3268:     if ($cid) {
 3269:        my $now=time;
 3270:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3271:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3272:                             $env{'course.'.$cid.'.num'}.
 3273: 	        	    ':nohist_expirationdates:'.
 3274:                             &escape($key).'='.$now,
 3275:                             $env{'course.'.$cid.'.home'})
 3276:     }
 3277:     return 'ok';
 3278: }
 3279: 
 3280: # ----------------------------------------------------- Devalidate Spreadsheets
 3281: 
 3282: sub devalidate {
 3283:     my ($symb,$uname,$udom)=@_;
 3284:     my $cid=$env{'request.course.id'}; 
 3285:     if ($cid) {
 3286:         # delete the stored spreadsheets for
 3287:         # - the student level sheet of this user in course's homespace
 3288:         # - the assessment level sheet for this resource 
 3289:         #   for this user in user's homespace
 3290: 	# - current conditional state info
 3291: 	my $key=$uname.':'.$udom.':';
 3292:         my $status=
 3293: 	    &del('nohist_calculatedsheets',
 3294: 		 [$key.'studentcalc:'],
 3295: 		 $env{'course.'.$cid.'.domain'},
 3296: 		 $env{'course.'.$cid.'.num'})
 3297: 		.' '.
 3298: 	    &del('nohist_calculatedsheets_'.$cid,
 3299: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3300:         unless ($status eq 'ok ok') {
 3301:            &logthis('Could not devalidate spreadsheet '.
 3302:                     $uname.' at '.$udom.' for '.
 3303: 		    $symb.': '.$status);
 3304:         }
 3305: 	&delenv('user.state.'.$cid);
 3306:     }
 3307: }
 3308: 
 3309: sub get_scalar {
 3310:     my ($string,$end) = @_;
 3311:     my $value;
 3312:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3313: 	$value = $1;
 3314:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3315: 	$value = $1;
 3316:     }
 3317:     return &unescape($value);
 3318: }
 3319: 
 3320: sub array2str {
 3321:   my (@array) = @_;
 3322:   my $result=&arrayref2str(\@array);
 3323:   $result=~s/^__ARRAY_REF__//;
 3324:   $result=~s/__END_ARRAY_REF__$//;
 3325:   return $result;
 3326: }
 3327: 
 3328: sub arrayref2str {
 3329:   my ($arrayref) = @_;
 3330:   my $result='__ARRAY_REF__';
 3331:   foreach my $elem (@$arrayref) {
 3332:     if(ref($elem) eq 'ARRAY') {
 3333:       $result.=&arrayref2str($elem).'&';
 3334:     } elsif(ref($elem) eq 'HASH') {
 3335:       $result.=&hashref2str($elem).'&';
 3336:     } elsif(ref($elem)) {
 3337:       #print("Got a ref of ".(ref($elem))." skipping.");
 3338:     } else {
 3339:       $result.=&escape($elem).'&';
 3340:     }
 3341:   }
 3342:   $result=~s/\&$//;
 3343:   $result .= '__END_ARRAY_REF__';
 3344:   return $result;
 3345: }
 3346: 
 3347: sub hash2str {
 3348:   my (%hash) = @_;
 3349:   my $result=&hashref2str(\%hash);
 3350:   $result=~s/^__HASH_REF__//;
 3351:   $result=~s/__END_HASH_REF__$//;
 3352:   return $result;
 3353: }
 3354: 
 3355: sub hashref2str {
 3356:   my ($hashref)=@_;
 3357:   my $result='__HASH_REF__';
 3358:   foreach my $key (sort(keys(%$hashref))) {
 3359:     if (ref($key) eq 'ARRAY') {
 3360:       $result.=&arrayref2str($key).'=';
 3361:     } elsif (ref($key) eq 'HASH') {
 3362:       $result.=&hashref2str($key).'=';
 3363:     } elsif (ref($key)) {
 3364:       $result.='=';
 3365:       #print("Got a ref of ".(ref($key))." skipping.");
 3366:     } else {
 3367: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3368:     }
 3369: 
 3370:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3371:       $result.=&arrayref2str($hashref->{$key}).'&';
 3372:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3373:       $result.=&hashref2str($hashref->{$key}).'&';
 3374:     } elsif(ref($hashref->{$key})) {
 3375:        $result.='&';
 3376:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3377:     } else {
 3378:       $result.=&escape($hashref->{$key}).'&';
 3379:     }
 3380:   }
 3381:   $result=~s/\&$//;
 3382:   $result .= '__END_HASH_REF__';
 3383:   return $result;
 3384: }
 3385: 
 3386: sub str2hash {
 3387:     my ($string)=@_;
 3388:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3389:     return %$hash;
 3390: }
 3391: 
 3392: sub str2hashref {
 3393:   my ($string) = @_;
 3394: 
 3395:   my %hash;
 3396: 
 3397:   if($string !~ /^__HASH_REF__/) {
 3398:       if (! ($string eq '' || !defined($string))) {
 3399: 	  $hash{'error'}='Not hash reference';
 3400:       }
 3401:       return (\%hash, $string);
 3402:   }
 3403: 
 3404:   $string =~ s/^__HASH_REF__//;
 3405: 
 3406:   while($string !~ /^__END_HASH_REF__/) {
 3407:       #key
 3408:       my $key='';
 3409:       if($string =~ /^__HASH_REF__/) {
 3410:           ($key, $string)=&str2hashref($string);
 3411:           if(defined($key->{'error'})) {
 3412:               $hash{'error'}='Bad data';
 3413:               return (\%hash, $string);
 3414:           }
 3415:       } elsif($string =~ /^__ARRAY_REF__/) {
 3416:           ($key, $string)=&str2arrayref($string);
 3417:           if($key->[0] eq 'Array reference error') {
 3418:               $hash{'error'}='Bad data';
 3419:               return (\%hash, $string);
 3420:           }
 3421:       } else {
 3422:           $string =~ s/^(.*?)=//;
 3423: 	  $key=&unescape($1);
 3424:       }
 3425:       $string =~ s/^=//;
 3426: 
 3427:       #value
 3428:       my $value='';
 3429:       if($string =~ /^__HASH_REF__/) {
 3430:           ($value, $string)=&str2hashref($string);
 3431:           if(defined($value->{'error'})) {
 3432:               $hash{'error'}='Bad data';
 3433:               return (\%hash, $string);
 3434:           }
 3435:       } elsif($string =~ /^__ARRAY_REF__/) {
 3436:           ($value, $string)=&str2arrayref($string);
 3437:           if($value->[0] eq 'Array reference error') {
 3438:               $hash{'error'}='Bad data';
 3439:               return (\%hash, $string);
 3440:           }
 3441:       } else {
 3442: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3443:       }
 3444:       $string =~ s/^&//;
 3445: 
 3446:       $hash{$key}=$value;
 3447:   }
 3448: 
 3449:   $string =~ s/^__END_HASH_REF__//;
 3450: 
 3451:   return (\%hash, $string);
 3452: }
 3453: 
 3454: sub str2array {
 3455:     my ($string)=@_;
 3456:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3457:     return @$array;
 3458: }
 3459: 
 3460: sub str2arrayref {
 3461:   my ($string) = @_;
 3462:   my @array;
 3463: 
 3464:   if($string !~ /^__ARRAY_REF__/) {
 3465:       if (! ($string eq '' || !defined($string))) {
 3466: 	  $array[0]='Array reference error';
 3467:       }
 3468:       return (\@array, $string);
 3469:   }
 3470: 
 3471:   $string =~ s/^__ARRAY_REF__//;
 3472: 
 3473:   while($string !~ /^__END_ARRAY_REF__/) {
 3474:       my $value='';
 3475:       if($string =~ /^__HASH_REF__/) {
 3476:           ($value, $string)=&str2hashref($string);
 3477:           if(defined($value->{'error'})) {
 3478:               $array[0] ='Array reference error';
 3479:               return (\@array, $string);
 3480:           }
 3481:       } elsif($string =~ /^__ARRAY_REF__/) {
 3482:           ($value, $string)=&str2arrayref($string);
 3483:           if($value->[0] eq 'Array reference error') {
 3484:               $array[0] ='Array reference error';
 3485:               return (\@array, $string);
 3486:           }
 3487:       } else {
 3488: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3489:       }
 3490:       $string =~ s/^&//;
 3491: 
 3492:       push(@array, $value);
 3493:   }
 3494: 
 3495:   $string =~ s/^__END_ARRAY_REF__//;
 3496: 
 3497:   return (\@array, $string);
 3498: }
 3499: 
 3500: # -------------------------------------------------------------------Temp Store
 3501: 
 3502: sub tmpreset {
 3503:   my ($symb,$namespace,$domain,$stuname) = @_;
 3504:   if (!$symb) {
 3505:     $symb=&symbread();
 3506:     if (!$symb) { $symb= $env{'request.url'}; }
 3507:   }
 3508:   $symb=escape($symb);
 3509: 
 3510:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3511:   $namespace=~s/\//\_/g;
 3512:   $namespace=~s/\W//g;
 3513: 
 3514:   if (!$domain) { $domain=$env{'user.domain'}; }
 3515:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3516:   if ($domain eq 'public' && $stuname eq 'public') {
 3517:       $stuname=$ENV{'REMOTE_ADDR'};
 3518:   }
 3519:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3520:   my %hash;
 3521:   if (tie(%hash,'GDBM_File',
 3522: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3523: 	  &GDBM_WRCREAT(),0640)) {
 3524:     foreach my $key (keys(%hash)) {
 3525:       if ($key=~ /:$symb/) {
 3526: 	delete($hash{$key});
 3527:       }
 3528:     }
 3529:   }
 3530: }
 3531: 
 3532: sub tmpstore {
 3533:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3534: 
 3535:   if (!$symb) {
 3536:     $symb=&symbread();
 3537:     if (!$symb) { $symb= $env{'request.url'}; }
 3538:   }
 3539:   $symb=escape($symb);
 3540: 
 3541:   if (!$namespace) {
 3542:     # I don't think we would ever want to store this for a course.
 3543:     # it seems this will only be used if we don't have a course.
 3544:     #$namespace=$env{'request.course.id'};
 3545:     #if (!$namespace) {
 3546:       $namespace=$env{'request.state'};
 3547:     #}
 3548:   }
 3549:   $namespace=~s/\//\_/g;
 3550:   $namespace=~s/\W//g;
 3551:   if (!$domain) { $domain=$env{'user.domain'}; }
 3552:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3553:   if ($domain eq 'public' && $stuname eq 'public') {
 3554:       $stuname=$ENV{'REMOTE_ADDR'};
 3555:   }
 3556:   my $now=time;
 3557:   my %hash;
 3558:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3559:   if (tie(%hash,'GDBM_File',
 3560: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3561: 	  &GDBM_WRCREAT(),0640)) {
 3562:     $hash{"version:$symb"}++;
 3563:     my $version=$hash{"version:$symb"};
 3564:     my $allkeys=''; 
 3565:     foreach my $key (keys(%$storehash)) {
 3566:       $allkeys.=$key.':';
 3567:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3568:     }
 3569:     $hash{"$version:$symb:timestamp"}=$now;
 3570:     $allkeys.='timestamp';
 3571:     $hash{"$version:keys:$symb"}=$allkeys;
 3572:     if (untie(%hash)) {
 3573:       return 'ok';
 3574:     } else {
 3575:       return "error:$!";
 3576:     }
 3577:   } else {
 3578:     return "error:$!";
 3579:   }
 3580: }
 3581: 
 3582: # -----------------------------------------------------------------Temp Restore
 3583: 
 3584: sub tmprestore {
 3585:   my ($symb,$namespace,$domain,$stuname) = @_;
 3586: 
 3587:   if (!$symb) {
 3588:     $symb=&symbread();
 3589:     if (!$symb) { $symb= $env{'request.url'}; }
 3590:   }
 3591:   $symb=escape($symb);
 3592: 
 3593:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3594: 
 3595:   if (!$domain) { $domain=$env{'user.domain'}; }
 3596:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3597:   if ($domain eq 'public' && $stuname eq 'public') {
 3598:       $stuname=$ENV{'REMOTE_ADDR'};
 3599:   }
 3600:   my %returnhash;
 3601:   $namespace=~s/\//\_/g;
 3602:   $namespace=~s/\W//g;
 3603:   my %hash;
 3604:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3605:   if (tie(%hash,'GDBM_File',
 3606: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3607: 	  &GDBM_READER(),0640)) {
 3608:     my $version=$hash{"version:$symb"};
 3609:     $returnhash{'version'}=$version;
 3610:     my $scope;
 3611:     for ($scope=1;$scope<=$version;$scope++) {
 3612:       my $vkeys=$hash{"$scope:keys:$symb"};
 3613:       my @keys=split(/:/,$vkeys);
 3614:       my $key;
 3615:       $returnhash{"$scope:keys"}=$vkeys;
 3616:       foreach $key (@keys) {
 3617: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3618: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3619:       }
 3620:     }
 3621:     if (!(untie(%hash))) {
 3622:       return "error:$!";
 3623:     }
 3624:   } else {
 3625:     return "error:$!";
 3626:   }
 3627:   return %returnhash;
 3628: }
 3629: 
 3630: # ----------------------------------------------------------------------- Store
 3631: 
 3632: sub store {
 3633:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3634:     my $home='';
 3635: 
 3636:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3637: 
 3638:     $symb=&symbclean($symb);
 3639:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3640: 
 3641:     if (!$domain) { $domain=$env{'user.domain'}; }
 3642:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3643: 
 3644:     &devalidate($symb,$stuname,$domain);
 3645: 
 3646:     $symb=escape($symb);
 3647:     if (!$namespace) { 
 3648:        unless ($namespace=$env{'request.course.id'}) { 
 3649:           return ''; 
 3650:        } 
 3651:     }
 3652:     if (!$home) { $home=$env{'user.home'}; }
 3653: 
 3654:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3655:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3656: 
 3657:     my $namevalue='';
 3658:     foreach my $key (keys(%$storehash)) {
 3659:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3660:     }
 3661:     $namevalue=~s/\&$//;
 3662:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3663:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3664: }
 3665: 
 3666: # -------------------------------------------------------------- Critical Store
 3667: 
 3668: sub cstore {
 3669:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3670:     my $home='';
 3671: 
 3672:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3673: 
 3674:     $symb=&symbclean($symb);
 3675:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3676: 
 3677:     if (!$domain) { $domain=$env{'user.domain'}; }
 3678:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3679: 
 3680:     &devalidate($symb,$stuname,$domain);
 3681: 
 3682:     $symb=escape($symb);
 3683:     if (!$namespace) { 
 3684:        unless ($namespace=$env{'request.course.id'}) { 
 3685:           return ''; 
 3686:        } 
 3687:     }
 3688:     if (!$home) { $home=$env{'user.home'}; }
 3689: 
 3690:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3691:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3692: 
 3693:     my $namevalue='';
 3694:     foreach my $key (keys(%$storehash)) {
 3695:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3696:     }
 3697:     $namevalue=~s/\&$//;
 3698:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3699:     return critical
 3700:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3701: }
 3702: 
 3703: # --------------------------------------------------------------------- Restore
 3704: 
 3705: sub restore {
 3706:     my ($symb,$namespace,$domain,$stuname) = @_;
 3707:     my $home='';
 3708: 
 3709:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3710: 
 3711:     if (!$symb) {
 3712:       unless ($symb=escape(&symbread())) { return ''; }
 3713:     } else {
 3714:       $symb=&escape(&symbclean($symb));
 3715:     }
 3716:     if (!$namespace) { 
 3717:        unless ($namespace=$env{'request.course.id'}) { 
 3718:           return ''; 
 3719:        } 
 3720:     }
 3721:     if (!$domain) { $domain=$env{'user.domain'}; }
 3722:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3723:     if (!$home) { $home=$env{'user.home'}; }
 3724:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3725: 
 3726:     my %returnhash=();
 3727:     foreach my $line (split(/\&/,$answer)) {
 3728: 	my ($name,$value)=split(/\=/,$line);
 3729:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3730:     }
 3731:     my $version;
 3732:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3733:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3734:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3735:        }
 3736:     }
 3737:     return %returnhash;
 3738: }
 3739: 
 3740: # ---------------------------------------------------------- Course Description
 3741: 
 3742: sub coursedescription {
 3743:     my ($courseid,$args)=@_;
 3744:     $courseid=~s/^\///;
 3745:     $courseid=~s/\_/\//g;
 3746:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3747:     my $chome=&homeserver($cnum,$cdomain);
 3748:     my $normalid=$cdomain.'_'.$cnum;
 3749:     # need to always cache even if we get errors otherwise we keep 
 3750:     # trying and trying and trying to get the course description.
 3751:     my %envhash=();
 3752:     my %returnhash=();
 3753:     
 3754:     my $expiretime=600;
 3755:     if ($env{'request.course.id'} eq $normalid) {
 3756: 	$expiretime=120;
 3757:     }
 3758: 
 3759:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3760:     if (!$args->{'freshen_cache'}
 3761: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3762: 	foreach my $key (keys(%env)) {
 3763: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3764: 	    my ($setting) = $1;
 3765: 	    $returnhash{$setting} = $env{$key};
 3766: 	}
 3767: 	return %returnhash;
 3768:     }
 3769: 
 3770:     # get the data agin
 3771:     if (!$args->{'one_time'}) {
 3772: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3773:     }
 3774: 
 3775:     if ($chome ne 'no_host') {
 3776:        %returnhash=&dump('environment',$cdomain,$cnum);
 3777:        if (!exists($returnhash{'con_lost'})) {
 3778:            $returnhash{'home'}= $chome;
 3779: 	   $returnhash{'domain'} = $cdomain;
 3780: 	   $returnhash{'num'} = $cnum;
 3781:            if (!defined($returnhash{'type'})) {
 3782:                $returnhash{'type'} = 'Course';
 3783:            }
 3784:            while (my ($name,$value) = each %returnhash) {
 3785:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3786:            }
 3787:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3788:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3789: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3790:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3791:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3792:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3793:        }
 3794:     }
 3795:     if (!$args->{'one_time'}) {
 3796: 	&appenv(\%envhash);
 3797:     }
 3798:     return %returnhash;
 3799: }
 3800: 
 3801: # -------------------------------------------------See if a user is privileged
 3802: 
 3803: sub privileged {
 3804:     my ($username,$domain)=@_;
 3805:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3806: 			&homeserver($username,$domain));
 3807:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3808:         ($rolesdump =~ /^error:/)) {
 3809:         return 0;
 3810:     }
 3811:     my $now=time;
 3812:     if ($rolesdump ne '') {
 3813:         foreach my $entry (split(/&/,$rolesdump)) {
 3814: 	    if ($entry!~/^rolesdef_/) {
 3815: 		my ($area,$role)=split(/=/,$entry);
 3816: 		$area=~s/\_\w\w$//;
 3817: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3818: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3819: 		    my $active=1;
 3820: 		    if ($tend) {
 3821: 			if ($tend<$now) { $active=0; }
 3822: 		    }
 3823: 		    if ($tstart) {
 3824: 			if ($tstart>$now) { $active=0; }
 3825: 		    }
 3826: 		    if ($active) { return 1; }
 3827: 		}
 3828: 	    }
 3829: 	}
 3830:     }
 3831:     return 0;
 3832: }
 3833: 
 3834: # -------------------------------------------------------- Get user privileges
 3835: 
 3836: sub rolesinit {
 3837:     my ($domain,$username,$authhost)=@_;
 3838:     my $now=time;
 3839:     my %userroles = ('user.login.time' => $now);
 3840:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3841:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3842:         ($rolesdump =~ /^error:/)) { 
 3843:         return \%userroles;
 3844:     }
 3845:     my %allroles=();
 3846:     my %allgroups=();   
 3847:     my $group_privs;
 3848: 
 3849:     if ($rolesdump ne '') {
 3850:         foreach my $entry (split(/&/,$rolesdump)) {
 3851: 	  if ($entry!~/^rolesdef_/) {
 3852:             my ($area,$role)=split(/=/,$entry);
 3853: 	    $area=~s/\_\w\w$//;
 3854:             my ($trole,$tend,$tstart,$group_privs);
 3855: 	    if ($role=~/^cr/) { 
 3856: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3857: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3858: 		    ($tend,$tstart)=split('_',$trest);
 3859: 		} else {
 3860: 		    $trole=$role;
 3861: 		}
 3862:             } elsif ($role =~ m|^gr/|) {
 3863:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3864:                 ($trole,$group_privs) = split(/\//,$trole);
 3865:                 $group_privs = &unescape($group_privs);
 3866: 	    } else {
 3867: 		($trole,$tend,$tstart)=split(/_/,$role);
 3868: 	    }
 3869: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3870: 					 $username);
 3871: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3872:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3873:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3874:             if (($area ne '') && ($trole ne '')) {
 3875: 		my $spec=$trole.'.'.$area;
 3876: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3877: 		if ($trole =~ /^cr\//) {
 3878:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3879:                 } elsif ($trole eq 'gr') {
 3880:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3881: 		} else {
 3882:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3883: 		}
 3884:             }
 3885:           }
 3886:         }
 3887:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3888:         $userroles{'user.adv'}    = $adv;
 3889: 	$userroles{'user.author'} = $author;
 3890:         $env{'user.adv'}=$adv;
 3891:     }
 3892:     return \%userroles;  
 3893: }
 3894: 
 3895: sub set_arearole {
 3896:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3897: # log the associated role with the area
 3898:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3899:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3900: }
 3901: 
 3902: sub custom_roleprivs {
 3903:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3904:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3905:     my $homsvr=homeserver($rauthor,$rdomain);
 3906:     if (&hostname($homsvr) ne '') {
 3907:         my ($rdummy,$roledef)=
 3908:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3909:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3910:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3911:             if (defined($syspriv)) {
 3912:                 if ($trest =~ /^$match_community$/) {
 3913:                     $syspriv =~ s/bre\&S//; 
 3914:                 }
 3915:                 $$allroles{'cm./'}.=':'.$syspriv;
 3916:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3917:             }
 3918:             if ($tdomain ne '') {
 3919:                 if (defined($dompriv)) {
 3920:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3921:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3922:                 }
 3923:                 if (($trest ne '') && (defined($coursepriv))) {
 3924:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3925:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3926:                 }
 3927:             }
 3928:         }
 3929:     }
 3930: }
 3931: 
 3932: sub group_roleprivs {
 3933:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3934:     my $access = 1;
 3935:     my $now = time;
 3936:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3937:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3938:     if ($access) {
 3939:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3940:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3941:     }
 3942: }
 3943: 
 3944: sub standard_roleprivs {
 3945:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3946:     if (defined($pr{$trole.':s'})) {
 3947:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3948:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3949:     }
 3950:     if ($tdomain ne '') {
 3951:         if (defined($pr{$trole.':d'})) {
 3952:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3953:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3954:         }
 3955:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3956:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3957:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3958:         }
 3959:     }
 3960: }
 3961: 
 3962: sub set_userprivs {
 3963:     my ($userroles,$allroles,$allgroups) = @_; 
 3964:     my $author=0;
 3965:     my $adv=0;
 3966:     my %grouproles = ();
 3967:     if (keys(%{$allgroups}) > 0) {
 3968:         foreach my $role (keys(%{$allroles})) {
 3969:             my ($trole,$area,$sec,$extendedarea);
 3970:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3971:                 $trole = $1;
 3972:                 $area = $2;
 3973:                 $sec = $3;
 3974:                 $extendedarea = $area.$sec;
 3975:                 if (exists($$allgroups{$area})) {
 3976:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3977:                         my $spec = $trole.'.'.$extendedarea;
 3978:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3979:                                                 $$allgroups{$area}{$group};
 3980:                     }
 3981:                 }
 3982:             }
 3983:         }
 3984:     }
 3985:     foreach my $group (keys(%grouproles)) {
 3986:         $$allroles{$group} = $grouproles{$group};
 3987:     }
 3988:     foreach my $role (keys(%{$allroles})) {
 3989:         my %thesepriv;
 3990:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3991:         foreach my $item (split(/:/,$$allroles{$role})) {
 3992:             if ($item ne '') {
 3993:                 my ($privilege,$restrictions)=split(/&/,$item);
 3994:                 if ($restrictions eq '') {
 3995:                     $thesepriv{$privilege}='F';
 3996:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3997:                     $thesepriv{$privilege}.=$restrictions;
 3998:                 }
 3999:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4000:             }
 4001:         }
 4002:         my $thesestr='';
 4003:         foreach my $priv (keys(%thesepriv)) {
 4004: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4005: 	}
 4006:         $userroles->{'user.priv.'.$role} = $thesestr;
 4007:     }
 4008:     return ($author,$adv);
 4009: }
 4010: 
 4011: sub role_status {
 4012:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4013:     my @pwhere = ();
 4014:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4015:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4016:         unless (!defined($$role) || $$role eq '') {
 4017:             $$where=join('.',@pwhere);
 4018:             $$trolecode=$$role.'.'.$$where;
 4019:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4020:             $$tstatus='is';
 4021:             if ($$tstart && $$tstart>$then) {
 4022:                 $$tstatus='future';
 4023:                 if ($$tstart<$now) {
 4024:                     if ($$tstart && $$tstart>$refresh) {
 4025:                         if (($$where ne '') && ($$role ne '')) {
 4026:                             my (%allroles,%allgroups,$group_privs);
 4027:                             my %userroles = (
 4028:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4029:                             );
 4030:                             my $spec=$$role.'.'.$$where;
 4031:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4032:                             if ($$role eq 'gr') {
 4033:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4034:                                                     $env{'user.name'})=@_;
 4035:                                 my ($trole) = split('_',$role,1);
 4036:                                 (undef,my $group_privs) = split(/\//,$trole);
 4037:                                 $group_privs = &unescape($group_privs);
 4038:                             }
 4039:                             if ($$role =~ /^cr\//) {
 4040:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4041:                             } elsif ($$role eq 'gr') {
 4042:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4043:                                                     $env{'user.name'});
 4044:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 4045:                                 (undef,my $group_privs) = split(/\//,$trole);
 4046:                                 $group_privs = &unescape($group_privs);
 4047:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4048:                             } else {
 4049:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4050:                             }
 4051:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4052:                             &appenv(\%userroles,[$$role,'cm']);
 4053:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4054:                         }
 4055:                     }
 4056:                     $$tstatus = 'is';
 4057:                 }
 4058:             }
 4059:             if ($$tend) {
 4060:                 if ($$tend<$then) {
 4061:                     $$tstatus='expired';
 4062:                 } elsif ($$tend<$now) {
 4063:                     $$tstatus='will_not';
 4064:                 }
 4065:             }
 4066:         }
 4067:     }
 4068: }
 4069: 
 4070: sub check_adhoc_privs {
 4071:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 4072:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4073:     if ($env{$cckey}) {
 4074:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4075:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4076:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4077:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4078:         }
 4079:     } else {
 4080:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4081:     }
 4082: }
 4083: 
 4084: sub set_adhoc_privileges {
 4085: # role can be cc or ca
 4086:     my ($dcdom,$pickedcourse,$role) = @_;
 4087:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4088:     my $spec = $role.'.'.$area;
 4089:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4090:                                   $env{'user.name'});
 4091:     my %ccrole = ();
 4092:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4093:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4094:     &appenv(\%userroles,[$role,'cm']);
 4095:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4096:     &appenv( {'request.role'        => $spec,
 4097:               'request.role.domain' => $dcdom,
 4098:               'request.course.sec'  => ''
 4099:              }
 4100:            );
 4101:     my $tadv=0;
 4102:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4103:     &appenv({'request.role.adv'    => $tadv});
 4104: }
 4105: 
 4106: # --------------------------------------------------------------- get interface
 4107: 
 4108: sub get {
 4109:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4110:    my $items='';
 4111:    foreach my $item (@$storearr) {
 4112:        $items.=&escape($item).'&';
 4113:    }
 4114:    $items=~s/\&$//;
 4115:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4116:    if (!$uname) { $uname=$env{'user.name'}; }
 4117:    my $uhome=&homeserver($uname,$udomain);
 4118: 
 4119:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4120:    my @pairs=split(/\&/,$rep);
 4121:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4122:      return @pairs;
 4123:    }
 4124:    my %returnhash=();
 4125:    my $i=0;
 4126:    foreach my $item (@$storearr) {
 4127:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4128:       $i++;
 4129:    }
 4130:    return %returnhash;
 4131: }
 4132: 
 4133: # --------------------------------------------------------------- del interface
 4134: 
 4135: sub del {
 4136:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4137:    my $items='';
 4138:    foreach my $item (@$storearr) {
 4139:        $items.=&escape($item).'&';
 4140:    }
 4141: 
 4142:    $items=~s/\&$//;
 4143:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4144:    if (!$uname) { $uname=$env{'user.name'}; }
 4145:    my $uhome=&homeserver($uname,$udomain);
 4146:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4147: }
 4148: 
 4149: # -------------------------------------------------------------- dump interface
 4150: 
 4151: sub dump {
 4152:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4153:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4154:     if (!$uname) { $uname=$env{'user.name'}; }
 4155:     my $uhome=&homeserver($uname,$udomain);
 4156:     if ($regexp) {
 4157: 	$regexp=&escape($regexp);
 4158:     } else {
 4159: 	$regexp='.';
 4160:     }
 4161:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4162:     my @pairs=split(/\&/,$rep);
 4163:     my %returnhash=();
 4164:     foreach my $item (@pairs) {
 4165: 	my ($key,$value)=split(/=/,$item,2);
 4166: 	$key = &unescape($key);
 4167: 	next if ($key =~ /^error: 2 /);
 4168: 	$returnhash{$key}=&thaw_unescape($value);
 4169:     }
 4170:     return %returnhash;
 4171: }
 4172: 
 4173: # --------------------------------------------------------- dumpstore interface
 4174: 
 4175: sub dumpstore {
 4176:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4177:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4178:    if (!$uname) { $uname=$env{'user.name'}; }
 4179:    my $uhome=&homeserver($uname,$udomain);
 4180:    if ($regexp) {
 4181:        $regexp=&escape($regexp);
 4182:    } else {
 4183:        $regexp='.';
 4184:    }
 4185:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4186:    my @pairs=split(/\&/,$rep);
 4187:    my %returnhash=();
 4188:    foreach my $item (@pairs) {
 4189:        my ($key,$value)=split(/=/,$item,2);
 4190:        next if ($key =~ /^error: 2 /);
 4191:        $returnhash{$key}=&thaw_unescape($value);
 4192:    }
 4193:    return %returnhash;
 4194: }
 4195: 
 4196: # -------------------------------------------------------------- keys interface
 4197: 
 4198: sub getkeys {
 4199:    my ($namespace,$udomain,$uname)=@_;
 4200:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4201:    if (!$uname) { $uname=$env{'user.name'}; }
 4202:    my $uhome=&homeserver($uname,$udomain);
 4203:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4204:    my @keyarray=();
 4205:    foreach my $key (split(/\&/,$rep)) {
 4206:       next if ($key =~ /^error: 2 /);
 4207:       push(@keyarray,&unescape($key));
 4208:    }
 4209:    return @keyarray;
 4210: }
 4211: 
 4212: # --------------------------------------------------------------- currentdump
 4213: sub currentdump {
 4214:    my ($courseid,$sdom,$sname)=@_;
 4215:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4216:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4217:    $sname    = $env{'user.name'}         if (! defined($sname));
 4218:    my $uhome = &homeserver($sname,$sdom);
 4219:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4220:    return if ($rep =~ /^(error:|no_such_host)/);
 4221:    #
 4222:    my %returnhash=();
 4223:    #
 4224:    if ($rep eq "unknown_cmd") { 
 4225:        # an old lond will not know currentdump
 4226:        # Do a dump and make it look like a currentdump
 4227:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4228:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4229:        my %hash = @tmp;
 4230:        @tmp=();
 4231:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4232:    } else {
 4233:        my @pairs=split(/\&/,$rep);
 4234:        foreach my $pair (@pairs) {
 4235:            my ($key,$value)=split(/=/,$pair,2);
 4236:            my ($symb,$param) = split(/:/,$key);
 4237:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4238:                                                         &thaw_unescape($value);
 4239:        }
 4240:    }
 4241:    return %returnhash;
 4242: }
 4243: 
 4244: sub convert_dump_to_currentdump{
 4245:     my %hash = %{shift()};
 4246:     my %returnhash;
 4247:     # Code ripped from lond, essentially.  The only difference
 4248:     # here is the unescaping done by lonnet::dump().  Conceivably
 4249:     # we might run in to problems with parameter names =~ /^v\./
 4250:     while (my ($key,$value) = each(%hash)) {
 4251:         my ($v,$symb,$param) = split(/:/,$key);
 4252: 	$symb  = &unescape($symb);
 4253: 	$param = &unescape($param);
 4254:         next if ($v eq 'version' || $symb eq 'keys');
 4255:         next if (exists($returnhash{$symb}) &&
 4256:                  exists($returnhash{$symb}->{$param}) &&
 4257:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4258:         $returnhash{$symb}->{$param}=$value;
 4259:         $returnhash{$symb}->{'v.'.$param}=$v;
 4260:     }
 4261:     #
 4262:     # Remove all of the keys in the hashes which keep track of
 4263:     # the version of the parameter.
 4264:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4265:         # use a foreach because we are going to delete from the hash.
 4266:         foreach my $key (keys(%$param_hash)) {
 4267:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4268:         }
 4269:     }
 4270:     return \%returnhash;
 4271: }
 4272: 
 4273: # ------------------------------------------------------ critical inc interface
 4274: 
 4275: sub cinc {
 4276:     return &inc(@_,'critical');
 4277: }
 4278: 
 4279: # --------------------------------------------------------------- inc interface
 4280: 
 4281: sub inc {
 4282:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4283:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4284:     if (!$uname) { $uname=$env{'user.name'}; }
 4285:     my $uhome=&homeserver($uname,$udomain);
 4286:     my $items='';
 4287:     if (! ref($store)) {
 4288:         # got a single value, so use that instead
 4289:         $items = &escape($store).'=&';
 4290:     } elsif (ref($store) eq 'SCALAR') {
 4291:         $items = &escape($$store).'=&';        
 4292:     } elsif (ref($store) eq 'ARRAY') {
 4293:         $items = join('=&',map {&escape($_);} @{$store});
 4294:     } elsif (ref($store) eq 'HASH') {
 4295:         while (my($key,$value) = each(%{$store})) {
 4296:             $items.= &escape($key).'='.&escape($value).'&';
 4297:         }
 4298:     }
 4299:     $items=~s/\&$//;
 4300:     if ($critical) {
 4301: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4302:     } else {
 4303: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4304:     }
 4305: }
 4306: 
 4307: # --------------------------------------------------------------- put interface
 4308: 
 4309: sub put {
 4310:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4311:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4312:    if (!$uname) { $uname=$env{'user.name'}; }
 4313:    my $uhome=&homeserver($uname,$udomain);
 4314:    my $items='';
 4315:    foreach my $item (keys(%$storehash)) {
 4316:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4317:    }
 4318:    $items=~s/\&$//;
 4319:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4320: }
 4321: 
 4322: # ------------------------------------------------------------ newput interface
 4323: 
 4324: sub newput {
 4325:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4326:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4327:    if (!$uname) { $uname=$env{'user.name'}; }
 4328:    my $uhome=&homeserver($uname,$udomain);
 4329:    my $items='';
 4330:    foreach my $key (keys(%$storehash)) {
 4331:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4332:    }
 4333:    $items=~s/\&$//;
 4334:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4335: }
 4336: 
 4337: # ---------------------------------------------------------  putstore interface
 4338: 
 4339: sub putstore {
 4340:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4341:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4342:    if (!$uname) { $uname=$env{'user.name'}; }
 4343:    my $uhome=&homeserver($uname,$udomain);
 4344:    my $items='';
 4345:    foreach my $key (keys(%$storehash)) {
 4346:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4347:    }
 4348:    $items=~s/\&$//;
 4349:    my $esc_symb=&escape($symb);
 4350:    my $esc_v=&escape($version);
 4351:    my $reply =
 4352:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4353: 	      $uhome);
 4354:    if ($reply eq 'unknown_cmd') {
 4355:        # gfall back to way things use to be done
 4356:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4357: 			    $uname);
 4358:    }
 4359:    return $reply;
 4360: }
 4361: 
 4362: sub old_putstore {
 4363:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4364:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4365:     if (!$uname) { $uname=$env{'user.name'}; }
 4366:     my $uhome=&homeserver($uname,$udomain);
 4367:     my %newstorehash;
 4368:     foreach my $item (keys(%$storehash)) {
 4369: 	my $key = $version.':'.&escape($symb).':'.$item;
 4370: 	$newstorehash{$key} = $storehash->{$item};
 4371:     }
 4372:     my $items='';
 4373:     my %allitems = ();
 4374:     foreach my $item (keys(%newstorehash)) {
 4375: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4376: 	    my $key = $1.':keys:'.$2;
 4377: 	    $allitems{$key} .= $3.':';
 4378: 	}
 4379: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4380:     }
 4381:     foreach my $item (keys(%allitems)) {
 4382: 	$allitems{$item} =~ s/\:$//;
 4383: 	$items.= $item.'='.$allitems{$item}.'&';
 4384:     }
 4385:     $items=~s/\&$//;
 4386:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4387: }
 4388: 
 4389: # ------------------------------------------------------ critical put interface
 4390: 
 4391: sub cput {
 4392:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4393:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4394:    if (!$uname) { $uname=$env{'user.name'}; }
 4395:    my $uhome=&homeserver($uname,$udomain);
 4396:    my $items='';
 4397:    foreach my $item (keys(%$storehash)) {
 4398:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4399:    }
 4400:    $items=~s/\&$//;
 4401:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4402: }
 4403: 
 4404: # -------------------------------------------------------------- eget interface
 4405: 
 4406: sub eget {
 4407:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4408:    my $items='';
 4409:    foreach my $item (@$storearr) {
 4410:        $items.=&escape($item).'&';
 4411:    }
 4412:    $items=~s/\&$//;
 4413:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4414:    if (!$uname) { $uname=$env{'user.name'}; }
 4415:    my $uhome=&homeserver($uname,$udomain);
 4416:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4417:    my @pairs=split(/\&/,$rep);
 4418:    my %returnhash=();
 4419:    my $i=0;
 4420:    foreach my $item (@$storearr) {
 4421:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4422:       $i++;
 4423:    }
 4424:    return %returnhash;
 4425: }
 4426: 
 4427: # ------------------------------------------------------------ tmpput interface
 4428: sub tmpput {
 4429:     my ($storehash,$server,$context)=@_;
 4430:     my $items='';
 4431:     foreach my $item (keys(%$storehash)) {
 4432: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4433:     }
 4434:     $items=~s/\&$//;
 4435:     if (defined($context)) {
 4436:         $items .= ':'.&escape($context);
 4437:     }
 4438:     return &reply("tmpput:$items",$server);
 4439: }
 4440: 
 4441: # ------------------------------------------------------------ tmpget interface
 4442: sub tmpget {
 4443:     my ($token,$server)=@_;
 4444:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4445:     my $rep=&reply("tmpget:$token",$server);
 4446:     my %returnhash;
 4447:     foreach my $item (split(/\&/,$rep)) {
 4448: 	my ($key,$value)=split(/=/,$item);
 4449:         next if ($key =~ /^error: 2 /);
 4450: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4451:     }
 4452:     return %returnhash;
 4453: }
 4454: 
 4455: # ------------------------------------------------------------ tmpget interface
 4456: sub tmpdel {
 4457:     my ($token,$server)=@_;
 4458:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4459:     return &reply("tmpdel:$token",$server);
 4460: }
 4461: 
 4462: # -------------------------------------------------- portfolio access checking
 4463: 
 4464: sub portfolio_access {
 4465:     my ($requrl) = @_;
 4466:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4467:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4468:     if ($result) {
 4469:         my %setters;
 4470:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4471:             my ($startblock,$endblock) =
 4472:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4473:             if ($startblock && $endblock) {
 4474:                 return 'B';
 4475:             }
 4476:         } else {
 4477:             my ($startblock,$endblock) =
 4478:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4479:             if ($startblock && $endblock) {
 4480:                 return 'B';
 4481:             }
 4482:         }
 4483:     }
 4484:     if ($result eq 'ok') {
 4485:        return 'F';
 4486:     } elsif ($result =~ /^[^:]+:guest_/) {
 4487:        return 'A';
 4488:     }
 4489:     return '';
 4490: }
 4491: 
 4492: sub get_portfolio_access {
 4493:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4494: 
 4495:     if (!ref($access_hash)) {
 4496: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4497: 	my %access_controls = &get_access_controls($current_perms,$group,
 4498: 						   $file_name);
 4499: 	$access_hash = $access_controls{$file_name};
 4500:     }
 4501: 
 4502:     my ($public,$guest,@domains,@users,@courses,@groups);
 4503:     my $now = time;
 4504:     if (ref($access_hash) eq 'HASH') {
 4505:         foreach my $key (keys(%{$access_hash})) {
 4506:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4507:             if ($start > $now) {
 4508:                 next;
 4509:             }
 4510:             if ($end && $end<$now) {
 4511:                 next;
 4512:             }
 4513:             if ($scope eq 'public') {
 4514:                 $public = $key;
 4515:                 last;
 4516:             } elsif ($scope eq 'guest') {
 4517:                 $guest = $key;
 4518:             } elsif ($scope eq 'domains') {
 4519:                 push(@domains,$key);
 4520:             } elsif ($scope eq 'users') {
 4521:                 push(@users,$key);
 4522:             } elsif ($scope eq 'course') {
 4523:                 push(@courses,$key);
 4524:             } elsif ($scope eq 'group') {
 4525:                 push(@groups,$key);
 4526:             }
 4527:         }
 4528:         if ($public) {
 4529:             return 'ok';
 4530:         }
 4531:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4532:             if ($guest) {
 4533:                 return $guest;
 4534:             }
 4535:         } else {
 4536:             if (@domains > 0) {
 4537:                 foreach my $domkey (@domains) {
 4538:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4539:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4540:                             return 'ok';
 4541:                         }
 4542:                     }
 4543:                 }
 4544:             }
 4545:             if (@users > 0) {
 4546:                 foreach my $userkey (@users) {
 4547:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4548:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4549:                             if (ref($item) eq 'HASH') {
 4550:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4551:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4552:                                     return 'ok';
 4553:                                 }
 4554:                             }
 4555:                         }
 4556:                     } 
 4557:                 }
 4558:             }
 4559:             my %roleshash;
 4560:             my @courses_and_groups = @courses;
 4561:             push(@courses_and_groups,@groups); 
 4562:             if (@courses_and_groups > 0) {
 4563:                 my (%allgroups,%allroles); 
 4564:                 my ($start,$end,$role,$sec,$group);
 4565:                 foreach my $envkey (%env) {
 4566:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4567:                         my $cid = $2.'_'.$3; 
 4568:                         if ($1 eq 'gr') {
 4569:                             $group = $4;
 4570:                             $allgroups{$cid}{$group} = $env{$envkey};
 4571:                         } else {
 4572:                             if ($4 eq '') {
 4573:                                 $sec = 'none';
 4574:                             } else {
 4575:                                 $sec = $4;
 4576:                             }
 4577:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4578:                         }
 4579:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4580:                         my $cid = $2.'_'.$3;
 4581:                         if ($4 eq '') {
 4582:                             $sec = 'none';
 4583:                         } else {
 4584:                             $sec = $4;
 4585:                         }
 4586:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4587:                     }
 4588:                 }
 4589:                 if (keys(%allroles) == 0) {
 4590:                     return;
 4591:                 }
 4592:                 foreach my $key (@courses_and_groups) {
 4593:                     my %content = %{$$access_hash{$key}};
 4594:                     my $cnum = $content{'number'};
 4595:                     my $cdom = $content{'domain'};
 4596:                     my $cid = $cdom.'_'.$cnum;
 4597:                     if (!exists($allroles{$cid})) {
 4598:                         next;
 4599:                     }    
 4600:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4601:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4602:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4603:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4604:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4605:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4606:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4607:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4608:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4609:                                         if (grep/^all$/,@sections) {
 4610:                                             return 'ok';
 4611:                                         } else {
 4612:                                             if (grep/^$sec$/,@sections) {
 4613:                                                 return 'ok';
 4614:                                             }
 4615:                                         }
 4616:                                     }
 4617:                                 }
 4618:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4619:                                     if (grep/^none$/,@groups) {
 4620:                                         return 'ok';
 4621:                                     }
 4622:                                 } else {
 4623:                                     if (grep/^all$/,@groups) {
 4624:                                         return 'ok';
 4625:                                     } 
 4626:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4627:                                         if (grep/^$group$/,@groups) {
 4628:                                             return 'ok';
 4629:                                         }
 4630:                                     }
 4631:                                 } 
 4632:                             }
 4633:                         }
 4634:                     }
 4635:                 }
 4636:             }
 4637:             if ($guest) {
 4638:                 return $guest;
 4639:             }
 4640:         }
 4641:     }
 4642:     return;
 4643: }
 4644: 
 4645: sub course_group_datechecker {
 4646:     my ($dates,$now,$status) = @_;
 4647:     my ($start,$end) = split(/\./,$dates);
 4648:     if (!$start && !$end) {
 4649:         return 'ok';
 4650:     }
 4651:     if (grep/^active$/,@{$status}) {
 4652:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4653:             return 'ok';
 4654:         }
 4655:     }
 4656:     if (grep/^previous$/,@{$status}) {
 4657:         if ($end > $now ) {
 4658:             return 'ok';
 4659:         }
 4660:     }
 4661:     if (grep/^future$/,@{$status}) {
 4662:         if ($start > $now) {
 4663:             return 'ok';
 4664:         }
 4665:     }
 4666:     return; 
 4667: }
 4668: 
 4669: sub parse_portfolio_url {
 4670:     my ($url) = @_;
 4671: 
 4672:     my ($type,$udom,$unum,$group,$file_name);
 4673:     
 4674:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4675: 	$type = 1;
 4676:         $udom = $1;
 4677:         $unum = $2;
 4678:         $file_name = $3;
 4679:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4680: 	$type = 2;
 4681:         $udom = $1;
 4682:         $unum = $2;
 4683:         $group = $3;
 4684:         $file_name = $3.'/'.$4;
 4685:     }
 4686:     if (wantarray) {
 4687: 	return ($type,$udom,$unum,$file_name,$group);
 4688:     }
 4689:     return $type;
 4690: }
 4691: 
 4692: sub is_portfolio_url {
 4693:     my ($url) = @_;
 4694:     return scalar(&parse_portfolio_url($url));
 4695: }
 4696: 
 4697: sub is_portfolio_file {
 4698:     my ($file) = @_;
 4699:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4700:         return 1;
 4701:     }
 4702:     return;
 4703: }
 4704: 
 4705: sub usertools_access {
 4706:     my ($uname,$udom,$tool,$action,$context) = @_;
 4707:     my ($access,%tools);
 4708:     if ($context eq '') {
 4709:         $context = 'tools';
 4710:     }
 4711:     if ($context eq 'requestcourses') {
 4712:         %tools = (
 4713:                       official   => 1,
 4714:                       unofficial => 1,
 4715:                       community  => 1,
 4716:                  );
 4717:     } else {
 4718:         %tools = (
 4719:                       aboutme   => 1,
 4720:                       blog      => 1,
 4721:                       portfolio => 1,
 4722:                  );
 4723:     }
 4724:     return if (!defined($tools{$tool}));
 4725: 
 4726:     if ((!defined($udom)) || (!defined($uname))) {
 4727:         $udom = $env{'user.domain'};
 4728:         $uname = $env{'user.name'};
 4729:     }
 4730: 
 4731:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4732:         if ($action ne 'reload') {
 4733:             if ($context eq 'requestcourses') {
 4734:                 return $env{'environment.canrequest.'.$tool};
 4735:             } else {
 4736:                 return $env{'environment.availabletools.'.$tool};
 4737:             }
 4738:         }
 4739:     }
 4740: 
 4741:     my ($toolstatus,$inststatus);
 4742: 
 4743:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4744:          ($action ne 'reload')) {
 4745:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4746:         $inststatus = $env{'environment.inststatus'};
 4747:     } else {
 4748:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 4749:         $toolstatus = $userenv{$context.'.'.$tool};
 4750:         $inststatus = $userenv{'inststatus'};
 4751:     }
 4752: 
 4753:     if ($toolstatus ne '') {
 4754:         if ($toolstatus) {
 4755:             $access = 1;
 4756:         } else {
 4757:             $access = 0;
 4758:         }
 4759:         return $access;
 4760:     }
 4761: 
 4762:     my $is_adv = &is_advanced_user($udom,$uname);
 4763:     my %domdef = &get_domain_defaults($udom);
 4764:     if (ref($domdef{$tool}) eq 'HASH') {
 4765:         if ($is_adv) {
 4766:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4767:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4768:                     $access = 1;
 4769:                 } else {
 4770:                     $access = 0;
 4771:                 }
 4772:                 return $access;
 4773:             }
 4774:         }
 4775:         if ($inststatus ne '') {
 4776:             my ($hasaccess,$hasnoaccess);
 4777:             foreach my $affiliation (split(/:/,$inststatus)) {
 4778:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4779:                     if ($domdef{$tool}{$affiliation}) {
 4780:                         $hasaccess = 1;
 4781:                     } else {
 4782:                         $hasnoaccess = 1;
 4783:                     }
 4784:                 }
 4785:             }
 4786:             if ($hasaccess || $hasnoaccess) {
 4787:                 if ($hasaccess) {
 4788:                     $access = 1;
 4789:                 } elsif ($hasnoaccess) {
 4790:                     $access = 0; 
 4791:                 }
 4792:                 return $access;
 4793:             }
 4794:         } else {
 4795:             if ($domdef{$tool}{'default'} ne '') {
 4796:                 if ($domdef{$tool}{'default'}) {
 4797:                     $access = 1;
 4798:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4799:                     $access = 0;
 4800:                 }
 4801:                 return $access;
 4802:             }
 4803:         }
 4804:     } else {
 4805:         if ($context eq 'tools') {
 4806:             $access = 1;
 4807:         } else {
 4808:             $access = 0;
 4809:         }
 4810:         return $access;
 4811:     }
 4812: }
 4813: 
 4814: sub is_advanced_user {
 4815:     my ($udom,$uname) = @_;
 4816:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4817:     my %allroles;
 4818:     my $is_adv;
 4819:     foreach my $role (keys(%roleshash)) {
 4820:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4821:         my $area = '/'.$tdomain.'/'.$trest;
 4822:         if ($sec ne '') {
 4823:             $area .= '/'.$sec;
 4824:         }
 4825:         if (($area ne '') && ($trole ne '')) {
 4826:             my $spec=$trole.'.'.$area;
 4827:             if ($trole =~ /^cr\//) {
 4828:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4829:             } elsif ($trole ne 'gr') {
 4830:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4831:             }
 4832:         }
 4833:     }
 4834:     foreach my $role (keys(%allroles)) {
 4835:         last if ($is_adv);
 4836:         foreach my $item (split(/:/,$allroles{$role})) {
 4837:             if ($item ne '') {
 4838:                 my ($privilege,$restrictions)=split(/&/,$item);
 4839:                 if ($privilege eq 'adv') {
 4840:                     $is_adv = 1;
 4841:                     last;
 4842:                 }
 4843:             }
 4844:         }
 4845:     }
 4846:     return $is_adv;
 4847: }
 4848: 
 4849: sub check_can_request {
 4850:     my ($dom,$can_request,$request_domains) = @_;
 4851:     my $canreq = 0;
 4852:     my ($types,$typename) = &Apache::loncommon::course_types();
 4853:     my @options = ('approval','validate','autolimit');
 4854:     my $optregex = join('|',@options);
 4855:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 4856:         foreach my $type (@{$types}) {
 4857:             if (&usertools_access($env{'user.name'},
 4858:                                   $env{'user.domain'},
 4859:                                   $type,undef,'requestcourses')) {
 4860:                 $canreq ++;
 4861:                 if (ref($request_domains) eq 'HASH') {
 4862:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 4863:                 }
 4864:                 if ($dom eq $env{'user.domain'}) {
 4865:                     $can_request->{$type} = 1;
 4866:                 }
 4867:             }
 4868:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 4869:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 4870:                 if (@curr > 0) {
 4871:                     foreach my $item (@curr) {
 4872:                         if (ref($request_domains) eq 'HASH') {
 4873:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 4874:                             if ($otherdom ne '') {
 4875:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 4876:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 4877:                                         push(@{$request_domains->{$type}},$otherdom);
 4878:                                     }
 4879:                                 } else {
 4880:                                     push(@{$request_domains->{$type}},$otherdom);
 4881:                                 }
 4882:                             }
 4883:                         }
 4884:                     }
 4885:                     unless($dom eq $env{'user.domain'}) {
 4886:                         $canreq ++;
 4887:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 4888:                             $can_request->{$type} = 1;
 4889:                         }
 4890:                     }
 4891:                 }
 4892:             }
 4893:         }
 4894:     }
 4895:     return $canreq;
 4896: }
 4897: 
 4898: # ---------------------------------------------- Custom access rule evaluation
 4899: 
 4900: sub customaccess {
 4901:     my ($priv,$uri)=@_;
 4902:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4903:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4904:     $udom = &LONCAPA::clean_domain($udom);
 4905:     $ucrs = &LONCAPA::clean_username($ucrs);
 4906:     my $access=0;
 4907:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4908: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4909: 	if ($type eq 'user') {
 4910: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4911: 		my ($tdom,$tuname)=split(m{/},$scope);
 4912: 		if ($tdom) {
 4913: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4914: 		}
 4915: 		if ($tuname) {
 4916: 		    if ($tuname ne $env{'user.name'}) { next; }
 4917: 		}
 4918: 		$access=($effect eq 'allow');
 4919: 		last;
 4920: 	    }
 4921: 	} else {
 4922: 	    if ($role) {
 4923: 		if ($role ne $urole) { next; }
 4924: 	    }
 4925: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4926: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4927: 		if ($tdom) {
 4928: 		    if ($tdom ne $udom) { next; }
 4929: 		}
 4930: 		if ($tcrs) {
 4931: 		    if ($tcrs ne $ucrs) { next; }
 4932: 		}
 4933: 		if ($tsec) {
 4934: 		    if ($tsec ne $usec) { next; }
 4935: 		}
 4936: 		$access=($effect eq 'allow');
 4937: 		last;
 4938: 	    }
 4939: 	    if ($realm eq '' && $role eq '') {
 4940: 		$access=($effect eq 'allow');
 4941: 	    }
 4942: 	}
 4943:     }
 4944:     return $access;
 4945: }
 4946: 
 4947: # ------------------------------------------------- Check for a user privilege
 4948: 
 4949: sub allowed {
 4950:     my ($priv,$uri,$symb,$role)=@_;
 4951:     my $ver_orguri=$uri;
 4952:     $uri=&deversion($uri);
 4953:     my $orguri=$uri;
 4954:     $uri=&declutter($uri);
 4955: 
 4956:     if ($priv eq 'evb') {
 4957: # Evade communication block restrictions for specified role in a course
 4958:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4959:             return $1;
 4960:         } else {
 4961:             return;
 4962:         }
 4963:     }
 4964: 
 4965:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4966: # Free bre access to adm and meta resources
 4967:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4968: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4969: 	&& ($priv eq 'bre')) {
 4970: 	return 'F';
 4971:     }
 4972: 
 4973: # Free bre access to user's own portfolio contents
 4974:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4975:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4976: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4977:         my %setters;
 4978:         my ($startblock,$endblock) = 
 4979:             &Apache::loncommon::blockcheck(\%setters,'port');
 4980:         if ($startblock && $endblock) {
 4981:             return 'B';
 4982:         } else {
 4983:             return 'F';
 4984:         }
 4985:     }
 4986: 
 4987: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4988:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4989:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4990:         if (exists($env{'request.course.id'})) {
 4991:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4992:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4993:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4994:                 my $courseprivid=$env{'request.course.id'};
 4995:                 $courseprivid=~s/\_/\//;
 4996:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4997:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4998:                     return $1; 
 4999:                 } else {
 5000:                     if ($env{'request.course.sec'}) {
 5001:                         $courseprivid.='/'.$env{'request.course.sec'};
 5002:                     }
 5003:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5004:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5005:                         return $2;
 5006:                     }
 5007:                 }
 5008:             }
 5009:         }
 5010:     }
 5011: 
 5012: # Free bre to public access
 5013: 
 5014:     if ($priv eq 'bre') {
 5015:         my $copyright=&metadata($uri,'copyright');
 5016: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5017:            return 'F'; 
 5018:         }
 5019:         if ($copyright eq 'priv') {
 5020:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5021: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5022: 		return '';
 5023:             }
 5024:         }
 5025:         if ($copyright eq 'domain') {
 5026:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5027: 	    unless (($env{'user.domain'} eq $1) ||
 5028:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5029: 		return '';
 5030:             }
 5031:         }
 5032:         if ($env{'request.role'}=~ /li\.\//) {
 5033:             # Library role, so allow browsing of resources in this domain.
 5034:             return 'F';
 5035:         }
 5036:         if ($copyright eq 'custom') {
 5037: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5038:         }
 5039:     }
 5040:     # Domain coordinator is trying to create a course
 5041:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5042:         # uri is the requested domain in this case.
 5043:         # comparison to 'request.role.domain' shows if the user has selected
 5044:         # a role of dc for the domain in question.
 5045:         return 'F' if ($uri eq $env{'request.role.domain'});
 5046:     }
 5047: 
 5048:     my $thisallowed='';
 5049:     my $statecond=0;
 5050:     my $courseprivid='';
 5051: 
 5052:     my $ownaccess;
 5053:     # Community Coordinator or Assistant Co-author browsing resource space.
 5054:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5055:         if ($uri eq '') {
 5056:             $ownaccess = 1;
 5057:         } else {
 5058:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5059:                 my $udom = $env{'user.domain'};
 5060:                 my $uname = $env{'user.name'};
 5061:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5062:                     $ownaccess = 1;
 5063:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5064:                     unless ($uri =~ m{\.\./}) {
 5065:                         $ownaccess = 1;
 5066:                     }
 5067:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5068:                     my $now = time;
 5069:                     if ($uri =~ m{^([^/]+)/?$}) {
 5070:                         my $adom = $1;
 5071:                         foreach my $key (keys(%env)) {
 5072:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5073:                                 my ($start,$end) = split('.',$env{$key});
 5074:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5075:                                     $ownaccess = 1;
 5076:                                     last;
 5077:                                 }
 5078:                             }
 5079:                         }
 5080:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5081:                         my $adom = $1;
 5082:                         my $aname = $2;
 5083:                         foreach my $role ('ca','aa') { 
 5084:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5085:                                 my ($start,$end) =
 5086:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5087:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5088:                                     $ownaccess = 1;
 5089:                                     last;
 5090:                                 }
 5091:                             }
 5092:                         }
 5093:                     }
 5094:                 }
 5095:             }
 5096:         }
 5097:     }
 5098: 
 5099: # Course
 5100: 
 5101:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5102:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5103:             $thisallowed.=$1;
 5104:         }
 5105:     }
 5106: 
 5107: # Domain
 5108: 
 5109:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5110:        =~/\Q$priv\E\&([^\:]*)/) {
 5111:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5112:             $thisallowed.=$1;
 5113:         }
 5114:     }
 5115: 
 5116: # Course: uri itself is a course
 5117:     my $courseuri=$uri;
 5118:     $courseuri=~s/\_(\d)/\/$1/;
 5119:     $courseuri=~s/^([^\/])/\/$1/;
 5120: 
 5121:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5122:        =~/\Q$priv\E\&([^\:]*)/) {
 5123:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5124:             $thisallowed.=$1;
 5125:         }
 5126:     }
 5127: 
 5128: # URI is an uploaded document for this course, default permissions don't matter
 5129: # not allowing 'edit' access (editupload) to uploaded course docs
 5130:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5131: 	$thisallowed='';
 5132:         my ($match)=&is_on_map($uri);
 5133:         if ($match) {
 5134:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5135:                   =~/\Q$priv\E\&([^\:]*)/) {
 5136:                 $thisallowed.=$1;
 5137:             }
 5138:         } else {
 5139:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5140:             if ($refuri) {
 5141:                 if ($refuri =~ m|^/adm/|) {
 5142:                     $thisallowed='F';
 5143:                 } else {
 5144:                     $refuri=&declutter($refuri);
 5145:                     my ($match) = &is_on_map($refuri);
 5146:                     if ($match) {
 5147:                         $thisallowed='F';
 5148:                     }
 5149:                 }
 5150:             }
 5151:         }
 5152:     }
 5153: 
 5154:     if ($priv eq 'bre'
 5155: 	&& $thisallowed ne 'F' 
 5156: 	&& $thisallowed ne '2'
 5157: 	&& &is_portfolio_url($uri)) {
 5158: 	$thisallowed = &portfolio_access($uri);
 5159:     }
 5160:     
 5161: # Full access at system, domain or course-wide level? Exit.
 5162:     if ($thisallowed=~/F/) {
 5163: 	return 'F';
 5164:     }
 5165: 
 5166: # If this is generating or modifying users, exit with special codes
 5167: 
 5168:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5169: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5170: 	    my ($audom,$auname)=split('/',$uri);
 5171: # no author name given, so this just checks on the general right to make a co-author in this domain
 5172: 	    unless ($auname) { return $thisallowed; }
 5173: # an author name is given, so we are about to actually make a co-author for a certain account
 5174: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5175: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5176: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5177: 	}
 5178: 	return $thisallowed;
 5179:     }
 5180: #
 5181: # Gathered so far: system, domain and course wide privileges
 5182: #
 5183: # Course: See if uri or referer is an individual resource that is part of 
 5184: # the course
 5185: 
 5186:     if ($env{'request.course.id'}) {
 5187: 
 5188:        $courseprivid=$env{'request.course.id'};
 5189:        if ($env{'request.course.sec'}) {
 5190:           $courseprivid.='/'.$env{'request.course.sec'};
 5191:        }
 5192:        $courseprivid=~s/\_/\//;
 5193:        my $checkreferer=1;
 5194:        my ($match,$cond)=&is_on_map($uri);
 5195:        if ($match) {
 5196:            $statecond=$cond;
 5197:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5198:                =~/\Q$priv\E\&([^\:]*)/) {
 5199:                $thisallowed.=$1;
 5200:                $checkreferer=0;
 5201:            }
 5202:        }
 5203:        
 5204:        if ($checkreferer) {
 5205: 	  my $refuri=$env{'httpref.'.$orguri};
 5206:             unless ($refuri) {
 5207:                 foreach my $key (keys(%env)) {
 5208: 		    if ($key=~/^httpref\..*\*/) {
 5209: 			my $pattern=$key;
 5210:                         $pattern=~s/^httpref\.\/res\///;
 5211:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5212:                         $pattern=~s/\//\\\//g;
 5213:                         if ($orguri=~/$pattern/) {
 5214: 			    $refuri=$env{$key};
 5215:                         }
 5216:                     }
 5217:                 }
 5218:             }
 5219: 
 5220:          if ($refuri) { 
 5221: 	  $refuri=&declutter($refuri);
 5222:           my ($match,$cond)=&is_on_map($refuri);
 5223:             if ($match) {
 5224:               my $refstatecond=$cond;
 5225:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5226:                   =~/\Q$priv\E\&([^\:]*)/) {
 5227:                   $thisallowed.=$1;
 5228:                   $uri=$refuri;
 5229:                   $statecond=$refstatecond;
 5230:               }
 5231:           }
 5232:         }
 5233:        }
 5234:    }
 5235: 
 5236: #
 5237: # Gathered now: all privileges that could apply, and condition number
 5238: # 
 5239: #
 5240: # Full or no access?
 5241: #
 5242: 
 5243:     if ($thisallowed=~/F/) {
 5244: 	return 'F';
 5245:     }
 5246: 
 5247:     unless ($thisallowed) {
 5248:         return '';
 5249:     }
 5250: 
 5251: # Restrictions exist, deal with them
 5252: #
 5253: #   C:according to course preferences
 5254: #   R:according to resource settings
 5255: #   L:unless locked
 5256: #   X:according to user session state
 5257: #
 5258: 
 5259: # Possibly locked functionality, check all courses
 5260: # Locks might take effect only after 10 minutes cache expiration for other
 5261: # courses, and 2 minutes for current course
 5262: 
 5263:     my $envkey;
 5264:     if ($thisallowed=~/L/) {
 5265:         foreach $envkey (keys(%env)) {
 5266:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5267:                my $courseid=$2;
 5268:                my $roleid=$1.'.'.$2;
 5269:                $courseid=~s/^\///;
 5270:                my $expiretime=600;
 5271:                if ($env{'request.role'} eq $roleid) {
 5272: 		  $expiretime=120;
 5273:                }
 5274: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5275:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5276:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5277: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5278:                }
 5279:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5280:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5281: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5282:                        &log($env{'user.domain'},$env{'user.name'},
 5283:                             $env{'user.home'},
 5284:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5285:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5286:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5287: 		       return '';
 5288:                    }
 5289:                }
 5290:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5291:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5292: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5293:                        &log($env{'user.domain'},$env{'user.name'},
 5294:                             $env{'user.home'},
 5295:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5296:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5297:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5298: 		       return '';
 5299:                    }
 5300:                }
 5301: 	   }
 5302:        }
 5303:     }
 5304:    
 5305: #
 5306: # Rest of the restrictions depend on selected course
 5307: #
 5308: 
 5309:     unless ($env{'request.course.id'}) {
 5310: 	if ($thisallowed eq 'A') {
 5311: 	    return 'A';
 5312:         } elsif ($thisallowed eq 'B') {
 5313:             return 'B';
 5314: 	} else {
 5315: 	    return '1';
 5316: 	}
 5317:     }
 5318: 
 5319: #
 5320: # Now user is definitely in a course
 5321: #
 5322: 
 5323: 
 5324: # Course preferences
 5325: 
 5326:    if ($thisallowed=~/C/) {
 5327:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5328:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5329:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5330: 	   =~/\Q$rolecode\E/) {
 5331: 	   if ($priv ne 'pch') { 
 5332: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5333: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5334: 			$env{'request.course.id'});
 5335: 	   }
 5336:            return '';
 5337:        }
 5338: 
 5339:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5340: 	   =~/\Q$unamedom\E/) {
 5341: 	   if ($priv ne 'pch') { 
 5342: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5343: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5344: 			$env{'request.course.id'});
 5345: 	   }
 5346:            return '';
 5347:        }
 5348:    }
 5349: 
 5350: # Resource preferences
 5351: 
 5352:    if ($thisallowed=~/R/) {
 5353:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5354:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5355: 	   if ($priv ne 'pch') { 
 5356: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5357: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5358: 	   }
 5359: 	   return '';
 5360:        }
 5361:    }
 5362: 
 5363: # Restricted by state or randomout?
 5364: 
 5365:    if ($thisallowed=~/X/) {
 5366:       if ($env{'acc.randomout'}) {
 5367: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5368:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5369:             return ''; 
 5370:          }
 5371:       }
 5372:       if (&condval($statecond)) {
 5373: 	 return '2';
 5374:       } else {
 5375:          return '';
 5376:       }
 5377:    }
 5378: 
 5379:     if ($thisallowed eq 'A') {
 5380: 	return 'A';
 5381:     } elsif ($thisallowed eq 'B') {
 5382:         return 'B';
 5383:     }
 5384:    return 'F';
 5385: }
 5386: 
 5387: sub split_uri_for_cond {
 5388:     my $uri=&deversion(&declutter(shift));
 5389:     my @uriparts=split(/\//,$uri);
 5390:     my $filename=pop(@uriparts);
 5391:     my $pathname=join('/',@uriparts);
 5392:     return ($pathname,$filename);
 5393: }
 5394: # --------------------------------------------------- Is a resource on the map?
 5395: 
 5396: sub is_on_map {
 5397:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5398:     #Trying to find the conditional for the file
 5399:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5400: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5401:     if ($match) {
 5402: 	return (1,$1);
 5403:     } else {
 5404: 	return (0,0);
 5405:     }
 5406: }
 5407: 
 5408: # --------------------------------------------------------- Get symb from alias
 5409: 
 5410: sub get_symb_from_alias {
 5411:     my $symb=shift;
 5412:     my ($map,$resid,$url)=&decode_symb($symb);
 5413: # Already is a symb
 5414:     if ($url) { return $symb; }
 5415: # Must be an alias
 5416:     my $aliassymb='';
 5417:     my %bighash;
 5418:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5419:                             &GDBM_READER(),0640)) {
 5420:         my $rid=$bighash{'mapalias_'.$symb};
 5421: 	if ($rid) {
 5422: 	    my ($mapid,$resid)=split(/\./,$rid);
 5423: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5424: 				    $resid,$bighash{'src_'.$rid});
 5425: 	}
 5426:         untie %bighash;
 5427:     }
 5428:     return $aliassymb;
 5429: }
 5430: 
 5431: # ----------------------------------------------------------------- Define Role
 5432: 
 5433: sub definerole {
 5434:   if (allowed('mcr','/')) {
 5435:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5436:     foreach my $role (split(':',$sysrole)) {
 5437: 	my ($crole,$cqual)=split(/\&/,$role);
 5438:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5439:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5440: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5441:                return "refused:s:$crole&$cqual"; 
 5442:             }
 5443:         }
 5444:     }
 5445:     foreach my $role (split(':',$domrole)) {
 5446: 	my ($crole,$cqual)=split(/\&/,$role);
 5447:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5448:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5449: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5450:                return "refused:d:$crole&$cqual"; 
 5451:             }
 5452:         }
 5453:     }
 5454:     foreach my $role (split(':',$courole)) {
 5455: 	my ($crole,$cqual)=split(/\&/,$role);
 5456:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5457:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5458: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5459:                return "refused:c:$crole&$cqual"; 
 5460:             }
 5461:         }
 5462:     }
 5463:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5464:                 "$env{'user.domain'}:$env{'user.name'}:".
 5465: 	        "rolesdef_$rolename=".
 5466:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5467:     return reply($command,$env{'user.home'});
 5468:   } else {
 5469:     return 'refused';
 5470:   }
 5471: }
 5472: 
 5473: # ---------------- Make a metadata query against the network of library servers
 5474: 
 5475: sub metadata_query {
 5476:     my ($query,$custom,$customshow,$server_array)=@_;
 5477:     my %rhash;
 5478:     my %libserv = &all_library();
 5479:     my @server_list = (defined($server_array) ? @$server_array
 5480:                                               : keys(%libserv) );
 5481:     for my $server (@server_list) {
 5482: 	unless ($custom or $customshow) {
 5483: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5484: 	    $rhash{$server}=$reply;
 5485: 	}
 5486: 	else {
 5487: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5488: 			     &escape($custom).':'.&escape($customshow),
 5489: 			     $server);
 5490: 	    $rhash{$server}=$reply;
 5491: 	}
 5492:     }
 5493:     return \%rhash;
 5494: }
 5495: 
 5496: # ----------------------------------------- Send log queries and wait for reply
 5497: 
 5498: sub log_query {
 5499:     my ($uname,$udom,$query,%filters)=@_;
 5500:     my $uhome=&homeserver($uname,$udom);
 5501:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5502:     my $uhost=&hostname($uhome);
 5503:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5504:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5505:                        $uhome);
 5506:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5507:     return get_query_reply($queryid);
 5508: }
 5509: 
 5510: # -------------------------- Update MySQL table for portfolio file
 5511: 
 5512: sub update_portfolio_table {
 5513:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5514:     if ($group ne '') {
 5515:         $file_name =~s /^\Q$group\E//;
 5516:     }
 5517:     my $homeserver = &homeserver($uname,$udom);
 5518:     my $queryid=
 5519:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5520:                ':'.&escape($file_name).':'.$action,$homeserver);
 5521:     my $reply = &get_query_reply($queryid);
 5522:     return $reply;
 5523: }
 5524: 
 5525: # -------------------------- Update MySQL allusers table
 5526: 
 5527: sub update_allusers_table {
 5528:     my ($uname,$udom,$names) = @_;
 5529:     my $homeserver = &homeserver($uname,$udom);
 5530:     my $queryid=
 5531:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5532:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5533:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5534:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5535:                'generation='.&escape($names->{'generation'}).'%%'.
 5536:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5537:                'id='.&escape($names->{'id'}),$homeserver);
 5538:     my $reply = &get_query_reply($queryid);
 5539:     return $reply;
 5540: }
 5541: 
 5542: # ------- Request retrieval of institutional classlists for course(s)
 5543: 
 5544: sub fetch_enrollment_query {
 5545:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5546:     my $homeserver;
 5547:     my $maxtries = 1;
 5548:     if ($context eq 'automated') {
 5549:         $homeserver = $perlvar{'lonHostID'};
 5550:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5551:     } else {
 5552:         $homeserver = &homeserver($cnum,$dom);
 5553:     }
 5554:     my $host=&hostname($homeserver);
 5555:     my $cmd = '';
 5556:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5557:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5558:     }
 5559:     $cmd =~ s/%%$//;
 5560:     $cmd = &escape($cmd);
 5561:     my $query = 'fetchenrollment';
 5562:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5563:     unless ($queryid=~/^\Q$host\E\_/) { 
 5564:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5565:         return 'error: '.$queryid;
 5566:     }
 5567:     my $reply = &get_query_reply($queryid);
 5568:     my $tries = 1;
 5569:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5570:         $reply = &get_query_reply($queryid);
 5571:         $tries ++;
 5572:     }
 5573:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5574:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5575:     } else {
 5576:         my @responses = split(/:/,$reply);
 5577:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5578:             foreach my $line (@responses) {
 5579:                 my ($key,$value) = split(/=/,$line,2);
 5580:                 $$replyref{$key} = $value;
 5581:             }
 5582:         } else {
 5583:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5584:             foreach my $line (@responses) {
 5585:                 my ($key,$value) = split(/=/,$line);
 5586:                 $$replyref{$key} = $value;
 5587:                 if ($value > 0) {
 5588:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5589:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5590:                         my $destname = $pathname.'/'.$filename;
 5591:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5592:                         if ($xml_classlist =~ /^error/) {
 5593:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5594:                         } else {
 5595:                             if ( open(FILE,">$destname") ) {
 5596:                                 print FILE &unescape($xml_classlist);
 5597:                                 close(FILE);
 5598:                             } else {
 5599:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5600:                             }
 5601:                         }
 5602:                     }
 5603:                 }
 5604:             }
 5605:         }
 5606:         return 'ok';
 5607:     }
 5608:     return 'error';
 5609: }
 5610: 
 5611: sub get_query_reply {
 5612:     my $queryid=shift;
 5613:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5614:     my $reply='';
 5615:     for (1..100) {
 5616: 	sleep 2;
 5617:         if (-e $replyfile.'.end') {
 5618: 	    if (open(my $fh,$replyfile)) {
 5619: 		$reply = join('',<$fh>);
 5620: 		close($fh);
 5621: 	   } else { return 'error: reply_file_error'; }
 5622:            return &unescape($reply);
 5623: 	}
 5624:     }
 5625:     return 'timeout:'.$queryid;
 5626: }
 5627: 
 5628: sub courselog_query {
 5629: #
 5630: # possible filters:
 5631: # url: url or symb
 5632: # username
 5633: # domain
 5634: # action: view, submit, grade
 5635: # start: timestamp
 5636: # end: timestamp
 5637: #
 5638:     my (%filters)=@_;
 5639:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5640:     if ($filters{'url'}) {
 5641: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5642:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5643:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5644:     }
 5645:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5646:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5647:     return &log_query($cname,$cdom,'courselog',%filters);
 5648: }
 5649: 
 5650: sub userlog_query {
 5651: #
 5652: # possible filters:
 5653: # action: log check role
 5654: # start: timestamp
 5655: # end: timestamp
 5656: #
 5657:     my ($uname,$udom,%filters)=@_;
 5658:     return &log_query($uname,$udom,'userlog',%filters);
 5659: }
 5660: 
 5661: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5662: 
 5663: sub auto_run {
 5664:     my ($cnum,$cdom) = @_;
 5665:     my $response = 0;
 5666:     my $settings;
 5667:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5668:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5669:         $settings = $domconfig{'autoenroll'};
 5670:         if ($settings->{'run'} eq '1') {
 5671:             $response = 1;
 5672:         }
 5673:     } else {
 5674:         my $homeserver;
 5675:         if (&is_course($cdom,$cnum)) {
 5676:             $homeserver = &homeserver($cnum,$cdom);
 5677:         } else {
 5678:             $homeserver = &domain($cdom,'primary');
 5679:         }
 5680:         if ($homeserver ne 'no_host') {
 5681:             $response = &reply('autorun:'.$cdom,$homeserver);
 5682:         }
 5683:     }
 5684:     return $response;
 5685: }
 5686: 
 5687: sub auto_get_sections {
 5688:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5689:     my $homeserver;
 5690:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5691:         $homeserver = &homeserver($cnum,$cdom);
 5692:     }
 5693:     if (!defined($homeserver)) { 
 5694:         if ($cdom =~ /^$match_domain$/) {
 5695:             $homeserver = &domain($cdom,'primary');
 5696:         }
 5697:     }
 5698:     my @secs;
 5699:     if (defined($homeserver)) {
 5700:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5701:         unless ($response eq 'refused') {
 5702:             @secs = split(/:/,$response);
 5703:         }
 5704:     }
 5705:     return @secs;
 5706: }
 5707: 
 5708: sub auto_new_course {
 5709:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5710:     my $homeserver = &homeserver($cnum,$cdom);
 5711:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5712:     return $response;
 5713: }
 5714: 
 5715: sub auto_validate_courseID {
 5716:     my ($cnum,$cdom,$inst_course_id) = @_;
 5717:     my $homeserver = &homeserver($cnum,$cdom);
 5718:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5719:     return $response;
 5720: }
 5721: 
 5722: sub auto_validate_instcode {
 5723:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5724:     my ($homeserver,$response);
 5725:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5726:         $homeserver = &homeserver($cnum,$cdom);
 5727:     }
 5728:     if (!defined($homeserver)) {
 5729:         if ($cdom =~ /^$match_domain$/) {
 5730:             $homeserver = &domain($cdom,'primary');
 5731:         }
 5732:     }
 5733:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5734:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5735:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 5736:     return ($outcome,$description);
 5737: }
 5738: 
 5739: sub auto_create_password {
 5740:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5741:     my ($homeserver,$response);
 5742:     my $create_passwd = 0;
 5743:     my $authchk = '';
 5744:     if ($udom =~ /^$match_domain$/) {
 5745:         $homeserver = &domain($udom,'primary');
 5746:     }
 5747:     if ($homeserver eq '') {
 5748:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5749:             $homeserver = &homeserver($cnum,$cdom);
 5750:         }
 5751:     }
 5752:     if ($homeserver eq '') {
 5753:         $authchk = 'nodomain';
 5754:     } else {
 5755:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5756:         if ($response eq 'refused') {
 5757:             $authchk = 'refused';
 5758:         } else {
 5759:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5760:         }
 5761:     }
 5762:     return ($authparam,$create_passwd,$authchk);
 5763: }
 5764: 
 5765: sub auto_photo_permission {
 5766:     my ($cnum,$cdom,$students) = @_;
 5767:     my $homeserver = &homeserver($cnum,$cdom);
 5768:     my ($outcome,$perm_reqd,$conditions) = 
 5769: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5770:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5771: 	return (undef,undef);
 5772:     }
 5773:     return ($outcome,$perm_reqd,$conditions);
 5774: }
 5775: 
 5776: sub auto_checkphotos {
 5777:     my ($uname,$udom,$pid) = @_;
 5778:     my $homeserver = &homeserver($uname,$udom);
 5779:     my ($result,$resulttype);
 5780:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5781: 				   &escape($uname).':'.&escape($pid),
 5782: 				   $homeserver));
 5783:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5784: 	return (undef,undef);
 5785:     }
 5786:     if ($outcome) {
 5787:         ($result,$resulttype) = split(/:/,$outcome);
 5788:     } 
 5789:     return ($result,$resulttype);
 5790: }
 5791: 
 5792: sub auto_photochoice {
 5793:     my ($cnum,$cdom) = @_;
 5794:     my $homeserver = &homeserver($cnum,$cdom);
 5795:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5796: 						       &escape($cdom),
 5797: 						       $homeserver)));
 5798:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5799: 	return (undef,undef);
 5800:     }
 5801:     return ($update,$comment);
 5802: }
 5803: 
 5804: sub auto_photoupdate {
 5805:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5806:     my $homeserver = &homeserver($cnum,$dom);
 5807:     my $host=&hostname($homeserver);
 5808:     my $cmd = '';
 5809:     my $maxtries = 1;
 5810:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5811:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5812:     }
 5813:     $cmd =~ s/%%$//;
 5814:     $cmd = &escape($cmd);
 5815:     my $query = 'institutionalphotos';
 5816:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5817:     unless ($queryid=~/^\Q$host\E\_/) {
 5818:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5819:         return 'error: '.$queryid;
 5820:     }
 5821:     my $reply = &get_query_reply($queryid);
 5822:     my $tries = 1;
 5823:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5824:         $reply = &get_query_reply($queryid);
 5825:         $tries ++;
 5826:     }
 5827:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5828:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5829:     } else {
 5830:         my @responses = split(/:/,$reply);
 5831:         my $outcome = shift(@responses); 
 5832:         foreach my $item (@responses) {
 5833:             my ($key,$value) = split(/=/,$item);
 5834:             $$photo{$key} = $value;
 5835:         }
 5836:         return $outcome;
 5837:     }
 5838:     return 'error';
 5839: }
 5840: 
 5841: sub auto_instcode_format {
 5842:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5843: 	$cat_order) = @_;
 5844:     my $courses = '';
 5845:     my @homeservers;
 5846:     if ($caller eq 'global') {
 5847: 	my %servers = &get_servers($codedom,'library');
 5848: 	foreach my $tryserver (keys(%servers)) {
 5849: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5850: 		push(@homeservers,$tryserver);
 5851: 	    }
 5852:         }
 5853:     } elsif ($caller eq 'requests') {
 5854:         if ($codedom =~ /^$match_domain$/) {
 5855:             my $chome = &domain($codedom,'primary');
 5856:             unless ($chome eq 'no_host') {
 5857:                 push(@homeservers,$chome);
 5858:             }
 5859:         }
 5860:     } else {
 5861:         push(@homeservers,&homeserver($caller,$codedom));
 5862:     }
 5863:     foreach my $code (keys(%{$instcodes})) {
 5864:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5865:     }
 5866:     chop($courses);
 5867:     my $ok_response = 0;
 5868:     my $response;
 5869:     while (@homeservers > 0 && $ok_response == 0) {
 5870:         my $server = shift(@homeservers); 
 5871:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5872:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5873:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5874: 		split(/:/,$response);
 5875:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5876:             push(@{$codetitles},&str2array($codetitles_str));
 5877:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5878:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5879:             $ok_response = 1;
 5880:         }
 5881:     }
 5882:     if ($ok_response) {
 5883:         return 'ok';
 5884:     } else {
 5885:         return $response;
 5886:     }
 5887: }
 5888: 
 5889: sub auto_instcode_defaults {
 5890:     my ($domain,$returnhash,$code_order) = @_;
 5891:     my @homeservers;
 5892: 
 5893:     my %servers = &get_servers($domain,'library');
 5894:     foreach my $tryserver (keys(%servers)) {
 5895: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5896: 	    push(@homeservers,$tryserver);
 5897: 	}
 5898:     }
 5899: 
 5900:     my $response;
 5901:     foreach my $server (@homeservers) {
 5902:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5903:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5904: 	
 5905: 	foreach my $pair (split(/\&/,$response)) {
 5906: 	    my ($name,$value)=split(/\=/,$pair);
 5907: 	    if ($name eq 'code_order') {
 5908: 		@{$code_order} = split(/\&/,&unescape($value));
 5909: 	    } else {
 5910: 		$returnhash->{&unescape($name)}=&unescape($value);
 5911: 	    }
 5912: 	}
 5913: 	return 'ok';
 5914:     }
 5915: 
 5916:     return $response;
 5917: }
 5918: 
 5919: sub auto_possible_instcodes {
 5920:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 5921:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 5922:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 5923:         return;
 5924:     }
 5925:     my (@homeservers,$uhome);
 5926:     if (defined(&domain($domain,'primary'))) {
 5927:         $uhome=&domain($domain,'primary');
 5928:         push(@homeservers,&domain($domain,'primary'));
 5929:     } else {
 5930:         my %servers = &get_servers($domain,'library');
 5931:         foreach my $tryserver (keys(%servers)) {
 5932:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5933:                 push(@homeservers,$tryserver);
 5934:             }
 5935:         }
 5936:     }
 5937:     my $response;
 5938:     foreach my $server (@homeservers) {
 5939:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 5940:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5941:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 5942:             split(':',$response);
 5943:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 5944:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 5945:         foreach my $item (split('&',$cat_title)) {   
 5946:             my ($name,$value)=split('=',$item);
 5947:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 5948:         }
 5949:         foreach my $item (split('&',$cat_order)) {
 5950:             my ($name,$value)=split('=',$item);
 5951:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 5952:         }
 5953:         return 'ok';
 5954:     }
 5955:     return $response;
 5956: }
 5957: 
 5958: sub auto_courserequest_checks {
 5959:     my ($dom) = @_;
 5960:     my ($homeserver,%validations);
 5961:     if ($dom =~ /^$match_domain$/) {
 5962:         $homeserver = &domain($dom,'primary');
 5963:     }
 5964:     unless ($homeserver eq 'no_host') {
 5965:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 5966:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 5967:             my @items = split(/&/,$response);
 5968:             foreach my $item (@items) {
 5969:                 my ($key,$value) = split('=',$item);
 5970:                 $validations{&unescape($key)} = &thaw_unescape($value);
 5971:             }
 5972:         }
 5973:     }
 5974:     return %validations; 
 5975: }
 5976: 
 5977: sub auto_courserequest_validation {
 5978:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 5979:     my ($homeserver,$response);
 5980:     if ($dom =~ /^$match_domain$/) {
 5981:         $homeserver = &domain($dom,'primary');
 5982:     }
 5983:     unless ($homeserver eq 'no_host') {  
 5984:           
 5985:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 5986:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 5987:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 5988:                                     $homeserver));
 5989:     }
 5990:     return $response;
 5991: }
 5992: 
 5993: sub auto_validate_class_sec {
 5994:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5995:     my $homeserver = &homeserver($cnum,$cdom);
 5996:     my $ownerlist;
 5997:     if (ref($owners) eq 'ARRAY') {
 5998:         $ownerlist = join(',',@{$owners});
 5999:     } else {
 6000:         $ownerlist = $owners;
 6001:     }
 6002:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6003:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6004:     return $response;
 6005: }
 6006: 
 6007: # ------------------------------------------------------- Course Group routines
 6008: 
 6009: sub get_coursegroups {
 6010:     my ($cdom,$cnum,$group,$namespace) = @_;
 6011:     return(&dump($namespace,$cdom,$cnum,$group));
 6012: }
 6013: 
 6014: sub modify_coursegroup {
 6015:     my ($cdom,$cnum,$groupsettings) = @_;
 6016:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6017: }
 6018: 
 6019: sub toggle_coursegroup_status {
 6020:     my ($cdom,$cnum,$group,$action) = @_;
 6021:     my ($from_namespace,$to_namespace);
 6022:     if ($action eq 'delete') {
 6023:         $from_namespace = 'coursegroups';
 6024:         $to_namespace = 'deleted_groups';
 6025:     } else {
 6026:         $from_namespace = 'deleted_groups';
 6027:         $to_namespace = 'coursegroups';
 6028:     }
 6029:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6030:     if (my $tmp = &error(%curr_group)) {
 6031:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6032:         return ('read error',$tmp);
 6033:     } else {
 6034:         my %savedsettings = %curr_group; 
 6035:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6036:         my $deloutcome;
 6037:         if ($result eq 'ok') {
 6038:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6039:         } else {
 6040:             return ('write error',$result);
 6041:         }
 6042:         if ($deloutcome eq 'ok') {
 6043:             return 'ok';
 6044:         } else {
 6045:             return ('delete error',$deloutcome);
 6046:         }
 6047:     }
 6048: }
 6049: 
 6050: sub modify_group_roles {
 6051:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6052:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6053:     my $role = 'gr/'.&escape($userprivs);
 6054:     my ($uname,$udom) = split(/:/,$user);
 6055:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6056:     if ($result eq 'ok') {
 6057:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6058:     }
 6059:     return $result;
 6060: }
 6061: 
 6062: sub modify_coursegroup_membership {
 6063:     my ($cdom,$cnum,$membership) = @_;
 6064:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6065:     return $result;
 6066: }
 6067: 
 6068: sub get_active_groups {
 6069:     my ($udom,$uname,$cdom,$cnum) = @_;
 6070:     my $now = time;
 6071:     my %groups = ();
 6072:     foreach my $key (keys(%env)) {
 6073:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6074:             my ($start,$end) = split(/\./,$env{$key});
 6075:             if (($end!=0) && ($end<$now)) { next; }
 6076:             if (($start!=0) && ($start>$now)) { next; }
 6077:             if ($1 eq $cdom && $2 eq $cnum) {
 6078:                 $groups{$3} = $env{$key} ;
 6079:             }
 6080:         }
 6081:     }
 6082:     return %groups;
 6083: }
 6084: 
 6085: sub get_group_membership {
 6086:     my ($cdom,$cnum,$group) = @_;
 6087:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6088: }
 6089: 
 6090: sub get_users_groups {
 6091:     my ($udom,$uname,$courseid) = @_;
 6092:     my @usersgroups;
 6093:     my $cachetime=1800;
 6094: 
 6095:     my $hashid="$udom:$uname:$courseid";
 6096:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6097:     if (defined($cached)) {
 6098:         @usersgroups = split(/:/,$grouplist);
 6099:     } else {  
 6100:         $grouplist = '';
 6101:         my $courseurl = &courseid_to_courseurl($courseid);
 6102:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 6103:         my $access_end = $env{'course.'.$courseid.
 6104:                               '.default_enrollment_end_date'};
 6105:         my $now = time;
 6106:         foreach my $key (keys(%roleshash)) {
 6107:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6108:                 my $group = $1;
 6109:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6110:                     my $start = $2;
 6111:                     my $end = $1;
 6112:                     if ($start == -1) { next; } # deleted from group
 6113:                     if (($start!=0) && ($start>$now)) { next; }
 6114:                     if (($end!=0) && ($end<$now)) {
 6115:                         if ($access_end && $access_end < $now) {
 6116:                             if ($access_end - $end < 86400) {
 6117:                                 push(@usersgroups,$group);
 6118:                             }
 6119:                         }
 6120:                         next;
 6121:                     }
 6122:                     push(@usersgroups,$group);
 6123:                 }
 6124:             }
 6125:         }
 6126:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6127:         $grouplist = join(':',@usersgroups);
 6128:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6129:     }
 6130:     return @usersgroups;
 6131: }
 6132: 
 6133: sub devalidate_getgroups_cache {
 6134:     my ($udom,$uname,$cdom,$cnum)=@_;
 6135:     my $courseid = $cdom.'_'.$cnum;
 6136: 
 6137:     my $hashid="$udom:$uname:$courseid";
 6138:     &devalidate_cache_new('getgroups',$hashid);
 6139: }
 6140: 
 6141: # ------------------------------------------------------------------ Plain Text
 6142: 
 6143: sub plaintext {
 6144:     my ($short,$type,$cid,$forcedefault) = @_;
 6145:     if ($short =~ /^cr/) {
 6146: 	return (split('/',$short))[-1];
 6147:     }
 6148:     if (!defined($cid)) {
 6149:         $cid = $env{'request.course.id'};
 6150:     }
 6151:     my %rolenames = (
 6152:                       Course    => 'std',
 6153:                       Community => 'alt1',
 6154:                     );
 6155:     if ($cid ne '') {
 6156:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6157:             unless ($forcedefault) {
 6158:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6159:                 &Apache::lonlocal::mt_escape(\$roletext);
 6160:                 return &Apache::lonlocal::mt($roletext);
 6161:             }
 6162:         }
 6163:     }
 6164:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6165:         (defined($rolenames{$type})) && 
 6166:         (defined($prp{$short}{$rolenames{$type}}))) {
 6167:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6168:     } elsif ($cid ne '') {
 6169:         my $crstype = $env{'course.'.$cid.'.type'};
 6170:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6171:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 6172:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 6173:         }
 6174:     }
 6175:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 6176: }
 6177: 
 6178: # ----------------------------------------------------------------- Assign Role
 6179: 
 6180: sub assignrole {
 6181:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6182:         $context)=@_;
 6183:     my $mrole;
 6184:     if ($role =~ /^cr\//) {
 6185:         my $cwosec=$url;
 6186:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6187: 	unless (&allowed('ccr',$cwosec)) {
 6188:            my $refused = 1;
 6189:            if ($context eq 'requestcourses') {
 6190:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 6191:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 6192:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 6193:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6194:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6195:                            if ($crsenv{'internal.courseowner'} eq
 6196:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 6197:                                $refused = '';
 6198:                            }
 6199:                        }
 6200:                    }
 6201:                }
 6202:            }
 6203:            if ($refused) {
 6204:                &logthis('Refused custom assignrole: '.
 6205:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 6206:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 6207:                return 'refused';
 6208:            }
 6209:         }
 6210:         $mrole='cr';
 6211:     } elsif ($role =~ /^gr\//) {
 6212:         my $cwogrp=$url;
 6213:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 6214:         unless (&allowed('mdg',$cwogrp)) {
 6215:             &logthis('Refused group assignrole: '.
 6216:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6217:                     $env{'user.name'}.' at '.$env{'user.domain'});
 6218:             return 'refused';
 6219:         }
 6220:         $mrole='gr';
 6221:     } else {
 6222:         my $cwosec=$url;
 6223:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6224:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 6225:             my $refused;
 6226:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 6227:                 if (!(&allowed('c'.$role,$url))) {
 6228:                     $refused = 1;
 6229:                 }
 6230:             } else {
 6231:                 $refused = 1;
 6232:             }
 6233:             if ($refused) {
 6234:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6235:                     $refused = '';
 6236:                 } elsif ($context eq 'requestcourses') {
 6237:                     my @possroles = ('st','ta','ep','in','cc','co');
 6238:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 6239:                         my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6240:                         my $wrongcc;
 6241:                         if ($cnum =~ /^$match_community$/) {
 6242:                             $wrongcc = 1 if ($role eq 'cc');
 6243:                         } else {
 6244:                             $wrongcc = 1 if ($role eq 'co');
 6245:                         }
 6246:                         unless ($wrongcc) {
 6247:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6248:                             if ($crsenv{'internal.courseowner'} eq 
 6249:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 6250:                                 $refused = '';
 6251:                             }
 6252:                         }
 6253:                     }
 6254:                 }
 6255:                 if ($refused) {
 6256:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6257:                              ' '.$role.' '.$end.' '.$start.' by '.
 6258: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6259:                     return 'refused';
 6260:                 }
 6261:             }
 6262:         }
 6263:         $mrole=$role;
 6264:     }
 6265:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6266:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6267:     if ($end) { $command.='_'.$end; }
 6268:     if ($start) {
 6269: 	if ($end) { 
 6270:            $command.='_'.$start; 
 6271:         } else {
 6272:            $command.='_0_'.$start;
 6273:         }
 6274:     }
 6275:     my $origstart = $start;
 6276:     my $origend = $end;
 6277:     my $delflag;
 6278: # actually delete
 6279:     if ($deleteflag) {
 6280: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6281: # modify command to delete the role
 6282:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6283:                 "$udom:$uname:$url".'_'."$mrole";
 6284: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6285: # set start and finish to negative values for userrolelog
 6286:            $start=-1;
 6287:            $end=-1;
 6288:            $delflag = 1;
 6289:         }
 6290:     }
 6291: # send command
 6292:     my $answer=&reply($command,&homeserver($uname,$udom));
 6293: # log new user role if status is ok
 6294:     if ($answer eq 'ok') {
 6295: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6296: # for course roles, perform group memberships changes triggered by role change.
 6297:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6298:         unless ($role =~ /^gr/) {
 6299:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6300:                                              $origstart,$selfenroll,$context);
 6301:         }
 6302:     }
 6303:     return $answer;
 6304: }
 6305: 
 6306: # -------------------------------------------------- Modify user authentication
 6307: # Overrides without validation
 6308: 
 6309: sub modifyuserauth {
 6310:     my ($udom,$uname,$umode,$upass)=@_;
 6311:     my $uhome=&homeserver($uname,$udom);
 6312:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6313:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6314:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6315:              ' in domain '.$env{'request.role.domain'});  
 6316:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6317: 		     &escape($upass),$uhome);
 6318:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6319:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6320:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6321:     &log($udom,,$uname,$uhome,
 6322:         'Authentication changed by '.$env{'user.domain'}.', '.
 6323:                                      $env{'user.name'}.', '.$umode.
 6324:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6325:     unless ($reply eq 'ok') {
 6326:         &logthis('Authentication mode error: '.$reply);
 6327: 	return 'error: '.$reply;
 6328:     }   
 6329:     return 'ok';
 6330: }
 6331: 
 6332: # --------------------------------------------------------------- Modify a user
 6333: 
 6334: sub modifyuser {
 6335:     my ($udom,    $uname, $uid,
 6336:         $umode,   $upass, $first,
 6337:         $middle,  $last,  $gene,
 6338:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6339:     $udom= &LONCAPA::clean_domain($udom);
 6340:     $uname=&LONCAPA::clean_username($uname);
 6341:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6342:              $umode.', '.$first.', '.$middle.', '.
 6343: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6344:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6345:                                      ' desiredhome not specified'). 
 6346:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6347:              ' in domain '.$env{'request.role.domain'});
 6348:     my $uhome=&homeserver($uname,$udom,'true');
 6349: # ----------------------------------------------------------------- Create User
 6350:     if (($uhome eq 'no_host') && 
 6351: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6352:         my $unhome='';
 6353:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6354:             $unhome = $desiredhome;
 6355: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6356: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6357:         } else { # load balancing routine for determining $unhome
 6358:             my $loadm=10000000;
 6359: 	    my %servers = &get_servers($udom,'library');
 6360: 	    foreach my $tryserver (keys(%servers)) {
 6361: 		my $answer=reply('load',$tryserver);
 6362: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6363: 		    $loadm=$answer;
 6364: 		    $unhome=$tryserver;
 6365: 		}
 6366: 	    }
 6367:         }
 6368:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6369: 	    return 'error: unable to find a home server for '.$uname.
 6370:                    ' in domain '.$udom;
 6371:         }
 6372:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6373:                          &escape($upass),$unhome);
 6374: 	unless ($reply eq 'ok') {
 6375:             return 'error: '.$reply;
 6376:         }   
 6377:         $uhome=&homeserver($uname,$udom,'true');
 6378:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6379: 	    return 'error: unable verify users home machine.';
 6380:         }
 6381:     }   # End of creation of new user
 6382: # ---------------------------------------------------------------------- Add ID
 6383:     if ($uid) {
 6384:        $uid=~tr/A-Z/a-z/;
 6385:        my %uidhash=&idrget($udom,$uname);
 6386:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6387:          && (!$forceid)) {
 6388: 	  unless ($uid eq $uidhash{$uname}) {
 6389: 	      return 'error: user id "'.$uid.'" does not match '.
 6390:                   'current user id "'.$uidhash{$uname}.'".';
 6391:           }
 6392:        } else {
 6393: 	  &idput($udom,($uname => $uid));
 6394:        }
 6395:     }
 6396: # -------------------------------------------------------------- Add names, etc
 6397:     my @tmp=&get('environment',
 6398: 		   ['firstname','middlename','lastname','generation','id',
 6399:                     'permanentemail','inststatus'],
 6400: 		   $udom,$uname);
 6401:     my %names;
 6402:     if ($tmp[0] =~ m/^error:.*/) { 
 6403:         %names=(); 
 6404:     } else {
 6405:         %names = @tmp;
 6406:     }
 6407: #
 6408: # Make sure to not trash student environment if instructor does not bother
 6409: # to supply name and email information
 6410: #
 6411:     if ($first)  { $names{'firstname'}  = $first; }
 6412:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6413:     if ($last)   { $names{'lastname'}   = $last; }
 6414:     if (defined($gene))   { $names{'generation'} = $gene; }
 6415:     if ($email) {
 6416:        $email=~s/[^\w\@\.\-\,]//gs;
 6417:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6418:     }
 6419:     if ($uid) { $names{'id'}  = $uid; }
 6420:     if (defined($inststatus)) {
 6421:         $names{'inststatus'} = '';
 6422:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6423:         if (ref($usertypes) eq 'HASH') {
 6424:             my @okstatuses; 
 6425:             foreach my $item (split(/:/,$inststatus)) {
 6426:                 if (defined($usertypes->{$item})) {
 6427:                     push(@okstatuses,$item);  
 6428:                 }
 6429:             }
 6430:             if (@okstatuses) {
 6431:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6432:             }
 6433:         }
 6434:     }
 6435:     my $reply = &put('environment', \%names, $udom,$uname);
 6436:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6437:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6438:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6439:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6440:                  $umode.', '.$first.', '.$middle.', '.
 6441: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6442:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6443:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6444:     } else {
 6445:         $logmsg .= ' during self creation';
 6446:     }
 6447:     &logthis($logmsg);
 6448:     return 'ok';
 6449: }
 6450: 
 6451: # -------------------------------------------------------------- Modify student
 6452: 
 6453: sub modifystudent {
 6454:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6455:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6456:         $selfenroll,$context,$inststatus)=@_;
 6457:     if (!$cid) {
 6458: 	unless ($cid=$env{'request.course.id'}) {
 6459: 	    return 'not_in_class';
 6460: 	}
 6461:     }
 6462: # --------------------------------------------------------------- Make the user
 6463:     my $reply=&modifyuser
 6464: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6465:          $desiredhome,$email,$inststatus);
 6466:     unless ($reply eq 'ok') { return $reply; }
 6467:     # This will cause &modify_student_enrollment to get the uid from the
 6468:     # students environment
 6469:     $uid = undef if (!$forceid);
 6470:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6471: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6472:     return $reply;
 6473: }
 6474: 
 6475: sub modify_student_enrollment {
 6476:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6477:     my ($cdom,$cnum,$chome);
 6478:     if (!$cid) {
 6479: 	unless ($cid=$env{'request.course.id'}) {
 6480: 	    return 'not_in_class';
 6481: 	}
 6482: 	$cdom=$env{'course.'.$cid.'.domain'};
 6483: 	$cnum=$env{'course.'.$cid.'.num'};
 6484:     } else {
 6485: 	($cdom,$cnum)=split(/_/,$cid);
 6486:     }
 6487:     $chome=$env{'course.'.$cid.'.home'};
 6488:     if (!$chome) {
 6489: 	$chome=&homeserver($cnum,$cdom);
 6490:     }
 6491:     if (!$chome) { return 'unknown_course'; }
 6492:     # Make sure the user exists
 6493:     my $uhome=&homeserver($uname,$udom);
 6494:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6495: 	return 'error: no such user';
 6496:     }
 6497:     # Get student data if we were not given enough information
 6498:     if (!defined($first)  || $first  eq '' || 
 6499:         !defined($last)   || $last   eq '' || 
 6500:         !defined($uid)    || $uid    eq '' || 
 6501:         !defined($middle) || $middle eq '' || 
 6502:         !defined($gene)   || $gene   eq '') {
 6503:         # They did not supply us with enough data to enroll the student, so
 6504:         # we need to pick up more information.
 6505:         my %tmp = &get('environment',
 6506:                        ['firstname','middlename','lastname', 'generation','id']
 6507:                        ,$udom,$uname);
 6508: 
 6509:         #foreach my $key (keys(%tmp)) {
 6510:         #    &logthis("key $key = ".$tmp{$key});
 6511:         #}
 6512:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6513:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6514:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6515:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6516:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6517:     }
 6518:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6519:     my $reply=cput('classlist',
 6520: 		   {"$uname:$udom" => 
 6521: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6522: 		   $cdom,$cnum);
 6523:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6524: 	return 'error: '.$reply;
 6525:     } else {
 6526: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6527:     }
 6528:     # Add student role to user
 6529:     my $uurl='/'.$cid;
 6530:     $uurl=~s/\_/\//g;
 6531:     if ($usec) {
 6532: 	$uurl.='/'.$usec;
 6533:     }
 6534:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6535: }
 6536: 
 6537: sub format_name {
 6538:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6539:     my $name;
 6540:     if ($first ne 'lastname') {
 6541: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6542:     } else {
 6543: 	if ($lastname=~/\S/) {
 6544: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6545: 	    $name=~s/\s+,/,/;
 6546: 	} else {
 6547: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6548: 	}
 6549:     }
 6550:     $name=~s/^\s+//;
 6551:     $name=~s/\s+$//;
 6552:     $name=~s/\s+/ /g;
 6553:     return $name;
 6554: }
 6555: 
 6556: # ------------------------------------------------- Write to course preferences
 6557: 
 6558: sub writecoursepref {
 6559:     my ($courseid,%prefs)=@_;
 6560:     $courseid=~s/^\///;
 6561:     $courseid=~s/\_/\//g;
 6562:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6563:     my $chome=homeserver($cnum,$cdomain);
 6564:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6565: 	return 'error: no such course';
 6566:     }
 6567:     my $cstring='';
 6568:     foreach my $pref (keys(%prefs)) {
 6569: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6570:     }
 6571:     $cstring=~s/\&$//;
 6572:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6573: }
 6574: 
 6575: # ---------------------------------------------------------- Make/modify course
 6576: 
 6577: sub createcourse {
 6578:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6579:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 6580:     $url=&declutter($url);
 6581:     my $cid='';
 6582:     if ($context eq 'requestcourses') {
 6583:         my $can_create = 0;
 6584:         my ($ownername,$ownerdom) = split(':',$course_owner);
 6585:         if ($udom eq $ownerdom) {
 6586:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 6587:                                   $context)) {
 6588:                 $can_create = 1;
 6589:             }
 6590:         } else {
 6591:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 6592:                                            $category);
 6593:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 6594:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 6595:                 if (@curr > 0) {
 6596:                     my @options = qw(approval validate autolimit);
 6597:                     my $optregex = join('|',@options);
 6598:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 6599:                         $can_create = 1;
 6600:                     }
 6601:                 }
 6602:             }
 6603:         }
 6604:         if ($can_create) {
 6605:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 6606:                 unless (&allowed('ccc',$udom)) {
 6607:                     return 'refused'; 
 6608:                 }
 6609:             }
 6610:         } else {
 6611:             return 'refused';
 6612:         }
 6613:     } elsif (!&allowed('ccc',$udom)) {
 6614:         return 'refused';
 6615:     }
 6616: # --------------------------------------------------------------- Get Unique ID
 6617:     my $uname;
 6618:     if ($cnum =~ /^$match_courseid$/) {
 6619:         my $chome=&homeserver($cnum,$udom,'true');
 6620:         if (($chome eq '') || ($chome eq 'no_host')) {
 6621:             $uname = $cnum;
 6622:         } else {
 6623:             $uname = &generate_coursenum($udom,$crstype);
 6624:         }
 6625:     } else {
 6626:         $uname = &generate_coursenum($udom,$crstype);
 6627:     }
 6628:     return $uname if ($uname =~ /^error/);
 6629: # -------------------------------------------------- Check supplied server name
 6630:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6631:     if (! &is_library($course_server)) {
 6632:         return 'error:bad server name '.$course_server;
 6633:     }
 6634: # ------------------------------------------------------------- Make the course
 6635:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6636:                       $course_server);
 6637:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6638:     my $uhome=&homeserver($uname,$udom,'true');
 6639:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6640: 	return 'error: no such course';
 6641:     }
 6642: # ----------------------------------------------------------------- Course made
 6643: # log existence
 6644:     my $now = time;
 6645:     my $newcourse = {
 6646:                     $udom.'_'.$uname => {
 6647:                                      description => $description,
 6648:                                      inst_code   => $inst_code,
 6649:                                      owner       => $course_owner,
 6650:                                      type        => $crstype,
 6651:                                      creator     => $env{'user.name'}.':'.
 6652:                                                     $env{'user.domain'},
 6653:                                      created     => $now,
 6654:                                      context     => $context,
 6655:                                                 },
 6656:                     };
 6657:     &courseidput($udom,$newcourse,$uhome,'notime');
 6658: # set toplevel url
 6659:     my $topurl=$url;
 6660:     unless ($nonstandard) {
 6661: # ------------------------------------------ For standard courses, make top url
 6662:         my $mapurl=&clutter($url);
 6663:         if ($mapurl eq '/res/') { $mapurl=''; }
 6664:         $env{'form.initmap'}=(<<ENDINITMAP);
 6665: <map>
 6666: <resource id="1" type="start"></resource>
 6667: <resource id="2" src="$mapurl"></resource>
 6668: <resource id="3" type="finish"></resource>
 6669: <link index="1" from="1" to="2"></link>
 6670: <link index="2" from="2" to="3"></link>
 6671: </map>
 6672: ENDINITMAP
 6673:         $topurl=&declutter(
 6674:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6675:                           );
 6676:     }
 6677: # ----------------------------------------------------------- Write preferences
 6678:     &writecoursepref($udom.'_'.$uname,
 6679:                      ('description' => $description,
 6680:                       'url'         => $topurl));
 6681:     return '/'.$udom.'/'.$uname;
 6682: }
 6683: 
 6684: # ------------------------------------------------------------------- Create ID
 6685: sub generate_coursenum {
 6686:     my ($udom,$crstype) = @_;
 6687:     my $domdesc = &domain($udom);
 6688:     return 'error: invalid domain' if ($domdesc eq '');
 6689:     my $first;
 6690:     if ($crstype eq 'Community') {
 6691:         $first = '0';
 6692:     } else {
 6693:         $first = int(1+rand(9)); 
 6694:     } 
 6695:     my $uname=$first.
 6696:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6697:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6698:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6699: # ----------------------------------------------- Make sure that does not exist
 6700:     my $uhome=&homeserver($uname,$udom,'true');
 6701:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6702:         if ($crstype eq 'Community') {
 6703:             $first = '0';
 6704:         } else {
 6705:             $first = int(1+rand(9));
 6706:         }
 6707:         $uname=$first.
 6708:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6709:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6710:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6711:         $uhome=&homeserver($uname,$udom,'true');
 6712:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6713:             return 'error: unable to generate unique course-ID';
 6714:         }
 6715:     }
 6716:     return $uname;
 6717: }
 6718: 
 6719: sub is_course {
 6720:     my ($cdom,$cnum) = @_;
 6721:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6722: 				undef,'.');
 6723:     if (exists($courses{$cdom.'_'.$cnum})) {
 6724:         return 1;
 6725:     }
 6726:     return 0;
 6727: }
 6728: 
 6729: sub store_userdata {
 6730:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 6731:     my $result;
 6732:     if ($datakey ne '') {
 6733:         if (ref($storehash) eq 'HASH') {
 6734:             if ($udom eq '' || $uname eq '') {
 6735:                 $udom = $env{'user.domain'};
 6736:                 $uname = $env{'user.name'};
 6737:             }
 6738:             my $uhome=&homeserver($uname,$udom);
 6739:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 6740:                 $result = 'error: no_host';
 6741:             } else {
 6742:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 6743:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 6744: 
 6745:                 my $namevalue='';
 6746:                 foreach my $key (keys(%{$storehash})) {
 6747:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6748:                 }
 6749:                 $namevalue=~s/\&$//;
 6750:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
 6751:                                   "$namespace:$datakey:$namevalue",$uhome);
 6752:             }
 6753:         } else {
 6754:             $result = 'error: data to store was not a hash reference'; 
 6755:         }
 6756:     } else {
 6757:         $result= 'error: invalid requestkey'; 
 6758:     }
 6759:     return $result;
 6760: }
 6761: 
 6762: # ---------------------------------------------------------- Assign Custom Role
 6763: 
 6764: sub assigncustomrole {
 6765:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6766:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6767:                        $end,$start,$deleteflag,$selfenroll,$context);
 6768: }
 6769: 
 6770: # ----------------------------------------------------------------- Revoke Role
 6771: 
 6772: sub revokerole {
 6773:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6774:     my $now=time;
 6775:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6776: }
 6777: 
 6778: # ---------------------------------------------------------- Revoke Custom Role
 6779: 
 6780: sub revokecustomrole {
 6781:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6782:     my $now=time;
 6783:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6784:            $deleteflag,$selfenroll,$context);
 6785: }
 6786: 
 6787: # ------------------------------------------------------------ Disk usage
 6788: sub diskusage {
 6789:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6790:     $directorypath =~ s/\/$//;
 6791:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6792:                        .&escape($getpropath).':'.&escape($uname).':'
 6793:                        .&escape($udom),homeserver($uname,$udom));
 6794:     if ($listing eq 'unknown_cmd') {
 6795:         if ($getpropath) {
 6796:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6797:         }
 6798:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6799:     }
 6800:     return $listing;
 6801: }
 6802: 
 6803: sub is_locked {
 6804:     my ($file_name, $domain, $user) = @_;
 6805:     my @check;
 6806:     my $is_locked;
 6807:     push @check, $file_name;
 6808:     my %locked = &get('file_permissions',\@check,
 6809: 		      $env{'user.domain'},$env{'user.name'});
 6810:     my ($tmp)=keys(%locked);
 6811:     if ($tmp=~/^error:/) { undef(%locked); }
 6812:     
 6813:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6814:         $is_locked = 'false';
 6815:         foreach my $entry (@{$locked{$file_name}}) {
 6816:            if (ref($entry) eq 'ARRAY') { 
 6817:                $is_locked = 'true';
 6818:                last;
 6819:            }
 6820:        }
 6821:     } else {
 6822:         $is_locked = 'false';
 6823:     }
 6824: }
 6825: 
 6826: sub declutter_portfile {
 6827:     my ($file) = @_;
 6828:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6829:     return $file;
 6830: }
 6831: 
 6832: # ------------------------------------------------------------- Mark as Read Only
 6833: 
 6834: sub mark_as_readonly {
 6835:     my ($domain,$user,$files,$what) = @_;
 6836:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6837:     my ($tmp)=keys(%current_permissions);
 6838:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6839:     foreach my $file (@{$files}) {
 6840: 	$file = &declutter_portfile($file);
 6841:         push(@{$current_permissions{$file}},$what);
 6842:     }
 6843:     &put('file_permissions',\%current_permissions,$domain,$user);
 6844:     return;
 6845: }
 6846: 
 6847: # ------------------------------------------------------------Save Selected Files
 6848: 
 6849: sub save_selected_files {
 6850:     my ($user, $path, @files) = @_;
 6851:     my $filename = $user."savedfiles";
 6852:     my @other_files = &files_not_in_path($user, $path);
 6853:     open (OUT, '>'.$tmpdir.$filename);
 6854:     foreach my $file (@files) {
 6855:         print (OUT $env{'form.currentpath'}.$file."\n");
 6856:     }
 6857:     foreach my $file (@other_files) {
 6858:         print (OUT $file."\n");
 6859:     }
 6860:     close (OUT);
 6861:     return 'ok';
 6862: }
 6863: 
 6864: sub clear_selected_files {
 6865:     my ($user) = @_;
 6866:     my $filename = $user."savedfiles";
 6867:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6868:     print (OUT undef);
 6869:     close (OUT);
 6870:     return ("ok");    
 6871: }
 6872: 
 6873: sub files_in_path {
 6874:     my ($user, $path) = @_;
 6875:     my $filename = $user."savedfiles";
 6876:     my %return_files;
 6877:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6878:     while (my $line_in = <IN>) {
 6879:         chomp ($line_in);
 6880:         my @paths_and_file = split (m!/!, $line_in);
 6881:         my $file_part = pop (@paths_and_file);
 6882:         my $path_part = join ('/', @paths_and_file);
 6883:         $path_part.='/';
 6884:         my $path_and_file = $path_part.$file_part;
 6885:         if ($path_part eq $path) {
 6886:             $return_files{$file_part}= 'selected';
 6887:         }
 6888:     }
 6889:     close (IN);
 6890:     return (\%return_files);
 6891: }
 6892: 
 6893: # called in portfolio select mode, to show files selected NOT in current directory
 6894: sub files_not_in_path {
 6895:     my ($user, $path) = @_;
 6896:     my $filename = $user."savedfiles";
 6897:     my @return_files;
 6898:     my $path_part;
 6899:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6900:     while (my $line = <IN>) {
 6901:         #ok, I know it's clunky, but I want it to work
 6902:         my @paths_and_file = split(m|/|, $line);
 6903:         my $file_part = pop(@paths_and_file);
 6904:         chomp($file_part);
 6905:         my $path_part = join('/', @paths_and_file);
 6906:         $path_part .= '/';
 6907:         my $path_and_file = $path_part.$file_part;
 6908:         if ($path_part ne $path) {
 6909:             push(@return_files, ($path_and_file));
 6910:         }
 6911:     }
 6912:     close(OUT);
 6913:     return (@return_files);
 6914: }
 6915: 
 6916: #----------------------------------------------Get portfolio file permissions
 6917: 
 6918: sub get_portfile_permissions {
 6919:     my ($domain,$user) = @_;
 6920:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6921:     my ($tmp)=keys(%current_permissions);
 6922:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6923:     return \%current_permissions;
 6924: }
 6925: 
 6926: #---------------------------------------------Get portfolio file access controls
 6927: 
 6928: sub get_access_controls {
 6929:     my ($current_permissions,$group,$file) = @_;
 6930:     my %access;
 6931:     my $real_file = $file;
 6932:     $file =~ s/\.meta$//;
 6933:     if (defined($file)) {
 6934:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6935:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6936:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6937:             }
 6938:         }
 6939:     } else {
 6940:         foreach my $key (keys(%{$current_permissions})) {
 6941:             if ($key =~ /\0accesscontrol$/) {
 6942:                 if (defined($group)) {
 6943:                     if ($key !~ m-^\Q$group\E/-) {
 6944:                         next;
 6945:                     }
 6946:                 }
 6947:                 my ($fullpath) = split(/\0/,$key);
 6948:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6949:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6950:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6951:                     }
 6952:                 }
 6953:             }
 6954:         }
 6955:     }
 6956:     return %access;
 6957: }
 6958: 
 6959: sub modify_access_controls {
 6960:     my ($file_name,$changes,$domain,$user)=@_;
 6961:     my ($outcome,$deloutcome);
 6962:     my %store_permissions;
 6963:     my %new_values;
 6964:     my %new_control;
 6965:     my %translation;
 6966:     my @deletions = ();
 6967:     my $now = time;
 6968:     if (exists($$changes{'activate'})) {
 6969:         if (ref($$changes{'activate'}) eq 'HASH') {
 6970:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6971:             my $numnew = scalar(@newitems);
 6972:             for (my $i=0; $i<$numnew; $i++) {
 6973:                 my $newkey = $newitems[$i];
 6974:                 my $newid = &Apache::loncommon::get_cgi_id();
 6975:                 if ($newkey =~ /^\d+:/) { 
 6976:                     $newkey =~ s/^(\d+)/$newid/;
 6977:                     $translation{$1} = $newid;
 6978:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6979:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6980:                     $translation{$1} = $newid;
 6981:                 }
 6982:                 $new_values{$file_name."\0".$newkey} = 
 6983:                                           $$changes{'activate'}{$newitems[$i]};
 6984:                 $new_control{$newkey} = $now;
 6985:             }
 6986:         }
 6987:     }
 6988:     my %todelete;
 6989:     my %changed_items;
 6990:     foreach my $action ('delete','update') {
 6991:         if (exists($$changes{$action})) {
 6992:             if (ref($$changes{$action}) eq 'HASH') {
 6993:                 foreach my $key (keys(%{$$changes{$action}})) {
 6994:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6995:                     if ($action eq 'delete') { 
 6996:                         $todelete{$itemnum} = 1;
 6997:                     } else {
 6998:                         $changed_items{$itemnum} = $key;
 6999:                     }
 7000:                 }
 7001:             }
 7002:         }
 7003:     }
 7004:     # get lock on access controls for file.
 7005:     my $lockhash = {
 7006:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 7007:                                                        ':'.$env{'user.domain'},
 7008:                    }; 
 7009:     my $tries = 0;
 7010:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7011:    
 7012:     while (($gotlock ne 'ok') && $tries <3) {
 7013:         $tries ++;
 7014:         sleep 1;
 7015:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7016:     }
 7017:     if ($gotlock eq 'ok') {
 7018:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 7019:         my ($tmp)=keys(%curr_permissions);
 7020:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 7021:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 7022:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 7023:             if (ref($curr_controls) eq 'HASH') {
 7024:                 foreach my $control_item (keys(%{$curr_controls})) {
 7025:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 7026:                     if (defined($todelete{$itemnum})) {
 7027:                         push(@deletions,$file_name."\0".$control_item);
 7028:                     } else {
 7029:                         if (defined($changed_items{$itemnum})) {
 7030:                             $new_control{$changed_items{$itemnum}} = $now;
 7031:                             push(@deletions,$file_name."\0".$control_item);
 7032:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 7033:                         } else {
 7034:                             $new_control{$control_item} = $$curr_controls{$control_item};
 7035:                         }
 7036:                     }
 7037:                 }
 7038:             }
 7039:         }
 7040:         my ($group);
 7041:         if (&is_course($domain,$user)) {
 7042:             ($group,my $file) = split(/\//,$file_name,2);
 7043:         }
 7044:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 7045:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 7046:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 7047:         #  remove lock
 7048:         my @del_lock = ($file_name."\0".'locked_access_records');
 7049:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 7050:         my $sqlresult =
 7051:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 7052:                                     $group);
 7053:     } else {
 7054:         $outcome = "error: could not obtain lockfile\n";  
 7055:     }
 7056:     return ($outcome,$deloutcome,\%new_values,\%translation);
 7057: }
 7058: 
 7059: sub make_public_indefinitely {
 7060:     my ($requrl) = @_;
 7061:     my $now = time;
 7062:     my $action = 'activate';
 7063:     my $aclnum = 0;
 7064:     if (&is_portfolio_url($requrl)) {
 7065:         my (undef,$udom,$unum,$file_name,$group) =
 7066:             &parse_portfolio_url($requrl);
 7067:         my $current_perms = &get_portfile_permissions($udom,$unum);
 7068:         my %access_controls = &get_access_controls($current_perms,
 7069:                                                    $group,$file_name);
 7070:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 7071:             my ($num,$scope,$end,$start) = 
 7072:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7073:             if ($scope eq 'public') {
 7074:                 if ($start <= $now && $end == 0) {
 7075:                     $action = 'none';
 7076:                 } else {
 7077:                     $action = 'update';
 7078:                     $aclnum = $num;
 7079:                 }
 7080:                 last;
 7081:             }
 7082:         }
 7083:         if ($action eq 'none') {
 7084:              return 'ok';
 7085:         } else {
 7086:             my %changes;
 7087:             my $newend = 0;
 7088:             my $newstart = $now;
 7089:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 7090:             $changes{$action}{$newkey} = {
 7091:                 type => 'public',
 7092:                 time => {
 7093:                     start => $newstart,
 7094:                     end   => $newend,
 7095:                 },
 7096:             };
 7097:             my ($outcome,$deloutcome,$new_values,$translation) =
 7098:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 7099:             return $outcome;
 7100:         }
 7101:     } else {
 7102:         return 'invalid';
 7103:     }
 7104: }
 7105: 
 7106: #------------------------------------------------------Get Marked as Read Only
 7107: 
 7108: sub get_marked_as_readonly {
 7109:     my ($domain,$user,$what,$group) = @_;
 7110:     my $current_permissions = &get_portfile_permissions($domain,$user);
 7111:     my @readonly_files;
 7112:     my $cmp1=$what;
 7113:     if (ref($what)) { $cmp1=join('',@{$what}) };
 7114:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7115:         if (defined($group)) {
 7116:             if ($file_name !~ m-^\Q$group\E/-) {
 7117:                 next;
 7118:             }
 7119:         }
 7120:         if (ref($value) eq "ARRAY"){
 7121:             foreach my $stored_what (@{$value}) {
 7122:                 my $cmp2=$stored_what;
 7123:                 if (ref($stored_what) eq 'ARRAY') {
 7124:                     $cmp2=join('',@{$stored_what});
 7125:                 }
 7126:                 if ($cmp1 eq $cmp2) {
 7127:                     push(@readonly_files, $file_name);
 7128:                     last;
 7129:                 } elsif (!defined($what)) {
 7130:                     push(@readonly_files, $file_name);
 7131:                     last;
 7132:                 }
 7133:             }
 7134:         }
 7135:     }
 7136:     return @readonly_files;
 7137: }
 7138: #-----------------------------------------------------------Get Marked as Read Only Hash
 7139: 
 7140: sub get_marked_as_readonly_hash {
 7141:     my ($current_permissions,$group,$what) = @_;
 7142:     my %readonly_files;
 7143:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7144:         if (defined($group)) {
 7145:             if ($file_name !~ m-^\Q$group\E/-) {
 7146:                 next;
 7147:             }
 7148:         }
 7149:         if (ref($value) eq "ARRAY"){
 7150:             foreach my $stored_what (@{$value}) {
 7151:                 if (ref($stored_what) eq 'ARRAY') {
 7152:                     foreach my $lock_descriptor(@{$stored_what}) {
 7153:                         if ($lock_descriptor eq 'graded') {
 7154:                             $readonly_files{$file_name} = 'graded';
 7155:                         } elsif ($lock_descriptor eq 'handback') {
 7156:                             $readonly_files{$file_name} = 'handback';
 7157:                         } else {
 7158:                             if (!exists($readonly_files{$file_name})) {
 7159:                                 $readonly_files{$file_name} = 'locked';
 7160:                             }
 7161:                         }
 7162:                     }
 7163:                 } 
 7164:             }
 7165:         } 
 7166:     }
 7167:     return %readonly_files;
 7168: }
 7169: # ------------------------------------------------------------ Unmark as Read Only
 7170: 
 7171: sub unmark_as_readonly {
 7172:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 7173:     # for portfolio submissions, $what contains [$symb,$crsid] 
 7174:     my ($domain,$user,$what,$file_name,$group) = @_;
 7175:     $file_name = &declutter_portfile($file_name);
 7176:     my $symb_crs = $what;
 7177:     if (ref($what)) { $symb_crs=join('',@$what); }
 7178:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 7179:     my ($tmp)=keys(%current_permissions);
 7180:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7181:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 7182:     foreach my $file (@readonly_files) {
 7183: 	my $clean_file = &declutter_portfile($file);
 7184: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 7185: 	my $current_locks = $current_permissions{$file};
 7186:         my @new_locks;
 7187:         my @del_keys;
 7188:         if (ref($current_locks) eq "ARRAY"){
 7189:             foreach my $locker (@{$current_locks}) {
 7190:                 my $compare=$locker;
 7191:                 if (ref($locker) eq 'ARRAY') {
 7192:                     $compare=join('',@{$locker});
 7193:                     if ($compare ne $symb_crs) {
 7194:                         push(@new_locks, $locker);
 7195:                     }
 7196:                 }
 7197:             }
 7198:             if (scalar(@new_locks) > 0) {
 7199:                 $current_permissions{$file} = \@new_locks;
 7200:             } else {
 7201:                 push(@del_keys, $file);
 7202:                 &del('file_permissions',\@del_keys, $domain, $user);
 7203:                 delete($current_permissions{$file});
 7204:             }
 7205:         }
 7206:     }
 7207:     &put('file_permissions',\%current_permissions,$domain,$user);
 7208:     return;
 7209: }
 7210: 
 7211: # ------------------------------------------------------------ Directory lister
 7212: 
 7213: sub dirlist {
 7214:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 7215:     $uri=~s/^\///;
 7216:     $uri=~s/\/$//;
 7217:     my ($udom, $uname);
 7218:     if ($getuserdir) {
 7219:         $udom = $userdomain;
 7220:         $uname = $username;
 7221:     } else {
 7222:         (undef,$udom,$uname)=split(/\//,$uri);
 7223:         if(defined($userdomain)) {
 7224:             $udom = $userdomain;
 7225:         }
 7226:         if(defined($username)) {
 7227:             $uname = $username;
 7228:         }
 7229:     }
 7230:     my ($dirRoot,$listing,@listing_results);
 7231: 
 7232:     $dirRoot = $perlvar{'lonDocRoot'};
 7233:     if (defined($getpropath)) {
 7234:         $dirRoot = &propath($udom,$uname);
 7235:         $dirRoot =~ s/\/$//;
 7236:     } elsif (defined($getuserdir)) {
 7237:         my $subdir=$uname.'__';
 7238:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 7239:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 7240:                    ."/$udom/$subdir/$uname";
 7241:     } elsif (defined($alternateRoot)) {
 7242:         $dirRoot = $alternateRoot;
 7243:     }
 7244: 
 7245:     if($udom) {
 7246:         if($uname) {
 7247:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 7248:                               .$getuserdir.':'.&escape($dirRoot)
 7249:                               .':'.&escape($uname).':'.&escape($udom),
 7250:                               &homeserver($uname,$udom));
 7251:             if ($listing eq 'unknown_cmd') {
 7252:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 7253:                                   &homeserver($uname,$udom));
 7254:             } else {
 7255:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7256:             }
 7257:             if ($listing eq 'unknown_cmd') {
 7258:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 7259: 				  &homeserver($uname,$udom));
 7260:                 @listing_results = split(/:/,$listing);
 7261:             } else {
 7262:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7263:             }
 7264:             return @listing_results;
 7265:         } elsif(!$alternateRoot) {
 7266:             my %allusers;
 7267: 	    my %servers = &get_servers($udom,'library');
 7268:  	    foreach my $tryserver (keys(%servers)) {
 7269:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 7270:                                   &escape($udom),$tryserver);
 7271:                 if ($listing eq 'unknown_cmd') {
 7272: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 7273: 				      $udom, $tryserver);
 7274:                 } else {
 7275:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 7276:                 }
 7277: 		if ($listing eq 'unknown_cmd') {
 7278: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 7279: 				      $udom, $tryserver);
 7280: 		    @listing_results = split(/:/,$listing);
 7281: 		} else {
 7282: 		    @listing_results =
 7283: 			map { &unescape($_); } split(/:/,$listing);
 7284: 		}
 7285: 		if ($listing_results[0] ne 'no_such_dir' && 
 7286: 		    $listing_results[0] ne 'empty'       &&
 7287: 		    $listing_results[0] ne 'con_lost') {
 7288: 		    foreach my $line (@listing_results) {
 7289: 			my ($entry) = split(/&/,$line,2);
 7290: 			$allusers{$entry} = 1;
 7291: 		    }
 7292: 		}
 7293:             }
 7294:             my $alluserstr='';
 7295:             foreach my $user (sort(keys(%allusers))) {
 7296:                 $alluserstr.=$user.'&user:';
 7297:             }
 7298:             $alluserstr=~s/:$//;
 7299:             return split(/:/,$alluserstr);
 7300:         } else {
 7301:             return ('missing user name');
 7302:         }
 7303:     } elsif(!defined($getpropath)) {
 7304:         my @all_domains = sort(&all_domains());
 7305:         foreach my $domain (@all_domains) {
 7306:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 7307:         }
 7308:         return @all_domains;
 7309:     } else {
 7310:         return ('missing domain');
 7311:     }
 7312: }
 7313: 
 7314: # --------------------------------------------- GetFileTimestamp
 7315: # This function utilizes dirlist and returns the date stamp for
 7316: # when it was last modified.  It will also return an error of -1
 7317: # if an error occurs
 7318: 
 7319: sub GetFileTimestamp {
 7320:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 7321:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 7322:     $studentName   = &LONCAPA::clean_username($studentName);
 7323:     my ($fileStat) = 
 7324:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 7325:                                  undef,$getuserdir);
 7326:     my @stats = split('&', $fileStat);
 7327:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7328:         # @stats contains first the filename, then the stat output
 7329:         return $stats[10]; # so this is 10 instead of 9.
 7330:     } else {
 7331:         return -1;
 7332:     }
 7333: }
 7334: 
 7335: sub stat_file {
 7336:     my ($uri) = @_;
 7337:     $uri = &clutter_with_no_wrapper($uri);
 7338: 
 7339:     my ($udom,$uname,$file);
 7340:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7341: 	($udom,$uname,$file) =
 7342: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7343: 	$file = 'userfiles/'.$file;
 7344:     }
 7345:     if ($uri =~ m-^/res/-) {
 7346: 	($udom,$uname) = 
 7347: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7348: 	$file = $uri;
 7349:     }
 7350: 
 7351:     if (!$udom || !$uname || !$file) {
 7352: 	# unable to handle the uri
 7353: 	return ();
 7354:     }
 7355:     my $getpropath;
 7356:     if ($file =~ /^userfiles\//) {
 7357:         $getpropath = 1;
 7358:     }
 7359:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7360:     my @stats = split('&', $result);
 7361:     
 7362:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7363: 	shift(@stats); #filename is first
 7364: 	return @stats;
 7365:     }
 7366:     return ();
 7367: }
 7368: 
 7369: # -------------------------------------------------------- Value of a Condition
 7370: 
 7371: # gets the value of a specific preevaluated condition
 7372: #    stored in the string  $env{user.state.<cid>}
 7373: # or looks up a condition reference in the bighash and if if hasn't
 7374: # already been evaluated recurses into docondval to get the value of
 7375: # the condition, then memoizing it to 
 7376: #   $env{user.state.<cid>.<condition>}
 7377: sub directcondval {
 7378:     my $number=shift;
 7379:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7380: 	&Apache::lonuserstate::evalstate();
 7381:     }
 7382:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7383: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7384:     } elsif ($number =~ /^_/) {
 7385: 	my $sub_condition;
 7386: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7387: 		&GDBM_READER(),0640)) {
 7388: 	    $sub_condition=$bighash{'conditions'.$number};
 7389: 	    untie(%bighash);
 7390: 	}
 7391: 	my $value = &docondval($sub_condition);
 7392: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7393: 	return $value;
 7394:     }
 7395:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7396:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7397:     } else {
 7398:        return 2;
 7399:     }
 7400: }
 7401: 
 7402: # get the collection of conditions for this resource
 7403: sub condval {
 7404:     my $condidx=shift;
 7405:     my $allpathcond='';
 7406:     foreach my $cond (split(/\|/,$condidx)) {
 7407: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7408: 	    $allpathcond.=
 7409: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7410: 	}
 7411:     }
 7412:     $allpathcond=~s/\|$//;
 7413:     return &docondval($allpathcond);
 7414: }
 7415: 
 7416: #evaluates an expression of conditions
 7417: sub docondval {
 7418:     my ($allpathcond) = @_;
 7419:     my $result=0;
 7420:     if ($env{'request.course.id'}
 7421: 	&& defined($allpathcond)) {
 7422: 	my $operand='|';
 7423: 	my @stack;
 7424: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7425: 	    if ($chunk eq '(') {
 7426: 		push @stack,($operand,$result);
 7427: 	    } elsif ($chunk eq ')') {
 7428: 		my $before=pop @stack;
 7429: 		if (pop @stack eq '&') {
 7430: 		    $result=$result>$before?$before:$result;
 7431: 		} else {
 7432: 		    $result=$result>$before?$result:$before;
 7433: 		}
 7434: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7435: 		$operand=$chunk;
 7436: 	    } else {
 7437: 		my $new=directcondval($chunk);
 7438: 		if ($operand eq '&') {
 7439: 		    $result=$result>$new?$new:$result;
 7440: 		} else {
 7441: 		    $result=$result>$new?$result:$new;
 7442: 		}
 7443: 	    }
 7444: 	}
 7445:     }
 7446:     return $result;
 7447: }
 7448: 
 7449: # ---------------------------------------------------- Devalidate courseresdata
 7450: 
 7451: sub devalidatecourseresdata {
 7452:     my ($coursenum,$coursedomain)=@_;
 7453:     my $hashid=$coursenum.':'.$coursedomain;
 7454:     &devalidate_cache_new('courseres',$hashid);
 7455: }
 7456: 
 7457: 
 7458: # --------------------------------------------------- Course Resourcedata Query
 7459: #
 7460: #  Parameters:
 7461: #      $coursenum    - Number of the course.
 7462: #      $coursedomain - Domain at which the course was created.
 7463: #  Returns:
 7464: #     A hash of the course parameters along (I think) with timestamps
 7465: #     and version info.
 7466: 
 7467: sub get_courseresdata {
 7468:     my ($coursenum,$coursedomain)=@_;
 7469:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7470:     my $hashid=$coursenum.':'.$coursedomain;
 7471:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7472:     my %dumpreply;
 7473:     unless (defined($cached)) {
 7474: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7475: 	$result=\%dumpreply;
 7476: 	my ($tmp) = keys(%dumpreply);
 7477: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7478: 	    &do_cache_new('courseres',$hashid,$result,600);
 7479: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7480: 	    return $tmp;
 7481: 	} elsif ($tmp =~ /^(error)/) {
 7482: 	    $result=undef;
 7483: 	    &do_cache_new('courseres',$hashid,$result,600);
 7484: 	}
 7485:     }
 7486:     return $result;
 7487: }
 7488: 
 7489: sub devalidateuserresdata {
 7490:     my ($uname,$udom)=@_;
 7491:     my $hashid="$udom:$uname";
 7492:     &devalidate_cache_new('userres',$hashid);
 7493: }
 7494: 
 7495: sub get_userresdata {
 7496:     my ($uname,$udom)=@_;
 7497:     #most student don\'t have any data set, check if there is some data
 7498:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7499: 
 7500:     my $hashid="$udom:$uname";
 7501:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7502:     if (!defined($cached)) {
 7503: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7504: 	$result=\%resourcedata;
 7505: 	&do_cache_new('userres',$hashid,$result,600);
 7506:     }
 7507:     my ($tmp)=keys(%$result);
 7508:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7509: 	return $result;
 7510:     }
 7511:     #error 2 occurs when the .db doesn't exist
 7512:     if ($tmp!~/error: 2 /) {
 7513: 	&logthis("<font color=\"blue\">WARNING:".
 7514: 		 " Trying to get resource data for ".
 7515: 		 $uname." at ".$udom.": ".
 7516: 		 $tmp."</font>");
 7517:     } elsif ($tmp=~/error: 2 /) {
 7518: 	#&EXT_cache_set($udom,$uname);
 7519: 	&do_cache_new('userres',$hashid,undef,600);
 7520: 	undef($tmp); # not really an error so don't send it back
 7521:     }
 7522:     return $tmp;
 7523: }
 7524: #----------------------------------------------- resdata - return resource data
 7525: #  Purpose:
 7526: #    Return resource data for either users or for a course.
 7527: #  Parameters:
 7528: #     $name      - Course/user name.
 7529: #     $domain    - Name of the domain the user/course is registered on.
 7530: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7531: #     @which     - Array of names of resources desired.
 7532: #  Returns:
 7533: #     The value of the first reasource in @which that is found in the
 7534: #     resource hash.
 7535: #  Exceptional Conditions:
 7536: #     If the $type passed in is not valid (not the string 'course' or 
 7537: #     'user', an undefined  reference is returned.
 7538: #     If none of the resources are found, an undef is returned
 7539: sub resdata {
 7540:     my ($name,$domain,$type,@which)=@_;
 7541:     my $result;
 7542:     if ($type eq 'course') {
 7543: 	$result=&get_courseresdata($name,$domain);
 7544:     } elsif ($type eq 'user') {
 7545: 	$result=&get_userresdata($name,$domain);
 7546:     }
 7547:     if (!ref($result)) { return $result; }    
 7548:     foreach my $item (@which) {
 7549: 	if (defined($result->{$item->[0]})) {
 7550: 	    return [$result->{$item->[0]},$item->[1]];
 7551: 	}
 7552:     }
 7553:     return undef;
 7554: }
 7555: 
 7556: #
 7557: # EXT resource caching routines
 7558: #
 7559: 
 7560: sub clear_EXT_cache_status {
 7561:     &delenv('cache.EXT.');
 7562: }
 7563: 
 7564: sub EXT_cache_status {
 7565:     my ($target_domain,$target_user) = @_;
 7566:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7567:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7568:         # We know already the user has no data
 7569:         return 1;
 7570:     } else {
 7571:         return 0;
 7572:     }
 7573: }
 7574: 
 7575: sub EXT_cache_set {
 7576:     my ($target_domain,$target_user) = @_;
 7577:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7578:     #&appenv({$cachename => time});
 7579: }
 7580: 
 7581: # --------------------------------------------------------- Value of a Variable
 7582: sub EXT {
 7583: 
 7584:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7585:     unless ($varname) { return ''; }
 7586:     #get real user name/domain, courseid and symb
 7587:     my $courseid;
 7588:     my $publicuser;
 7589:     if ($symbparm) {
 7590: 	$symbparm=&get_symb_from_alias($symbparm);
 7591:     }
 7592:     if (!($uname && $udom)) {
 7593:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7594:       if (!$symbparm) {	$symbparm=$cursymb; }
 7595:     } else {
 7596: 	$courseid=$env{'request.course.id'};
 7597:     }
 7598:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7599:     my $rest;
 7600:     if (defined($therest[0])) {
 7601:        $rest=join('.',@therest);
 7602:     } else {
 7603:        $rest='';
 7604:     }
 7605: 
 7606:     my $qualifierrest=$qualifier;
 7607:     if ($rest) { $qualifierrest.='.'.$rest; }
 7608:     my $spacequalifierrest=$space;
 7609:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7610:     if ($realm eq 'user') {
 7611: # --------------------------------------------------------------- user.resource
 7612: 	if ($space eq 'resource') {
 7613: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7614: 		  || defined($Apache::lonhomework::parsing_a_task))
 7615: 		 &&
 7616: 		 ($symbparm eq &symbread()) ) {	
 7617: 		# if we are in the middle of processing the resource the
 7618: 		# get the value we are planning on committing
 7619:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7620:                     return $Apache::lonhomework::results{$qualifierrest};
 7621:                 } else {
 7622:                     return $Apache::lonhomework::history{$qualifierrest};
 7623:                 }
 7624: 	    } else {
 7625: 		my %restored;
 7626: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7627: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7628: 		} else {
 7629: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7630: 		}
 7631: 		return $restored{$qualifierrest};
 7632: 	    }
 7633: # ----------------------------------------------------------------- user.access
 7634:         } elsif ($space eq 'access') {
 7635: 	    # FIXME - not supporting calls for a specific user
 7636:             return &allowed($qualifier,$rest);
 7637: # ------------------------------------------ user.preferences, user.environment
 7638:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7639: 	    if (($uname eq $env{'user.name'}) &&
 7640: 		($udom eq $env{'user.domain'})) {
 7641: 		return $env{join('.',('environment',$qualifierrest))};
 7642: 	    } else {
 7643: 		my %returnhash;
 7644: 		if (!$publicuser) {
 7645: 		    %returnhash=&userenvironment($udom,$uname,
 7646: 						 $qualifierrest);
 7647: 		}
 7648: 		return $returnhash{$qualifierrest};
 7649: 	    }
 7650: # ----------------------------------------------------------------- user.course
 7651:         } elsif ($space eq 'course') {
 7652: 	    # FIXME - not supporting calls for a specific user
 7653:             return $env{join('.',('request.course',$qualifier))};
 7654: # ------------------------------------------------------------------- user.role
 7655:         } elsif ($space eq 'role') {
 7656: 	    # FIXME - not supporting calls for a specific user
 7657:             my ($role,$where)=split(/\./,$env{'request.role'});
 7658:             if ($qualifier eq 'value') {
 7659: 		return $role;
 7660:             } elsif ($qualifier eq 'extent') {
 7661:                 return $where;
 7662:             }
 7663: # ----------------------------------------------------------------- user.domain
 7664:         } elsif ($space eq 'domain') {
 7665:             return $udom;
 7666: # ------------------------------------------------------------------- user.name
 7667:         } elsif ($space eq 'name') {
 7668:             return $uname;
 7669: # ---------------------------------------------------- Any other user namespace
 7670:         } else {
 7671: 	    my %reply;
 7672: 	    if (!$publicuser) {
 7673: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7674: 	    }
 7675: 	    return $reply{$qualifierrest};
 7676:         }
 7677:     } elsif ($realm eq 'query') {
 7678: # ---------------------------------------------- pull stuff out of query string
 7679:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7680: 						[$spacequalifierrest]);
 7681: 	return $env{'form.'.$spacequalifierrest}; 
 7682:    } elsif ($realm eq 'request') {
 7683: # ------------------------------------------------------------- request.browser
 7684:         if ($space eq 'browser') {
 7685: 	    if ($qualifier eq 'textremote') {
 7686: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7687: 		    return 1;
 7688: 		} else {
 7689: 		    return 0;
 7690: 		}
 7691: 	    } else {
 7692: 		return $env{'browser.'.$qualifier};
 7693: 	    }
 7694: # ------------------------------------------------------------ request.filename
 7695:         } else {
 7696:             return $env{'request.'.$spacequalifierrest};
 7697:         }
 7698:     } elsif ($realm eq 'course') {
 7699: # ---------------------------------------------------------- course.description
 7700:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7701:     } elsif ($realm eq 'resource') {
 7702: 
 7703: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7704: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7705: 	}
 7706: 
 7707: 	if ($space eq 'title') {
 7708: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7709: 	    return &gettitle($symbparm);
 7710: 	}
 7711: 	
 7712: 	if ($space eq 'map') {
 7713: 	    my ($map) = &decode_symb($symbparm);
 7714: 	    return &symbread($map);
 7715: 	}
 7716: 	if ($space eq 'filename') {
 7717: 	    if ($symbparm) {
 7718: 		return &clutter((&decode_symb($symbparm))[2]);
 7719: 	    }
 7720: 	    return &hreflocation('',$env{'request.filename'});
 7721: 	}
 7722: 
 7723: 	my ($section, $group, @groups);
 7724: 	my ($courselevelm,$courselevel);
 7725: 	if ($symbparm && defined($courseid) && 
 7726: 	    $courseid eq $env{'request.course.id'}) {
 7727: 
 7728: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7729: 
 7730: # ----------------------------------------------------- Cascading lookup scheme
 7731: 	    my $symbp=$symbparm;
 7732: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7733: 
 7734: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7735: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7736: 
 7737: 	    if (($env{'user.name'} eq $uname) &&
 7738: 		($env{'user.domain'} eq $udom)) {
 7739: 		$section=$env{'request.course.sec'};
 7740:                 @groups = split(/:/,$env{'request.course.groups'});  
 7741:                 @groups=&sort_course_groups($courseid,@groups); 
 7742: 	    } else {
 7743: 		if (! defined($usection)) {
 7744: 		    $section=&getsection($udom,$uname,$courseid);
 7745: 		} else {
 7746: 		    $section = $usection;
 7747: 		}
 7748:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7749: 	    }
 7750: 
 7751: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7752: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7753: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7754: 
 7755: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7756: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7757: 	    $courselevelm=$courseid.'.'.$mapparm;
 7758: 
 7759: # ----------------------------------------------------------- first, check user
 7760: 
 7761: 	    my $userreply=&resdata($uname,$udom,'user',
 7762: 				       ([$courselevelr,'resource'],
 7763: 					[$courselevelm,'map'     ],
 7764: 					[$courselevel, 'course'  ]));
 7765: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7766: 
 7767: # ------------------------------------------------ second, check some of course
 7768:             my $coursereply;
 7769:             if (@groups > 0) {
 7770:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7771:                                        $mapparm,$spacequalifierrest);
 7772:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7773:             }
 7774: 
 7775: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7776: 				  $env{'course.'.$courseid.'.domain'},
 7777: 				  'course',
 7778: 				  ([$seclevelr,   'resource'],
 7779: 				   [$seclevelm,   'map'     ],
 7780: 				   [$seclevel,    'course'  ],
 7781: 				   [$courselevelr,'resource']));
 7782: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7783: 
 7784: # ------------------------------------------------------ third, check map parms
 7785: 	    my %parmhash=();
 7786: 	    my $thisparm='';
 7787: 	    if (tie(%parmhash,'GDBM_File',
 7788: 		    $env{'request.course.fn'}.'_parms.db',
 7789: 		    &GDBM_READER(),0640)) {
 7790: 		$thisparm=$parmhash{$symbparm};
 7791: 		untie(%parmhash);
 7792: 	    }
 7793: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7794: 	}
 7795: # ------------------------------------------ fourth, look in resource metadata
 7796: 
 7797: 	$spacequalifierrest=~s/\./\_/;
 7798: 	my $filename;
 7799: 	if (!$symbparm) { $symbparm=&symbread(); }
 7800: 	if ($symbparm) {
 7801: 	    $filename=(&decode_symb($symbparm))[2];
 7802: 	} else {
 7803: 	    $filename=$env{'request.filename'};
 7804: 	}
 7805: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7806: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7807: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7808: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7809: 
 7810: # ---------------------------------------------- fourth, look in rest of course
 7811: 	if ($symbparm && defined($courseid) && 
 7812: 	    $courseid eq $env{'request.course.id'}) {
 7813: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7814: 				     $env{'course.'.$courseid.'.domain'},
 7815: 				     'course',
 7816: 				     ([$courselevelm,'map'   ],
 7817: 				      [$courselevel, 'course']));
 7818: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7819: 	}
 7820: # ------------------------------------------------------------------ Cascade up
 7821: 	unless ($space eq '0') {
 7822: 	    my @parts=split(/_/,$space);
 7823: 	    my $id=pop(@parts);
 7824: 	    my $part=join('_',@parts);
 7825: 	    if ($part eq '') { $part='0'; }
 7826: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7827: 				 $symbparm,$udom,$uname,$section,1);
 7828: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7829: 	}
 7830: 	if ($recurse) { return undef; }
 7831: 	my $pack_def=&packages_tab_default($filename,$varname);
 7832: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7833: # ---------------------------------------------------- Any other user namespace
 7834:     } elsif ($realm eq 'environment') {
 7835: # ----------------------------------------------------------------- environment
 7836: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7837: 	    return $env{'environment.'.$spacequalifierrest};
 7838: 	} else {
 7839: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7840: 		return '';
 7841: 	    }
 7842: 	    my %returnhash=&userenvironment($udom,$uname,
 7843: 					    $spacequalifierrest);
 7844: 	    return $returnhash{$spacequalifierrest};
 7845: 	}
 7846:     } elsif ($realm eq 'system') {
 7847: # ----------------------------------------------------------------- system.time
 7848: 	if ($space eq 'time') {
 7849: 	    return time;
 7850:         }
 7851:     } elsif ($realm eq 'server') {
 7852: # ----------------------------------------------------------------- system.time
 7853: 	if ($space eq 'name') {
 7854: 	    return $ENV{'SERVER_NAME'};
 7855:         }
 7856:     }
 7857:     return '';
 7858: }
 7859: 
 7860: sub get_reply {
 7861:     my ($reply_value) = @_;
 7862:     if (ref($reply_value) eq 'ARRAY') {
 7863:         if (wantarray) {
 7864: 	    return @$reply_value;
 7865:         }
 7866:         return $reply_value->[0];
 7867:     } else {
 7868:         return $reply_value;
 7869:     }
 7870: }
 7871: 
 7872: sub check_group_parms {
 7873:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7874:     my @groupitems = ();
 7875:     my $resultitem;
 7876:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7877:     foreach my $group (@{$groups}) {
 7878:         foreach my $level (@levels) {
 7879:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7880:              push(@groupitems,[$item,$level->[1]]);
 7881:         }
 7882:     }
 7883:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7884:                             $env{'course.'.$courseid.'.domain'},
 7885:                                      'course',@groupitems);
 7886:     return $coursereply;
 7887: }
 7888: 
 7889: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7890:     my ($courseid,@groups) = @_;
 7891:     @groups = sort(@groups);
 7892:     return @groups;
 7893: }
 7894: 
 7895: sub packages_tab_default {
 7896:     my ($uri,$varname)=@_;
 7897:     my (undef,$part,$name)=split(/\./,$varname);
 7898: 
 7899:     my (@extension,@specifics,$do_default);
 7900:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7901: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7902: 	if ($pack_type eq 'default') {
 7903: 	    $do_default=1;
 7904: 	} elsif ($pack_type eq 'extension') {
 7905: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7906: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7907: 	    # only look at packages defaults for packages that this id is
 7908: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7909: 	}
 7910:     }
 7911:     # first look for a package that matches the requested part id
 7912:     foreach my $package (@specifics) {
 7913: 	my (undef,$pack_type,$pack_part)=@{$package};
 7914: 	next if ($pack_part ne $part);
 7915: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7916: 	    return $packagetab{"$pack_type&$name&default"};
 7917: 	}
 7918:     }
 7919:     # look for any possible matching non extension_ package
 7920:     foreach my $package (@specifics) {
 7921: 	my (undef,$pack_type,$pack_part)=@{$package};
 7922: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7923: 	    return $packagetab{"$pack_type&$name&default"};
 7924: 	}
 7925: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7926: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7927: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7928: 	}
 7929:     }
 7930:     # look for any posible extension_ match
 7931:     foreach my $package (@extension) {
 7932: 	my ($package,$pack_type)=@{$package};
 7933: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7934: 	    return $packagetab{"$pack_type&$name&default"};
 7935: 	}
 7936: 	if (defined($packagetab{$package."&$name&default"})) {
 7937: 	    return $packagetab{$package."&$name&default"};
 7938: 	}
 7939:     }
 7940:     # look for a global default setting
 7941:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7942: 	return $packagetab{"default&$name&default"};
 7943:     }
 7944:     return undef;
 7945: }
 7946: 
 7947: sub add_prefix_and_part {
 7948:     my ($prefix,$part)=@_;
 7949:     my $keyroot;
 7950:     if (defined($prefix) && $prefix !~ /^__/) {
 7951: 	# prefix that has a part already
 7952: 	$keyroot=$prefix;
 7953:     } elsif (defined($prefix)) {
 7954: 	# prefix that is missing a part
 7955: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7956:     } else {
 7957: 	# no prefix at all
 7958: 	if (defined($part)) { $keyroot='_'.$part; }
 7959:     }
 7960:     return $keyroot;
 7961: }
 7962: 
 7963: # ---------------------------------------------------------------- Get metadata
 7964: 
 7965: my %metaentry;
 7966: sub metadata {
 7967:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7968:     $uri=&declutter($uri);
 7969:     # if it is a non metadata possible uri return quickly
 7970:     if (($uri eq '') || 
 7971: 	(($uri =~ m|^/*adm/|) && 
 7972: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7973:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7974: 	return undef;
 7975:     }
 7976:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7977: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7978: 	return undef;
 7979:     }
 7980:     my $filename=$uri;
 7981:     $uri=~s/\.meta$//;
 7982: #
 7983: # Is the metadata already cached?
 7984: # Look at timestamp of caching
 7985: # Everything is cached by the main uri, libraries are never directly cached
 7986: #
 7987:     if (!defined($liburi)) {
 7988: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7989: 	if (defined($cached)) { return $result->{':'.$what}; }
 7990:     }
 7991:     {
 7992: #
 7993: # Is this a recursive call for a library?
 7994: #
 7995: #	if (! exists($metacache{$uri})) {
 7996: #	    $metacache{$uri}={};
 7997: #	}
 7998: 	my $cachetime = 60*60;
 7999:         if ($liburi) {
 8000: 	    $liburi=&declutter($liburi);
 8001:             $filename=$liburi;
 8002:         } else {
 8003: 	    &devalidate_cache_new('meta',$uri);
 8004: 	    undef(%metaentry);
 8005: 	}
 8006:         my %metathesekeys=();
 8007:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 8008: 	my $metastring;
 8009: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 8010: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 8011: 	    $metastring = 
 8012: 		&Apache::lonnet::ssi_body($which,
 8013: 					  ('grade_target' => 'meta'));
 8014: 	    $cachetime = 1; # only want this cached in the child not long term
 8015: 	} elsif ($uri !~ m -^(editupload)/-) {
 8016: 	    my $file=&filelocation('',&clutter($filename));
 8017: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 8018: 	    $metastring=&getfile($file);
 8019: 	}
 8020:         my $parser=HTML::LCParser->new(\$metastring);
 8021:         my $token;
 8022:         undef %metathesekeys;
 8023:         while ($token=$parser->get_token) {
 8024: 	    if ($token->[0] eq 'S') {
 8025: 		if (defined($token->[2]->{'package'})) {
 8026: #
 8027: # This is a package - get package info
 8028: #
 8029: 		    my $package=$token->[2]->{'package'};
 8030: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8031: 		    if (defined($token->[2]->{'id'})) { 
 8032: 			$keyroot.='_'.$token->[2]->{'id'}; 
 8033: 		    }
 8034: 		    if ($metaentry{':packages'}) {
 8035: 			$metaentry{':packages'}.=','.$package.$keyroot;
 8036: 		    } else {
 8037: 			$metaentry{':packages'}=$package.$keyroot;
 8038: 		    }
 8039: 		    foreach my $pack_entry (keys(%packagetab)) {
 8040: 			my $part=$keyroot;
 8041: 			$part=~s/^\_//;
 8042: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 8043: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 8044: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 8045: 			    # ignore package.tab specified default values
 8046:                             # here &package_tab_default() will fetch those
 8047: 			    if ($subp eq 'default') { next; }
 8048: 			    my $value=$packagetab{$pack_entry};
 8049: 			    my $unikey;
 8050: 			    if ($pack =~ /_0$/) {
 8051: 				$unikey='parameter_0_'.$name;
 8052: 				$part=0;
 8053: 			    } else {
 8054: 				$unikey='parameter'.$keyroot.'_'.$name;
 8055: 			    }
 8056: 			    if ($subp eq 'display') {
 8057: 				$value.=' [Part: '.$part.']';
 8058: 			    }
 8059: 			    $metaentry{':'.$unikey.'.part'}=$part;
 8060: 			    $metathesekeys{$unikey}=1;
 8061: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8062: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 8063: 			    }
 8064: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 8065: 				$metaentry{':'.$unikey}=
 8066: 				    $metaentry{':'.$unikey.'.default'};
 8067: 			    }
 8068: 			}
 8069: 		    }
 8070: 		} else {
 8071: #
 8072: # This is not a package - some other kind of start tag
 8073: #
 8074: 		    my $entry=$token->[1];
 8075: 		    my $unikey;
 8076: 		    if ($entry eq 'import') {
 8077: 			$unikey='';
 8078: 		    } else {
 8079: 			$unikey=$entry;
 8080: 		    }
 8081: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8082: 
 8083: 		    if (defined($token->[2]->{'id'})) { 
 8084: 			$unikey.='_'.$token->[2]->{'id'}; 
 8085: 		    }
 8086: 
 8087: 		    if ($entry eq 'import') {
 8088: #
 8089: # Importing a library here
 8090: #
 8091: 			if ($depthcount<20) {
 8092: 			    my $location=$parser->get_text('/import');
 8093: 			    my $dir=$filename;
 8094: 			    $dir=~s|[^/]*$||;
 8095: 			    $location=&filelocation($dir,$location);
 8096: 			    my $metadata = 
 8097: 				&metadata($uri,'keys', $location,$unikey,
 8098: 					  $depthcount+1);
 8099: 			    foreach my $meta (split(',',$metadata)) {
 8100: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 8101: 				$metathesekeys{$meta}=1;
 8102: 			    }
 8103: 			}
 8104: 		    } else { 
 8105: 			
 8106: 			if (defined($token->[2]->{'name'})) { 
 8107: 			    $unikey.='_'.$token->[2]->{'name'}; 
 8108: 			}
 8109: 			$metathesekeys{$unikey}=1;
 8110: 			foreach my $param (@{$token->[3]}) {
 8111: 			    $metaentry{':'.$unikey.'.'.$param} =
 8112: 				$token->[2]->{$param};
 8113: 			}
 8114: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 8115: 			my $default=$metaentry{':'.$unikey.'.default'};
 8116: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 8117: 		 # only ws inside the tag, and not in default, so use default
 8118: 		 # as value
 8119: 			    $metaentry{':'.$unikey}=$default;
 8120: 			} elsif ( $internaltext =~ /\S/ ) {
 8121: 		  # something interesting inside the tag
 8122: 			    $metaentry{':'.$unikey}=$internaltext;
 8123: 			} else {
 8124: 		  # no interesting values, don't set a default
 8125: 			}
 8126: # end of not-a-package not-a-library import
 8127: 		    }
 8128: # end of not-a-package start tag
 8129: 		}
 8130: # the next is the end of "start tag"
 8131: 	    }
 8132: 	}
 8133: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 8134: 	$extension = lc($extension);
 8135: 	if ($extension eq 'htm') { $extension='html'; }
 8136: 
 8137: 	foreach my $key (keys(%packagetab)) {
 8138: 	    #no specific packages #how's our extension
 8139: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 8140: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 8141: 					 \%metathesekeys);
 8142: 	}
 8143: 
 8144: 	if (!exists($metaentry{':packages'})
 8145: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 8146: 	    foreach my $key (keys(%packagetab)) {
 8147: 		#no specific packages well let's get default then
 8148: 		if ($key!~/^default&/) { next; }
 8149: 		&metadata_create_package_def($uri,$key,'default',
 8150: 					     \%metathesekeys);
 8151: 	    }
 8152: 	}
 8153: # are there custom rights to evaluate
 8154: 	if ($metaentry{':copyright'} eq 'custom') {
 8155: 
 8156:     #
 8157:     # Importing a rights file here
 8158:     #
 8159: 	    unless ($depthcount) {
 8160: 		my $location=$metaentry{':customdistributionfile'};
 8161: 		my $dir=$filename;
 8162: 		$dir=~s|[^/]*$||;
 8163: 		$location=&filelocation($dir,$location);
 8164: 		my $rights_metadata =
 8165: 		    &metadata($uri,'keys',$location,'_rights',
 8166: 			      $depthcount+1);
 8167: 		foreach my $rights (split(',',$rights_metadata)) {
 8168: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 8169: 		    $metathesekeys{$rights}=1;
 8170: 		}
 8171: 	    }
 8172: 	}
 8173: 	# uniqifiy package listing
 8174: 	my %seen;
 8175: 	my @uniq_packages =
 8176: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 8177: 	$metaentry{':packages'} = join(',',@uniq_packages);
 8178: 
 8179: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 8180: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 8181: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 8182: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 8183: # this is the end of "was not already recently cached
 8184:     }
 8185:     return $metaentry{':'.$what};
 8186: }
 8187: 
 8188: sub metadata_create_package_def {
 8189:     my ($uri,$key,$package,$metathesekeys)=@_;
 8190:     my ($pack,$name,$subp)=split(/\&/,$key);
 8191:     if ($subp eq 'default') { next; }
 8192:     
 8193:     if (defined($metaentry{':packages'})) {
 8194: 	$metaentry{':packages'}.=','.$package;
 8195:     } else {
 8196: 	$metaentry{':packages'}=$package;
 8197:     }
 8198:     my $value=$packagetab{$key};
 8199:     my $unikey;
 8200:     $unikey='parameter_0_'.$name;
 8201:     $metaentry{':'.$unikey.'.part'}=0;
 8202:     $$metathesekeys{$unikey}=1;
 8203:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8204: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 8205:     }
 8206:     if (defined($metaentry{':'.$unikey.'.default'})) {
 8207: 	$metaentry{':'.$unikey}=
 8208: 	    $metaentry{':'.$unikey.'.default'};
 8209:     }
 8210: }
 8211: 
 8212: sub metadata_generate_part0 {
 8213:     my ($metadata,$metacache,$uri) = @_;
 8214:     my %allnames;
 8215:     foreach my $metakey (keys(%$metadata)) {
 8216: 	if ($metakey=~/^parameter\_(.*)/) {
 8217: 	  my $part=$$metacache{':'.$metakey.'.part'};
 8218: 	  my $name=$$metacache{':'.$metakey.'.name'};
 8219: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 8220: 	    $allnames{$name}=$part;
 8221: 	  }
 8222: 	}
 8223:     }
 8224:     foreach my $name (keys(%allnames)) {
 8225:       $$metadata{"parameter_0_$name"}=1;
 8226:       my $key=":parameter_0_$name";
 8227:       $$metacache{"$key.part"}='0';
 8228:       $$metacache{"$key.name"}=$name;
 8229:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 8230: 					   $allnames{$name}.'_'.$name.
 8231: 					   '.type'};
 8232:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 8233: 			     '.display'};
 8234:       my $expr='[Part: '.$allnames{$name}.']';
 8235:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 8236:       $$metacache{"$key.display"}=$olddis;
 8237:     }
 8238: }
 8239: 
 8240: # ------------------------------------------------------ Devalidate title cache
 8241: 
 8242: sub devalidate_title_cache {
 8243:     my ($url)=@_;
 8244:     if (!$env{'request.course.id'}) { return; }
 8245:     my $symb=&symbread($url);
 8246:     if (!$symb) { return; }
 8247:     my $key=$env{'request.course.id'}."\0".$symb;
 8248:     &devalidate_cache_new('title',$key);
 8249: }
 8250: 
 8251: # ------------------------------------------------- Get the title of a course
 8252: 
 8253: sub current_course_title {
 8254:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 8255: }
 8256: # ------------------------------------------------- Get the title of a resource
 8257: 
 8258: sub gettitle {
 8259:     my $urlsymb=shift;
 8260:     my $symb=&symbread($urlsymb);
 8261:     if ($symb) {
 8262: 	my $key=$env{'request.course.id'}."\0".$symb;
 8263: 	my ($result,$cached)=&is_cached_new('title',$key);
 8264: 	if (defined($cached)) { 
 8265: 	    return $result;
 8266: 	}
 8267: 	my ($map,$resid,$url)=&decode_symb($symb);
 8268: 	my $title='';
 8269: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 8270: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 8271: 	} else {
 8272: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8273: 		    &GDBM_READER(),0640)) {
 8274: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 8275: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 8276: 		untie(%bighash);
 8277: 	    }
 8278: 	}
 8279: 	$title=~s/\&colon\;/\:/gs;
 8280: 	if ($title) {
 8281: 	    return &do_cache_new('title',$key,$title,600);
 8282: 	}
 8283: 	$urlsymb=$url;
 8284:     }
 8285:     my $title=&metadata($urlsymb,'title');
 8286:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 8287:     return $title;
 8288: }
 8289: 
 8290: sub get_slot {
 8291:     my ($which,$cnum,$cdom)=@_;
 8292:     if (!$cnum || !$cdom) {
 8293: 	(undef,my $courseid)=&whichuser();
 8294: 	$cdom=$env{'course.'.$courseid.'.domain'};
 8295: 	$cnum=$env{'course.'.$courseid.'.num'};
 8296:     }
 8297:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 8298:     my %slotinfo;
 8299:     if (exists($remembered{$key})) {
 8300: 	$slotinfo{$which} = $remembered{$key};
 8301:     } else {
 8302: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 8303: 	&Apache::lonhomework::showhash(%slotinfo);
 8304: 	my ($tmp)=keys(%slotinfo);
 8305: 	if ($tmp=~/^error:/) { return (); }
 8306: 	$remembered{$key} = $slotinfo{$which};
 8307:     }
 8308:     if (ref($slotinfo{$which}) eq 'HASH') {
 8309: 	return %{$slotinfo{$which}};
 8310:     }
 8311:     return $slotinfo{$which};
 8312: }
 8313: # ------------------------------------------------- Update symbolic store links
 8314: 
 8315: sub symblist {
 8316:     my ($mapname,%newhash)=@_;
 8317:     $mapname=&deversion(&declutter($mapname));
 8318:     my %hash;
 8319:     if (($env{'request.course.fn'}) && (%newhash)) {
 8320:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8321:                       &GDBM_WRCREAT(),0640)) {
 8322: 	    foreach my $url (keys(%newhash)) {
 8323: 		next if ($url eq 'last_known'
 8324: 			 && $env{'form.no_update_last_known'});
 8325: 		$hash{declutter($url)}=&encode_symb($mapname,
 8326: 						    $newhash{$url}->[1],
 8327: 						    $newhash{$url}->[0]);
 8328:             }
 8329:             if (untie(%hash)) {
 8330: 		return 'ok';
 8331:             }
 8332:         }
 8333:     }
 8334:     return 'error';
 8335: }
 8336: 
 8337: # --------------------------------------------------------------- Verify a symb
 8338: 
 8339: sub symbverify {
 8340:     my ($symb,$thisurl)=@_;
 8341:     my $thisfn=$thisurl;
 8342:     $thisfn=&declutter($thisfn);
 8343: # direct jump to resource in page or to a sequence - will construct own symbs
 8344:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8345: # check URL part
 8346:     my ($map,$resid,$url)=&decode_symb($symb);
 8347: 
 8348:     unless ($url eq $thisfn) { return 0; }
 8349: 
 8350:     $symb=&symbclean($symb);
 8351:     $thisurl=&deversion($thisurl);
 8352:     $thisfn=&deversion($thisfn);
 8353: 
 8354:     my %bighash;
 8355:     my $okay=0;
 8356: 
 8357:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8358:                             &GDBM_READER(),0640)) {
 8359:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 8360:             $thisurl =~ s/\?.+$//;
 8361:         }
 8362:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8363:         unless ($ids) { 
 8364:            $ids=$bighash{'ids_/'.$thisurl};
 8365:         }
 8366:         if ($ids) {
 8367: # ------------------------------------------------------------------- Has ID(s)
 8368: 	    foreach my $id (split(/\,/,$ids)) {
 8369: 	       my ($mapid,$resid)=split(/\./,$id);
 8370:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 8371:                    $symb =~ s/\?.+$//;
 8372:                }
 8373:                if (
 8374:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8375:    eq $symb) { 
 8376: 		   if (($env{'request.role.adv'}) ||
 8377: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8378: 		       $okay=1; 
 8379: 		   }
 8380: 	       }
 8381: 	   }
 8382:         }
 8383: 	untie(%bighash);
 8384:     }
 8385:     return $okay;
 8386: }
 8387: 
 8388: # --------------------------------------------------------------- Clean-up symb
 8389: 
 8390: sub symbclean {
 8391:     my $symb=shift;
 8392:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8393: # remove version from map
 8394:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8395: 
 8396: # remove version from URL
 8397:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8398: 
 8399: # remove wrapper
 8400: 
 8401:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8402:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8403:     return $symb;
 8404: }
 8405: 
 8406: # ---------------------------------------------- Split symb to find map and url
 8407: 
 8408: sub encode_symb {
 8409:     my ($map,$resid,$url)=@_;
 8410:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8411: }
 8412: 
 8413: sub decode_symb {
 8414:     my $symb=shift;
 8415:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8416:     my ($map,$resid,$url)=split(/___/,$symb);
 8417:     return (&fixversion($map),$resid,&fixversion($url));
 8418: }
 8419: 
 8420: sub fixversion {
 8421:     my $fn=shift;
 8422:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8423:     my %bighash;
 8424:     my $uri=&clutter($fn);
 8425:     my $key=$env{'request.course.id'}.'_'.$uri;
 8426: # is this cached?
 8427:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8428:     if (defined($cached)) { return $result; }
 8429: # unfortunately not cached, or expired
 8430:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8431: 	    &GDBM_READER(),0640)) {
 8432:  	if ($bighash{'version_'.$uri}) {
 8433:  	    my $version=$bighash{'version_'.$uri};
 8434:  	    unless (($version eq 'mostrecent') || 
 8435: 		    ($version==&getversion($uri))) {
 8436:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8437:  	    }
 8438:  	}
 8439:  	untie %bighash;
 8440:     }
 8441:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8442: }
 8443: 
 8444: sub deversion {
 8445:     my $url=shift;
 8446:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8447:     return $url;
 8448: }
 8449: 
 8450: # ------------------------------------------------------ Return symb list entry
 8451: 
 8452: sub symbread {
 8453:     my ($thisfn,$donotrecurse)=@_;
 8454:     my $cache_str='request.symbread.cached.'.$thisfn;
 8455:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8456: # no filename provided? try from environment
 8457:     unless ($thisfn) {
 8458:         if ($env{'request.symb'}) {
 8459: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8460: 	}
 8461: 	$thisfn=$env{'request.filename'};
 8462:     }
 8463:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8464: # is that filename actually a symb? Verify, clean, and return
 8465:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8466: 	if (&symbverify($thisfn,$1)) {
 8467: 	    return $env{$cache_str}=&symbclean($thisfn);
 8468: 	}
 8469:     }
 8470:     $thisfn=declutter($thisfn);
 8471:     my %hash;
 8472:     my %bighash;
 8473:     my $syval='';
 8474:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8475:         my $targetfn = $thisfn;
 8476:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8477:             $targetfn = 'adm/wrapper/'.$thisfn;
 8478:         }
 8479: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8480: 	    $targetfn=$1;
 8481: 	}
 8482:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8483:                       &GDBM_READER(),0640)) {
 8484: 	    $syval=$hash{$targetfn};
 8485:             untie(%hash);
 8486:         }
 8487: # ---------------------------------------------------------- There was an entry
 8488:         if ($syval) {
 8489: 	    #unless ($syval=~/\_\d+$/) {
 8490: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8491: 		    #&appenv({'request.ambiguous' => $thisfn});
 8492: 		    #return $env{$cache_str}='';
 8493: 		#}    
 8494: 		#$syval.=$1;
 8495: 	    #}
 8496:         } else {
 8497: # ------------------------------------------------------- Was not in symb table
 8498:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8499:                             &GDBM_READER(),0640)) {
 8500: # ---------------------------------------------- Get ID(s) for current resource
 8501:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8502:               unless ($ids) { 
 8503:                  $ids=$bighash{'ids_/'.$thisfn};
 8504:               }
 8505:               unless ($ids) {
 8506: # alias?
 8507: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8508:               }
 8509:               if ($ids) {
 8510: # ------------------------------------------------------------------- Has ID(s)
 8511:                  my @possibilities=split(/\,/,$ids);
 8512:                  if ($#possibilities==0) {
 8513: # ----------------------------------------------- There is only one possibility
 8514: 		     my ($mapid,$resid)=split(/\./,$ids);
 8515: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8516: 						    $resid,$thisfn);
 8517:                  } elsif (!$donotrecurse) {
 8518: # ------------------------------------------ There is more than one possibility
 8519:                      my $realpossible=0;
 8520:                      foreach my $id (@possibilities) {
 8521: 			 my $file=$bighash{'src_'.$id};
 8522:                          if (&allowed('bre',$file)) {
 8523:          		    my ($mapid,$resid)=split(/\./,$id);
 8524:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8525: 				$realpossible++;
 8526:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8527: 						    $resid,$thisfn);
 8528:                             }
 8529: 			 }
 8530:                      }
 8531: 		     if ($realpossible!=1) { $syval=''; }
 8532:                  } else {
 8533:                      $syval='';
 8534:                  }
 8535: 	      }
 8536:               untie(%bighash)
 8537:            }
 8538:         }
 8539:         if ($syval) {
 8540: 	    return $env{$cache_str}=$syval;
 8541:         }
 8542:     }
 8543:     &appenv({'request.ambiguous' => $thisfn});
 8544:     return $env{$cache_str}='';
 8545: }
 8546: 
 8547: # ---------------------------------------------------------- Return random seed
 8548: 
 8549: sub numval {
 8550:     my $txt=shift;
 8551:     $txt=~tr/A-J/0-9/;
 8552:     $txt=~tr/a-j/0-9/;
 8553:     $txt=~tr/K-T/0-9/;
 8554:     $txt=~tr/k-t/0-9/;
 8555:     $txt=~tr/U-Z/0-5/;
 8556:     $txt=~tr/u-z/0-5/;
 8557:     $txt=~s/\D//g;
 8558:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8559:     return int($txt);
 8560: }
 8561: 
 8562: sub numval2 {
 8563:     my $txt=shift;
 8564:     $txt=~tr/A-J/0-9/;
 8565:     $txt=~tr/a-j/0-9/;
 8566:     $txt=~tr/K-T/0-9/;
 8567:     $txt=~tr/k-t/0-9/;
 8568:     $txt=~tr/U-Z/0-5/;
 8569:     $txt=~tr/u-z/0-5/;
 8570:     $txt=~s/\D//g;
 8571:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8572:     my $total;
 8573:     foreach my $val (@txts) { $total+=$val; }
 8574:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8575:     return int($total);
 8576: }
 8577: 
 8578: sub numval3 {
 8579:     use integer;
 8580:     my $txt=shift;
 8581:     $txt=~tr/A-J/0-9/;
 8582:     $txt=~tr/a-j/0-9/;
 8583:     $txt=~tr/K-T/0-9/;
 8584:     $txt=~tr/k-t/0-9/;
 8585:     $txt=~tr/U-Z/0-5/;
 8586:     $txt=~tr/u-z/0-5/;
 8587:     $txt=~s/\D//g;
 8588:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8589:     my $total;
 8590:     foreach my $val (@txts) { $total+=$val; }
 8591:     if ($_64bit) { $total=(($total<<32)>>32); }
 8592:     return $total;
 8593: }
 8594: 
 8595: sub digest {
 8596:     my ($data)=@_;
 8597:     my $digest=&Digest::MD5::md5($data);
 8598:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8599:     my ($e,$f);
 8600:     {
 8601:         use integer;
 8602:         $e=($a+$b);
 8603:         $f=($c+$d);
 8604:         if ($_64bit) {
 8605:             $e=(($e<<32)>>32);
 8606:             $f=(($f<<32)>>32);
 8607:         }
 8608:     }
 8609:     if (wantarray) {
 8610: 	return ($e,$f);
 8611:     } else {
 8612: 	my $g;
 8613: 	{
 8614: 	    use integer;
 8615: 	    $g=($e+$f);
 8616: 	    if ($_64bit) {
 8617: 		$g=(($g<<32)>>32);
 8618: 	    }
 8619: 	}
 8620: 	return $g;
 8621:     }
 8622: }
 8623: 
 8624: sub latest_rnd_algorithm_id {
 8625:     return '64bit5';
 8626: }
 8627: 
 8628: sub get_rand_alg {
 8629:     my ($courseid)=@_;
 8630:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8631:     if ($courseid) {
 8632: 	return $env{"course.$courseid.rndseed"};
 8633:     }
 8634:     return &latest_rnd_algorithm_id();
 8635: }
 8636: 
 8637: sub validCODE {
 8638:     my ($CODE)=@_;
 8639:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8640:     return 0;
 8641: }
 8642: 
 8643: sub getCODE {
 8644:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8645:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8646: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8647: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8648: 	return $Apache::lonhomework::history{'resource.CODE'};
 8649:     }
 8650:     return undef;
 8651: }
 8652: 
 8653: sub rndseed {
 8654:     my ($symb,$courseid,$domain,$username)=@_;
 8655:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8656:     if (!defined($symb)) {
 8657: 	unless ($symb=$wsymb) { return time; }
 8658:     }
 8659:     if (!$courseid) { $courseid=$wcourseid; }
 8660:     if (!$domain) { $domain=$wdomain; }
 8661:     if (!$username) { $username=$wusername }
 8662:     my $which=&get_rand_alg();
 8663: 
 8664:     if (defined(&getCODE())) {
 8665: 	if ($which eq '64bit5') {
 8666: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8667: 	} elsif ($which eq '64bit4') {
 8668: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8669: 	} else {
 8670: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8671: 	}
 8672:     } elsif ($which eq '64bit5') {
 8673: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8674:     } elsif ($which eq '64bit4') {
 8675: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8676:     } elsif ($which eq '64bit3') {
 8677: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8678:     } elsif ($which eq '64bit2') {
 8679: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8680:     } elsif ($which eq '64bit') {
 8681: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8682:     }
 8683:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8684: }
 8685: 
 8686: sub rndseed_32bit {
 8687:     my ($symb,$courseid,$domain,$username)=@_;
 8688:     {
 8689: 	use integer;
 8690: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8691: 	my $symbseed=numval($symb) << 22;
 8692: 	my $namechck=unpack("%32C*",$username) << 17;
 8693: 	my $nameseed=numval($username) << 12;
 8694: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8695: 	my $courseseed=unpack("%32C*",$courseid);
 8696: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8697: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8698: 	#&logthis("rndseed :$num:$symb");
 8699: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8700: 	return $num;
 8701:     }
 8702: }
 8703: 
 8704: sub rndseed_64bit {
 8705:     my ($symb,$courseid,$domain,$username)=@_;
 8706:     {
 8707: 	use integer;
 8708: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8709: 	my $symbseed=numval($symb) << 10;
 8710: 	my $namechck=unpack("%32S*",$username);
 8711: 	
 8712: 	my $nameseed=numval($username) << 21;
 8713: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8714: 	my $courseseed=unpack("%32S*",$courseid);
 8715: 	
 8716: 	my $num1=$symbchck+$symbseed+$namechck;
 8717: 	my $num2=$nameseed+$domainseed+$courseseed;
 8718: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8719: 	#&logthis("rndseed :$num:$symb");
 8720: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8721: 	return "$num1,$num2";
 8722:     }
 8723: }
 8724: 
 8725: sub rndseed_64bit2 {
 8726:     my ($symb,$courseid,$domain,$username)=@_;
 8727:     {
 8728: 	use integer;
 8729: 	# strings need to be an even # of cahracters long, it it is odd the
 8730:         # last characters gets thrown away
 8731: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8732: 	my $symbseed=numval($symb) << 10;
 8733: 	my $namechck=unpack("%32S*",$username.' ');
 8734: 	
 8735: 	my $nameseed=numval($username) << 21;
 8736: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8737: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8738: 	
 8739: 	my $num1=$symbchck+$symbseed+$namechck;
 8740: 	my $num2=$nameseed+$domainseed+$courseseed;
 8741: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8742: 	#&logthis("rndseed :$num:$symb");
 8743: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8744: 	return "$num1,$num2";
 8745:     }
 8746: }
 8747: 
 8748: sub rndseed_64bit3 {
 8749:     my ($symb,$courseid,$domain,$username)=@_;
 8750:     {
 8751: 	use integer;
 8752: 	# strings need to be an even # of cahracters long, it it is odd the
 8753:         # last characters gets thrown away
 8754: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8755: 	my $symbseed=numval2($symb) << 10;
 8756: 	my $namechck=unpack("%32S*",$username.' ');
 8757: 	
 8758: 	my $nameseed=numval2($username) << 21;
 8759: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8760: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8761: 	
 8762: 	my $num1=$symbchck+$symbseed+$namechck;
 8763: 	my $num2=$nameseed+$domainseed+$courseseed;
 8764: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8765: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8766: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8767: 	
 8768: 	return "$num1:$num2";
 8769:     }
 8770: }
 8771: 
 8772: sub rndseed_64bit4 {
 8773:     my ($symb,$courseid,$domain,$username)=@_;
 8774:     {
 8775: 	use integer;
 8776: 	# strings need to be an even # of cahracters long, it it is odd the
 8777:         # last characters gets thrown away
 8778: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8779: 	my $symbseed=numval3($symb) << 10;
 8780: 	my $namechck=unpack("%32S*",$username.' ');
 8781: 	
 8782: 	my $nameseed=numval3($username) << 21;
 8783: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8784: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8785: 	
 8786: 	my $num1=$symbchck+$symbseed+$namechck;
 8787: 	my $num2=$nameseed+$domainseed+$courseseed;
 8788: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8789: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8790: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8791: 	
 8792: 	return "$num1:$num2";
 8793:     }
 8794: }
 8795: 
 8796: sub rndseed_64bit5 {
 8797:     my ($symb,$courseid,$domain,$username)=@_;
 8798:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8799:     return "$num1:$num2";
 8800: }
 8801: 
 8802: sub rndseed_CODE_64bit {
 8803:     my ($symb,$courseid,$domain,$username)=@_;
 8804:     {
 8805: 	use integer;
 8806: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8807: 	my $symbseed=numval2($symb);
 8808: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8809: 	my $CODEseed=numval(&getCODE());
 8810: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8811: 	my $num1=$symbseed+$CODEchck;
 8812: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8813: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8814: 	#&logthis("rndseed :$num1:$num2:$symb");
 8815: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8816: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8817: 	return "$num1:$num2";
 8818:     }
 8819: }
 8820: 
 8821: sub rndseed_CODE_64bit4 {
 8822:     my ($symb,$courseid,$domain,$username)=@_;
 8823:     {
 8824: 	use integer;
 8825: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8826: 	my $symbseed=numval3($symb);
 8827: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8828: 	my $CODEseed=numval3(&getCODE());
 8829: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8830: 	my $num1=$symbseed+$CODEchck;
 8831: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8832: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8833: 	#&logthis("rndseed :$num1:$num2:$symb");
 8834: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8835: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8836: 	return "$num1:$num2";
 8837:     }
 8838: }
 8839: 
 8840: sub rndseed_CODE_64bit5 {
 8841:     my ($symb,$courseid,$domain,$username)=@_;
 8842:     my $code = &getCODE();
 8843:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8844:     return "$num1:$num2";
 8845: }
 8846: 
 8847: sub setup_random_from_rndseed {
 8848:     my ($rndseed)=@_;
 8849:     if ($rndseed =~/([,:])/) {
 8850: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8851: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8852:     } else {
 8853: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8854:     }
 8855: }
 8856: 
 8857: sub latest_receipt_algorithm_id {
 8858:     return 'receipt3';
 8859: }
 8860: 
 8861: sub recunique {
 8862:     my $fucourseid=shift;
 8863:     my $unique;
 8864:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8865: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8866: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8867:     } else {
 8868: 	$unique=$perlvar{'lonReceipt'};
 8869:     }
 8870:     return unpack("%32C*",$unique);
 8871: }
 8872: 
 8873: sub recprefix {
 8874:     my $fucourseid=shift;
 8875:     my $prefix;
 8876:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8877: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8878: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8879:     } else {
 8880: 	$prefix=$perlvar{'lonHostID'};
 8881:     }
 8882:     return unpack("%32C*",$prefix);
 8883: }
 8884: 
 8885: sub ireceipt {
 8886:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8887: 
 8888:     my $return =&recprefix($fucourseid).'-';
 8889: 
 8890:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8891: 	$env{'request.state'} eq 'construct') {
 8892: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8893: 	return $return;
 8894:     }
 8895: 
 8896:     my $cuname=unpack("%32C*",$funame);
 8897:     my $cudom=unpack("%32C*",$fudom);
 8898:     my $cucourseid=unpack("%32C*",$fucourseid);
 8899:     my $cusymb=unpack("%32C*",$fusymb);
 8900:     my $cunique=&recunique($fucourseid);
 8901:     my $cpart=unpack("%32S*",$part);
 8902:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8903: 
 8904: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8905: 			       
 8906: 	$return.= ($cunique%$cuname+
 8907: 		   $cunique%$cudom+
 8908: 		   $cusymb%$cuname+
 8909: 		   $cusymb%$cudom+
 8910: 		   $cucourseid%$cuname+
 8911: 		   $cucourseid%$cudom+
 8912: 		   $cpart%$cuname+
 8913: 		   $cpart%$cudom);
 8914:     } else {
 8915: 	$return.= ($cunique%$cuname+
 8916: 		   $cunique%$cudom+
 8917: 		   $cusymb%$cuname+
 8918: 		   $cusymb%$cudom+
 8919: 		   $cucourseid%$cuname+
 8920: 		   $cucourseid%$cudom);
 8921:     }
 8922:     return $return;
 8923: }
 8924: 
 8925: sub receipt {
 8926:     my ($part)=@_;
 8927:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8928:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8929: }
 8930: 
 8931: sub whichuser {
 8932:     my ($passedsymb)=@_;
 8933:     my ($symb,$courseid,$domain,$name,$publicuser);
 8934:     if (defined($env{'form.grade_symb'})) {
 8935: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8936: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8937: 	if (!$allowed &&
 8938: 	    exists($env{'request.course.sec'}) &&
 8939: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8940: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8941: 			      '/'.$env{'request.course.sec'});
 8942: 	}
 8943: 	if ($allowed) {
 8944: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8945: 	    $courseid=$tmp_courseid;
 8946: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8947: 	    ($name)=&get_env_multiple('form.grade_username');
 8948: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8949: 	}
 8950:     }
 8951:     if (!$passedsymb) {
 8952: 	$symb=&symbread();
 8953:     } else {
 8954: 	$symb=$passedsymb;
 8955:     }
 8956:     $courseid=$env{'request.course.id'};
 8957:     $domain=$env{'user.domain'};
 8958:     $name=$env{'user.name'};
 8959:     if ($name eq 'public' && $domain eq 'public') {
 8960: 	if (!defined($env{'form.username'})) {
 8961: 	    $env{'form.username'}.=time.rand(10000000);
 8962: 	}
 8963: 	$name.=$env{'form.username'};
 8964:     }
 8965:     return ($symb,$courseid,$domain,$name,$publicuser);
 8966: 
 8967: }
 8968: 
 8969: # ------------------------------------------------------------ Serves up a file
 8970: # returns either the contents of the file or 
 8971: # -1 if the file doesn't exist
 8972: #
 8973: # if the target is a file that was uploaded via DOCS, 
 8974: # a check will be made to see if a current copy exists on the local server,
 8975: # if it does this will be served, otherwise a copy will be retrieved from
 8976: # the home server for the course and stored in /home/httpd/html/userfiles on
 8977: # the local server.   
 8978: 
 8979: sub getfile {
 8980:     my ($file) = @_;
 8981:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8982:     &repcopy($file);
 8983:     return &readfile($file);
 8984: }
 8985: 
 8986: sub repcopy_userfile {
 8987:     my ($file)=@_;
 8988:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8989:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8990:     my ($cdom,$cnum,$filename) = 
 8991: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8992:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8993:     if (-e "$file") {
 8994: # we already have a local copy, check it out
 8995: 	my @fileinfo = stat($file);
 8996: 	my $rtncode;
 8997: 	my $info;
 8998: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8999: 	if ($lwpresp ne 'ok') {
 9000: # there is no such file anymore, even though we had a local copy
 9001: 	    if ($rtncode eq '404') {
 9002: 		unlink($file);
 9003: 	    }
 9004: 	    return -1;
 9005: 	}
 9006: 	if ($info < $fileinfo[9]) {
 9007: # nice, the file we have is up-to-date, just say okay
 9008: 	    return 'ok';
 9009: 	} else {
 9010: # the file is outdated, get rid of it
 9011: 	    unlink($file);
 9012: 	}
 9013:     }
 9014: # one way or the other, at this point, we don't have the file
 9015: # construct the correct path for the file
 9016:     my @parts = ($cdom,$cnum); 
 9017:     if ($filename =~ m|^(.+)/[^/]+$|) {
 9018: 	push @parts, split(/\//,$1);
 9019:     }
 9020:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 9021:     foreach my $part (@parts) {
 9022: 	$path .= '/'.$part;
 9023: 	if (!-e $path) {
 9024: 	    mkdir($path,0770);
 9025: 	}
 9026:     }
 9027: # now the path exists for sure
 9028: # get a user agent
 9029:     my $ua=new LWP::UserAgent;
 9030:     my $transferfile=$file.'.in.transfer';
 9031: # FIXME: this should flock
 9032:     if (-e $transferfile) { return 'ok'; }
 9033:     my $request;
 9034:     $uri=~s/^\///;
 9035:     my $homeserver = &homeserver($cnum,$cdom);
 9036:     my $protocol = $protocol{$homeserver};
 9037:     $protocol = 'http' if ($protocol ne 'https');
 9038:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 9039:     my $response=$ua->request($request,$transferfile);
 9040: # did it work?
 9041:     if ($response->is_error()) {
 9042: 	unlink($transferfile);
 9043: 	&logthis("Userfile repcopy failed for $uri");
 9044: 	return -1;
 9045:     }
 9046: # worked, rename the transfer file
 9047:     rename($transferfile,$file);
 9048:     return 'ok';
 9049: }
 9050: 
 9051: sub tokenwrapper {
 9052:     my $uri=shift;
 9053:     $uri=~s|^https?\://([^/]+)||;
 9054:     $uri=~s|^/||;
 9055:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 9056:     my $token=$1;
 9057:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 9058:     if ($udom && $uname && $file) {
 9059: 	$file=~s|(\?\.*)*$||;
 9060:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 9061:         my $homeserver = &homeserver($uname,$udom);
 9062:         my $protocol = $protocol{$homeserver};
 9063:         $protocol = 'http' if ($protocol ne 'https');
 9064:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 9065:                (($uri=~/\?/)?'&':'?').'token='.$token.
 9066:                                '&tokenissued='.$perlvar{'lonHostID'};
 9067:     } else {
 9068:         return '/adm/notfound.html';
 9069:     }
 9070: }
 9071: 
 9072: # call with reqtype HEAD: get last modification time
 9073: # call with reqtype GET: get the file contents
 9074: # Do not call this with reqtype GET for large files! It loads everything into memory
 9075: #
 9076: sub getuploaded {
 9077:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 9078:     $uri=~s/^\///;
 9079:     my $homeserver = &homeserver($cnum,$cdom);
 9080:     my $protocol = $protocol{$homeserver};
 9081:     $protocol = 'http' if ($protocol ne 'https');
 9082:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 9083:     my $ua=new LWP::UserAgent;
 9084:     my $request=new HTTP::Request($reqtype,$uri);
 9085:     my $response=$ua->request($request);
 9086:     $$rtncode = $response->code;
 9087:     if (! $response->is_success()) {
 9088: 	return 'failed';
 9089:     }      
 9090:     if ($reqtype eq 'HEAD') {
 9091: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 9092:     } elsif ($reqtype eq 'GET') {
 9093: 	$$info = $response->content;
 9094:     }
 9095:     return 'ok';
 9096: }
 9097: 
 9098: sub readfile {
 9099:     my $file = shift;
 9100:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 9101:     my $fh;
 9102:     open($fh,"<$file");
 9103:     my $a='';
 9104:     while (my $line = <$fh>) { $a .= $line; }
 9105:     return $a;
 9106: }
 9107: 
 9108: sub filelocation {
 9109:     my ($dir,$file) = @_;
 9110:     my $location;
 9111:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 9112: 
 9113:     if ($file =~ m-^/adm/-) {
 9114: 	$file=~s-^/adm/wrapper/-/-;
 9115: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9116:     }
 9117: 
 9118:     if ($file=~m:^/~:) { # is a contruction space reference
 9119:         $location = $file;
 9120:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 9121:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 9122: 	# is a correct contruction space reference
 9123:         $location = $file;
 9124:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 9125:         $location = $file;
 9126:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 9127:         my ($udom,$uname,$filename)=
 9128:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 9129:         my $home=&homeserver($uname,$udom);
 9130:         my $is_me=0;
 9131:         my @ids=&current_machine_ids();
 9132:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 9133:         if ($is_me) {
 9134:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 9135:         } else {
 9136:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 9137:   	      $udom.'/'.$uname.'/'.$filename;
 9138:         }
 9139:     } elsif ($file =~ m-^/adm/-) {
 9140: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 9141:     } else {
 9142:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9143:         $file=~s:^/res/:/:;
 9144:         if ( !( $file =~ m:^/:) ) {
 9145:             $location = $dir. '/'.$file;
 9146:         } else {
 9147:             $location = '/home/httpd/html/res'.$file;
 9148:         }
 9149:     }
 9150:     $location=~s://+:/:g; # remove duplicate /
 9151:     while ($location=~m{/\.\./}) {
 9152: 	if ($location =~ m{/[^/]+/\.\./}) {
 9153: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 9154: 	} else {
 9155: 	    $location=~ s{/\.\./}{/}g;
 9156: 	}
 9157:     } #remove dir/..
 9158:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 9159:     return $location;
 9160: }
 9161: 
 9162: sub hreflocation {
 9163:     my ($dir,$file)=@_;
 9164:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 9165: 	$file=filelocation($dir,$file);
 9166:     } elsif ($file=~m-^/adm/-) {
 9167: 	$file=~s-^/adm/wrapper/-/-;
 9168: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9169:     }
 9170:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 9171: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 9172:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 9173: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 9174:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 9175: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 9176: 	    -/uploaded/$1/$2/-x;
 9177:     }
 9178:     if ($file=~ m{^/userfiles/}) {
 9179: 	$file =~ s{^/userfiles/}{/uploaded/};
 9180:     }
 9181:     return $file;
 9182: }
 9183: 
 9184: sub current_machine_domains {
 9185:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 9186: }
 9187: 
 9188: sub machine_domains {
 9189:     my ($hostname) = @_;
 9190:     my @domains;
 9191:     my %hostname = &all_hostnames();
 9192:     while( my($id, $name) = each(%hostname)) {
 9193: #	&logthis("-$id-$name-$hostname-");
 9194: 	if ($hostname eq $name) {
 9195: 	    push(@domains,&host_domain($id));
 9196: 	}
 9197:     }
 9198:     return @domains;
 9199: }
 9200: 
 9201: sub current_machine_ids {
 9202:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 9203: }
 9204: 
 9205: sub machine_ids {
 9206:     my ($hostname) = @_;
 9207:     $hostname ||= &hostname($perlvar{'lonHostID'});
 9208:     my @ids;
 9209:     my %name_to_host = &all_names();
 9210:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 9211: 	return @{ $name_to_host{$hostname} };
 9212:     }
 9213:     return;
 9214: }
 9215: 
 9216: sub additional_machine_domains {
 9217:     my @domains;
 9218:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 9219:     while( my $line = <$fh>) {
 9220:         $line =~ s/\s//g;
 9221:         push(@domains,$line);
 9222:     }
 9223:     return @domains;
 9224: }
 9225: 
 9226: sub default_login_domain {
 9227:     my $domain = $perlvar{'lonDefDomain'};
 9228:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 9229:     foreach my $posdom (&current_machine_domains(),
 9230:                         &additional_machine_domains()) {
 9231:         if (lc($posdom) eq lc($testdomain)) {
 9232:             $domain=$posdom;
 9233:             last;
 9234:         }
 9235:     }
 9236:     return $domain;
 9237: }
 9238: 
 9239: # ------------------------------------------------------------- Declutters URLs
 9240: 
 9241: sub declutter {
 9242:     my $thisfn=shift;
 9243:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9244:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9245:     $thisfn=~s/^\///;
 9246:     $thisfn=~s|^adm/wrapper/||;
 9247:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 9248:     $thisfn=~s/^res\///;
 9249:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
 9250:         $thisfn=~s/\?.+$//;
 9251:     }
 9252:     return $thisfn;
 9253: }
 9254: 
 9255: # ------------------------------------------------------------- Clutter up URLs
 9256: 
 9257: sub clutter {
 9258:     my $thisfn='/'.&declutter(shift);
 9259:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 9260: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 9261:        $thisfn='/res'.$thisfn; 
 9262:     }
 9263:     if ($thisfn !~m|^/adm|) {
 9264: 	if ($thisfn =~ m|^/ext/|) {
 9265: 	    $thisfn='/adm/wrapper'.$thisfn;
 9266: 	} else {
 9267: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 9268: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 9269: 	    if ($embstyle eq 'ssi'
 9270: 		|| ($embstyle eq 'hdn')
 9271: 		|| ($embstyle eq 'rat')
 9272: 		|| ($embstyle eq 'prv')
 9273: 		|| ($embstyle eq 'ign')) {
 9274: 		#do nothing with these
 9275: 	    } elsif (($embstyle eq 'img') 
 9276: 		|| ($embstyle eq 'emb')
 9277: 		|| ($embstyle eq 'wrp')) {
 9278: 		$thisfn='/adm/wrapper'.$thisfn;
 9279: 	    } elsif ($embstyle eq 'unk'
 9280: 		     && $thisfn!~/\.(sequence|page)$/) {
 9281: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 9282: 	    } else {
 9283: #		&logthis("Got a blank emb style");
 9284: 	    }
 9285: 	}
 9286:     }
 9287:     return $thisfn;
 9288: }
 9289: 
 9290: sub clutter_with_no_wrapper {
 9291:     my $uri = &clutter(shift);
 9292:     if ($uri =~ m-^/adm/-) {
 9293: 	$uri =~ s-^/adm/wrapper/-/-;
 9294: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 9295:     }
 9296:     return $uri;
 9297: }
 9298: 
 9299: sub freeze_escape {
 9300:     my ($value)=@_;
 9301:     if (ref($value)) {
 9302: 	$value=&nfreeze($value);
 9303: 	return '__FROZEN__'.&escape($value);
 9304:     }
 9305:     return &escape($value);
 9306: }
 9307: 
 9308: 
 9309: sub thaw_unescape {
 9310:     my ($value)=@_;
 9311:     if ($value =~ /^__FROZEN__/) {
 9312: 	substr($value,0,10,undef);
 9313: 	$value=&unescape($value);
 9314: 	return &thaw($value);
 9315:     }
 9316:     return &unescape($value);
 9317: }
 9318: 
 9319: sub correct_line_ends {
 9320:     my ($result)=@_;
 9321:     $$result =~s/\r\n/\n/mg;
 9322:     $$result =~s/\r/\n/mg;
 9323: }
 9324: # ================================================================ Main Program
 9325: 
 9326: sub goodbye {
 9327:    &logthis("Starting Shut down");
 9328: #not converted to using infrastruture and probably shouldn't be
 9329:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 9330: #converted
 9331: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 9332:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 9333: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 9334: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 9335: #1.1 only
 9336: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 9337: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 9338: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 9339: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 9340:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 9341:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 9342:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 9343:    &flushcourselogs();
 9344:    &logthis("Shutting down");
 9345: }
 9346: 
 9347: sub get_dns {
 9348:     my ($url,$func,$ignore_cache) = @_;
 9349:     if (!$ignore_cache) {
 9350: 	my ($content,$cached)=
 9351: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9352: 	if ($cached) {
 9353: 	    &$func($content);
 9354: 	    return;
 9355: 	}
 9356:     }
 9357: 
 9358:     my %alldns;
 9359:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9360:     foreach my $dns (<$config>) {
 9361: 	next if ($dns !~ /^\^(\S*)/x);
 9362:         my $line = $1;
 9363:         my ($host,$protocol) = split(/:/,$line);
 9364:         if ($protocol ne 'https') {
 9365:             $protocol = 'http';
 9366:         }
 9367: 	$alldns{$host} = $protocol;
 9368:     }
 9369:     while (%alldns) {
 9370: 	my ($dns) = keys(%alldns);
 9371: 	my $ua=new LWP::UserAgent;
 9372: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9373: 	my $response=$ua->request($request);
 9374:         delete($alldns{$dns});
 9375: 	next if ($response->is_error());
 9376: 	my @content = split("\n",$response->content);
 9377: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9378: 	&$func(\@content);
 9379: 	return;
 9380:     }
 9381:     close($config);
 9382:     my $which = (split('/',$url))[3];
 9383:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9384:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9385:     my @content = <$config>;
 9386:     &$func(\@content);
 9387:     return;
 9388: }
 9389: # ------------------------------------------------------------ Read domain file
 9390: {
 9391:     my $loaded;
 9392:     my %domain;
 9393: 
 9394:     sub parse_domain_tab {
 9395: 	my ($lines) = @_;
 9396: 	foreach my $line (@$lines) {
 9397: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9398: 
 9399: 	    chomp($line);
 9400: 	    my ($name,@elements) = split(/:/,$line,9);
 9401: 	    my %this_domain;
 9402: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9403: 			       'lang_def', 'city', 'longi', 'lati',
 9404: 			       'primary') {
 9405: 		$this_domain{$field} = shift(@elements);
 9406: 	    }
 9407: 	    $domain{$name} = \%this_domain;
 9408: 	}
 9409:     }
 9410: 
 9411:     sub reset_domain_info {
 9412: 	undef($loaded);
 9413: 	undef(%domain);
 9414:     }
 9415: 
 9416:     sub load_domain_tab {
 9417: 	my ($ignore_cache) = @_;
 9418: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9419: 	my $fh;
 9420: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9421: 	    my @lines = <$fh>;
 9422: 	    &parse_domain_tab(\@lines);
 9423: 	}
 9424: 	close($fh);
 9425: 	$loaded = 1;
 9426:     }
 9427: 
 9428:     sub domain {
 9429: 	&load_domain_tab() if (!$loaded);
 9430: 
 9431: 	my ($name,$what) = @_;
 9432: 	return if ( !exists($domain{$name}) );
 9433: 
 9434: 	if (!$what) {
 9435: 	    return $domain{$name}{'description'};
 9436: 	}
 9437: 	return $domain{$name}{$what};
 9438:     }
 9439: 
 9440:     sub domain_info {
 9441:         &load_domain_tab() if (!$loaded);
 9442:         return %domain;
 9443:     }
 9444: 
 9445: }
 9446: 
 9447: 
 9448: # ------------------------------------------------------------- Read hosts file
 9449: {
 9450:     my %hostname;
 9451:     my %hostdom;
 9452:     my %libserv;
 9453:     my $loaded;
 9454:     my %name_to_host;
 9455: 
 9456:     sub parse_hosts_tab {
 9457: 	my ($file) = @_;
 9458: 	foreach my $configline (@$file) {
 9459: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9460: 	    next if ($configline =~ /^\^/);
 9461: 	    chomp($configline);
 9462: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9463: 	    $name=~s/\s//g;
 9464: 	    if ($id && $domain && $role && $name) {
 9465: 		$hostname{$id}=$name;
 9466: 		push(@{$name_to_host{$name}}, $id);
 9467: 		$hostdom{$id}=$domain;
 9468: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9469:                 if (defined($protocol)) {
 9470:                     if ($protocol eq 'https') {
 9471:                         $protocol{$id} = $protocol;
 9472:                     } else {
 9473:                         $protocol{$id} = 'http'; 
 9474:                     }
 9475:                 } else {
 9476:                     $protocol{$id} = 'http';
 9477:                 }
 9478: 	    }
 9479: 	}
 9480:     }
 9481:     
 9482:     sub reset_hosts_info {
 9483: 	&purge_remembered();
 9484: 	&reset_domain_info();
 9485: 	&reset_hosts_ip_info();
 9486: 	undef(%name_to_host);
 9487: 	undef(%hostname);
 9488: 	undef(%hostdom);
 9489: 	undef(%libserv);
 9490: 	undef($loaded);
 9491:     }
 9492: 
 9493:     sub load_hosts_tab {
 9494: 	my ($ignore_cache) = @_;
 9495: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9496: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9497: 	my @config = <$config>;
 9498: 	&parse_hosts_tab(\@config);
 9499: 	close($config);
 9500: 	$loaded=1;
 9501:     }
 9502: 
 9503:     sub hostname {
 9504: 	&load_hosts_tab() if (!$loaded);
 9505: 
 9506: 	my ($lonid) = @_;
 9507: 	return $hostname{$lonid};
 9508:     }
 9509: 
 9510:     sub all_hostnames {
 9511: 	&load_hosts_tab() if (!$loaded);
 9512: 
 9513: 	return %hostname;
 9514:     }
 9515: 
 9516:     sub all_names {
 9517: 	&load_hosts_tab() if (!$loaded);
 9518: 
 9519: 	return %name_to_host;
 9520:     }
 9521: 
 9522:     sub all_host_domain {
 9523:         &load_hosts_tab() if (!$loaded);
 9524:         return %hostdom;
 9525:     }
 9526: 
 9527:     sub is_library {
 9528: 	&load_hosts_tab() if (!$loaded);
 9529: 
 9530: 	return exists($libserv{$_[0]});
 9531:     }
 9532: 
 9533:     sub all_library {
 9534: 	&load_hosts_tab() if (!$loaded);
 9535: 
 9536: 	return %libserv;
 9537:     }
 9538: 
 9539:     sub get_servers {
 9540: 	&load_hosts_tab() if (!$loaded);
 9541: 
 9542: 	my ($domain,$type) = @_;
 9543: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9544: 	                                          : %hostname;
 9545: 	my %result;
 9546: 	if (ref($domain) eq 'ARRAY') {
 9547: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9548: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9549: 		    $result{$host} = $hostname;
 9550: 		}
 9551: 	    }
 9552: 	} else {
 9553: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9554: 		if ($hostdom{$host} eq $domain) {
 9555: 		    $result{$host} = $hostname;
 9556: 		}
 9557: 	    }
 9558: 	}
 9559: 	return %result;
 9560:     }
 9561: 
 9562:     sub host_domain {
 9563: 	&load_hosts_tab() if (!$loaded);
 9564: 
 9565: 	my ($lonid) = @_;
 9566: 	return $hostdom{$lonid};
 9567:     }
 9568: 
 9569:     sub all_domains {
 9570: 	&load_hosts_tab() if (!$loaded);
 9571: 
 9572: 	my %seen;
 9573: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9574: 	return @uniq;
 9575:     }
 9576: }
 9577: 
 9578: { 
 9579:     my %iphost;
 9580:     my %name_to_ip;
 9581:     my %lonid_to_ip;
 9582: 
 9583:     sub get_hosts_from_ip {
 9584: 	my ($ip) = @_;
 9585: 	my %iphosts = &get_iphost();
 9586: 	if (ref($iphosts{$ip})) {
 9587: 	    return @{$iphosts{$ip}};
 9588: 	}
 9589: 	return;
 9590:     }
 9591:     
 9592:     sub reset_hosts_ip_info {
 9593: 	undef(%iphost);
 9594: 	undef(%name_to_ip);
 9595: 	undef(%lonid_to_ip);
 9596:     }
 9597: 
 9598:     sub get_host_ip {
 9599: 	my ($lonid) = @_;
 9600: 	if (exists($lonid_to_ip{$lonid})) {
 9601: 	    return $lonid_to_ip{$lonid};
 9602: 	}
 9603: 	my $name=&hostname($lonid);
 9604:    	my $ip = gethostbyname($name);
 9605: 	return if (!$ip || length($ip) ne 4);
 9606: 	$ip=inet_ntoa($ip);
 9607: 	$name_to_ip{$name}   = $ip;
 9608: 	$lonid_to_ip{$lonid} = $ip;
 9609: 	return $ip;
 9610:     }
 9611:     
 9612:     sub get_iphost {
 9613: 	my ($ignore_cache) = @_;
 9614: 
 9615: 	if (!$ignore_cache) {
 9616: 	    if (%iphost) {
 9617: 		return %iphost;
 9618: 	    }
 9619: 	    my ($ip_info,$cached)=
 9620: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9621: 	    if ($cached) {
 9622: 		%iphost      = %{$ip_info->[0]};
 9623: 		%name_to_ip  = %{$ip_info->[1]};
 9624: 		%lonid_to_ip = %{$ip_info->[2]};
 9625: 		return %iphost;
 9626: 	    }
 9627: 	}
 9628: 
 9629: 	# get yesterday's info for fallback
 9630: 	my %old_name_to_ip;
 9631: 	my ($ip_info,$cached)=
 9632: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9633: 	if ($cached) {
 9634: 	    %old_name_to_ip = %{$ip_info->[1]};
 9635: 	}
 9636: 
 9637: 	my %name_to_host = &all_names();
 9638: 	foreach my $name (keys(%name_to_host)) {
 9639: 	    my $ip;
 9640: 	    if (!exists($name_to_ip{$name})) {
 9641: 		$ip = gethostbyname($name);
 9642: 		if (!$ip || length($ip) ne 4) {
 9643: 		    if (defined($old_name_to_ip{$name})) {
 9644: 			$ip = $old_name_to_ip{$name};
 9645: 			&logthis("Can't find $name defaulting to old $ip");
 9646: 		    } else {
 9647: 			&logthis("Name $name no IP found");
 9648: 			next;
 9649: 		    }
 9650: 		} else {
 9651: 		    $ip=inet_ntoa($ip);
 9652: 		}
 9653: 		$name_to_ip{$name} = $ip;
 9654: 	    } else {
 9655: 		$ip = $name_to_ip{$name};
 9656: 	    }
 9657: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9658: 		$lonid_to_ip{$id} = $ip;
 9659: 	    }
 9660: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9661: 	}
 9662: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9663: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9664: 				      48*60*60);
 9665: 
 9666: 	return %iphost;
 9667:     }
 9668: 
 9669:     #
 9670:     #  Given a DNS returns the loncapa host name for that DNS 
 9671:     # 
 9672:     sub host_from_dns {
 9673:         my ($dns) = @_;
 9674:         my @hosts;
 9675:         my $ip;
 9676: 
 9677:         if (exists($name_to_ip{$dns})) {
 9678:             $ip = $name_to_ip{$dns};
 9679:         }
 9680:         if (!$ip) {
 9681:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9682:             if (length($ip) == 4) { 
 9683: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9684:             }
 9685:         }
 9686:         if ($ip) {
 9687: 	    @hosts = get_hosts_from_ip($ip);
 9688: 	    return $hosts[0];
 9689:         }
 9690:         return undef;
 9691:     }
 9692: 
 9693: }
 9694: 
 9695: BEGIN {
 9696: 
 9697: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9698:     unless ($readit) {
 9699: {
 9700:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9701:     %perlvar = (%perlvar,%{$configvars});
 9702: }
 9703: 
 9704: 
 9705: # ------------------------------------------------------ Read spare server file
 9706: {
 9707:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9708: 
 9709:     while (my $configline=<$config>) {
 9710:        chomp($configline);
 9711:        if ($configline) {
 9712: 	   my ($host,$type) = split(':',$configline,2);
 9713: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9714: 	   push(@{ $spareid{$type} }, $host);
 9715:        }
 9716:     }
 9717:     close($config);
 9718: }
 9719: # ------------------------------------------------------------ Read permissions
 9720: {
 9721:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9722: 
 9723:     while (my $configline=<$config>) {
 9724: 	chomp($configline);
 9725: 	if ($configline) {
 9726: 	    my ($role,$perm)=split(/ /,$configline);
 9727: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9728: 	}
 9729:     }
 9730:     close($config);
 9731: }
 9732: 
 9733: # -------------------------------------------- Read plain texts for permissions
 9734: {
 9735:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9736: 
 9737:     while (my $configline=<$config>) {
 9738: 	chomp($configline);
 9739: 	if ($configline) {
 9740: 	    my ($short,@plain)=split(/:/,$configline);
 9741:             %{$prp{$short}} = ();
 9742: 	    if (@plain > 0) {
 9743:                 $prp{$short}{'std'} = $plain[0];
 9744:                 for (my $i=1; $i<@plain; $i++) {
 9745:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9746:                 }
 9747:             }
 9748: 	}
 9749:     }
 9750:     close($config);
 9751: }
 9752: 
 9753: # ---------------------------------------------------------- Read package table
 9754: {
 9755:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9756: 
 9757:     while (my $configline=<$config>) {
 9758: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9759: 	chomp($configline);
 9760: 	my ($short,$plain)=split(/:/,$configline);
 9761: 	my ($pack,$name)=split(/\&/,$short);
 9762: 	if ($plain ne '') {
 9763: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9764: 	    $packagetab{$short}=$plain; 
 9765: 	}
 9766:     }
 9767:     close($config);
 9768: }
 9769: 
 9770: # ------------- set up temporary directory
 9771: {
 9772:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9773: 
 9774: }
 9775: 
 9776: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9777: 				'compress_threshold'=> 20_000,
 9778:  			        });
 9779: 
 9780: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9781: $dumpcount=0;
 9782: $locknum=0;
 9783: 
 9784: &logtouch();
 9785: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9786: $readit=1;
 9787:     {
 9788: 	use integer;
 9789: 	my $test=(2**32)+1;
 9790: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9791: 	&logthis(" Detected 64bit platform ($_64bit)");
 9792:     }
 9793: }
 9794: }
 9795: 
 9796: 1;
 9797: __END__
 9798: 
 9799: =pod
 9800: 
 9801: =head1 NAME
 9802: 
 9803: Apache::lonnet - Subroutines to ask questions about things in the network.
 9804: 
 9805: =head1 SYNOPSIS
 9806: 
 9807: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9808: 
 9809:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9810: 
 9811: Common parameters:
 9812: 
 9813: =over 4
 9814: 
 9815: =item *
 9816: 
 9817: $uname : an internal username (if $cname expecting a course Id specifically)
 9818: 
 9819: =item *
 9820: 
 9821: $udom : a domain (if $cdom expecting a course's domain specifically)
 9822: 
 9823: =item *
 9824: 
 9825: $symb : a resource instance identifier
 9826: 
 9827: =item *
 9828: 
 9829: $namespace : the name of a .db file that contains the data needed or
 9830: being set.
 9831: 
 9832: =back
 9833: 
 9834: =head1 OVERVIEW
 9835: 
 9836: lonnet provides subroutines which interact with the
 9837: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9838: about classes, users, and resources.
 9839: 
 9840: For many of these objects you can also use this to store data about
 9841: them or modify them in various ways.
 9842: 
 9843: =head2 Symbs
 9844: 
 9845: To identify a specific instance of a resource, LON-CAPA uses symbols
 9846: or "symbs"X<symb>. These identifiers are built from the URL of the
 9847: map, the resource number of the resource in the map, and the URL of
 9848: the resource itself. The latter is somewhat redundant, but might help
 9849: if maps change.
 9850: 
 9851: An example is
 9852: 
 9853:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9854: 
 9855: The respective map entry is
 9856: 
 9857:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9858:   title="Problem 2">
 9859:  </resource>
 9860: 
 9861: Symbs are used by the random number generator, as well as to store and
 9862: restore data specific to a certain instance of for example a problem.
 9863: 
 9864: =head2 Storing And Retrieving Data
 9865: 
 9866: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9867: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9868: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9869: is is the non-critical message twin of cstore. These functions are for
 9870: handlers to store a perl hash to a user's permanent data space in an
 9871: easy manner, and to retrieve it again on another call. It is expected
 9872: that a handler would use this once at the beginning to retrieve data,
 9873: and then again once at the end to send only the new data back.
 9874: 
 9875: The data is stored in the user's data directory on the user's
 9876: homeserver under the ID of the course.
 9877: 
 9878: The hash that is returned by restore will have all of the previous
 9879: value for all of the elements of the hash.
 9880: 
 9881: Example:
 9882: 
 9883:  #creating a hash
 9884:  my %hash;
 9885:  $hash{'foo'}='bar';
 9886: 
 9887:  #storing it
 9888:  &Apache::lonnet::cstore(\%hash);
 9889: 
 9890:  #changing a value
 9891:  $hash{'foo'}='notbar';
 9892: 
 9893:  #adding a new value
 9894:  $hash{'bar'}='foo';
 9895:  &Apache::lonnet::cstore(\%hash);
 9896: 
 9897:  #retrieving the hash
 9898:  my %history=&Apache::lonnet::restore();
 9899: 
 9900:  #print the hash
 9901:  foreach my $key (sort(keys(%history))) {
 9902:    print("\%history{$key} = $history{$key}");
 9903:  }
 9904: 
 9905: Will print out:
 9906: 
 9907:  %history{1:foo} = bar
 9908:  %history{1:keys} = foo:timestamp
 9909:  %history{1:timestamp} = 990455579
 9910:  %history{2:bar} = foo
 9911:  %history{2:foo} = notbar
 9912:  %history{2:keys} = foo:bar:timestamp
 9913:  %history{2:timestamp} = 990455580
 9914:  %history{bar} = foo
 9915:  %history{foo} = notbar
 9916:  %history{timestamp} = 990455580
 9917:  %history{version} = 2
 9918: 
 9919: Note that the special hash entries C<keys>, C<version> and
 9920: C<timestamp> were added to the hash. C<version> will be equal to the
 9921: total number of versions of the data that have been stored. The
 9922: C<timestamp> attribute will be the UNIX time the hash was
 9923: stored. C<keys> is available in every historical section to list which
 9924: keys were added or changed at a specific historical revision of a
 9925: hash.
 9926: 
 9927: B<Warning>: do not store the hash that restore returns directly. This
 9928: will cause a mess since it will restore the historical keys as if the
 9929: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9930: 
 9931: Calling convention:
 9932: 
 9933:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9934:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9935: 
 9936: For more detailed information, see lonnet specific documentation.
 9937: 
 9938: =head1 RETURN MESSAGES
 9939: 
 9940: =over 4
 9941: 
 9942: =item * B<con_lost>: unable to contact remote host
 9943: 
 9944: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9945: when the connection is brought back up
 9946: 
 9947: =item * B<con_failed>: unable to contact remote host and unable to save message
 9948: for later delivery
 9949: 
 9950: =item * B<error:>: an error a occurred, a description of the error follows the :
 9951: 
 9952: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9953: that was requested
 9954: 
 9955: =back
 9956: 
 9957: =head1 PUBLIC SUBROUTINES
 9958: 
 9959: =head2 Session Environment Functions
 9960: 
 9961: =over 4
 9962: 
 9963: =item * 
 9964: X<appenv()>
 9965: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9966: the user envirnoment file, and will be restored for each access this
 9967: user makes during this session, also modifies the %env for the current
 9968: process. Optional rolesarrayref - if defined contains a reference to an array
 9969: of roles which are exempt from the restriction on modifying user.role entries 
 9970: in the user's environment.db and in %env.    
 9971: 
 9972: =item *
 9973: X<delenv()>
 9974: B<delenv($delthis,$regexp)>: removes all items from the session
 9975: environment file that begin with $delthis. If the 
 9976: optional second arg - $regexp - is true, $delthis is treated as a 
 9977: regular expression, otherwise \Q$delthis\E is used. 
 9978: The values are also deleted from the current processes %env.
 9979: 
 9980: =item * get_env_multiple($name) 
 9981: 
 9982: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9983: values may be defined and end up as an array ref.
 9984: 
 9985: returns an array of values
 9986: 
 9987: =back
 9988: 
 9989: =head2 User Information
 9990: 
 9991: =over 4
 9992: 
 9993: =item *
 9994: X<queryauthenticate()>
 9995: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9996: authentication scheme
 9997: 
 9998: =item *
 9999: X<authenticate()>
10000: B<authenticate($uname,$upass,$udom)>: try to
10001: authenticate user from domain's lib servers (first use the current
10002: one). C<$upass> should be the users password.
10003: 
10004: =item *
10005: X<homeserver()>
10006: B<homeserver($uname,$udom)>: find the server which has
10007: the user's directory and files (there must be only one), this caches
10008: the answer, and also caches if there is a borken connection.
10009: 
10010: =item *
10011: X<idget()>
10012: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10013: (IDs are a unique resource in a domain, there must be only 1 ID per
10014: username, and only 1 username per ID in a specific domain) (returns
10015: hash: id=>name,id=>name)
10016: 
10017: =item *
10018: X<idrget()>
10019: B<idrget($udom,@unames)>: find the IDs behind a list of
10020: usernames (returns hash: name=>id,name=>id)
10021: 
10022: =item *
10023: X<idput()>
10024: B<idput($udom,%ids)>: store away a list of names and associated IDs
10025: 
10026: =item *
10027: X<rolesinit()>
10028: B<rolesinit($udom,$username,$authhost)>: get user privileges
10029: 
10030: =item *
10031: X<getsection()>
10032: B<getsection($udom,$uname,$cname)>: finds the section of student in the
10033: course $cname, return section name/number or '' for "not in course"
10034: and '-1' for "no section"
10035: 
10036: =item *
10037: X<userenvironment()>
10038: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
10039: passed in @what from the requested user's environment, returns a hash
10040: 
10041: =item * 
10042: X<userlog_query()>
10043: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10044: activity.log file. %filters defines filters applied when parsing the
10045: log file. These can be start or end timestamps, or the type of action
10046: - log to look for Login or Logout events, check for Checkin or
10047: Checkout, role for role selection. The response is in the form
10048: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
10049: escaped strings of the action recorded in the activity.log file.
10050: 
10051: =back
10052: 
10053: =head2 User Roles
10054: 
10055: =over 4
10056: 
10057: =item *
10058: 
10059: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
10060:  F: full access
10061:  U,I,K: authentication modes (cxx only)
10062:  '': forbidden
10063:  1: user needs to choose course
10064:  2: browse allowed
10065:  A: passphrase authentication needed
10066: 
10067: =item *
10068: 
10069: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10070: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10071: and course level
10072: 
10073: =item *
10074: 
10075: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
10076: (rolesplain.tab); plain text explanation of a user role term.
10077: $type is Course (default) or Community.
10078: If $forcedefault evaluates to true, text returned will be default 
10079: text for $type. Otherwise, if this is a course, the text returned 
10080: will be a custom name for the role (if defined in the course's 
10081: environment).  If no custom name is defined the default is returned.
10082:    
10083: =item *
10084: 
10085: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
10086: All arguments are optional. Returns a hash of a roles, either for
10087: co-author/assistant author roles for a user's Construction Space
10088: (default), or if $context is 'userroles', roles for the user himself,
10089: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10090: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10091: For each key, value is set to colon-separated start and end times for
10092: the role.  If no username and domain are specified, will default to
10093: current user/domain. Types, roles, and roledoms are references to arrays
10094: of role statuses (active, future or previous), roles 
10095: (e.g., cc,in, st etc.) and domains of the roles which can be used
10096: to restrict the list of roles reported. If no array ref is 
10097: provided for types, will default to return only active roles.
10098: 
10099: =back
10100: 
10101: =head2 User Modification
10102: 
10103: =over 4
10104: 
10105: =item *
10106: 
10107: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10108: user for the level given by URL.  Optional start and end dates (leave empty
10109: string or zero for "no date")
10110: 
10111: =item *
10112: 
10113: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10114: change a users, password, possible return values are: ok,
10115: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10116: refused
10117: 
10118: =item *
10119: 
10120: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10121: 
10122: =item *
10123: 
10124: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
10125:            $forceid,$desiredhome,$email,$inststatus) : 
10126: modify user
10127: 
10128: =item *
10129: 
10130: modifystudent
10131: 
10132: modify a student's enrollment and identification information.
10133: The course id is resolved based on the current users environment.  
10134: This means the envoking user must be a course coordinator or otherwise
10135: associated with a course.
10136: 
10137: This call is essentially a wrapper for lonnet::modifyuser and
10138: lonnet::modify_student_enrollment
10139: 
10140: Inputs: 
10141: 
10142: =over 4
10143: 
10144: =item B<$udom> Student's loncapa domain
10145: 
10146: =item B<$uname> Student's loncapa login name
10147: 
10148: =item B<$uid> Student/Employee ID
10149: 
10150: =item B<$umode> Student's authentication mode
10151: 
10152: =item B<$upass> Student's password
10153: 
10154: =item B<$first> Student's first name
10155: 
10156: =item B<$middle> Student's middle name
10157: 
10158: =item B<$last> Student's last name
10159: 
10160: =item B<$gene> Student's generation
10161: 
10162: =item B<$usec> Student's section in course
10163: 
10164: =item B<$end> Unix time of the roles expiration
10165: 
10166: =item B<$start> Unix time of the roles start date
10167: 
10168: =item B<$forceid> If defined, allow $uid to be changed
10169: 
10170: =item B<$desiredhome> server to use as home server for student
10171: 
10172: =item B<$email> Student's permanent e-mail address
10173: 
10174: =item B<$type> Type of enrollment (auto or manual)
10175: 
10176: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
10177: 
10178: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10179: 
10180: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10181: 
10182: =item B<$context> role change context (shown in User Management Logs display in a course)
10183: 
10184: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
10185: 
10186: =back
10187: 
10188: =item *
10189: 
10190: modify_student_enrollment
10191: 
10192: Change a students enrollment status in a class.  The environment variable
10193: 'role.request.course' must be defined for this function to proceed.
10194: 
10195: Inputs:
10196: 
10197: =over 4
10198: 
10199: =item $udom, students domain
10200: 
10201: =item $uname, students name
10202: 
10203: =item $uid, students user id
10204: 
10205: =item $first, students first name
10206: 
10207: =item $middle
10208: 
10209: =item $last
10210: 
10211: =item $gene
10212: 
10213: =item $usec
10214: 
10215: =item $end
10216: 
10217: =item $start
10218: 
10219: =item $type
10220: 
10221: =item $locktype
10222: 
10223: =item $cid
10224: 
10225: =item $selfenroll
10226: 
10227: =item $context
10228: 
10229: =back
10230: 
10231: 
10232: =item *
10233: 
10234: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10235: custom role; give a custom role to a user for the level given by URL.  Specify
10236: name and domain of role author, and role name
10237: 
10238: =item *
10239: 
10240: revokerole($udom,$uname,$url,$role) : revoke a role for url
10241: 
10242: =item *
10243: 
10244: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10245: 
10246: =back
10247: 
10248: =head2 Course Infomation
10249: 
10250: =over 4
10251: 
10252: =item *
10253: 
10254: coursedescription($courseid) : returns a hash of information about the
10255: specified course id, including all environment settings for the
10256: course, the description of the course will be in the hash under the
10257: key 'description'
10258: 
10259: =item *
10260: 
10261: resdata($name,$domain,$type,@which) : request for current parameter
10262: setting for a specific $type, where $type is either 'course' or 'user',
10263: @what should be a list of parameters to ask about. This routine caches
10264: answers for 5 minutes.
10265: 
10266: =item *
10267: 
10268: get_courseresdata($courseid, $domain) : dump the entire course resource
10269: data base, returning a hash that is keyed by the resource name and has
10270: values that are the resource value.  I believe that the timestamps and
10271: versions are also returned.
10272: 
10273: 
10274: =back
10275: 
10276: =head2 Course Modification
10277: 
10278: =over 4
10279: 
10280: =item *
10281: 
10282: writecoursepref($courseid,%prefs) : write preferences (environment
10283: database) for a course
10284: 
10285: =item *
10286: 
10287: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10288: 
10289: =item *
10290: 
10291: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
10292: 
10293: =back
10294: 
10295: =head2 Resource Subroutines
10296: 
10297: =over 4
10298: 
10299: =item *
10300: 
10301: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10302: 
10303: =item *
10304: 
10305: repcopy($filename) : subscribes to the requested file, and attempts to
10306: replicate from the owning library server, Might return
10307: 'unavailable', 'not_found', 'forbidden', 'ok', or
10308: 'bad_request', also attempts to grab the metadata for the
10309: resource. Expects the local filesystem pathname
10310: (/home/httpd/html/res/....)
10311: 
10312: =back
10313: 
10314: =head2 Resource Information
10315: 
10316: =over 4
10317: 
10318: =item *
10319: 
10320: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10321: a vairety of different possible values, $varname should be a request
10322: string, and the other parameters can be used to specify who and what
10323: one is asking about.
10324: 
10325: Possible values for $varname are environment.lastname (or other item
10326: from the envirnment hash), user.name (or someother aspect about the
10327: user), resource.0.maxtries (or some other part and parameter of a
10328: resource)
10329: 
10330: =item *
10331: 
10332: directcondval($number) : get current value of a condition; reads from a state
10333: string
10334: 
10335: =item *
10336: 
10337: condval($condidx) : value of condition index based on state
10338: 
10339: =item *
10340: 
10341: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10342: resource's metadata, $what should be either a specific key, or either
10343: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10344: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10345: 
10346: this function automatically caches all requests
10347: 
10348: =item *
10349: 
10350: metadata_query($query,$custom,$customshow) : make a metadata query against the
10351: network of library servers; returns file handle of where SQL and regex results
10352: will be stored for query
10353: 
10354: =item *
10355: 
10356: symbread($filename) : return symbolic list entry (filename argument optional);
10357: returns the data handle
10358: 
10359: =item *
10360: 
10361: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10362: a possible symb for the URL in $thisfn, and if is an encryypted
10363: resource that the user accessed using /enc/ returns a 1 on success, 0
10364: on failure, user must be in a course, as it assumes the existance of
10365: the course initial hash, and uses $env('request.course.id'}
10366: 
10367: 
10368: =item *
10369: 
10370: symbclean($symb) : removes versions numbers from a symb, returns the
10371: cleaned symb
10372: 
10373: =item *
10374: 
10375: is_on_map($uri) : checks if the $uri is somewhere on the current
10376: course map, user must be in a course for it to work.
10377: 
10378: =item *
10379: 
10380: numval($salt) : return random seed value (addend for rndseed)
10381: 
10382: =item *
10383: 
10384: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10385: a random seed, all arguments are optional, if they aren't sent it uses the
10386: environment to derive them. Note: if symb isn't sent and it can't get one
10387: from &symbread it will use the current time as its return value
10388: 
10389: =item *
10390: 
10391: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10392: unfakeable, receipt
10393: 
10394: =item *
10395: 
10396: receipt() : API to ireceipt working off of env values; given out to users
10397: 
10398: =item *
10399: 
10400: countacc($url) : count the number of accesses to a given URL
10401: 
10402: =item *
10403: 
10404: 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
10405: 
10406: =item *
10407: 
10408: 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)
10409: 
10410: =item *
10411: 
10412: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10413: 
10414: =item *
10415: 
10416: devalidate($symb) : devalidate temporary spreadsheet calculations,
10417: forcing spreadsheet to reevaluate the resource scores next time.
10418: 
10419: =back
10420: 
10421: =head2 Storing/Retreiving Data
10422: 
10423: =over 4
10424: 
10425: =item *
10426: 
10427: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10428: for this url; hashref needs to be given and should be a \%hashname; the
10429: remaining args aren't required and if they aren't passed or are '' they will
10430: be derived from the env
10431: 
10432: =item *
10433: 
10434: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10435: uses critical subroutine
10436: 
10437: =item *
10438: 
10439: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10440: all args are optional
10441: 
10442: =item *
10443: 
10444: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10445: dumps the complete (or key matching regexp) namespace into a hash
10446: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10447: normally &store()ed into
10448: 
10449: $range should be either an integer '100' (give me the first 100
10450:                                            matching records)
10451:               or be  two integers sperated by a - with no spaces
10452:                  '30-50' (give me the 30th through the 50th matching
10453:                           records)
10454: 
10455: 
10456: =item *
10457: 
10458: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10459: replaces a &store() version of data with a replacement set of data
10460: for a particular resource in a namespace passed in the $storehash hash 
10461: reference
10462: 
10463: =item *
10464: 
10465: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10466: works very similar to store/cstore, but all data is stored in a
10467: temporary location and can be reset using tmpreset, $storehash should
10468: be a hash reference, returns nothing on success
10469: 
10470: =item *
10471: 
10472: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10473: similar to restore, but all data is stored in a temporary location and
10474: can be reset using tmpreset. Returns a hash of values on success,
10475: error string otherwise.
10476: 
10477: =item *
10478: 
10479: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10480: deltes all keys for $symb form the temporary storage hash.
10481: 
10482: =item *
10483: 
10484: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10485: reference filled in from namesp ($udom and $uname are optional)
10486: 
10487: =item *
10488: 
10489: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10490: namesp ($udom and $uname are optional)
10491: 
10492: =item *
10493: 
10494: dump($namespace,$udom,$uname,$regexp,$range) : 
10495: dumps the complete (or key matching regexp) namespace into a hash
10496: ($udom, $uname, $regexp, $range are optional)
10497: 
10498: $range should be either an integer '100' (give me the first 100
10499:                                            matching records)
10500:               or be  two integers sperated by a - with no spaces
10501:                  '30-50' (give me the 30th through the 50th matching
10502:                           records)
10503: =item *
10504: 
10505: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10506: $store can be a scalar, an array reference, or if the amount to be 
10507: incremented is > 1, a hash reference.
10508: 
10509: ($udom and $uname are optional)
10510: 
10511: =item *
10512: 
10513: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10514: ($udom and $uname are optional)
10515: 
10516: =item *
10517: 
10518: cput($namespace,$storehash,$udom,$uname) : critical put
10519: ($udom and $uname are optional)
10520: 
10521: =item *
10522: 
10523: newput($namespace,$storehash,$udom,$uname) :
10524: 
10525: Attempts to store the items in the $storehash, but only if they don't
10526: currently exist, if this succeeds you can be certain that you have 
10527: successfully created a new key value pair in the $namespace db.
10528: 
10529: 
10530: Args:
10531:  $namespace: name of database to store values to
10532:  $storehash: hashref to store to the db
10533:  $udom: (optional) domain of user containing the db
10534:  $uname: (optional) name of user caontaining the db
10535: 
10536: Returns:
10537:  'ok' -> succeeded in storing all keys of $storehash
10538:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10539:                         least <key> already existed in the db (other
10540:                         requested keys may also already exist)
10541:  'error: <msg>' -> unable to tie the DB or other error occurred
10542:  'con_lost' -> unable to contact request server
10543:  'refused' -> action was not allowed by remote machine
10544: 
10545: 
10546: =item *
10547: 
10548: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10549: reference filled in from namesp (encrypts the return communication)
10550: ($udom and $uname are optional)
10551: 
10552: =item *
10553: 
10554: log($udom,$name,$home,$message) : write to permanent log for user; use
10555: critical subroutine
10556: 
10557: =item *
10558: 
10559: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10560: array reference filled in from namespace found in domain level on either
10561: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10562: 
10563: =item *
10564: 
10565: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10566: domain level either on specified domain server ($uhome) or primary domain 
10567: server ($udom and $uhome are optional)
10568: 
10569: =item * 
10570: 
10571: get_domain_defaults($target_domain) : returns hash with defaults for
10572: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10573: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10574: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10575: Values are retrieved from cache (if current), or from domain's configuration.db
10576: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10577: or lonTabs/domain.tab. 
10578: 
10579: %domdefaults = &get_auth_defaults($target_domain);
10580: 
10581: =back
10582: 
10583: =head2 Network Status Functions
10584: 
10585: =over 4
10586: 
10587: =item *
10588: 
10589: dirlist($uri) : return directory list based on URI
10590: 
10591: =item *
10592: 
10593: spareserver() : find server with least workload from spare.tab
10594: 
10595: 
10596: =item *
10597: 
10598: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10599: if there is no corresponding loncapa host.
10600: 
10601: =back
10602: 
10603: 
10604: =head2 Apache Request
10605: 
10606: =over 4
10607: 
10608: =item *
10609: 
10610: ssi($url,%hash) : server side include, does a complete request cycle on url to
10611: localhost, posts hash
10612: 
10613: =back
10614: 
10615: =head2 Data to String to Data
10616: 
10617: =over 4
10618: 
10619: =item *
10620: 
10621: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10622: and '&' separators, supports elements that are arrayrefs and hashrefs
10623: 
10624: =item *
10625: 
10626: hashref2str($hashref) : convert a hashref into a string complete with
10627: escaping and '=' and '&' separators, supports elements that are
10628: arrayrefs and hashrefs
10629: 
10630: =item *
10631: 
10632: arrayref2str($arrayref) : convert an arrayref into a string complete
10633: with escaping and '&' separators, supports elements that are arrayrefs
10634: and hashrefs
10635: 
10636: =item *
10637: 
10638: str2hash($string) : convert string to hash using unescaping and
10639: splitting on '=' and '&', supports elements that are arrayrefs and
10640: hashrefs
10641: 
10642: =item *
10643: 
10644: str2array($string) : convert string to hash using unescaping and
10645: splitting on '&', supports elements that are arrayrefs and hashrefs
10646: 
10647: =back
10648: 
10649: =head2 Logging Routines
10650: 
10651: =over 4
10652: 
10653: These routines allow one to make log messages in the lonnet.log and
10654: lonnet.perm logfiles.
10655: 
10656: =item *
10657: 
10658: logtouch() : make sure the logfile, lonnet.log, exists
10659: 
10660: =item *
10661: 
10662: logthis() : append message to the normal lonnet.log file, it gets
10663: preiodically rolled over and deleted.
10664: 
10665: =item *
10666: 
10667: logperm() : append a permanent message to lonnet.perm.log, this log
10668: file never gets deleted by any automated portion of the system, only
10669: messages of critical importance should go in here.
10670: 
10671: =back
10672: 
10673: =head2 General File Helper Routines
10674: 
10675: =over 4
10676: 
10677: =item *
10678: 
10679: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10680: (a) files in /uploaded
10681:   (i) If a local copy of the file exists - 
10682:       compares modification date of local copy with last-modified date for 
10683:       definitive version stored on home server for course. If local copy is 
10684:       stale, requests a new version from the home server and stores it. 
10685:       If the original has been removed from the home server, then local copy 
10686:       is unlinked.
10687:   (ii) If local copy does not exist -
10688:       requests the file from the home server and stores it. 
10689:   
10690:   If $caller is 'uploadrep':  
10691:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10692:     for request for files originally uploaded via DOCS. 
10693:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10694:   
10695:   Otherwise:
10696:      This indicates a call from the content generation phase of the request.
10697:      -  returns the entire contents of the file or -1.
10698:      
10699: (b) files in /res
10700:    - returns the entire contents of a file or -1; 
10701:    it properly subscribes to and replicates the file if neccessary.
10702: 
10703: 
10704: =item *
10705: 
10706: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10707:                   reference
10708: 
10709: returns either a stat() list of data about the file or an empty list
10710: if the file doesn't exist or couldn't find out about it (connection
10711: problems or user unknown)
10712: 
10713: =item *
10714: 
10715: filelocation($dir,$file) : returns file system location of a file
10716: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10717: directory that relative $file lookups are to looked in ($dir of /a/dir
10718: and a file of ../bob will become /a/bob)
10719: 
10720: =item *
10721: 
10722: hreflocation($dir,$file) : returns file system location or a URL; same as
10723: filelocation except for hrefs
10724: 
10725: =item *
10726: 
10727: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10728: 
10729: =back
10730: 
10731: =head2 Usererfile file routines (/uploaded*)
10732: 
10733: =over 4
10734: 
10735: =item *
10736: 
10737: userfileupload(): main rotine for putting a file in a user or course's
10738:                   filespace, arguments are,
10739: 
10740:  formname - required - this is the name of the element in $env where the
10741:            filename, and the contents of the file to create/modifed exist
10742:            the filename is in $env{'form.'.$formname.'.filename'} and the
10743:            contents of the file is located in $env{'form.'.$formname}
10744:  coursedoc - if true, store the file in the course of the active role
10745:              of the current user
10746:  subdir - required - subdirectory to put the file in under ../userfiles/
10747:          if undefined, it will be placed in "unknown"
10748: 
10749:  (This routine calls clean_filename() to remove any dangerous
10750:  characters from the filename, and then calls finuserfileupload() to
10751:  complete the transaction)
10752: 
10753:  returns either the url of the uploaded file (/uploaded/....) if successful
10754:  and /adm/notfound.html if unsuccessful
10755: 
10756: =item *
10757: 
10758: clean_filename(): routine for cleaing a filename up for storage in
10759:                  userfile space, argument is:
10760: 
10761:  filename - proposed filename
10762: 
10763: returns: the new clean filename
10764: 
10765: =item *
10766: 
10767: finishuserfileupload(): routine that creaes and sends the file to
10768: userspace, probably shouldn't be called directly
10769: 
10770:   docuname: username or courseid of destination for the file
10771:   docudom: domain of user/course of destination for the file
10772:   formname: same as for userfileupload()
10773:   fname: filename (inculding subdirectories) for the file
10774: 
10775:  returns either the url of the uploaded file (/uploaded/....) if successful
10776:  and /adm/notfound.html if unsuccessful
10777: 
10778: =item *
10779: 
10780: renameuserfile(): renames an existing userfile to a new name
10781: 
10782:   Args:
10783:    docuname: username or courseid of destination for the file
10784:    docudom: domain of user/course of destination for the file
10785:    old: current file name (including any subdirs under userfiles)
10786:    new: desired file name (including any subdirs under userfiles)
10787: 
10788: =item *
10789: 
10790: mkdiruserfile(): creates a directory is a userfiles dir
10791: 
10792:   Args:
10793:    docuname: username or courseid of destination for the file
10794:    docudom: domain of user/course of destination for the file
10795:    dir: dir to create (including any subdirs under userfiles)
10796: 
10797: =item *
10798: 
10799: removeuserfile(): removes a file that exists in userfiles
10800: 
10801:   Args:
10802:    docuname: username or courseid of destination for the file
10803:    docudom: domain of user/course of destination for the file
10804:    fname: filname to delete (including any subdirs under userfiles)
10805: 
10806: =item *
10807: 
10808: removeuploadedurl(): convience function for removeuserfile()
10809: 
10810:   Args:
10811:    url:  a full /uploaded/... url to delete
10812: 
10813: =item * 
10814: 
10815: get_portfile_permissions():
10816:   Args:
10817:     domain: domain of user or course contain the portfolio files
10818:     user: name of user or num of course contain the portfolio files
10819:   Returns:
10820:     hashref of a dump of the proper file_permissions.db
10821:    
10822: 
10823: =item * 
10824: 
10825: get_access_controls():
10826: 
10827: Args:
10828:   current_permissions: the hash ref returned from get_portfile_permissions()
10829:   group: (optional) the group you want the files associated with
10830:   file: (optional) the file you want access info on
10831: 
10832: Returns:
10833:     a hash (keys are file names) of hashes containing
10834:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10835:         values are XML containing access control settings (see below) 
10836: 
10837: Internal notes:
10838: 
10839:  access controls are stored in file_permissions.db as key=value pairs.
10840:     key -> path to file/file_name\0uniqueID:scope_end_start
10841:         where scope -> public,guest,course,group,domains or users.
10842:               end -> UNIX time for end of access (0 -> no end date)
10843:               start -> UNIX time for start of access
10844: 
10845:     value -> XML description of access control
10846:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10847:             <start></start>
10848:             <end></end>
10849: 
10850:             <password></password>  for scope type = guest
10851: 
10852:             <domain></domain>     for scope type = course or group
10853:             <number></number>
10854:             <roles id="">
10855:              <role></role>
10856:              <access></access>
10857:              <section></section>
10858:              <group></group>
10859:             </roles>
10860: 
10861:             <dom></dom>         for scope type = domains
10862: 
10863:             <users>             for scope type = users
10864:              <user>
10865:               <uname></uname>
10866:               <udom></udom>
10867:              </user>
10868:             </users>
10869:            </scope> 
10870:               
10871:  Access data is also aggregated for each file in an additional key=value pair:
10872:  key -> path to file/file_name\0accesscontrol 
10873:  value -> reference to hash
10874:           hash contains key = value pairs
10875:           where key = uniqueID:scope_end_start
10876:                 value = UNIX time record was last updated
10877: 
10878:           Used to improve speed of look-ups of access controls for each file.  
10879:  
10880:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10881: 
10882: modify_access_controls():
10883: 
10884: Modifies access controls for a portfolio file
10885: Args
10886: 1. file name
10887: 2. reference to hash of required changes,
10888: 3. domain
10889: 4. username
10890:   where domain,username are the domain of the portfolio owner 
10891:   (either a user or a course) 
10892: 
10893: Returns:
10894: 1. result of additions or updates ('ok' or 'error', with error message). 
10895: 2. result of deletions ('ok' or 'error', with error message).
10896: 3. reference to hash of any new or updated access controls.
10897: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10898:    key = integer (inbound ID)
10899:    value = uniqueID  
10900: 
10901: =back
10902: 
10903: =head2 HTTP Helper Routines
10904: 
10905: =over 4
10906: 
10907: =item *
10908: 
10909: escape() : unpack non-word characters into CGI-compatible hex codes
10910: 
10911: =item *
10912: 
10913: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10914: 
10915: =back
10916: 
10917: =head1 PRIVATE SUBROUTINES
10918: 
10919: =head2 Underlying communication routines (Shouldn't call)
10920: 
10921: =over 4
10922: 
10923: =item *
10924: 
10925: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10926: 
10927: =item *
10928: 
10929: reply() : uses subreply to send a message to remote machine, logs all failures
10930: 
10931: =item *
10932: 
10933: critical() : passes a critical message to another server; if cannot
10934: get through then place message in connection buffer directory and
10935: returns con_delayed, if incapable of saving message, returns
10936: con_failed
10937: 
10938: =item *
10939: 
10940: reconlonc() : tries to reconnect lonc client processes.
10941: 
10942: =back
10943: 
10944: =head2 Resource Access Logging
10945: 
10946: =over 4
10947: 
10948: =item *
10949: 
10950: flushcourselogs() : flush (save) buffer logs and access logs
10951: 
10952: =item *
10953: 
10954: courselog($what) : save message for course in hash
10955: 
10956: =item *
10957: 
10958: courseacclog($what) : save message for course using &courselog().  Perform
10959: special processing for specific resource types (problems, exams, quizzes, etc).
10960: 
10961: =item *
10962: 
10963: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10964: as a PerlChildExitHandler
10965: 
10966: =back
10967: 
10968: =head2 Other
10969: 
10970: =over 4
10971: 
10972: =item *
10973: 
10974: symblist($mapname,%newhash) : update symbolic storage links
10975: 
10976: =back
10977: 
10978: =cut
10979: 

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