File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1047: download - view: text, annotated - select for diffs
Mon Nov 30 06:23:37 2009 UTC (14 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6121.
  - Display of "Upload PDF Forms" in Main Menu in a course/community
    controlled by domain default or course configuration.
courseprefs.pm
  - lonnet::delenv() used to update current user's session when a
    course environment setting is deleted.
domainprefs.pm
  - code moved from &print_helpsettings() to &radiobutton_prefs()
    to facilitate reuse in course defaults menu (canuse_pdfforms).
lonnet.pm
  - canuse_pdfforms domain default cached in domdefaults.
Work in progess.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1047 2009/11/30 06:23:37 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol);
   80: 
   81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   84:     %courseownerbuf, %coursetypebuf,$locknum);
   85: 
   86: use IO::Socket;
   87: use GDBM_File;
   88: use HTML::LCParser;
   89: use Fcntl qw(:flock);
   90: use Storable qw(thaw nfreeze);
   91: use Time::HiRes qw( gettimeofday tv_interval );
   92: use Cache::Memcached;
   93: use Digest::MD5;
   94: use Math::Random;
   95: use File::MMagic;
   96: use LONCAPA qw(:DEFAULT :match);
   97: use LONCAPA::Configuration;
   98: 
   99: my $readit;
  100: my $max_connection_retries = 10;     # Or some such value.
  101: 
  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  103: 
  104: require Exporter;
  105: 
  106: our @ISA = qw (Exporter);
  107: our @EXPORT = qw(%env);
  108: 
  109: 
  110: # --------------------------------------------------------------------- Logging
  111: {
  112:     my $logid;
  113:     sub instructor_log {
  114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  115:         if (($cnum eq '') || ($cdom eq '')) {
  116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  118:         }
  119: 	$logid++;
  120:         my $now = time();
  121: 	my $id=$now.'00000'.$$.'00000'.$logid;
  122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  123: 				    { $id => {
  124: 					'exe_uname' => $env{'user.name'},
  125: 					'exe_udom'  => $env{'user.domain'},
  126: 					'exe_time'  => $now,
  127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  128: 					'delflag'   => $delflag,
  129: 					'logentry'  => $storehash,
  130: 					'uname'     => $uname,
  131: 					'udom'      => $udom,
  132: 				    }
  133: 				  },$cdom,$cnum);
  134:     }
  135: }
  136: 
  137: sub logtouch {
  138:     my $execdir=$perlvar{'lonDaemons'};
  139:     unless (-e "$execdir/logs/lonnet.log") {	
  140: 	open(my $fh,">>$execdir/logs/lonnet.log");
  141: 	close $fh;
  142:     }
  143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  145: }
  146: 
  147: sub logthis {
  148:     my $message=shift;
  149:     my $execdir=$perlvar{'lonDaemons'};
  150:     my $now=time;
  151:     my $local=localtime($now);
  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  154: 	print $fh $logstring;
  155: 	close($fh);
  156:     }
  157:     return 1;
  158: }
  159: 
  160: sub logperm {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  166: 	print $fh "$now:$message:$local\n";
  167: 	close($fh);
  168:     }
  169:     return 1;
  170: }
  171: 
  172: sub create_connection {
  173:     my ($hostname,$lonid) = @_;
  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  175: 				     Type    => SOCK_STREAM,
  176: 				     Timeout => 10);
  177:     return 0 if (!$client);
  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  179:     my $result = <$client>;
  180:     chomp($result);
  181:     return 1 if ($result eq 'done');
  182:     return 0;
  183: }
  184: 
  185: sub get_server_timezone {
  186:     my ($cnum,$cdom) = @_;
  187:     my $home=&homeserver($cnum,$cdom);
  188:     if ($home ne 'no_host') {
  189:         my $cachetime = 24*3600;
  190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  191:         if (defined($cached)) {
  192:             return $timezone;
  193:         } else {
  194:             my $timezone = &reply('servertimezone',$home);
  195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  196:         }
  197:     }
  198: }
  199: 
  200: sub get_server_loncaparev {
  201:     my ($dom,$lonhost) = @_;
  202:     if (defined($lonhost)) {
  203:         if (!defined(&hostname($lonhost))) {
  204:             undef($lonhost);
  205:         }
  206:     }
  207:     if (!defined($lonhost)) {
  208:         if (defined(&domain($dom,'primary'))) {
  209:             $lonhost=&domain($dom,'primary');
  210:             if ($lonhost eq 'no_host') {
  211:                 undef($lonhost);
  212:             }
  213:         }
  214:     }
  215:     if (defined($lonhost)) {
  216:         my $cachetime = 24*3600;
  217:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  218:         if (defined($cached)) {
  219:             return $loncaparev;
  220:         } else {
  221:             my $loncaparev = &reply('serverloncaparev',$lonhost);
  222:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  223:         }
  224:     }
  225: }
  226: 
  227: # -------------------------------------------------- Non-critical communication
  228: sub subreply {
  229:     my ($cmd,$server)=@_;
  230:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  231:     #
  232:     #  With loncnew process trimming, there's a timing hole between lonc server
  233:     #  process exit and the master server picking up the listen on the AF_UNIX
  234:     #  socket.  In that time interval, a lock file will exist:
  235: 
  236:     my $lockfile=$peerfile.".lock";
  237:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  238: 	sleep(1);
  239:     }
  240:     # At this point, either a loncnew parent is listening or an old lonc
  241:     # or loncnew child is listening so we can connect or everything's dead.
  242:     #
  243:     #   We'll give the connection a few tries before abandoning it.  If
  244:     #   connection is not possible, we'll con_lost back to the client.
  245:     #   
  246:     my $client;
  247:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  248: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  249: 				      Type    => SOCK_STREAM,
  250: 				      Timeout => 10);
  251: 	if ($client) {
  252: 	    last;		# Connected!
  253: 	} else {
  254: 	    &create_connection(&hostname($server),$server);
  255: 	}
  256:         sleep(1);		# Try again later if failed connection.
  257:     }
  258:     my $answer;
  259:     if ($client) {
  260: 	print $client "sethost:$server:$cmd\n";
  261: 	$answer=<$client>;
  262: 	if (!$answer) { $answer="con_lost"; }
  263: 	chomp($answer);
  264:     } else {
  265: 	$answer = 'con_lost';	# Failed connection.
  266:     }
  267:     return $answer;
  268: }
  269: 
  270: sub reply {
  271:     my ($cmd,$server)=@_;
  272:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  273:     my $answer=subreply($cmd,$server);
  274:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  275:        &logthis("<font color=\"blue\">WARNING:".
  276:                 " $cmd to $server returned $answer</font>");
  277:     }
  278:     return $answer;
  279: }
  280: 
  281: # ----------------------------------------------------------- Send USR1 to lonc
  282: 
  283: sub reconlonc {
  284:     my ($lonid) = @_;
  285:     my $hostname = &hostname($lonid);
  286:     if ($lonid) {
  287: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  288: 	if ($hostname && -e $peerfile) {
  289: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  290: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  291: 					     Type    => SOCK_STREAM,
  292: 					     Timeout => 10);
  293: 	    if ($client) {
  294: 		print $client ("reset_retries\n");
  295: 		my $answer=<$client>;
  296: 		#reset just this one.
  297: 	    }
  298: 	}
  299: 	return;
  300:     }
  301: 
  302:     &logthis("Trying to reconnect lonc");
  303:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  304:     if (open(my $fh,"<$loncfile")) {
  305: 	my $loncpid=<$fh>;
  306:         chomp($loncpid);
  307:         if (kill 0 => $loncpid) {
  308: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  309:             kill USR1 => $loncpid;
  310:             sleep 1;
  311:          } else {
  312: 	    &logthis(
  313:                "<font color=\"blue\">WARNING:".
  314:                " lonc at pid $loncpid not responding, giving up</font>");
  315:         }
  316:     } else {
  317: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  318:     }
  319: }
  320: 
  321: # ------------------------------------------------------ Critical communication
  322: 
  323: sub critical {
  324:     my ($cmd,$server)=@_;
  325:     unless (&hostname($server)) {
  326:         &logthis("<font color=\"blue\">WARNING:".
  327:                " Critical message to unknown server ($server)</font>");
  328:         return 'no_such_host';
  329:     }
  330:     my $answer=reply($cmd,$server);
  331:     if ($answer eq 'con_lost') {
  332: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  333: 	my $answer=reply($cmd,$server);
  334:         if ($answer eq 'con_lost') {
  335:             my $now=time;
  336:             my $middlename=$cmd;
  337:             $middlename=substr($middlename,0,16);
  338:             $middlename=~s/\W//g;
  339:             my $dfilename=
  340:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  341:             $dumpcount++;
  342:             {
  343: 		my $dfh;
  344: 		if (open($dfh,">$dfilename")) {
  345: 		    print $dfh "$cmd\n"; 
  346: 		    close($dfh);
  347: 		}
  348:             }
  349:             sleep 2;
  350:             my $wcmd='';
  351:             {
  352: 		my $dfh;
  353: 		if (open($dfh,"<$dfilename")) {
  354: 		    $wcmd=<$dfh>; 
  355: 		    close($dfh);
  356: 		}
  357:             }
  358:             chomp($wcmd);
  359:             if ($wcmd eq $cmd) {
  360: 		&logthis("<font color=\"blue\">WARNING: ".
  361:                          "Connection buffer $dfilename: $cmd</font>");
  362:                 &logperm("D:$server:$cmd");
  363: 	        return 'con_delayed';
  364:             } else {
  365:                 &logthis("<font color=\"red\">CRITICAL:"
  366:                         ." Critical connection failed: $server $cmd</font>");
  367:                 &logperm("F:$server:$cmd");
  368:                 return 'con_failed';
  369:             }
  370:         }
  371:     }
  372:     return $answer;
  373: }
  374: 
  375: # ------------------------------------------- check if return value is an error
  376: 
  377: sub error {
  378:     my ($result) = @_;
  379:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  380: 	if ($2 == 2) { return undef; }
  381: 	return $1;
  382:     }
  383:     return undef;
  384: }
  385: 
  386: sub convert_and_load_session_env {
  387:     my ($lonidsdir,$handle)=@_;
  388:     my @profile;
  389:     {
  390: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  391: 	if (!$opened) {
  392: 	    return 0;
  393: 	}
  394: 	flock($idf,LOCK_SH);
  395: 	@profile=<$idf>;
  396: 	close($idf);
  397:     }
  398:     my %temp_env;
  399:     foreach my $line (@profile) {
  400: 	if ($line !~ m/=/) {
  401: 	    return 0;
  402: 	}
  403: 	chomp($line);
  404: 	my ($envname,$envvalue)=split(/=/,$line,2);
  405: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  406:     }
  407:     unlink("$lonidsdir/$handle.id");
  408:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  409: 	    0640)) {
  410: 	%disk_env = %temp_env;
  411: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  412: 	untie(%disk_env);
  413:     }
  414:     return 1;
  415: }
  416: 
  417: # ------------------------------------------- Transfer profile into environment
  418: my $env_loaded;
  419: sub transfer_profile_to_env {
  420:     my ($lonidsdir,$handle,$force_transfer) = @_;
  421:     if (!$force_transfer && $env_loaded) { return; } 
  422: 
  423:     if (!defined($lonidsdir)) {
  424: 	$lonidsdir = $perlvar{'lonIDsDir'};
  425:     }
  426:     if (!defined($handle)) {
  427:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  428:     }
  429: 
  430:     my $convert;
  431:     {
  432:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  433: 	if (!$opened) {
  434: 	    return;
  435: 	}
  436: 	flock($idf,LOCK_SH);
  437: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  438: 		&GDBM_READER(),0640)) {
  439: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  440: 	    untie(%disk_env);
  441: 	} else {
  442: 	    $convert = 1;
  443: 	}
  444:     }
  445:     if ($convert) {
  446: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  447: 	    &logthis("Failed to load session, or convert session.");
  448: 	}
  449:     }
  450: 
  451:     my %remove;
  452:     while ( my $envname = each(%env) ) {
  453:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  454:             if ($time < time-300) {
  455:                 $remove{$key}++;
  456:             }
  457:         }
  458:     }
  459: 
  460:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  461:     $env_loaded=1;
  462:     foreach my $expired_key (keys(%remove)) {
  463:         &delenv($expired_key);
  464:     }
  465: }
  466: 
  467: # ---------------------------------------------------- Check for valid session 
  468: sub check_for_valid_session {
  469:     my ($r) = @_;
  470:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  471:     my $lonid=$cookies{'lonID'};
  472:     return undef if (!$lonid);
  473: 
  474:     my $handle=&LONCAPA::clean_handle($lonid->value);
  475:     my $lonidsdir=$r->dir_config('lonIDsDir');
  476:     return undef if (!-e "$lonidsdir/$handle.id");
  477: 
  478:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  479:     return undef if (!$opened);
  480: 
  481:     flock($idf,LOCK_SH);
  482:     my %disk_env;
  483:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  484: 	    &GDBM_READER(),0640)) {
  485: 	return undef;	
  486:     }
  487: 
  488:     if (!defined($disk_env{'user.name'})
  489: 	|| !defined($disk_env{'user.domain'})) {
  490: 	return undef;
  491:     }
  492:     return $handle;
  493: }
  494: 
  495: sub timed_flock {
  496:     my ($file,$lock_type) = @_;
  497:     my $failed=0;
  498:     eval {
  499: 	local $SIG{__DIE__}='DEFAULT';
  500: 	local $SIG{ALRM}=sub {
  501: 	    $failed=1;
  502: 	    die("failed lock");
  503: 	};
  504: 	alarm(13);
  505: 	flock($file,$lock_type);
  506: 	alarm(0);
  507:     };
  508:     if ($failed) {
  509: 	return undef;
  510:     } else {
  511: 	return 1;
  512:     }
  513: }
  514: 
  515: # ---------------------------------------------------------- Append Environment
  516: 
  517: sub appenv {
  518:     my ($newenv,$roles) = @_;
  519:     if (ref($newenv) eq 'HASH') {
  520:         foreach my $key (keys(%{$newenv})) {
  521:             my $refused = 0;
  522: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  523:                 $refused = 1;
  524:                 if (ref($roles) eq 'ARRAY') {
  525:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  526:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  527:                         $refused = 0;
  528:                     }
  529:                 }
  530:             }
  531:             if ($refused) {
  532:                 &logthis("<font color=\"blue\">WARNING: ".
  533:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  534:                          .'</font>');
  535: 	        delete($newenv->{$key});
  536:             } else {
  537:                 $env{$key}=$newenv->{$key};
  538:             }
  539:         }
  540:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  541:         if ($opened
  542: 	    && &timed_flock($env_file,LOCK_EX)
  543: 	    &&
  544: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  545: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  546: 	    while (my ($key,$value) = each(%{$newenv})) {
  547: 	        $disk_env{$key} = $value;
  548: 	    }
  549: 	    untie(%disk_env);
  550:         }
  551:     }
  552:     return 'ok';
  553: }
  554: # ----------------------------------------------------- Delete from Environment
  555: 
  556: sub delenv {
  557:     my ($delthis,$regexp) = @_;
  558:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  559:         &logthis("<font color=\"blue\">WARNING: ".
  560:                 "Attempt to delete from environment ".$delthis);
  561:         return 'error';
  562:     }
  563:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  564:     if ($opened
  565: 	&& &timed_flock($env_file,LOCK_EX)
  566: 	&&
  567: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  568: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  569: 	foreach my $key (keys(%disk_env)) {
  570: 	    if ($regexp) {
  571:                 if ($key=~/^$delthis/) {
  572:                     delete($env{$key});
  573:                     delete($disk_env{$key});
  574:                 } 
  575:             } else {
  576:                 if ($key=~/^\Q$delthis\E/) {
  577: 		    delete($env{$key});
  578: 		    delete($disk_env{$key});
  579: 	        }
  580:             }
  581: 	}
  582: 	untie(%disk_env);
  583:     }
  584:     return 'ok';
  585: }
  586: 
  587: sub get_env_multiple {
  588:     my ($name) = @_;
  589:     my @values;
  590:     if (defined($env{$name})) {
  591:         # exists is it an array
  592:         if (ref($env{$name})) {
  593:             @values=@{ $env{$name} };
  594:         } else {
  595:             $values[0]=$env{$name};
  596:         }
  597:     }
  598:     return(@values);
  599: }
  600: 
  601: # ------------------------------------------------------------------- Locking
  602: 
  603: sub set_lock {
  604:     my ($text)=@_;
  605:     $locknum++;
  606:     my $id=$$.'-'.$locknum;
  607:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  608:              'session.lock.'.$id => $text});
  609:     return $id;
  610: }
  611: 
  612: sub get_locks {
  613:     my $num=0;
  614:     my %texts=();
  615:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  616:        if ($lock=~/\w/) {
  617:           $num++;
  618:           $texts{$lock}=$env{'session.lock.'.$lock};
  619:        }
  620:    }
  621:    return ($num,%texts);
  622: }
  623: 
  624: sub remove_lock {
  625:     my ($id)=@_;
  626:     my $newlocks='';
  627:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  628:        if (($lock=~/\w/) && ($lock ne $id)) {
  629:           $newlocks.=','.$lock;
  630:        }
  631:     }
  632:     &appenv({'session.locks' => $newlocks});
  633:     &delenv('session.lock.'.$id);
  634: }
  635: 
  636: sub remove_all_locks {
  637:     my $activelocks=$env{'session.locks'};
  638:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  639:        if ($lock=~/\w/) {
  640:           &remove_lock($lock);
  641:        }
  642:     }
  643: }
  644: 
  645: 
  646: # ------------------------------------------ Find out current server userload
  647: sub userload {
  648:     my $numusers=0;
  649:     {
  650: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  651: 	my $filename;
  652: 	my $curtime=time;
  653: 	while ($filename=readdir(LONIDS)) {
  654: 	    next if ($filename eq '.' || $filename eq '..');
  655: 	    next if ($filename =~ /publicuser_\d+\.id/);
  656: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  657: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  658: 	}
  659: 	closedir(LONIDS);
  660:     }
  661:     my $userloadpercent=0;
  662:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  663:     if ($maxuserload) {
  664: 	$userloadpercent=100*$numusers/$maxuserload;
  665:     }
  666:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  667:     return $userloadpercent;
  668: }
  669: 
  670: # ------------------------------------------ Fight off request when overloaded
  671: 
  672: sub overloaderror {
  673:     my ($r,$checkserver)=@_;
  674:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  675:     my $loadavg;
  676:     if ($checkserver eq $perlvar{'lonHostID'}) {
  677:        open(my $loadfile,'/proc/loadavg');
  678:        $loadavg=<$loadfile>;
  679:        $loadavg =~ s/\s.*//g;
  680:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  681:        close($loadfile);
  682:     } else {
  683:        $loadavg=&reply('load',$checkserver);
  684:     }
  685:     my $overload=$loadavg-100;
  686:     if ($overload>0) {
  687: 	$r->err_headers_out->{'Retry-After'}=$overload;
  688:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  689:         return 413;
  690:     }    
  691:     return '';
  692: }
  693: 
  694: # ------------------------------ Find server with least workload from spare.tab
  695: 
  696: sub spareserver {
  697:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  698:     my $spare_server;
  699:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  700:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  701:                                                      :  $userloadpercent;
  702:     
  703:     foreach my $try_server (@{ $spareid{'primary'} }) {
  704: 	($spare_server, $lowest_load) =
  705: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  706:     }
  707: 
  708:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  709: 
  710:     if (!$found_server) {
  711: 	foreach my $try_server (@{ $spareid{'default'} }) {
  712: 	    ($spare_server, $lowest_load) =
  713: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  714: 	}
  715:     }
  716: 
  717:     if (!$want_server_name) {
  718:         my $protocol = 'http';
  719:         if ($protocol{$spare_server} eq 'https') {
  720:             $protocol = $protocol{$spare_server};
  721:         }
  722:         if (defined($spare_server)) {
  723:             my $hostname = &hostname($spare_server);
  724:             if (defined($hostname)) {  
  725: 	        $spare_server = $protocol.'://'.$hostname;
  726:             }
  727:         }
  728:     }
  729:     return $spare_server;
  730: }
  731: 
  732: sub compare_server_load {
  733:     my ($try_server, $spare_server, $lowest_load) = @_;
  734: 
  735:     my $loadans     = &reply('load',    $try_server);
  736:     my $userloadans = &reply('userload',$try_server);
  737: 
  738:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  739: 	next; #didn't get a number from the server
  740:     }
  741: 
  742:     my $load;
  743:     if ($loadans =~ /\d/) {
  744: 	if ($userloadans =~ /\d/) {
  745: 	    #both are numbers, pick the bigger one
  746: 	    $load = ($loadans > $userloadans) ? $loadans 
  747: 		                              : $userloadans;
  748: 	} else {
  749: 	    $load = $loadans;
  750: 	}
  751:     } else {
  752: 	$load = $userloadans;
  753:     }
  754: 
  755:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  756: 	$spare_server = $try_server;
  757: 	$lowest_load  = $load;
  758:     }
  759:     return ($spare_server,$lowest_load);
  760: }
  761: 
  762: # --------------------------- ask offload servers if user already has a session
  763: sub find_existing_session {
  764:     my ($udom,$uname) = @_;
  765:     foreach my $try_server (@{ $spareid{'primary'} },
  766: 			    @{ $spareid{'default'} }) {
  767: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  768:     }
  769:     return;
  770: }
  771: 
  772: # -------------------------------- ask if server already has a session for user
  773: sub has_user_session {
  774:     my ($lonid,$udom,$uname) = @_;
  775:     my $result = &reply(join(':','userhassession',
  776: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  777:     return 1 if ($result eq 'ok');
  778: 
  779:     return 0;
  780: }
  781: 
  782: # --------------------------------------------- Try to change a user's password
  783: 
  784: sub changepass {
  785:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  786:     $currentpass = &escape($currentpass);
  787:     $newpass     = &escape($newpass);
  788:     my $lonhost = $perlvar{'lonHostID'};
  789:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  790: 		       $server);
  791:     if (! $answer) {
  792: 	&logthis("No reply on password change request to $server ".
  793: 		 "by $uname in domain $udom.");
  794:     } elsif ($answer =~ "^ok") {
  795:         &logthis("$uname in $udom successfully changed their password ".
  796: 		 "on $server.");
  797:     } elsif ($answer =~ "^pwchange_failure") {
  798: 	&logthis("$uname in $udom was unable to change their password ".
  799: 		 "on $server.  The action was blocked by either lcpasswd ".
  800: 		 "or pwchange");
  801:     } elsif ($answer =~ "^non_authorized") {
  802:         &logthis("$uname in $udom did not get their password correct when ".
  803: 		 "attempting to change it on $server.");
  804:     } elsif ($answer =~ "^auth_mode_error") {
  805:         &logthis("$uname in $udom attempted to change their password despite ".
  806: 		 "not being locally or internally authenticated on $server.");
  807:     } elsif ($answer =~ "^unknown_user") {
  808:         &logthis("$uname in $udom attempted to change their password ".
  809: 		 "on $server but were unable to because $server is not ".
  810: 		 "their home server.");
  811:     } elsif ($answer =~ "^refused") {
  812: 	&logthis("$server refused to change $uname in $udom password because ".
  813: 		 "it was sent an unencrypted request to change the password.");
  814:     } elsif ($answer =~ "invalid_client") {
  815:         &logthis("$server refused to change $uname in $udom password because ".
  816:                  "it was a reset by e-mail originating from an invalid server.");
  817:     }
  818:     return $answer;
  819: }
  820: 
  821: # ----------------------- Try to determine user's current authentication scheme
  822: 
  823: sub queryauthenticate {
  824:     my ($uname,$udom)=@_;
  825:     my $uhome=&homeserver($uname,$udom);
  826:     if (!$uhome) {
  827: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  828: 	return 'no_host';
  829:     }
  830:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  831:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  832: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  833:     }
  834:     return $answer;
  835: }
  836: 
  837: # --------- Try to authenticate user from domain's lib servers (first this one)
  838: 
  839: sub authenticate {
  840:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  841:     $upass=&escape($upass);
  842:     $uname= &LONCAPA::clean_username($uname);
  843:     my $uhome=&homeserver($uname,$udom,1);
  844:     my $newhome;
  845:     if ((!$uhome) || ($uhome eq 'no_host')) {
  846: # Maybe the machine was offline and only re-appeared again recently?
  847:         &reconlonc();
  848: # One more
  849: 	$uhome=&homeserver($uname,$udom,1);
  850:         if (($uhome eq 'no_host') && $checkdefauth) {
  851:             if (defined(&domain($udom,'primary'))) {
  852:                 $newhome=&domain($udom,'primary');
  853:             }
  854:             if ($newhome ne '') {
  855:                 $uhome = $newhome;
  856:             }
  857:         }
  858: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  859: 	    &logthis("User $uname at $udom is unknown in authenticate");
  860: 	    return 'no_host';
  861:         }
  862:     }
  863:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  864:     if ($answer eq 'authorized') {
  865:         if ($newhome) {
  866:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  867:             return 'no_account_on_host'; 
  868:         } else {
  869:             &logthis("User $uname at $udom authorized by $uhome");
  870:             return $uhome;
  871:         }
  872:     }
  873:     if ($answer eq 'non_authorized') {
  874: 	&logthis("User $uname at $udom rejected by $uhome");
  875: 	return 'no_host'; 
  876:     }
  877:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  878:     return 'no_host';
  879: }
  880: 
  881: # ---------------------- Find the homebase for a user from domain's lib servers
  882: 
  883: my %homecache;
  884: sub homeserver {
  885:     my ($uname,$udom,$ignoreBadCache)=@_;
  886:     my $index="$uname:$udom";
  887: 
  888:     if (exists($homecache{$index})) { return $homecache{$index}; }
  889: 
  890:     my %servers = &get_servers($udom,'library');
  891:     foreach my $tryserver (keys(%servers)) {
  892:         next if ($ignoreBadCache ne 'true' && 
  893: 		 exists($badServerCache{$tryserver}));
  894: 
  895: 	my $answer=reply("home:$udom:$uname",$tryserver);
  896: 	if ($answer eq 'found') {
  897: 	    delete($badServerCache{$tryserver}); 
  898: 	    return $homecache{$index}=$tryserver;
  899: 	} elsif ($answer eq 'no_host') {
  900: 	    $badServerCache{$tryserver}=1;
  901: 	}
  902:     }    
  903:     return 'no_host';
  904: }
  905: 
  906: # ------------------------------------- Find the usernames behind a list of IDs
  907: 
  908: sub idget {
  909:     my ($udom,@ids)=@_;
  910:     my %returnhash=();
  911:     
  912:     my %servers = &get_servers($udom,'library');
  913:     foreach my $tryserver (keys(%servers)) {
  914: 	my $idlist=join('&',@ids);
  915: 	$idlist=~tr/A-Z/a-z/; 
  916: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  917: 	my @answer=();
  918: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  919: 	    @answer=split(/\&/,$reply);
  920: 	}                    ;
  921: 	my $i;
  922: 	for ($i=0;$i<=$#ids;$i++) {
  923: 	    if ($answer[$i]) {
  924: 		$returnhash{$ids[$i]}=$answer[$i];
  925: 	    } 
  926: 	}
  927:     } 
  928:     return %returnhash;
  929: }
  930: 
  931: # ------------------------------------- Find the IDs behind a list of usernames
  932: 
  933: sub idrget {
  934:     my ($udom,@unames)=@_;
  935:     my %returnhash=();
  936:     foreach my $uname (@unames) {
  937:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  938:     }
  939:     return %returnhash;
  940: }
  941: 
  942: # ------------------------------- Store away a list of names and associated IDs
  943: 
  944: sub idput {
  945:     my ($udom,%ids)=@_;
  946:     my %servers=();
  947:     foreach my $uname (keys(%ids)) {
  948: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  949:         my $uhom=&homeserver($uname,$udom);
  950:         if ($uhom ne 'no_host') {
  951:             my $id=&escape($ids{$uname});
  952:             $id=~tr/A-Z/a-z/;
  953:             my $esc_unam=&escape($uname);
  954: 	    if ($servers{$uhom}) {
  955: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  956:             } else {
  957:                 $servers{$uhom}=$id.'='.$esc_unam;
  958:             }
  959:         }
  960:     }
  961:     foreach my $server (keys(%servers)) {
  962:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  963:     }
  964: }
  965: 
  966: # ------------------------------dump from db file owned by domainconfig user
  967: sub dump_dom {
  968:     my ($namespace,$udom,$regexp,$range)=@_;
  969:     if (!$udom) {
  970:         $udom=$env{'user.domain'};
  971:     }
  972:     my %returnhash;
  973:     if ($udom) {
  974:         my $uname = &get_domainconfiguser($udom);
  975:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
  976:     }
  977:     return %returnhash;
  978: }
  979: 
  980: # ------------------------------------------ get items from domain db files   
  981: 
  982: sub get_dom {
  983:     my ($namespace,$storearr,$udom,$uhome)=@_;
  984:     my $items='';
  985:     foreach my $item (@$storearr) {
  986:         $items.=&escape($item).'&';
  987:     }
  988:     $items=~s/\&$//;
  989:     if (!$udom) {
  990:         $udom=$env{'user.domain'};
  991:         if (defined(&domain($udom,'primary'))) {
  992:             $uhome=&domain($udom,'primary');
  993:         } else {
  994:             undef($uhome);
  995:         }
  996:     } else {
  997:         if (!$uhome) {
  998:             if (defined(&domain($udom,'primary'))) {
  999:                 $uhome=&domain($udom,'primary');
 1000:             }
 1001:         }
 1002:     }
 1003:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1004:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1005:         my %returnhash;
 1006:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1007:             return %returnhash;
 1008:         }
 1009:         my @pairs=split(/\&/,$rep);
 1010:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1011:             return @pairs;
 1012:         }
 1013:         my $i=0;
 1014:         foreach my $item (@$storearr) {
 1015:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1016:             $i++;
 1017:         }
 1018:         return %returnhash;
 1019:     } else {
 1020:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1021:     }
 1022: }
 1023: 
 1024: # -------------------------------------------- put items in domain db files 
 1025: 
 1026: sub put_dom {
 1027:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1028:     if (!$udom) {
 1029:         $udom=$env{'user.domain'};
 1030:         if (defined(&domain($udom,'primary'))) {
 1031:             $uhome=&domain($udom,'primary');
 1032:         } else {
 1033:             undef($uhome);
 1034:         }
 1035:     } else {
 1036:         if (!$uhome) {
 1037:             if (defined(&domain($udom,'primary'))) {
 1038:                 $uhome=&domain($udom,'primary');
 1039:             }
 1040:         }
 1041:     } 
 1042:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1043:         my $items='';
 1044:         foreach my $item (keys(%$storehash)) {
 1045:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1046:         }
 1047:         $items=~s/\&$//;
 1048:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1049:     } else {
 1050:         &logthis("put_dom failed - no homeserver and/or domain");
 1051:     }
 1052: }
 1053: 
 1054: # --------------------- newput for items in db file owned by domainconfig user
 1055: sub newput_dom {
 1056:     my ($namespace,$storehash,$udom) = @_;
 1057:     my $result;
 1058:     if (!$udom) {
 1059:         $udom=$env{'user.domain'};
 1060:     }
 1061:     if ($udom) {
 1062:         my $uname = &get_domainconfiguser($udom);
 1063:         $result = &newput($namespace,$storehash,$udom,$uname);
 1064:     }
 1065:     return $result;
 1066: }
 1067: 
 1068: # --------------------- delete for items in db file owned by domainconfig user
 1069: sub del_dom {
 1070:     my ($namespace,$storearr,$udom)=@_;
 1071:     if (ref($storearr) eq 'ARRAY') {
 1072:         if (!$udom) {
 1073:             $udom=$env{'user.domain'};
 1074:         }
 1075:         if ($udom) {
 1076:             my $uname = &get_domainconfiguser($udom); 
 1077:             return &del($namespace,$storearr,$udom,$uname);
 1078:         }
 1079:     }
 1080: }
 1081: 
 1082: # ----------------------------------construct domainconfig user for a domain 
 1083: sub get_domainconfiguser {
 1084:     my ($udom) = @_;
 1085:     return $udom.'-domainconfig';
 1086: }
 1087: 
 1088: sub retrieve_inst_usertypes {
 1089:     my ($udom) = @_;
 1090:     my (%returnhash,@order);
 1091:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1092:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1093:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1094:         %returnhash = %{$domdefs{'inststatustypes'}};
 1095:         @order = @{$domdefs{'inststatusorder'}};
 1096:     } else {
 1097:         if (defined(&domain($udom,'primary'))) {
 1098:             my $uhome=&domain($udom,'primary');
 1099:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1100:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1101:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1102:                 return (\%returnhash,\@order);
 1103:             }
 1104:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1105:             my @pairs=split(/\&/,$hashitems);
 1106:             foreach my $item (@pairs) {
 1107:                 my ($key,$value)=split(/=/,$item,2);
 1108:                 $key = &unescape($key);
 1109:                 next if ($key =~ /^error: 2 /);
 1110:                 $returnhash{$key}=&thaw_unescape($value);
 1111:             }
 1112:             my @esc_order = split(/\&/,$orderitems);
 1113:             foreach my $item (@esc_order) {
 1114:                 push(@order,&unescape($item));
 1115:             }
 1116:         } else {
 1117:             &logthis("get_dom failed - no primary domain server for $udom");
 1118:         }
 1119:     }
 1120:     return (\%returnhash,\@order);
 1121: }
 1122: 
 1123: sub is_domainimage {
 1124:     my ($url) = @_;
 1125:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1126:         if (&domain($1) ne '') {
 1127:             return '1';
 1128:         }
 1129:     }
 1130:     return;
 1131: }
 1132: 
 1133: sub inst_directory_query {
 1134:     my ($srch) = @_;
 1135:     my $udom = $srch->{'srchdomain'};
 1136:     my %results;
 1137:     my $homeserver = &domain($udom,'primary');
 1138:     my $outcome;
 1139:     if ($homeserver ne '') {
 1140: 	my $queryid=&reply("querysend:instdirsearch:".
 1141: 			   &escape($srch->{'srchby'}).':'.
 1142: 			   &escape($srch->{'srchterm'}).':'.
 1143: 			   &escape($srch->{'srchtype'}),$homeserver);
 1144: 	my $host=&hostname($homeserver);
 1145: 	if ($queryid !~/^\Q$host\E\_/) {
 1146: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1147: 	    return;
 1148: 	}
 1149: 	my $response = &get_query_reply($queryid);
 1150: 	my $maxtries = 5;
 1151: 	my $tries = 1;
 1152: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1153: 	    $response = &get_query_reply($queryid);
 1154: 	    $tries ++;
 1155: 	}
 1156: 
 1157:         if (!&error($response) && $response ne 'refused') {
 1158:             if ($response eq 'unavailable') {
 1159:                 $outcome = $response;
 1160:             } else {
 1161:                 $outcome = 'ok';
 1162:                 my @matches = split(/\n/,$response);
 1163:                 foreach my $match (@matches) {
 1164:                     my ($key,$value) = split(/=/,$match);
 1165:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1166:                 }
 1167:             }
 1168:         }
 1169:     }
 1170:     return ($outcome,%results);
 1171: }
 1172: 
 1173: sub usersearch {
 1174:     my ($srch) = @_;
 1175:     my $dom = $srch->{'srchdomain'};
 1176:     my %results;
 1177:     my %libserv = &all_library();
 1178:     my $query = 'usersearch';
 1179:     foreach my $tryserver (keys(%libserv)) {
 1180:         if (&host_domain($tryserver) eq $dom) {
 1181:             my $host=&hostname($tryserver);
 1182:             my $queryid=
 1183:                 &reply("querysend:".&escape($query).':'.
 1184:                        &escape($srch->{'srchby'}).':'.
 1185:                        &escape($srch->{'srchtype'}).':'.
 1186:                        &escape($srch->{'srchterm'}),$tryserver);
 1187:             if ($queryid !~/^\Q$host\E\_/) {
 1188:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1189:                 next;
 1190:             }
 1191:             my $reply = &get_query_reply($queryid);
 1192:             my $maxtries = 1;
 1193:             my $tries = 1;
 1194:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1195:                 $reply = &get_query_reply($queryid);
 1196:                 $tries ++;
 1197:             }
 1198:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1199:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1200:             } else {
 1201:                 my @matches;
 1202:                 if ($reply =~ /\n/) {
 1203:                     @matches = split(/\n/,$reply);
 1204:                 } else {
 1205:                     @matches = split(/\&/,$reply);
 1206:                 }
 1207:                 foreach my $match (@matches) {
 1208:                     my ($uname,$udom,%userhash);
 1209:                     foreach my $entry (split(/:/,$match)) {
 1210:                         my ($key,$value) =
 1211:                             map {&unescape($_);} split(/=/,$entry);
 1212:                         $userhash{$key} = $value;
 1213:                         if ($key eq 'username') {
 1214:                             $uname = $value;
 1215:                         } elsif ($key eq 'domain') {
 1216:                             $udom = $value;
 1217:                         }
 1218:                     }
 1219:                     $results{$uname.':'.$udom} = \%userhash;
 1220:                 }
 1221:             }
 1222:         }
 1223:     }
 1224:     return %results;
 1225: }
 1226: 
 1227: sub get_instuser {
 1228:     my ($udom,$uname,$id) = @_;
 1229:     my $homeserver = &domain($udom,'primary');
 1230:     my ($outcome,%results);
 1231:     if ($homeserver ne '') {
 1232:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1233:                            &escape($id).':'.&escape($udom),$homeserver);
 1234:         my $host=&hostname($homeserver);
 1235:         if ($queryid !~/^\Q$host\E\_/) {
 1236:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1237:             return;
 1238:         }
 1239:         my $response = &get_query_reply($queryid);
 1240:         my $maxtries = 5;
 1241:         my $tries = 1;
 1242:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1243:             $response = &get_query_reply($queryid);
 1244:             $tries ++;
 1245:         }
 1246:         if (!&error($response) && $response ne 'refused') {
 1247:             if ($response eq 'unavailable') {
 1248:                 $outcome = $response;
 1249:             } else {
 1250:                 $outcome = 'ok';
 1251:                 my @matches = split(/\n/,$response);
 1252:                 foreach my $match (@matches) {
 1253:                     my ($key,$value) = split(/=/,$match);
 1254:                     $results{&unescape($key)} = &thaw_unescape($value);
 1255:                 }
 1256:             }
 1257:         }
 1258:     }
 1259:     my %userinfo;
 1260:     if (ref($results{$uname}) eq 'HASH') {
 1261:         %userinfo = %{$results{$uname}};
 1262:     } 
 1263:     return ($outcome,%userinfo);
 1264: }
 1265: 
 1266: sub inst_rulecheck {
 1267:     my ($udom,$uname,$id,$item,$rules) = @_;
 1268:     my %returnhash;
 1269:     if ($udom ne '') {
 1270:         if (ref($rules) eq 'ARRAY') {
 1271:             @{$rules} = map {&escape($_);} (@{$rules});
 1272:             my $rulestr = join(':',@{$rules});
 1273:             my $homeserver=&domain($udom,'primary');
 1274:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1275:                 my $response;
 1276:                 if ($item eq 'username') {                
 1277:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1278:                                               ':'.&escape($uname).':'.$rulestr,
 1279:                                               $homeserver));
 1280:                 } elsif ($item eq 'id') {
 1281:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1282:                                               ':'.&escape($id).':'.$rulestr,
 1283:                                               $homeserver));
 1284:                 } elsif ($item eq 'selfcreate') {
 1285:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1286:                                                &escape($udom).':'.&escape($uname).
 1287:                                               ':'.$rulestr,$homeserver));
 1288:                 }
 1289:                 if ($response ne 'refused') {
 1290:                     my @pairs=split(/\&/,$response);
 1291:                     foreach my $item (@pairs) {
 1292:                         my ($key,$value)=split(/=/,$item,2);
 1293:                         $key = &unescape($key);
 1294:                         next if ($key =~ /^error: 2 /);
 1295:                         $returnhash{$key}=&thaw_unescape($value);
 1296:                     }
 1297:                 }
 1298:             }
 1299:         }
 1300:     }
 1301:     return %returnhash;
 1302: }
 1303: 
 1304: sub inst_userrules {
 1305:     my ($udom,$check) = @_;
 1306:     my (%ruleshash,@ruleorder);
 1307:     if ($udom ne '') {
 1308:         my $homeserver=&domain($udom,'primary');
 1309:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1310:             my $response;
 1311:             if ($check eq 'id') {
 1312:                 $response=&reply('instidrules:'.&escape($udom),
 1313:                                  $homeserver);
 1314:             } elsif ($check eq 'email') {
 1315:                 $response=&reply('instemailrules:'.&escape($udom),
 1316:                                  $homeserver);
 1317:             } else {
 1318:                 $response=&reply('instuserrules:'.&escape($udom),
 1319:                                  $homeserver);
 1320:             }
 1321:             if (($response ne 'refused') && ($response ne 'error') && 
 1322:                 ($response ne 'unknown_cmd') && 
 1323:                 ($response ne 'no_such_host')) {
 1324:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1325:                 my @pairs=split(/\&/,$hashitems);
 1326:                 foreach my $item (@pairs) {
 1327:                     my ($key,$value)=split(/=/,$item,2);
 1328:                     $key = &unescape($key);
 1329:                     next if ($key =~ /^error: 2 /);
 1330:                     $ruleshash{$key}=&thaw_unescape($value);
 1331:                 }
 1332:                 my @esc_order = split(/\&/,$orderitems);
 1333:                 foreach my $item (@esc_order) {
 1334:                     push(@ruleorder,&unescape($item));
 1335:                 }
 1336:             }
 1337:         }
 1338:     }
 1339:     return (\%ruleshash,\@ruleorder);
 1340: }
 1341: 
 1342: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1343: 
 1344: sub get_domain_defaults {
 1345:     my ($domain) = @_;
 1346:     my $cachetime = 60*60*24;
 1347:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1348:     if (defined($cached)) {
 1349:         if (ref($result) eq 'HASH') {
 1350:             return %{$result};
 1351:         }
 1352:     }
 1353:     my %domdefaults;
 1354:     my %domconfig =
 1355:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1356:                                   'requestcourses','inststatus',
 1357:                                   'coursedefaults'],$domain);
 1358:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1359:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1360:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1361:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1362:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1363:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1364:     } else {
 1365:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1366:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1367:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1368:     }
 1369:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1370:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1371:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1372:         } else {
 1373:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1374:         } 
 1375:         my @usertools = ('aboutme','blog','portfolio');
 1376:         foreach my $item (@usertools) {
 1377:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1378:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1379:             }
 1380:         }
 1381:     }
 1382:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1383:         foreach my $item ('official','unofficial','community') {
 1384:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1385:         }
 1386:     }
 1387:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1388:         foreach my $item ('inststatustypes','inststatusorder') {
 1389:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1390:         }
 1391:     }
 1392:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1393:         foreach my $item ('canuse_pdfforms') {
 1394:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1395:         }
 1396:     }
 1397:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1398:                                   $cachetime);
 1399:     return %domdefaults;
 1400: }
 1401: 
 1402: # --------------------------------------------------- Assign a key to a student
 1403: 
 1404: sub assign_access_key {
 1405: #
 1406: # a valid key looks like uname:udom#comments
 1407: # comments are being appended
 1408: #
 1409:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1410:     $kdom=
 1411:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1412:     $knum=
 1413:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1414:     $cdom=
 1415:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1416:     $cnum=
 1417:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1418:     $udom=$env{'user.name'} unless (defined($udom));
 1419:     $uname=$env{'user.domain'} unless (defined($uname));
 1420:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1421:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1422:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1423:                                                   # assigned to this person
 1424:                                                   # - this should not happen,
 1425:                                                   # unless something went wrong
 1426:                                                   # the first time around
 1427: # ready to assign
 1428:         $logentry=$1.'; '.$logentry;
 1429:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1430:                                                  $kdom,$knum) eq 'ok') {
 1431: # key now belongs to user
 1432: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1433:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1434:                 &appenv({'environment.'.$envkey => $ckey});
 1435:                 return 'ok';
 1436:             } else {
 1437:                 return 
 1438:   'error: Count not permanently assign key, will need to be re-entered later.';
 1439: 	    }
 1440:         } else {
 1441:             return 'error: Could not assign key, try again later.';
 1442:         }
 1443:     } elsif (!$existing{$ckey}) {
 1444: # the key does not exist
 1445: 	return 'error: The key does not exist';
 1446:     } else {
 1447: # the key is somebody else's
 1448: 	return 'error: The key is already in use';
 1449:     }
 1450: }
 1451: 
 1452: # ------------------------------------------ put an additional comment on a key
 1453: 
 1454: sub comment_access_key {
 1455: #
 1456: # a valid key looks like uname:udom#comments
 1457: # comments are being appended
 1458: #
 1459:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1460:     $cdom=
 1461:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1462:     $cnum=
 1463:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1464:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1465:     if ($existing{$ckey}) {
 1466:         $existing{$ckey}.='; '.$logentry;
 1467: # ready to assign
 1468:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1469:                                                  $cdom,$cnum) eq 'ok') {
 1470: 	    return 'ok';
 1471:         } else {
 1472: 	    return 'error: Count not store comment.';
 1473:         }
 1474:     } else {
 1475: # the key does not exist
 1476: 	return 'error: The key does not exist';
 1477:     }
 1478: }
 1479: 
 1480: # ------------------------------------------------------ Generate a set of keys
 1481: 
 1482: sub generate_access_keys {
 1483:     my ($number,$cdom,$cnum,$logentry)=@_;
 1484:     $cdom=
 1485:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1486:     $cnum=
 1487:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1488:     unless (&allowed('mky',$cdom)) { return 0; }
 1489:     unless (($cdom) && ($cnum)) { return 0; }
 1490:     if ($number>10000) { return 0; }
 1491:     sleep(2); # make sure don't get same seed twice
 1492:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1493:     my $total=0;
 1494:     for (my $i=1;$i<=$number;$i++) {
 1495:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1496:                   sprintf("%lx",int(100000*rand)).'-'.
 1497:                   sprintf("%lx",int(100000*rand));
 1498:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1499:        $newkey=~s/0/h/g; # and also 0 and O
 1500:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1501:        if ($existing{$newkey}) {
 1502:            $i--;
 1503:        } else {
 1504: 	  if (&put('accesskeys',
 1505:               { $newkey => '# generated '.localtime().
 1506:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1507:                            '; '.$logentry },
 1508: 		   $cdom,$cnum) eq 'ok') {
 1509:               $total++;
 1510: 	  }
 1511:        }
 1512:     }
 1513:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1514:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1515:     return $total;
 1516: }
 1517: 
 1518: # ------------------------------------------------------- Validate an accesskey
 1519: 
 1520: sub validate_access_key {
 1521:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1522:     $cdom=
 1523:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1524:     $cnum=
 1525:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1526:     $udom=$env{'user.domain'} unless (defined($udom));
 1527:     $uname=$env{'user.name'} unless (defined($uname));
 1528:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1529:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1530: }
 1531: 
 1532: # ------------------------------------- Find the section of student in a course
 1533: sub devalidate_getsection_cache {
 1534:     my ($udom,$unam,$courseid)=@_;
 1535:     my $hashid="$udom:$unam:$courseid";
 1536:     &devalidate_cache_new('getsection',$hashid);
 1537: }
 1538: 
 1539: sub courseid_to_courseurl {
 1540:     my ($courseid) = @_;
 1541:     #already url style courseid
 1542:     return $courseid if ($courseid =~ m{^/});
 1543: 
 1544:     if (exists($env{'course.'.$courseid.'.num'})) {
 1545: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1546: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1547: 	return "/$cdom/$cnum";
 1548:     }
 1549: 
 1550:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1551:     if (exists($courseinfo{'num'})) {
 1552: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1553:     }
 1554: 
 1555:     return undef;
 1556: }
 1557: 
 1558: sub getsection {
 1559:     my ($udom,$unam,$courseid)=@_;
 1560:     my $cachetime=1800;
 1561: 
 1562:     my $hashid="$udom:$unam:$courseid";
 1563:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1564:     if (defined($cached)) { return $result; }
 1565: 
 1566:     my %Pending; 
 1567:     my %Expired;
 1568:     #
 1569:     # Each role can either have not started yet (pending), be active, 
 1570:     #    or have expired.
 1571:     #
 1572:     # If there is an active role, we are done.
 1573:     #
 1574:     # If there is more than one role which has not started yet, 
 1575:     #     choose the one which will start sooner
 1576:     # If there is one role which has not started yet, return it.
 1577:     #
 1578:     # If there is more than one expired role, choose the one which ended last.
 1579:     # If there is a role which has expired, return it.
 1580:     #
 1581:     $courseid = &courseid_to_courseurl($courseid);
 1582:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1583:     foreach my $key (keys(%roleshash)) {
 1584:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1585:         my $section=$1;
 1586:         if ($key eq $courseid.'_st') { $section=''; }
 1587:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1588:         my $now=time;
 1589:         if (defined($end) && $end && ($now > $end)) {
 1590:             $Expired{$end}=$section;
 1591:             next;
 1592:         }
 1593:         if (defined($start) && $start && ($now < $start)) {
 1594:             $Pending{$start}=$section;
 1595:             next;
 1596:         }
 1597:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1598:     }
 1599:     #
 1600:     # Presumedly there will be few matching roles from the above
 1601:     # loop and the sorting time will be negligible.
 1602:     if (scalar(keys(%Pending))) {
 1603:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1604:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1605:     } 
 1606:     if (scalar(keys(%Expired))) {
 1607:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1608:         my $time = pop(@sorted);
 1609:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1610:     }
 1611:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1612: }
 1613: 
 1614: sub save_cache {
 1615:     &purge_remembered();
 1616:     #&Apache::loncommon::validate_page();
 1617:     undef(%env);
 1618:     undef($env_loaded);
 1619: }
 1620: 
 1621: my $to_remember=-1;
 1622: my %remembered;
 1623: my %accessed;
 1624: my $kicks=0;
 1625: my $hits=0;
 1626: sub make_key {
 1627:     my ($name,$id) = @_;
 1628:     if (length($id) > 65 
 1629: 	&& length(&escape($id)) > 200) {
 1630: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1631:     }
 1632:     return &escape($name.':'.$id);
 1633: }
 1634: 
 1635: sub devalidate_cache_new {
 1636:     my ($name,$id,$debug) = @_;
 1637:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1638:     $id=&make_key($name,$id);
 1639:     $memcache->delete($id);
 1640:     delete($remembered{$id});
 1641:     delete($accessed{$id});
 1642: }
 1643: 
 1644: sub is_cached_new {
 1645:     my ($name,$id,$debug) = @_;
 1646:     $id=&make_key($name,$id);
 1647:     if (exists($remembered{$id})) {
 1648: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1649: 	$accessed{$id}=[&gettimeofday()];
 1650: 	$hits++;
 1651: 	return ($remembered{$id},1);
 1652:     }
 1653:     my $value = $memcache->get($id);
 1654:     if (!(defined($value))) {
 1655: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1656: 	return (undef,undef);
 1657:     }
 1658:     if ($value eq '__undef__') {
 1659: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1660: 	$value=undef;
 1661:     }
 1662:     &make_room($id,$value,$debug);
 1663:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1664:     return ($value,1);
 1665: }
 1666: 
 1667: sub do_cache_new {
 1668:     my ($name,$id,$value,$time,$debug) = @_;
 1669:     $id=&make_key($name,$id);
 1670:     my $setvalue=$value;
 1671:     if (!defined($setvalue)) {
 1672: 	$setvalue='__undef__';
 1673:     }
 1674:     if (!defined($time) ) {
 1675: 	$time=600;
 1676:     }
 1677:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1678:     my $result = $memcache->set($id,$setvalue,$time);
 1679:     if (! $result) {
 1680: 	&logthis("caching of id -> $id  failed");
 1681: 	$memcache->disconnect_all();
 1682:     }
 1683:     # need to make a copy of $value
 1684:     &make_room($id,$value,$debug);
 1685:     return $value;
 1686: }
 1687: 
 1688: sub make_room {
 1689:     my ($id,$value,$debug)=@_;
 1690: 
 1691:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1692:                                     : $value;
 1693:     if ($to_remember<0) { return; }
 1694:     $accessed{$id}=[&gettimeofday()];
 1695:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1696:     my $to_kick;
 1697:     my $max_time=0;
 1698:     foreach my $other (keys(%accessed)) {
 1699: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1700: 	    $to_kick=$other;
 1701: 	    $max_time=&tv_interval($accessed{$other});
 1702: 	}
 1703:     }
 1704:     delete($remembered{$to_kick});
 1705:     delete($accessed{$to_kick});
 1706:     $kicks++;
 1707:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1708:     return;
 1709: }
 1710: 
 1711: sub purge_remembered {
 1712:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1713:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1714:     undef(%remembered);
 1715:     undef(%accessed);
 1716: }
 1717: # ------------------------------------- Read an entry from a user's environment
 1718: 
 1719: sub userenvironment {
 1720:     my ($udom,$unam,@what)=@_;
 1721:     my $items;
 1722:     foreach my $item (@what) {
 1723:         $items.=&escape($item).'&';
 1724:     }
 1725:     $items=~s/\&$//;
 1726:     my %returnhash=();
 1727:     my $uhome = &homeserver($unam,$udom);
 1728:     unless ($uhome eq 'no_host') {
 1729:         my @answer=split(/\&/, 
 1730:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 1731:         my $i;
 1732:         for ($i=0;$i<=$#what;$i++) {
 1733: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 1734:         }
 1735:     }
 1736:     return %returnhash;
 1737: }
 1738: 
 1739: # ---------------------------------------------------------- Get a studentphoto
 1740: sub studentphoto {
 1741:     my ($udom,$unam,$ext) = @_;
 1742:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1743:     if (defined($env{'request.course.id'})) {
 1744:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1745:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1746:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1747:             } else {
 1748:                 my ($result,$perm_reqd)=
 1749: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1750:                 if ($result eq 'ok') {
 1751:                     if (!($perm_reqd eq 'yes')) {
 1752:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1753:                     }
 1754:                 }
 1755:             }
 1756:         }
 1757:     } else {
 1758:         my ($result,$perm_reqd) = 
 1759: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1760:         if ($result eq 'ok') {
 1761:             if (!($perm_reqd eq 'yes')) {
 1762:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1763:             }
 1764:         }
 1765:     }
 1766:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1767: }
 1768: 
 1769: sub retrievestudentphoto {
 1770:     my ($udom,$unam,$ext,$type) = @_;
 1771:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1772:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1773:     if ($ret eq 'ok') {
 1774:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1775:         if ($type eq 'thumbnail') {
 1776:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1777:         }
 1778:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1779:         return $tokenurl;
 1780:     } else {
 1781:         if ($type eq 'thumbnail') {
 1782:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1783:         } else { 
 1784:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1785:         }
 1786:     }
 1787: }
 1788: 
 1789: # -------------------------------------------------------------------- New chat
 1790: 
 1791: sub chatsend {
 1792:     my ($newentry,$anon,$group)=@_;
 1793:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1794:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1795:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1796:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1797: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1798: 		   &escape($newentry)).':'.$group,$chome);
 1799: }
 1800: 
 1801: # ------------------------------------------ Find current version of a resource
 1802: 
 1803: sub getversion {
 1804:     my $fname=&clutter(shift);
 1805:     unless ($fname=~/^\/res\//) { return -1; }
 1806:     return &currentversion(&filelocation('',$fname));
 1807: }
 1808: 
 1809: sub currentversion {
 1810:     my $fname=shift;
 1811:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1812:     if (defined($cached)) { return $result; }
 1813:     my $author=$fname;
 1814:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1815:     my ($udom,$uname)=split(/\//,$author);
 1816:     my $home=homeserver($uname,$udom);
 1817:     if ($home eq 'no_host') { 
 1818:         return -1; 
 1819:     }
 1820:     my $answer=reply("currentversion:$fname",$home);
 1821:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1822: 	return -1;
 1823:     }
 1824:     return &do_cache_new('resversion',$fname,$answer,600);
 1825: }
 1826: 
 1827: # ----------------------------- Subscribe to a resource, return URL if possible
 1828: 
 1829: sub subscribe {
 1830:     my $fname=shift;
 1831:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1832:     $fname=~s/[\n\r]//g;
 1833:     my $author=$fname;
 1834:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1835:     my ($udom,$uname)=split(/\//,$author);
 1836:     my $home=homeserver($uname,$udom);
 1837:     if ($home eq 'no_host') {
 1838:         return 'not_found';
 1839:     }
 1840:     my $answer=reply("sub:$fname",$home);
 1841:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1842: 	$answer.=' by '.$home;
 1843:     }
 1844:     return $answer;
 1845: }
 1846:     
 1847: # -------------------------------------------------------------- Replicate file
 1848: 
 1849: sub repcopy {
 1850:     my $filename=shift;
 1851:     $filename=~s/\/+/\//g;
 1852:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1853:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1854:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1855: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1856: 	return &repcopy_userfile($filename);
 1857:     }
 1858:     $filename=~s/[\n\r]//g;
 1859:     my $transname="$filename.in.transfer";
 1860: # FIXME: this should flock
 1861:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1862:     my $remoteurl=subscribe($filename);
 1863:     if ($remoteurl =~ /^con_lost by/) {
 1864: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1865:            return 'unavailable';
 1866:     } elsif ($remoteurl eq 'not_found') {
 1867: 	   #&logthis("Subscribe returned not_found: $filename");
 1868: 	   return 'not_found';
 1869:     } elsif ($remoteurl =~ /^rejected by/) {
 1870: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1871:            return 'forbidden';
 1872:     } elsif ($remoteurl eq 'directory') {
 1873:            return 'ok';
 1874:     } else {
 1875:         my $author=$filename;
 1876:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1877:         my ($udom,$uname)=split(/\//,$author);
 1878:         my $home=homeserver($uname,$udom);
 1879:         unless ($home eq $perlvar{'lonHostID'}) {
 1880:            my @parts=split(/\//,$filename);
 1881:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1882:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1883:                &logthis("Malconfiguration for replication: $filename");
 1884: 	       return 'bad_request';
 1885:            }
 1886:            my $count;
 1887:            for ($count=5;$count<$#parts;$count++) {
 1888:                $path.="/$parts[$count]";
 1889:                if ((-e $path)!=1) {
 1890: 		   mkdir($path,0777);
 1891:                }
 1892:            }
 1893:            my $ua=new LWP::UserAgent;
 1894:            my $request=new HTTP::Request('GET',"$remoteurl");
 1895:            my $response=$ua->request($request,$transname);
 1896:            if ($response->is_error()) {
 1897: 	       unlink($transname);
 1898:                my $message=$response->status_line;
 1899:                &logthis("<font color=\"blue\">WARNING:"
 1900:                        ." LWP get: $message: $filename</font>");
 1901:                return 'unavailable';
 1902:            } else {
 1903: 	       if ($remoteurl!~/\.meta$/) {
 1904:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1905:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1906:                   if ($mresponse->is_error()) {
 1907: 		      unlink($filename.'.meta');
 1908:                       &logthis(
 1909:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1910:                   }
 1911: 	       }
 1912:                rename($transname,$filename);
 1913:                return 'ok';
 1914:            }
 1915:        }
 1916:     }
 1917: }
 1918: 
 1919: # ------------------------------------------------ Get server side include body
 1920: sub ssi_body {
 1921:     my ($filelink,%form)=@_;
 1922:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1923:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1924:     }
 1925:     my $output='';
 1926:     my $response;
 1927:     if ($filelink=~/^https?\:/) {
 1928:        ($output,$response)=&externalssi($filelink);
 1929:     } else {
 1930:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 1931:        $filelink .= 'inhibitmenu=yes';
 1932:        ($output,$response)=&ssi($filelink,%form);
 1933:     }
 1934:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1935:     $output=~s/^.*?\<body[^\>]*\>//si;
 1936:     $output=~s/\<\/body\s*\>.*?$//si;
 1937:     if (wantarray) {
 1938:         return ($output, $response);
 1939:     } else {
 1940:         return $output;
 1941:     }
 1942: }
 1943: 
 1944: # --------------------------------------------------------- Server Side Include
 1945: 
 1946: sub absolute_url {
 1947:     my ($host_name) = @_;
 1948:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1949:     if ($host_name eq '') {
 1950: 	$host_name = $ENV{'SERVER_NAME'};
 1951:     }
 1952:     return $protocol.$host_name;
 1953: }
 1954: 
 1955: #
 1956: #   Server side include.
 1957: # Parameters:
 1958: #  fn     Possibly encrypted resource name/id.
 1959: #  form   Hash that describes how the rendering should be done
 1960: #         and other things.
 1961: # Returns:
 1962: #   Scalar context: The content of the response.
 1963: #   Array context:  2 element list of the content and the full response object.
 1964: #     
 1965: sub ssi {
 1966: 
 1967:     my ($fn,%form)=@_;
 1968:     my $ua=new LWP::UserAgent;
 1969:     my $request;
 1970: 
 1971:     $form{'no_update_last_known'}=1;
 1972:     &Apache::lonenc::check_encrypt(\$fn);
 1973:     if (%form) {
 1974:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1975:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1976:     } else {
 1977:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1978:     }
 1979: 
 1980:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1981:     my $response=$ua->request($request);
 1982: 
 1983:     if (wantarray) {
 1984: 	return ($response->content, $response);
 1985:     } else {
 1986: 	return $response->content;
 1987:     }
 1988: }
 1989: 
 1990: sub externalssi {
 1991:     my ($url)=@_;
 1992:     my $ua=new LWP::UserAgent;
 1993:     my $request=new HTTP::Request('GET',$url);
 1994:     my $response=$ua->request($request);
 1995:     if (wantarray) {
 1996:         return ($response->content, $response);
 1997:     } else {
 1998:         return $response->content;
 1999:     }
 2000: }
 2001: 
 2002: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2003: 
 2004: sub allowuploaded {
 2005:     my ($srcurl,$url)=@_;
 2006:     $url=&clutter(&declutter($url));
 2007:     my $dir=$url;
 2008:     $dir=~s/\/[^\/]+$//;
 2009:     my %httpref=();
 2010:     my $httpurl=&hreflocation('',$url);
 2011:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2012:     &Apache::lonnet::appenv(\%httpref);
 2013: }
 2014: 
 2015: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2016: # input: action, courseID, current domain, intended
 2017: #        path to file, source of file, instruction to parse file for objects,
 2018: #        ref to hash for embedded objects,
 2019: #        ref to hash for codebase of java objects.
 2020: #
 2021: # output: url to file (if action was uploaddoc), 
 2022: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2023: #
 2024: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2025: # course.
 2026: #
 2027: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2028: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2029: #          course's home server.
 2030: #
 2031: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2032: #          be copied from $source (current location) to 
 2033: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2034: #         and will then be copied to
 2035: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2036: #         course's home server.
 2037: #
 2038: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2039: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2040: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2041: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2042: #         in course's home server.
 2043: #
 2044: 
 2045: sub process_coursefile {
 2046:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 2047:     my $fetchresult;
 2048:     my $home=&homeserver($docuname,$docudom);
 2049:     if ($action eq 'propagate') {
 2050:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2051: 			     $home);
 2052:     } else {
 2053:         my $fpath = '';
 2054:         my $fname = $file;
 2055:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2056:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2057:         my $filepath = &build_filepath($fpath);
 2058:         if ($action eq 'copy') {
 2059:             if ($source eq '') {
 2060:                 $fetchresult = 'no source file';
 2061:                 return $fetchresult;
 2062:             } else {
 2063:                 my $destination = $filepath.'/'.$fname;
 2064:                 rename($source,$destination);
 2065:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2066:                                  $home);
 2067:             }
 2068:         } elsif ($action eq 'uploaddoc') {
 2069:             open(my $fh,'>'.$filepath.'/'.$fname);
 2070:             print $fh $env{'form.'.$source};
 2071:             close($fh);
 2072:             if ($parser eq 'parse') {
 2073:                 my $mm = new File::MMagic;
 2074:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
 2075:                 if ($mime_type eq 'text/html') {
 2076:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2077:                     unless ($parse_result eq 'ok') {
 2078:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2079:                     }
 2080:                 }
 2081:             }
 2082:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2083:                                  $home);
 2084:             if ($fetchresult eq 'ok') {
 2085:                 return '/uploaded/'.$fpath.'/'.$fname;
 2086:             } else {
 2087:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2088:                         ' to host '.$home.': '.$fetchresult);
 2089:                 return '/adm/notfound.html';
 2090:             }
 2091:         }
 2092:     }
 2093:     unless ( $fetchresult eq 'ok') {
 2094:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2095:              ' to host '.$home.': '.$fetchresult);
 2096:     }
 2097:     return $fetchresult;
 2098: }
 2099: 
 2100: sub build_filepath {
 2101:     my ($fpath) = @_;
 2102:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2103:     unless ($fpath eq '') {
 2104:         my @parts=split('/',$fpath);
 2105:         foreach my $part (@parts) {
 2106:             $filepath.= '/'.$part;
 2107:             if ((-e $filepath)!=1) {
 2108:                 mkdir($filepath,0777);
 2109:             }
 2110:         }
 2111:     }
 2112:     return $filepath;
 2113: }
 2114: 
 2115: sub store_edited_file {
 2116:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2117:     my $file = $primary_url;
 2118:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2119:     my $fpath = '';
 2120:     my $fname = $file;
 2121:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2122:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2123:     my $filepath = &build_filepath($fpath);
 2124:     open(my $fh,'>'.$filepath.'/'.$fname);
 2125:     print $fh $content;
 2126:     close($fh);
 2127:     my $home=&homeserver($docuname,$docudom);
 2128:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2129: 			  $home);
 2130:     if ($$fetchresult eq 'ok') {
 2131:         return '/uploaded/'.$fpath.'/'.$fname;
 2132:     } else {
 2133:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2134: 		 ' to host '.$home.': '.$$fetchresult);
 2135:         return '/adm/notfound.html';
 2136:     }
 2137: }
 2138: 
 2139: sub clean_filename {
 2140:     my ($fname,$args)=@_;
 2141: # Replace Windows backslashes by forward slashes
 2142:     $fname=~s/\\/\//g;
 2143:     if (!$args->{'keep_path'}) {
 2144:         # Get rid of everything but the actual filename
 2145: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2146:     }
 2147: # Replace spaces by underscores
 2148:     $fname=~s/\s+/\_/g;
 2149: # Replace all other weird characters by nothing
 2150:     $fname=~s{[^/\w\.\-]}{}g;
 2151: # Replace all .\d. sequences with _\d. so they no longer look like version
 2152: # numbers
 2153:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2154:     return $fname;
 2155: }
 2156: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2157: sub resizeImage {
 2158: 	my($img_url) = @_;	
 2159: 	my $ima = Image::Magick->new;                       
 2160:         $ima->Read($img_url);
 2161: 	if($ima->Get('width') > 400)
 2162: 	{
 2163: 		my $factor = $ima->Get('width')/400;
 2164:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2165: 	}
 2166: 	if($ima->Get('height') > 500)
 2167:         {
 2168:         	my $factor = $ima->Get('height')/500;
 2169:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2170:         } 
 2171: 		
 2172: 	$ima->Write($img_url);
 2173: }
 2174: 
 2175: #Wrapper function for userphotoupload
 2176: sub userphotoupload
 2177: {
 2178: 	my($formname,$subdir) = @_;
 2179: 	$upload_photo_form = 1;
 2180: 	return &userfileupload($formname,undef,$subdir);
 2181: }
 2182: 
 2183: # --------------- Take an uploaded file and put it into the userfiles directory
 2184: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2185: #                    the desired filenam is in $env{"form.$formname.filename"}
 2186: #        $coursedoc - if true up to the current course
 2187: #                     if false
 2188: #        $subdir - directory in userfile to store the file into
 2189: #        $parser - instruction to parse file for objects ($parser = parse)    
 2190: #        $allfiles - reference to hash for embedded objects
 2191: #        $codebase - reference to hash for codebase of java objects
 2192: #        $desuname - username for permanent storage of uploaded file
 2193: #        $dsetudom - domain for permanaent storage of uploaded file
 2194: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2195: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2196: # 
 2197: # output: url of file in userspace, or error: <message> 
 2198: #             or /adm/notfound.html if failure to upload occurse
 2199: 
 2200: 
 2201: sub userfileupload {
 2202:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2203:         $destudom,$thumbwidth,$thumbheight)=@_;
 2204:     if (!defined($subdir)) { $subdir='unknown'; }
 2205:     my $fname=$env{'form.'.$formname.'.filename'};
 2206:     $fname=&clean_filename($fname);
 2207: # See if there is anything left
 2208:     unless ($fname) { return 'error: no uploaded file'; }
 2209:     chop($env{'form.'.$formname});
 2210:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2211:         my $now = time;
 2212:         my $filepath = 'tmp/helprequests/'.$now;
 2213:         my @parts=split(/\//,$filepath);
 2214:         my $fullpath = $perlvar{'lonDaemons'};
 2215:         for (my $i=0;$i<@parts;$i++) {
 2216:             $fullpath .= '/'.$parts[$i];
 2217:             if ((-e $fullpath)!=1) {
 2218:                 mkdir($fullpath,0777);
 2219:             }
 2220:         }
 2221:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2222:         print $fh $env{'form.'.$formname};
 2223:         close($fh);
 2224:         return $fullpath.'/'.$fname;
 2225:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2226:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2227:                        '_'.$env{'user.domain'}.'/pending';
 2228:         my @parts=split(/\//,$filepath);
 2229:         my $fullpath = $perlvar{'lonDaemons'};
 2230:         for (my $i=0;$i<@parts;$i++) {
 2231:             $fullpath .= '/'.$parts[$i];
 2232:             if ((-e $fullpath)!=1) {
 2233:                 mkdir($fullpath,0777);
 2234:             }
 2235:         }
 2236:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2237:         print $fh $env{'form.'.$formname};
 2238:         close($fh);
 2239:         return $fullpath.'/'.$fname;
 2240:     }
 2241:     if ($subdir eq 'scantron') {
 2242:         $fname = 'scantron_orig_'.$fname;
 2243:     } else {   
 2244: # Create the directory if not present
 2245:         $fname="$subdir/$fname";
 2246:     }
 2247:     if ($coursedoc) {
 2248: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2249: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2250:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2251:             return &finishuserfileupload($docuname,$docudom,
 2252: 					 $formname,$fname,$parser,$allfiles,
 2253: 					 $codebase,$thumbwidth,$thumbheight);
 2254:         } else {
 2255:             $fname=$env{'form.folder'}.'/'.$fname;
 2256:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2257: 				       $fname,$formname,$parser,
 2258: 				       $allfiles,$codebase);
 2259:         }
 2260:     } elsif (defined($destuname)) {
 2261:         my $docuname=$destuname;
 2262:         my $docudom=$destudom;
 2263: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2264: 				     $parser,$allfiles,$codebase,
 2265:                                      $thumbwidth,$thumbheight);
 2266:         
 2267:     } else {
 2268:         my $docuname=$env{'user.name'};
 2269:         my $docudom=$env{'user.domain'};
 2270:         if (exists($env{'form.group'})) {
 2271:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2272:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2273:         }
 2274: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2275: 				     $parser,$allfiles,$codebase,
 2276:                                      $thumbwidth,$thumbheight);
 2277:     }
 2278: }
 2279: 
 2280: sub finishuserfileupload {
 2281:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2282:         $thumbwidth,$thumbheight) = @_;
 2283:     my $path=$docudom.'/'.$docuname.'/';
 2284:     my $filepath=$perlvar{'lonDocRoot'};
 2285:   
 2286:     my ($fnamepath,$file,$fetchthumb);
 2287:     $file=$fname;
 2288:     if ($fname=~m|/|) {
 2289:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2290: 	$path.=$fnamepath.'/';
 2291:     }
 2292:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2293:     my $count;
 2294:     for ($count=4;$count<=$#parts;$count++) {
 2295:         $filepath.="/$parts[$count]";
 2296:         if ((-e $filepath)!=1) {
 2297: 	    mkdir($filepath,0777);
 2298:         }
 2299:     }
 2300: 
 2301: # Save the file
 2302:     {
 2303: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2304: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2305: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2306: 	    return '/adm/notfound.html';
 2307: 	}
 2308: 	if (!print FH ($env{'form.'.$formname})) {
 2309: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2310: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2311: 	    return '/adm/notfound.html';
 2312: 	}
 2313: 	close(FH);
 2314: 	if($upload_photo_form==1)
 2315: 	{
 2316: 		resizeImage($filepath.'/'.$file);		
 2317: 		$upload_photo_form = 0;
 2318: 	}
 2319:     }
 2320:     if ($parser eq 'parse') {
 2321:         my $mm = new File::MMagic;
 2322:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2323:         if ($mime_type eq 'text/html') {
 2324:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2325:                                                        $allfiles,$codebase);
 2326:             unless ($parse_result eq 'ok') {
 2327:                 &logthis('Failed to parse '.$filepath.$file.
 2328: 	   	         ' for embedded media: '.$parse_result); 
 2329:             }
 2330:         }
 2331:     }
 2332:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2333:         my $input = $filepath.'/'.$file;
 2334:         my $output = $filepath.'/'.'tn-'.$file;
 2335:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2336:         system("convert -sample $thumbsize $input $output");
 2337:         if (-e $filepath.'/'.'tn-'.$file) {
 2338:             $fetchthumb  = 1; 
 2339:         }
 2340:     }
 2341:  
 2342: # Notify homeserver to grep it
 2343: #
 2344:     my $docuhome=&homeserver($docuname,$docudom);	
 2345:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2346:     if ($fetchresult eq 'ok') {
 2347:         if ($fetchthumb) {
 2348:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2349:             if ($thumbresult ne 'ok') {
 2350:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2351:                          $docuhome.': '.$thumbresult);
 2352:             }
 2353:         }
 2354: #
 2355: # Return the URL to it
 2356:         return '/uploaded/'.$path.$file;
 2357:     } else {
 2358:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2359: 		 ': '.$fetchresult);
 2360:         return '/adm/notfound.html';
 2361:     }
 2362: }
 2363: 
 2364: sub extract_embedded_items {
 2365:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2366:     my @state = ();
 2367:     my %javafiles = (
 2368:                       codebase => '',
 2369:                       code => '',
 2370:                       archive => ''
 2371:                     );
 2372:     my %mediafiles = (
 2373:                       src => '',
 2374:                       movie => '',
 2375:                      );
 2376:     my $p;
 2377:     if ($content) {
 2378:         $p = HTML::LCParser->new($content);
 2379:     } else {
 2380:         $p = HTML::LCParser->new($fullpath);
 2381:     }
 2382:     while (my $t=$p->get_token()) {
 2383: 	if ($t->[0] eq 'S') {
 2384: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2385: 	    push(@state, $tagname);
 2386:             if (lc($tagname) eq 'allow') {
 2387:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2388:             }
 2389: 	    if (lc($tagname) eq 'img') {
 2390: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2391: 	    }
 2392: 	    if (lc($tagname) eq 'a') {
 2393: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2394: 	    }
 2395:             if (lc($tagname) eq 'script') {
 2396:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2397:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2398:                 } else {
 2399:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2400:                 }
 2401:             }
 2402:             if (lc($tagname) eq 'link') {
 2403:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2404:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2405:                 }
 2406:             }
 2407: 	    if (lc($tagname) eq 'object' ||
 2408: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2409: 		foreach my $item (keys(%javafiles)) {
 2410: 		    $javafiles{$item} = '';
 2411: 		}
 2412: 	    }
 2413: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2414: 		my $name = lc($attr->{'name'});
 2415: 		foreach my $item (keys(%javafiles)) {
 2416: 		    if ($name eq $item) {
 2417: 			$javafiles{$item} = $attr->{'value'};
 2418: 			last;
 2419: 		    }
 2420: 		}
 2421: 		foreach my $item (keys(%mediafiles)) {
 2422: 		    if ($name eq $item) {
 2423: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2424: 			last;
 2425: 		    }
 2426: 		}
 2427: 	    }
 2428: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2429: 		foreach my $item (keys(%javafiles)) {
 2430: 		    if ($attr->{$item}) {
 2431: 			$javafiles{$item} = $attr->{$item};
 2432: 			last;
 2433: 		    }
 2434: 		}
 2435: 		foreach my $item (keys(%mediafiles)) {
 2436: 		    if ($attr->{$item}) {
 2437: 			&add_filetype($allfiles,$attr->{$item},$item);
 2438: 			last;
 2439: 		    }
 2440: 		}
 2441: 	    }
 2442: 	} elsif ($t->[0] eq 'E') {
 2443: 	    my ($tagname) = ($t->[1]);
 2444: 	    if ($javafiles{'codebase'} ne '') {
 2445: 		$javafiles{'codebase'} .= '/';
 2446: 	    }  
 2447: 	    if (lc($tagname) eq 'applet' ||
 2448: 		lc($tagname) eq 'object' ||
 2449: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2450: 		) {
 2451: 		foreach my $item (keys(%javafiles)) {
 2452: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2453: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2454: 			&add_filetype($allfiles,$file,$item);
 2455: 		    }
 2456: 		}
 2457: 	    } 
 2458: 	    pop @state;
 2459: 	}
 2460:     }
 2461:     return 'ok';
 2462: }
 2463: 
 2464: sub add_filetype {
 2465:     my ($allfiles,$file,$type)=@_;
 2466:     if (exists($allfiles->{$file})) {
 2467: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2468: 	    push(@{$allfiles->{$file}}, &escape($type));
 2469: 	}
 2470:     } else {
 2471: 	@{$allfiles->{$file}} = (&escape($type));
 2472:     }
 2473: }
 2474: 
 2475: sub removeuploadedurl {
 2476:     my ($url)=@_;	
 2477:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2478:     return &removeuserfile($uname,$udom,$fname);
 2479: }
 2480: 
 2481: sub removeuserfile {
 2482:     my ($docuname,$docudom,$fname)=@_;
 2483:     my $home=&homeserver($docuname,$docudom);    
 2484:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2485:     if ($result eq 'ok') {	
 2486:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2487:             my $metafile = $fname.'.meta';
 2488:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2489: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2490:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2491:             my $sqlresult = 
 2492:                 &update_portfolio_table($docuname,$docudom,$file,
 2493:                                         'portfolio_metadata',$group,
 2494:                                         'delete');
 2495:         }
 2496:     }
 2497:     return $result;
 2498: }
 2499: 
 2500: sub mkdiruserfile {
 2501:     my ($docuname,$docudom,$dir)=@_;
 2502:     my $home=&homeserver($docuname,$docudom);
 2503:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2504: }
 2505: 
 2506: sub renameuserfile {
 2507:     my ($docuname,$docudom,$old,$new)=@_;
 2508:     my $home=&homeserver($docuname,$docudom);
 2509:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2510:                         &escape("$old").':'.&escape("$new"),$home);
 2511:     if ($result eq 'ok') {
 2512:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2513:             my $oldmeta = $old.'.meta';
 2514:             my $newmeta = $new.'.meta';
 2515:             my $metaresult = 
 2516:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2517: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2518:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2519:             my $sqlresult = 
 2520:                 &update_portfolio_table($docuname,$docudom,$file,
 2521:                                         'portfolio_metadata',$group,
 2522:                                         'delete');
 2523:         }
 2524:     }
 2525:     return $result;
 2526: }
 2527: 
 2528: # ------------------------------------------------------------------------- Log
 2529: 
 2530: sub log {
 2531:     my ($dom,$nam,$hom,$what)=@_;
 2532:     return critical("log:$dom:$nam:$what",$hom);
 2533: }
 2534: 
 2535: # ------------------------------------------------------------------ Course Log
 2536: #
 2537: # This routine flushes several buffers of non-mission-critical nature
 2538: #
 2539: 
 2540: sub flushcourselogs {
 2541:     &logthis('Flushing log buffers');
 2542: #
 2543: # course logs
 2544: # This is a log of all transactions in a course, which can be used
 2545: # for data mining purposes
 2546: #
 2547: # It also collects the courseid database, which lists last transaction
 2548: # times and course titles for all courseids
 2549: #
 2550:     my %courseidbuffer=();
 2551:     foreach my $crsid (keys(%courselogs)) {
 2552:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2553: 		          &escape($courselogs{$crsid}),
 2554: 		          $coursehombuf{$crsid}) eq 'ok') {
 2555: 	    delete $courselogs{$crsid};
 2556:         } else {
 2557:             &logthis('Failed to flush log buffer for '.$crsid);
 2558:             if (length($courselogs{$crsid})>40000) {
 2559:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2560:                         " exceeded maximum size, deleting.</font>");
 2561:                delete $courselogs{$crsid};
 2562:             }
 2563:         }
 2564:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2565:             'description' => $coursedescrbuf{$crsid},
 2566:             'inst_code'    => $courseinstcodebuf{$crsid},
 2567:             'type'        => $coursetypebuf{$crsid},
 2568:             'owner'       => $courseownerbuf{$crsid},
 2569:         };
 2570:     }
 2571: #
 2572: # Write course id database (reverse lookup) to homeserver of courses 
 2573: # Is used in pickcourse
 2574: #
 2575:     foreach my $crs_home (keys(%courseidbuffer)) {
 2576:         my $response = &courseidput(&host_domain($crs_home),
 2577:                                     $courseidbuffer{$crs_home},
 2578:                                     $crs_home,'timeonly');
 2579:     }
 2580: #
 2581: # File accesses
 2582: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2583: #
 2584:     foreach my $entry (keys(%accesshash)) {
 2585:         if ($entry =~ /___count$/) {
 2586:             my ($dom,$name);
 2587:             ($dom,$name,undef)=
 2588: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2589:             if (! defined($dom) || $dom eq '' || 
 2590:                 ! defined($name) || $name eq '') {
 2591:                 my $cid = $env{'request.course.id'};
 2592:                 $dom  = $env{'request.'.$cid.'.domain'};
 2593:                 $name = $env{'request.'.$cid.'.num'};
 2594:             }
 2595:             my $value = $accesshash{$entry};
 2596:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2597:             my %temphash=($url => $value);
 2598:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2599:             if ($result eq 'ok') {
 2600:                 delete $accesshash{$entry};
 2601:             } elsif ($result eq 'unknown_cmd') {
 2602:                 # Target server has old code running on it.
 2603:                 my %temphash=($entry => $value);
 2604:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2605:                     delete $accesshash{$entry};
 2606:                 }
 2607:             }
 2608:         } else {
 2609:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2610:             my %temphash=($entry => $accesshash{$entry});
 2611:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2612:                 delete $accesshash{$entry};
 2613:             }
 2614:         }
 2615:     }
 2616: #
 2617: # Roles
 2618: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2619: #
 2620:     foreach my $entry (keys(%userrolehash)) {
 2621:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2622: 	    split(/\:/,$entry);
 2623:         if (&Apache::lonnet::put('nohist_userroles',
 2624:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2625:                 $rudom,$runame) eq 'ok') {
 2626: 	    delete $userrolehash{$entry};
 2627:         }
 2628:     }
 2629: #
 2630: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2631: #
 2632:     my %domrolebuffer = ();
 2633:     foreach my $entry (keys(%domainrolehash)) {
 2634:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2635:         if ($domrolebuffer{$rudom}) {
 2636:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2637:                       '='.&escape($domainrolehash{$entry});
 2638:         } else {
 2639:             $domrolebuffer{$rudom}.=&escape($entry).
 2640:                       '='.&escape($domainrolehash{$entry});
 2641:         }
 2642:         delete $domainrolehash{$entry};
 2643:     }
 2644:     foreach my $dom (keys(%domrolebuffer)) {
 2645: 	my %servers = &get_servers($dom,'library');
 2646: 	foreach my $tryserver (keys(%servers)) {
 2647: 	    unless (&reply('domroleput:'.$dom.':'.
 2648: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2649: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2650: 	    }
 2651:         }
 2652:     }
 2653:     $dumpcount++;
 2654: }
 2655: 
 2656: sub courselog {
 2657:     my $what=shift;
 2658:     $what=time.':'.$what;
 2659:     unless ($env{'request.course.id'}) { return ''; }
 2660:     $coursedombuf{$env{'request.course.id'}}=
 2661:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2662:     $coursenumbuf{$env{'request.course.id'}}=
 2663:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2664:     $coursehombuf{$env{'request.course.id'}}=
 2665:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2666:     $coursedescrbuf{$env{'request.course.id'}}=
 2667:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2668:     $courseinstcodebuf{$env{'request.course.id'}}=
 2669:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2670:     $courseownerbuf{$env{'request.course.id'}}=
 2671:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2672:     $coursetypebuf{$env{'request.course.id'}}=
 2673:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2674:     if (defined $courselogs{$env{'request.course.id'}}) {
 2675: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2676:     } else {
 2677: 	$courselogs{$env{'request.course.id'}}.=$what;
 2678:     }
 2679:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2680: 	&flushcourselogs();
 2681:     }
 2682: }
 2683: 
 2684: sub courseacclog {
 2685:     my $fnsymb=shift;
 2686:     unless ($env{'request.course.id'}) { return ''; }
 2687:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2688:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2689:         $what.=':POST';
 2690:         # FIXME: Probably ought to escape things....
 2691: 	foreach my $key (keys(%env)) {
 2692:             if ($key=~/^form\.(.*)/) {
 2693:                 my $formitem = $1;
 2694:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2695:                     $what.=':'.$formitem.'='.$env{$key};
 2696:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2697:                     $what.=':'.$formitem.'='.$env{$key};
 2698:                 }
 2699:             }
 2700:         }
 2701:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2702:         # FIXME: We should not be depending on a form parameter that someone
 2703:         # editing lonsearchcat.pm might change in the future.
 2704:         if ($env{'form.phase'} eq 'course_search') {
 2705:             $what.= ':POST';
 2706:             # FIXME: Probably ought to escape things....
 2707:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2708:                                  'crsdiscuss') {
 2709:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2710:             }
 2711:         }
 2712:     }
 2713:     &courselog($what);
 2714: }
 2715: 
 2716: sub countacc {
 2717:     my $url=&declutter(shift);
 2718:     return if (! defined($url) || $url eq '');
 2719:     unless ($env{'request.course.id'}) { return ''; }
 2720:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2721:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2722:     $accesshash{$key}++;
 2723: }
 2724: 
 2725: sub linklog {
 2726:     my ($from,$to)=@_;
 2727:     $from=&declutter($from);
 2728:     $to=&declutter($to);
 2729:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2730:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2731: }
 2732:   
 2733: sub userrolelog {
 2734:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2735:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2736:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2737:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2738:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 2739:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2740:        $userrolehash
 2741:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2742:                     =$tend.':'.$tstart;
 2743:     }
 2744:     if (($env{'request.role'} =~ /dc\./) &&
 2745: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2746: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2747: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 2748:          ($trole=~/^co/))) {
 2749:        $userrolehash
 2750:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2751:                     =$tend.':'.$tstart;
 2752:     }
 2753:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2754:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2755:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2756:         ($trole=~/^sc/)) {
 2757:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2758:        $domainrolehash
 2759:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2760:                     = $tend.':'.$tstart;
 2761:     }
 2762: }
 2763: 
 2764: sub courserolelog {
 2765:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2766:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2767:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2768:         ($trole eq 'ta') || ($trole eq 'st') ||
 2769:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 2770:         ($trole eq 'co')) {
 2771:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2772:             my $cdom = $1;
 2773:             my $cnum = $2;
 2774:             my $sec = $3;
 2775:             my $namespace = 'rolelog';
 2776:             my %storehash = (
 2777:                                role    => $trole,
 2778:                                start   => $tstart,
 2779:                                end     => $tend,
 2780:                                selfenroll => $selfenroll,
 2781:                                context    => $context,
 2782:                             );
 2783:             if ($trole eq 'gr') {
 2784:                 $namespace = 'groupslog';
 2785:                 $storehash{'group'} = $sec;
 2786:             } else {
 2787:                 $storehash{'section'} = $sec;
 2788:             }
 2789:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2790:             if (($trole ne 'st') || ($sec ne '')) {
 2791:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2792:             }
 2793:         }
 2794:     }
 2795:     return;
 2796: }
 2797: 
 2798: sub get_course_adv_roles {
 2799:     my ($cid,$codes) = @_;
 2800:     $cid=$env{'request.course.id'} unless (defined($cid));
 2801:     my %coursehash=&coursedescription($cid);
 2802:     my $crstype = &Apache::loncommon::course_type($cid);
 2803:     my %nothide=();
 2804:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2805:         if ($user !~ /:/) {
 2806: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2807:         } else {
 2808:             $nothide{$user}=1;
 2809:         }
 2810:     }
 2811:     my %returnhash=();
 2812:     my %dumphash=
 2813:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2814:     my $now=time;
 2815:     my %privileged;
 2816:     foreach my $entry (keys(%dumphash)) {
 2817: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2818:         if (($tstart) && ($tstart<0)) { next; }
 2819:         if (($tend) && ($tend<$now)) { next; }
 2820:         if (($tstart) && ($now<$tstart)) { next; }
 2821:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2822: 	if ($username eq '' || $domain eq '') { next; }
 2823:         unless (ref($privileged{$domain}) eq 'HASH') {
 2824:             my %dompersonnel =
 2825:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2826:             $privileged{$domain} = {};
 2827:             foreach my $server (keys(%dompersonnel)) {
 2828:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2829:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2830:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2831:                         $privileged{$udom}{$uname} = 1;
 2832:                     }
 2833:                 }
 2834:             }
 2835:         }
 2836:         if ((exists($privileged{$domain}{$username})) && 
 2837:             (!$nothide{$username.':'.$domain})) { next; }
 2838: 	if ($role eq 'cr') { next; }
 2839:         if ($codes) {
 2840:             if ($section) { $role .= ':'.$section; }
 2841:             if ($returnhash{$role}) {
 2842:                 $returnhash{$role}.=','.$username.':'.$domain;
 2843:             } else {
 2844:                 $returnhash{$role}=$username.':'.$domain;
 2845:             }
 2846:         } else {
 2847:             my $key=&plaintext($role,$crstype);
 2848:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2849:             if ($returnhash{$key}) {
 2850: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2851:             } else {
 2852:                 $returnhash{$key}=$username.':'.$domain;
 2853:             }
 2854:         }
 2855:     }
 2856:     return %returnhash;
 2857: }
 2858: 
 2859: sub get_my_roles {
 2860:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2861:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2862:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2863:     my (%dumphash,%nothide);
 2864:     if ($context eq 'userroles') { 
 2865:         %dumphash = &dump('roles',$udom,$uname);
 2866:     } else {
 2867:         %dumphash=
 2868:             &dump('nohist_userroles',$udom,$uname);
 2869:         if ($hidepriv) {
 2870:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2871:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2872:                 if ($user !~ /:/) {
 2873:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2874:                 } else {
 2875:                     $nothide{$user} = 1;
 2876:                 }
 2877:             }
 2878:         }
 2879:     }
 2880:     my %returnhash=();
 2881:     my $now=time;
 2882:     my %privileged;
 2883:     foreach my $entry (keys(%dumphash)) {
 2884:         my ($role,$tend,$tstart);
 2885:         if ($context eq 'userroles') {
 2886: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2887:         } else {
 2888:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2889:         }
 2890:         if (($tstart) && ($tstart<0)) { next; }
 2891:         my $status = 'active';
 2892:         if (($tend) && ($tend<=$now)) {
 2893:             $status = 'previous';
 2894:         } 
 2895:         if (($tstart) && ($now<$tstart)) {
 2896:             $status = 'future';
 2897:         }
 2898:         if (ref($types) eq 'ARRAY') {
 2899:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2900:                 next;
 2901:             } 
 2902:         } else {
 2903:             if ($status ne 'active') {
 2904:                 next;
 2905:             }
 2906:         }
 2907:         my ($rolecode,$username,$domain,$section,$area);
 2908:         if ($context eq 'userroles') {
 2909:             ($area,$rolecode) = split(/_/,$entry);
 2910:             (undef,$domain,$username,$section) = split(/\//,$area);
 2911:         } else {
 2912:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2913:         }
 2914:         if (ref($roledoms) eq 'ARRAY') {
 2915:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2916:                 next;
 2917:             }
 2918:         }
 2919:         if (ref($roles) eq 'ARRAY') {
 2920:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2921:                 if ($role =~ /^cr\//) {
 2922:                     if (!grep(/^cr$/,@{$roles})) {
 2923:                         next;
 2924:                     }
 2925:                 } else {
 2926:                     next;
 2927:                 }
 2928:             }
 2929:         }
 2930:         if ($hidepriv) {
 2931:             if ($context eq 'userroles') {
 2932:                 if ((&privileged($username,$domain)) &&
 2933:                     (!$nothide{$username.':'.$domain})) {
 2934:                     next;
 2935:                 }
 2936:             } else {
 2937:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2938:                     my %dompersonnel =
 2939:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2940:                     $privileged{$domain} = {};
 2941:                     if (keys(%dompersonnel)) {
 2942:                         foreach my $server (keys(%dompersonnel)) {
 2943:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2944:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2945:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2946:                                     $privileged{$udom}{$uname} = $trole;
 2947:                                 }
 2948:                             }
 2949:                         }
 2950:                     }
 2951:                 }
 2952:                 if (exists($privileged{$domain}{$username})) {
 2953:                     if (!$nothide{$username.':'.$domain}) {
 2954:                         next;
 2955:                     }
 2956:                 }
 2957:             }
 2958:         }
 2959:         if ($withsec) {
 2960:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2961:                 $tstart.':'.$tend;
 2962:         } else {
 2963:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2964:         }
 2965:     }
 2966:     return %returnhash;
 2967: }
 2968: 
 2969: # ----------------------------------------------------- Frontpage Announcements
 2970: #
 2971: #
 2972: 
 2973: sub postannounce {
 2974:     my ($server,$text)=@_;
 2975:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2976:     unless ($text=~/\w/) { $text=''; }
 2977:     return &reply('setannounce:'.&escape($text),$server);
 2978: }
 2979: 
 2980: sub getannounce {
 2981: 
 2982:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2983: 	my $announcement='';
 2984: 	while (my $line = <$fh>) { $announcement .= $line; }
 2985: 	close($fh);
 2986: 	if ($announcement=~/\w/) { 
 2987: 	    return 
 2988:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2989:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2990: 	} else {
 2991: 	    return '';
 2992: 	}
 2993:     } else {
 2994: 	return '';
 2995:     }
 2996: }
 2997: 
 2998: # ---------------------------------------------------------- Course ID routines
 2999: # Deal with domain's nohist_courseid.db files
 3000: #
 3001: 
 3002: sub courseidput {
 3003:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3004:     my $outcome;
 3005:     if ($caller eq 'timeonly') {
 3006:         my $cids = '';
 3007:         foreach my $item (keys(%$storehash)) {
 3008:             $cids.=&escape($item).'&';
 3009:         }
 3010:         $cids=~s/\&$//;
 3011:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3012:                           $coursehome);       
 3013:     } else {
 3014:         my $items = '';
 3015:         foreach my $item (keys(%$storehash)) {
 3016:             $items.= &escape($item).'='.
 3017:                      &freeze_escape($$storehash{$item}).'&';
 3018:         }
 3019:         $items=~s/\&$//;
 3020:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3021:                           $coursehome);
 3022:     }
 3023:     if ($outcome eq 'unknown_cmd') {
 3024:         my $what;
 3025:         foreach my $cid (keys(%$storehash)) {
 3026:             $what .= &escape($cid).'=';
 3027:             foreach my $item ('description','inst_code','owner','type') {
 3028:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3029:             }
 3030:             $what =~ s/\:$/&/;
 3031:         }
 3032:         $what =~ s/\&$//;  
 3033:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3034:     } else {
 3035:         return $outcome;
 3036:     }
 3037: }
 3038: 
 3039: sub courseiddump {
 3040:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3041:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3042:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3043:         $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
 3044:     my $as_hash = 1;
 3045:     my %returnhash;
 3046:     if (!$domfilter) { $domfilter=''; }
 3047:     my %libserv = &all_library();
 3048:     foreach my $tryserver (keys(%libserv)) {
 3049:         if ( (  $hostidflag == 1 
 3050: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3051: 	     || (!defined($hostidflag)) ) {
 3052: 
 3053: 	    if (($domfilter eq '') ||
 3054: 		(&host_domain($tryserver) eq $domfilter)) {
 3055:                 my $rep = 
 3056:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3057:                          $sincefilter.':'.&escape($descfilter).':'.
 3058:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3059:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3060:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3061:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3062:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3063:                          &escape($cc_clone).':'.$cloneonly.':'.
 3064:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3065:                          &escape($creationcontext),$tryserver);
 3066:                 my @pairs=split(/\&/,$rep);
 3067:                 foreach my $item (@pairs) {
 3068:                     my ($key,$value)=split(/\=/,$item,2);
 3069:                     $key = &unescape($key);
 3070:                     next if ($key =~ /^error: 2 /);
 3071:                     my $result = &thaw_unescape($value);
 3072:                     if (ref($result) eq 'HASH') {
 3073:                         $returnhash{$key}=$result;
 3074:                     } else {
 3075:                         my @responses = split(/:/,$value);
 3076:                         my @items = ('description','inst_code','owner','type');
 3077:                         for (my $i=0; $i<@responses; $i++) {
 3078:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3079:                         }
 3080:                     }
 3081:                 }
 3082:             }
 3083:         }
 3084:     }
 3085:     return %returnhash;
 3086: }
 3087: 
 3088: # ---------------------------------------------------------- DC e-mail
 3089: 
 3090: sub dcmailput {
 3091:     my ($domain,$msgid,$message,$server)=@_;
 3092:     my $status = &Apache::lonnet::critical(
 3093:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3094:        &escape($message),$server);
 3095:     return $status;
 3096: }
 3097: 
 3098: sub dcmaildump {
 3099:     my ($dom,$startdate,$enddate,$senders) = @_;
 3100:     my %returnhash=();
 3101: 
 3102:     if (defined(&domain($dom,'primary'))) {
 3103:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3104:                                                          &escape($enddate).':';
 3105: 	my @esc_senders=map { &escape($_)} @$senders;
 3106: 	$cmd.=&escape(join('&',@esc_senders));
 3107: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3108:             my ($key,$value) = split(/\=/,$line,2);
 3109:             if (($key) && ($value)) {
 3110:                 $returnhash{&unescape($key)} = &unescape($value);
 3111:             }
 3112:         }
 3113:     }
 3114:     return %returnhash;
 3115: }
 3116: # ---------------------------------------------------------- Domain roles
 3117: 
 3118: sub get_domain_roles {
 3119:     my ($dom,$roles,$startdate,$enddate)=@_;
 3120:     if ((!defined($startdate)) || ($startdate eq '')) {
 3121:         $startdate = '.';
 3122:     }
 3123:     if ((!defined($enddate)) || ($enddate eq '')) {
 3124:         $enddate = '.';
 3125:     }
 3126:     my $rolelist;
 3127:     if (ref($roles) eq 'ARRAY') {
 3128:         $rolelist = join(':',@{$roles});
 3129:     }
 3130:     my %personnel = ();
 3131: 
 3132:     my %servers = &get_servers($dom,'library');
 3133:     foreach my $tryserver (keys(%servers)) {
 3134: 	%{$personnel{$tryserver}}=();
 3135: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3136: 					    &escape($startdate).':'.
 3137: 					    &escape($enddate).':'.
 3138: 					    &escape($rolelist), $tryserver))) {
 3139: 	    my ($key,$value) = split(/\=/,$line,2);
 3140: 	    if (($key) && ($value)) {
 3141: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3142: 	    }
 3143: 	}
 3144:     }
 3145:     return %personnel;
 3146: }
 3147: 
 3148: # ----------------------------------------------------------- Check out an item
 3149: 
 3150: sub get_first_access {
 3151:     my ($type,$argsymb)=@_;
 3152:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3153:     if ($argsymb) { $symb=$argsymb; }
 3154:     my ($map,$id,$res)=&decode_symb($symb);
 3155:     if ($type eq 'course') {
 3156: 	$res='course';
 3157:     } elsif ($type eq 'map') {
 3158: 	$res=&symbread($map);
 3159:     } else {
 3160: 	$res=$symb;
 3161:     }
 3162:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3163:     return $times{"$courseid\0$res"};
 3164: }
 3165: 
 3166: sub set_first_access {
 3167:     my ($type)=@_;
 3168:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3169:     my ($map,$id,$res)=&decode_symb($symb);
 3170:     if ($type eq 'course') {
 3171: 	$res='course';
 3172:     } elsif ($type eq 'map') {
 3173: 	$res=&symbread($map);
 3174:     } else {
 3175: 	$res=$symb;
 3176:     }
 3177:     my $firstaccess=&get_first_access($type,$symb);
 3178:     if (!$firstaccess) {
 3179: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3180:     }
 3181:     return 'already_set';
 3182: }
 3183: 
 3184: sub checkout {
 3185:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3186:     my $now=time;
 3187:     my $lonhost=$perlvar{'lonHostID'};
 3188:     my $infostr=&escape(
 3189:                  'CHECKOUTTOKEN&'.
 3190:                  $tuname.'&'.
 3191:                  $tudom.'&'.
 3192:                  $tcrsid.'&'.
 3193:                  $symb.'&'.
 3194: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3195:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3196:     if ($token=~/^error\:/) { 
 3197:         &logthis("<font color=\"blue\">WARNING: ".
 3198:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3199:                  "</font>");
 3200:         return ''; 
 3201:     }
 3202: 
 3203:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3204:     $token=~tr/a-z/A-Z/;
 3205: 
 3206:     my %infohash=('resource.0.outtoken' => $token,
 3207:                   'resource.0.checkouttime' => $now,
 3208:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3209: 
 3210:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3211:        return '';
 3212:     } else {
 3213:         &logthis("<font color=\"blue\">WARNING: ".
 3214:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3215:                  "</font>");
 3216:     }    
 3217: 
 3218:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3219:                          &escape('Checkout '.$infostr.' - '.
 3220:                                                  $token)) ne 'ok') {
 3221: 	return '';
 3222:     } else {
 3223:         &logthis("<font color=\"blue\">WARNING: ".
 3224:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3225:                  "</font>");
 3226:     }
 3227:     return $token;
 3228: }
 3229: 
 3230: # ------------------------------------------------------------ Check in an item
 3231: 
 3232: sub checkin {
 3233:     my $token=shift;
 3234:     my $now=time;
 3235:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3236:     $lonhost=~tr/A-Z/a-z/;
 3237:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3238:     $dtoken=~s/\W/\_/g;
 3239:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3240:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3241: 
 3242:     unless (($tuname) && ($tudom)) {
 3243:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3244:         return '';
 3245:     }
 3246:     
 3247:     unless (&allowed('mgr',$tcrsid)) {
 3248:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3249:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3250:         return '';
 3251:     }
 3252: 
 3253:     my %infohash=('resource.0.intoken' => $token,
 3254:                   'resource.0.checkintime' => $now,
 3255:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3256: 
 3257:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3258:        return '';
 3259:     }    
 3260: 
 3261:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3262:                          &escape('Checkin - '.$token)) ne 'ok') {
 3263: 	return '';
 3264:     }
 3265: 
 3266:     return ($symb,$tuname,$tudom,$tcrsid);    
 3267: }
 3268: 
 3269: # --------------------------------------------- Set Expire Date for Spreadsheet
 3270: 
 3271: sub expirespread {
 3272:     my ($uname,$udom,$stype,$usymb)=@_;
 3273:     my $cid=$env{'request.course.id'}; 
 3274:     if ($cid) {
 3275:        my $now=time;
 3276:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3277:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3278:                             $env{'course.'.$cid.'.num'}.
 3279: 	        	    ':nohist_expirationdates:'.
 3280:                             &escape($key).'='.$now,
 3281:                             $env{'course.'.$cid.'.home'})
 3282:     }
 3283:     return 'ok';
 3284: }
 3285: 
 3286: # ----------------------------------------------------- Devalidate Spreadsheets
 3287: 
 3288: sub devalidate {
 3289:     my ($symb,$uname,$udom)=@_;
 3290:     my $cid=$env{'request.course.id'}; 
 3291:     if ($cid) {
 3292:         # delete the stored spreadsheets for
 3293:         # - the student level sheet of this user in course's homespace
 3294:         # - the assessment level sheet for this resource 
 3295:         #   for this user in user's homespace
 3296: 	# - current conditional state info
 3297: 	my $key=$uname.':'.$udom.':';
 3298:         my $status=
 3299: 	    &del('nohist_calculatedsheets',
 3300: 		 [$key.'studentcalc:'],
 3301: 		 $env{'course.'.$cid.'.domain'},
 3302: 		 $env{'course.'.$cid.'.num'})
 3303: 		.' '.
 3304: 	    &del('nohist_calculatedsheets_'.$cid,
 3305: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3306:         unless ($status eq 'ok ok') {
 3307:            &logthis('Could not devalidate spreadsheet '.
 3308:                     $uname.' at '.$udom.' for '.
 3309: 		    $symb.': '.$status);
 3310:         }
 3311: 	&delenv('user.state.'.$cid);
 3312:     }
 3313: }
 3314: 
 3315: sub get_scalar {
 3316:     my ($string,$end) = @_;
 3317:     my $value;
 3318:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3319: 	$value = $1;
 3320:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3321: 	$value = $1;
 3322:     }
 3323:     return &unescape($value);
 3324: }
 3325: 
 3326: sub array2str {
 3327:   my (@array) = @_;
 3328:   my $result=&arrayref2str(\@array);
 3329:   $result=~s/^__ARRAY_REF__//;
 3330:   $result=~s/__END_ARRAY_REF__$//;
 3331:   return $result;
 3332: }
 3333: 
 3334: sub arrayref2str {
 3335:   my ($arrayref) = @_;
 3336:   my $result='__ARRAY_REF__';
 3337:   foreach my $elem (@$arrayref) {
 3338:     if(ref($elem) eq 'ARRAY') {
 3339:       $result.=&arrayref2str($elem).'&';
 3340:     } elsif(ref($elem) eq 'HASH') {
 3341:       $result.=&hashref2str($elem).'&';
 3342:     } elsif(ref($elem)) {
 3343:       #print("Got a ref of ".(ref($elem))." skipping.");
 3344:     } else {
 3345:       $result.=&escape($elem).'&';
 3346:     }
 3347:   }
 3348:   $result=~s/\&$//;
 3349:   $result .= '__END_ARRAY_REF__';
 3350:   return $result;
 3351: }
 3352: 
 3353: sub hash2str {
 3354:   my (%hash) = @_;
 3355:   my $result=&hashref2str(\%hash);
 3356:   $result=~s/^__HASH_REF__//;
 3357:   $result=~s/__END_HASH_REF__$//;
 3358:   return $result;
 3359: }
 3360: 
 3361: sub hashref2str {
 3362:   my ($hashref)=@_;
 3363:   my $result='__HASH_REF__';
 3364:   foreach my $key (sort(keys(%$hashref))) {
 3365:     if (ref($key) eq 'ARRAY') {
 3366:       $result.=&arrayref2str($key).'=';
 3367:     } elsif (ref($key) eq 'HASH') {
 3368:       $result.=&hashref2str($key).'=';
 3369:     } elsif (ref($key)) {
 3370:       $result.='=';
 3371:       #print("Got a ref of ".(ref($key))." skipping.");
 3372:     } else {
 3373: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3374:     }
 3375: 
 3376:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3377:       $result.=&arrayref2str($hashref->{$key}).'&';
 3378:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3379:       $result.=&hashref2str($hashref->{$key}).'&';
 3380:     } elsif(ref($hashref->{$key})) {
 3381:        $result.='&';
 3382:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3383:     } else {
 3384:       $result.=&escape($hashref->{$key}).'&';
 3385:     }
 3386:   }
 3387:   $result=~s/\&$//;
 3388:   $result .= '__END_HASH_REF__';
 3389:   return $result;
 3390: }
 3391: 
 3392: sub str2hash {
 3393:     my ($string)=@_;
 3394:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3395:     return %$hash;
 3396: }
 3397: 
 3398: sub str2hashref {
 3399:   my ($string) = @_;
 3400: 
 3401:   my %hash;
 3402: 
 3403:   if($string !~ /^__HASH_REF__/) {
 3404:       if (! ($string eq '' || !defined($string))) {
 3405: 	  $hash{'error'}='Not hash reference';
 3406:       }
 3407:       return (\%hash, $string);
 3408:   }
 3409: 
 3410:   $string =~ s/^__HASH_REF__//;
 3411: 
 3412:   while($string !~ /^__END_HASH_REF__/) {
 3413:       #key
 3414:       my $key='';
 3415:       if($string =~ /^__HASH_REF__/) {
 3416:           ($key, $string)=&str2hashref($string);
 3417:           if(defined($key->{'error'})) {
 3418:               $hash{'error'}='Bad data';
 3419:               return (\%hash, $string);
 3420:           }
 3421:       } elsif($string =~ /^__ARRAY_REF__/) {
 3422:           ($key, $string)=&str2arrayref($string);
 3423:           if($key->[0] eq 'Array reference error') {
 3424:               $hash{'error'}='Bad data';
 3425:               return (\%hash, $string);
 3426:           }
 3427:       } else {
 3428:           $string =~ s/^(.*?)=//;
 3429: 	  $key=&unescape($1);
 3430:       }
 3431:       $string =~ s/^=//;
 3432: 
 3433:       #value
 3434:       my $value='';
 3435:       if($string =~ /^__HASH_REF__/) {
 3436:           ($value, $string)=&str2hashref($string);
 3437:           if(defined($value->{'error'})) {
 3438:               $hash{'error'}='Bad data';
 3439:               return (\%hash, $string);
 3440:           }
 3441:       } elsif($string =~ /^__ARRAY_REF__/) {
 3442:           ($value, $string)=&str2arrayref($string);
 3443:           if($value->[0] eq 'Array reference error') {
 3444:               $hash{'error'}='Bad data';
 3445:               return (\%hash, $string);
 3446:           }
 3447:       } else {
 3448: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3449:       }
 3450:       $string =~ s/^&//;
 3451: 
 3452:       $hash{$key}=$value;
 3453:   }
 3454: 
 3455:   $string =~ s/^__END_HASH_REF__//;
 3456: 
 3457:   return (\%hash, $string);
 3458: }
 3459: 
 3460: sub str2array {
 3461:     my ($string)=@_;
 3462:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3463:     return @$array;
 3464: }
 3465: 
 3466: sub str2arrayref {
 3467:   my ($string) = @_;
 3468:   my @array;
 3469: 
 3470:   if($string !~ /^__ARRAY_REF__/) {
 3471:       if (! ($string eq '' || !defined($string))) {
 3472: 	  $array[0]='Array reference error';
 3473:       }
 3474:       return (\@array, $string);
 3475:   }
 3476: 
 3477:   $string =~ s/^__ARRAY_REF__//;
 3478: 
 3479:   while($string !~ /^__END_ARRAY_REF__/) {
 3480:       my $value='';
 3481:       if($string =~ /^__HASH_REF__/) {
 3482:           ($value, $string)=&str2hashref($string);
 3483:           if(defined($value->{'error'})) {
 3484:               $array[0] ='Array reference error';
 3485:               return (\@array, $string);
 3486:           }
 3487:       } elsif($string =~ /^__ARRAY_REF__/) {
 3488:           ($value, $string)=&str2arrayref($string);
 3489:           if($value->[0] eq 'Array reference error') {
 3490:               $array[0] ='Array reference error';
 3491:               return (\@array, $string);
 3492:           }
 3493:       } else {
 3494: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3495:       }
 3496:       $string =~ s/^&//;
 3497: 
 3498:       push(@array, $value);
 3499:   }
 3500: 
 3501:   $string =~ s/^__END_ARRAY_REF__//;
 3502: 
 3503:   return (\@array, $string);
 3504: }
 3505: 
 3506: # -------------------------------------------------------------------Temp Store
 3507: 
 3508: sub tmpreset {
 3509:   my ($symb,$namespace,$domain,$stuname) = @_;
 3510:   if (!$symb) {
 3511:     $symb=&symbread();
 3512:     if (!$symb) { $symb= $env{'request.url'}; }
 3513:   }
 3514:   $symb=escape($symb);
 3515: 
 3516:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3517:   $namespace=~s/\//\_/g;
 3518:   $namespace=~s/\W//g;
 3519: 
 3520:   if (!$domain) { $domain=$env{'user.domain'}; }
 3521:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3522:   if ($domain eq 'public' && $stuname eq 'public') {
 3523:       $stuname=$ENV{'REMOTE_ADDR'};
 3524:   }
 3525:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3526:   my %hash;
 3527:   if (tie(%hash,'GDBM_File',
 3528: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3529: 	  &GDBM_WRCREAT(),0640)) {
 3530:     foreach my $key (keys(%hash)) {
 3531:       if ($key=~ /:$symb/) {
 3532: 	delete($hash{$key});
 3533:       }
 3534:     }
 3535:   }
 3536: }
 3537: 
 3538: sub tmpstore {
 3539:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3540: 
 3541:   if (!$symb) {
 3542:     $symb=&symbread();
 3543:     if (!$symb) { $symb= $env{'request.url'}; }
 3544:   }
 3545:   $symb=escape($symb);
 3546: 
 3547:   if (!$namespace) {
 3548:     # I don't think we would ever want to store this for a course.
 3549:     # it seems this will only be used if we don't have a course.
 3550:     #$namespace=$env{'request.course.id'};
 3551:     #if (!$namespace) {
 3552:       $namespace=$env{'request.state'};
 3553:     #}
 3554:   }
 3555:   $namespace=~s/\//\_/g;
 3556:   $namespace=~s/\W//g;
 3557:   if (!$domain) { $domain=$env{'user.domain'}; }
 3558:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3559:   if ($domain eq 'public' && $stuname eq 'public') {
 3560:       $stuname=$ENV{'REMOTE_ADDR'};
 3561:   }
 3562:   my $now=time;
 3563:   my %hash;
 3564:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3565:   if (tie(%hash,'GDBM_File',
 3566: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3567: 	  &GDBM_WRCREAT(),0640)) {
 3568:     $hash{"version:$symb"}++;
 3569:     my $version=$hash{"version:$symb"};
 3570:     my $allkeys=''; 
 3571:     foreach my $key (keys(%$storehash)) {
 3572:       $allkeys.=$key.':';
 3573:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3574:     }
 3575:     $hash{"$version:$symb:timestamp"}=$now;
 3576:     $allkeys.='timestamp';
 3577:     $hash{"$version:keys:$symb"}=$allkeys;
 3578:     if (untie(%hash)) {
 3579:       return 'ok';
 3580:     } else {
 3581:       return "error:$!";
 3582:     }
 3583:   } else {
 3584:     return "error:$!";
 3585:   }
 3586: }
 3587: 
 3588: # -----------------------------------------------------------------Temp Restore
 3589: 
 3590: sub tmprestore {
 3591:   my ($symb,$namespace,$domain,$stuname) = @_;
 3592: 
 3593:   if (!$symb) {
 3594:     $symb=&symbread();
 3595:     if (!$symb) { $symb= $env{'request.url'}; }
 3596:   }
 3597:   $symb=escape($symb);
 3598: 
 3599:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3600: 
 3601:   if (!$domain) { $domain=$env{'user.domain'}; }
 3602:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3603:   if ($domain eq 'public' && $stuname eq 'public') {
 3604:       $stuname=$ENV{'REMOTE_ADDR'};
 3605:   }
 3606:   my %returnhash;
 3607:   $namespace=~s/\//\_/g;
 3608:   $namespace=~s/\W//g;
 3609:   my %hash;
 3610:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3611:   if (tie(%hash,'GDBM_File',
 3612: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3613: 	  &GDBM_READER(),0640)) {
 3614:     my $version=$hash{"version:$symb"};
 3615:     $returnhash{'version'}=$version;
 3616:     my $scope;
 3617:     for ($scope=1;$scope<=$version;$scope++) {
 3618:       my $vkeys=$hash{"$scope:keys:$symb"};
 3619:       my @keys=split(/:/,$vkeys);
 3620:       my $key;
 3621:       $returnhash{"$scope:keys"}=$vkeys;
 3622:       foreach $key (@keys) {
 3623: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3624: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3625:       }
 3626:     }
 3627:     if (!(untie(%hash))) {
 3628:       return "error:$!";
 3629:     }
 3630:   } else {
 3631:     return "error:$!";
 3632:   }
 3633:   return %returnhash;
 3634: }
 3635: 
 3636: # ----------------------------------------------------------------------- Store
 3637: 
 3638: sub store {
 3639:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3640:     my $home='';
 3641: 
 3642:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3643: 
 3644:     $symb=&symbclean($symb);
 3645:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3646: 
 3647:     if (!$domain) { $domain=$env{'user.domain'}; }
 3648:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3649: 
 3650:     &devalidate($symb,$stuname,$domain);
 3651: 
 3652:     $symb=escape($symb);
 3653:     if (!$namespace) { 
 3654:        unless ($namespace=$env{'request.course.id'}) { 
 3655:           return ''; 
 3656:        } 
 3657:     }
 3658:     if (!$home) { $home=$env{'user.home'}; }
 3659: 
 3660:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3661:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3662: 
 3663:     my $namevalue='';
 3664:     foreach my $key (keys(%$storehash)) {
 3665:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3666:     }
 3667:     $namevalue=~s/\&$//;
 3668:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3669:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3670: }
 3671: 
 3672: # -------------------------------------------------------------- Critical Store
 3673: 
 3674: sub cstore {
 3675:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3676:     my $home='';
 3677: 
 3678:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3679: 
 3680:     $symb=&symbclean($symb);
 3681:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3682: 
 3683:     if (!$domain) { $domain=$env{'user.domain'}; }
 3684:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3685: 
 3686:     &devalidate($symb,$stuname,$domain);
 3687: 
 3688:     $symb=escape($symb);
 3689:     if (!$namespace) { 
 3690:        unless ($namespace=$env{'request.course.id'}) { 
 3691:           return ''; 
 3692:        } 
 3693:     }
 3694:     if (!$home) { $home=$env{'user.home'}; }
 3695: 
 3696:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3697:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3698: 
 3699:     my $namevalue='';
 3700:     foreach my $key (keys(%$storehash)) {
 3701:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3702:     }
 3703:     $namevalue=~s/\&$//;
 3704:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3705:     return critical
 3706:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3707: }
 3708: 
 3709: # --------------------------------------------------------------------- Restore
 3710: 
 3711: sub restore {
 3712:     my ($symb,$namespace,$domain,$stuname) = @_;
 3713:     my $home='';
 3714: 
 3715:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3716: 
 3717:     if (!$symb) {
 3718:       unless ($symb=escape(&symbread())) { return ''; }
 3719:     } else {
 3720:       $symb=&escape(&symbclean($symb));
 3721:     }
 3722:     if (!$namespace) { 
 3723:        unless ($namespace=$env{'request.course.id'}) { 
 3724:           return ''; 
 3725:        } 
 3726:     }
 3727:     if (!$domain) { $domain=$env{'user.domain'}; }
 3728:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3729:     if (!$home) { $home=$env{'user.home'}; }
 3730:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3731: 
 3732:     my %returnhash=();
 3733:     foreach my $line (split(/\&/,$answer)) {
 3734: 	my ($name,$value)=split(/\=/,$line);
 3735:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3736:     }
 3737:     my $version;
 3738:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3739:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3740:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3741:        }
 3742:     }
 3743:     return %returnhash;
 3744: }
 3745: 
 3746: # ---------------------------------------------------------- Course Description
 3747: 
 3748: sub coursedescription {
 3749:     my ($courseid,$args)=@_;
 3750:     $courseid=~s/^\///;
 3751:     $courseid=~s/\_/\//g;
 3752:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3753:     my $chome=&homeserver($cnum,$cdomain);
 3754:     my $normalid=$cdomain.'_'.$cnum;
 3755:     # need to always cache even if we get errors otherwise we keep 
 3756:     # trying and trying and trying to get the course description.
 3757:     my %envhash=();
 3758:     my %returnhash=();
 3759:     
 3760:     my $expiretime=600;
 3761:     if ($env{'request.course.id'} eq $normalid) {
 3762: 	$expiretime=120;
 3763:     }
 3764: 
 3765:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3766:     if (!$args->{'freshen_cache'}
 3767: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3768: 	foreach my $key (keys(%env)) {
 3769: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3770: 	    my ($setting) = $1;
 3771: 	    $returnhash{$setting} = $env{$key};
 3772: 	}
 3773: 	return %returnhash;
 3774:     }
 3775: 
 3776:     # get the data agin
 3777:     if (!$args->{'one_time'}) {
 3778: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3779:     }
 3780: 
 3781:     if ($chome ne 'no_host') {
 3782:        %returnhash=&dump('environment',$cdomain,$cnum);
 3783:        if (!exists($returnhash{'con_lost'})) {
 3784:            $returnhash{'home'}= $chome;
 3785: 	   $returnhash{'domain'} = $cdomain;
 3786: 	   $returnhash{'num'} = $cnum;
 3787:            if (!defined($returnhash{'type'})) {
 3788:                $returnhash{'type'} = 'Course';
 3789:            }
 3790:            while (my ($name,$value) = each %returnhash) {
 3791:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3792:            }
 3793:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3794:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3795: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3796:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3797:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3798:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3799:        }
 3800:     }
 3801:     if (!$args->{'one_time'}) {
 3802: 	&appenv(\%envhash);
 3803:     }
 3804:     return %returnhash;
 3805: }
 3806: 
 3807: # -------------------------------------------------See if a user is privileged
 3808: 
 3809: sub privileged {
 3810:     my ($username,$domain)=@_;
 3811:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3812: 			&homeserver($username,$domain));
 3813:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3814:         ($rolesdump =~ /^error:/)) {
 3815:         return 0;
 3816:     }
 3817:     my $now=time;
 3818:     if ($rolesdump ne '') {
 3819:         foreach my $entry (split(/&/,$rolesdump)) {
 3820: 	    if ($entry!~/^rolesdef_/) {
 3821: 		my ($area,$role)=split(/=/,$entry);
 3822: 		$area=~s/\_\w\w$//;
 3823: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3824: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3825: 		    my $active=1;
 3826: 		    if ($tend) {
 3827: 			if ($tend<$now) { $active=0; }
 3828: 		    }
 3829: 		    if ($tstart) {
 3830: 			if ($tstart>$now) { $active=0; }
 3831: 		    }
 3832: 		    if ($active) { return 1; }
 3833: 		}
 3834: 	    }
 3835: 	}
 3836:     }
 3837:     return 0;
 3838: }
 3839: 
 3840: # -------------------------------------------------------- Get user privileges
 3841: 
 3842: sub rolesinit {
 3843:     my ($domain,$username,$authhost)=@_;
 3844:     my $now=time;
 3845:     my %userroles = ('user.login.time' => $now);
 3846:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3847:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3848:         ($rolesdump =~ /^error:/)) { 
 3849:         return \%userroles;
 3850:     }
 3851:     my %allroles=();
 3852:     my %allgroups=();   
 3853:     my $group_privs;
 3854: 
 3855:     if ($rolesdump ne '') {
 3856:         foreach my $entry (split(/&/,$rolesdump)) {
 3857: 	  if ($entry!~/^rolesdef_/) {
 3858:             my ($area,$role)=split(/=/,$entry);
 3859: 	    $area=~s/\_\w\w$//;
 3860:             my ($trole,$tend,$tstart,$group_privs);
 3861: 	    if ($role=~/^cr/) { 
 3862: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3863: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3864: 		    ($tend,$tstart)=split('_',$trest);
 3865: 		} else {
 3866: 		    $trole=$role;
 3867: 		}
 3868:             } elsif ($role =~ m|^gr/|) {
 3869:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3870:                 ($trole,$group_privs) = split(/\//,$trole);
 3871:                 $group_privs = &unescape($group_privs);
 3872: 	    } else {
 3873: 		($trole,$tend,$tstart)=split(/_/,$role);
 3874: 	    }
 3875: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3876: 					 $username);
 3877: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3878:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3879:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3880:             if (($area ne '') && ($trole ne '')) {
 3881: 		my $spec=$trole.'.'.$area;
 3882: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3883: 		if ($trole =~ /^cr\//) {
 3884:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3885:                 } elsif ($trole eq 'gr') {
 3886:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3887: 		} else {
 3888:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3889: 		}
 3890:             }
 3891:           }
 3892:         }
 3893:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3894:         $userroles{'user.adv'}    = $adv;
 3895: 	$userroles{'user.author'} = $author;
 3896:         $env{'user.adv'}=$adv;
 3897:     }
 3898:     return \%userroles;  
 3899: }
 3900: 
 3901: sub set_arearole {
 3902:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3903: # log the associated role with the area
 3904:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3905:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3906: }
 3907: 
 3908: sub custom_roleprivs {
 3909:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3910:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3911:     my $homsvr=homeserver($rauthor,$rdomain);
 3912:     if (&hostname($homsvr) ne '') {
 3913:         my ($rdummy,$roledef)=
 3914:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3915:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3916:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3917:             if (defined($syspriv)) {
 3918:                 if ($trest =~ /^$match_community$/) {
 3919:                     $syspriv =~ s/bre\&S//; 
 3920:                 }
 3921:                 $$allroles{'cm./'}.=':'.$syspriv;
 3922:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3923:             }
 3924:             if ($tdomain ne '') {
 3925:                 if (defined($dompriv)) {
 3926:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3927:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3928:                 }
 3929:                 if (($trest ne '') && (defined($coursepriv))) {
 3930:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3931:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3932:                 }
 3933:             }
 3934:         }
 3935:     }
 3936: }
 3937: 
 3938: sub group_roleprivs {
 3939:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3940:     my $access = 1;
 3941:     my $now = time;
 3942:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3943:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3944:     if ($access) {
 3945:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3946:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3947:     }
 3948: }
 3949: 
 3950: sub standard_roleprivs {
 3951:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3952:     if (defined($pr{$trole.':s'})) {
 3953:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3954:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3955:     }
 3956:     if ($tdomain ne '') {
 3957:         if (defined($pr{$trole.':d'})) {
 3958:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3959:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3960:         }
 3961:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3962:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3963:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3964:         }
 3965:     }
 3966: }
 3967: 
 3968: sub set_userprivs {
 3969:     my ($userroles,$allroles,$allgroups) = @_; 
 3970:     my $author=0;
 3971:     my $adv=0;
 3972:     my %grouproles = ();
 3973:     if (keys(%{$allgroups}) > 0) {
 3974:         foreach my $role (keys(%{$allroles})) {
 3975:             my ($trole,$area,$sec,$extendedarea);
 3976:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3977:                 $trole = $1;
 3978:                 $area = $2;
 3979:                 $sec = $3;
 3980:                 $extendedarea = $area.$sec;
 3981:                 if (exists($$allgroups{$area})) {
 3982:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3983:                         my $spec = $trole.'.'.$extendedarea;
 3984:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3985:                                                 $$allgroups{$area}{$group};
 3986:                     }
 3987:                 }
 3988:             }
 3989:         }
 3990:     }
 3991:     foreach my $group (keys(%grouproles)) {
 3992:         $$allroles{$group} = $grouproles{$group};
 3993:     }
 3994:     foreach my $role (keys(%{$allroles})) {
 3995:         my %thesepriv;
 3996:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3997:         foreach my $item (split(/:/,$$allroles{$role})) {
 3998:             if ($item ne '') {
 3999:                 my ($privilege,$restrictions)=split(/&/,$item);
 4000:                 if ($restrictions eq '') {
 4001:                     $thesepriv{$privilege}='F';
 4002:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4003:                     $thesepriv{$privilege}.=$restrictions;
 4004:                 }
 4005:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4006:             }
 4007:         }
 4008:         my $thesestr='';
 4009:         foreach my $priv (keys(%thesepriv)) {
 4010: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4011: 	}
 4012:         $userroles->{'user.priv.'.$role} = $thesestr;
 4013:     }
 4014:     return ($author,$adv);
 4015: }
 4016: 
 4017: sub role_status {
 4018:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4019:     my @pwhere = ();
 4020:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4021:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4022:         unless (!defined($$role) || $$role eq '') {
 4023:             $$where=join('.',@pwhere);
 4024:             $$trolecode=$$role.'.'.$$where;
 4025:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4026:             $$tstatus='is';
 4027:             if ($$tstart && $$tstart>$then) {
 4028:                 $$tstatus='future';
 4029:                 if ($$tstart<$now) {
 4030:                     if ($$tstart && $$tstart>$refresh) {
 4031:                         if (($$where ne '') && ($$role ne '')) {
 4032:                             my (%allroles,%allgroups,$group_privs);
 4033:                             my %userroles = (
 4034:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4035:                             );
 4036:                             my $spec=$$role.'.'.$$where;
 4037:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4038:                             if ($$role eq 'gr') {
 4039:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4040:                                                     $env{'user.name'})=@_;
 4041:                                 my ($trole) = split('_',$role,1);
 4042:                                 (undef,my $group_privs) = split(/\//,$trole);
 4043:                                 $group_privs = &unescape($group_privs);
 4044:                             }
 4045:                             if ($$role =~ /^cr\//) {
 4046:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4047:                             } elsif ($$role eq 'gr') {
 4048:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4049:                                                     $env{'user.name'});
 4050:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 4051:                                 (undef,my $group_privs) = split(/\//,$trole);
 4052:                                 $group_privs = &unescape($group_privs);
 4053:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4054:                             } else {
 4055:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4056:                             }
 4057:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4058:                             &appenv(\%userroles,[$$role,'cm']);
 4059:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4060:                         }
 4061:                     }
 4062:                     $$tstatus = 'is';
 4063:                 }
 4064:             }
 4065:             if ($$tend) {
 4066:                 if ($$tend<$then) {
 4067:                     $$tstatus='expired';
 4068:                 } elsif ($$tend<$now) {
 4069:                     $$tstatus='will_not';
 4070:                 }
 4071:             }
 4072:         }
 4073:     }
 4074: }
 4075: 
 4076: sub check_adhoc_privs {
 4077:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 4078:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4079:     if ($env{$cckey}) {
 4080:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4081:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4082:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4083:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4084:         }
 4085:     } else {
 4086:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4087:     }
 4088: }
 4089: 
 4090: sub set_adhoc_privileges {
 4091: # role can be cc or ca
 4092:     my ($dcdom,$pickedcourse,$role) = @_;
 4093:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4094:     my $spec = $role.'.'.$area;
 4095:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4096:                                   $env{'user.name'});
 4097:     my %ccrole = ();
 4098:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4099:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4100:     &appenv(\%userroles,[$role,'cm']);
 4101:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4102:     &appenv( {'request.role'        => $spec,
 4103:               'request.role.domain' => $dcdom,
 4104:               'request.course.sec'  => ''
 4105:              }
 4106:            );
 4107:     my $tadv=0;
 4108:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4109:     &appenv({'request.role.adv'    => $tadv});
 4110: }
 4111: 
 4112: # --------------------------------------------------------------- get interface
 4113: 
 4114: sub get {
 4115:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4116:    my $items='';
 4117:    foreach my $item (@$storearr) {
 4118:        $items.=&escape($item).'&';
 4119:    }
 4120:    $items=~s/\&$//;
 4121:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4122:    if (!$uname) { $uname=$env{'user.name'}; }
 4123:    my $uhome=&homeserver($uname,$udomain);
 4124: 
 4125:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4126:    my @pairs=split(/\&/,$rep);
 4127:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4128:      return @pairs;
 4129:    }
 4130:    my %returnhash=();
 4131:    my $i=0;
 4132:    foreach my $item (@$storearr) {
 4133:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4134:       $i++;
 4135:    }
 4136:    return %returnhash;
 4137: }
 4138: 
 4139: # --------------------------------------------------------------- del interface
 4140: 
 4141: sub del {
 4142:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4143:    my $items='';
 4144:    foreach my $item (@$storearr) {
 4145:        $items.=&escape($item).'&';
 4146:    }
 4147: 
 4148:    $items=~s/\&$//;
 4149:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4150:    if (!$uname) { $uname=$env{'user.name'}; }
 4151:    my $uhome=&homeserver($uname,$udomain);
 4152:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4153: }
 4154: 
 4155: # -------------------------------------------------------------- dump interface
 4156: 
 4157: sub dump {
 4158:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4159:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4160:     if (!$uname) { $uname=$env{'user.name'}; }
 4161:     my $uhome=&homeserver($uname,$udomain);
 4162:     if ($regexp) {
 4163: 	$regexp=&escape($regexp);
 4164:     } else {
 4165: 	$regexp='.';
 4166:     }
 4167:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4168:     my @pairs=split(/\&/,$rep);
 4169:     my %returnhash=();
 4170:     foreach my $item (@pairs) {
 4171: 	my ($key,$value)=split(/=/,$item,2);
 4172: 	$key = &unescape($key);
 4173: 	next if ($key =~ /^error: 2 /);
 4174: 	$returnhash{$key}=&thaw_unescape($value);
 4175:     }
 4176:     return %returnhash;
 4177: }
 4178: 
 4179: # --------------------------------------------------------- dumpstore interface
 4180: 
 4181: sub dumpstore {
 4182:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4183:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4184:    if (!$uname) { $uname=$env{'user.name'}; }
 4185:    my $uhome=&homeserver($uname,$udomain);
 4186:    if ($regexp) {
 4187:        $regexp=&escape($regexp);
 4188:    } else {
 4189:        $regexp='.';
 4190:    }
 4191:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4192:    my @pairs=split(/\&/,$rep);
 4193:    my %returnhash=();
 4194:    foreach my $item (@pairs) {
 4195:        my ($key,$value)=split(/=/,$item,2);
 4196:        next if ($key =~ /^error: 2 /);
 4197:        $returnhash{$key}=&thaw_unescape($value);
 4198:    }
 4199:    return %returnhash;
 4200: }
 4201: 
 4202: # -------------------------------------------------------------- keys interface
 4203: 
 4204: sub getkeys {
 4205:    my ($namespace,$udomain,$uname)=@_;
 4206:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4207:    if (!$uname) { $uname=$env{'user.name'}; }
 4208:    my $uhome=&homeserver($uname,$udomain);
 4209:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4210:    my @keyarray=();
 4211:    foreach my $key (split(/\&/,$rep)) {
 4212:       next if ($key =~ /^error: 2 /);
 4213:       push(@keyarray,&unescape($key));
 4214:    }
 4215:    return @keyarray;
 4216: }
 4217: 
 4218: # --------------------------------------------------------------- currentdump
 4219: sub currentdump {
 4220:    my ($courseid,$sdom,$sname)=@_;
 4221:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4222:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4223:    $sname    = $env{'user.name'}         if (! defined($sname));
 4224:    my $uhome = &homeserver($sname,$sdom);
 4225:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4226:    return if ($rep =~ /^(error:|no_such_host)/);
 4227:    #
 4228:    my %returnhash=();
 4229:    #
 4230:    if ($rep eq "unknown_cmd") { 
 4231:        # an old lond will not know currentdump
 4232:        # Do a dump and make it look like a currentdump
 4233:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4234:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4235:        my %hash = @tmp;
 4236:        @tmp=();
 4237:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4238:    } else {
 4239:        my @pairs=split(/\&/,$rep);
 4240:        foreach my $pair (@pairs) {
 4241:            my ($key,$value)=split(/=/,$pair,2);
 4242:            my ($symb,$param) = split(/:/,$key);
 4243:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4244:                                                         &thaw_unescape($value);
 4245:        }
 4246:    }
 4247:    return %returnhash;
 4248: }
 4249: 
 4250: sub convert_dump_to_currentdump{
 4251:     my %hash = %{shift()};
 4252:     my %returnhash;
 4253:     # Code ripped from lond, essentially.  The only difference
 4254:     # here is the unescaping done by lonnet::dump().  Conceivably
 4255:     # we might run in to problems with parameter names =~ /^v\./
 4256:     while (my ($key,$value) = each(%hash)) {
 4257:         my ($v,$symb,$param) = split(/:/,$key);
 4258: 	$symb  = &unescape($symb);
 4259: 	$param = &unescape($param);
 4260:         next if ($v eq 'version' || $symb eq 'keys');
 4261:         next if (exists($returnhash{$symb}) &&
 4262:                  exists($returnhash{$symb}->{$param}) &&
 4263:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4264:         $returnhash{$symb}->{$param}=$value;
 4265:         $returnhash{$symb}->{'v.'.$param}=$v;
 4266:     }
 4267:     #
 4268:     # Remove all of the keys in the hashes which keep track of
 4269:     # the version of the parameter.
 4270:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4271:         # use a foreach because we are going to delete from the hash.
 4272:         foreach my $key (keys(%$param_hash)) {
 4273:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4274:         }
 4275:     }
 4276:     return \%returnhash;
 4277: }
 4278: 
 4279: # ------------------------------------------------------ critical inc interface
 4280: 
 4281: sub cinc {
 4282:     return &inc(@_,'critical');
 4283: }
 4284: 
 4285: # --------------------------------------------------------------- inc interface
 4286: 
 4287: sub inc {
 4288:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4289:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4290:     if (!$uname) { $uname=$env{'user.name'}; }
 4291:     my $uhome=&homeserver($uname,$udomain);
 4292:     my $items='';
 4293:     if (! ref($store)) {
 4294:         # got a single value, so use that instead
 4295:         $items = &escape($store).'=&';
 4296:     } elsif (ref($store) eq 'SCALAR') {
 4297:         $items = &escape($$store).'=&';        
 4298:     } elsif (ref($store) eq 'ARRAY') {
 4299:         $items = join('=&',map {&escape($_);} @{$store});
 4300:     } elsif (ref($store) eq 'HASH') {
 4301:         while (my($key,$value) = each(%{$store})) {
 4302:             $items.= &escape($key).'='.&escape($value).'&';
 4303:         }
 4304:     }
 4305:     $items=~s/\&$//;
 4306:     if ($critical) {
 4307: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4308:     } else {
 4309: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4310:     }
 4311: }
 4312: 
 4313: # --------------------------------------------------------------- put interface
 4314: 
 4315: sub put {
 4316:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4317:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4318:    if (!$uname) { $uname=$env{'user.name'}; }
 4319:    my $uhome=&homeserver($uname,$udomain);
 4320:    my $items='';
 4321:    foreach my $item (keys(%$storehash)) {
 4322:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4323:    }
 4324:    $items=~s/\&$//;
 4325:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4326: }
 4327: 
 4328: # ------------------------------------------------------------ newput interface
 4329: 
 4330: sub newput {
 4331:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4332:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4333:    if (!$uname) { $uname=$env{'user.name'}; }
 4334:    my $uhome=&homeserver($uname,$udomain);
 4335:    my $items='';
 4336:    foreach my $key (keys(%$storehash)) {
 4337:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4338:    }
 4339:    $items=~s/\&$//;
 4340:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4341: }
 4342: 
 4343: # ---------------------------------------------------------  putstore interface
 4344: 
 4345: sub putstore {
 4346:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4347:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4348:    if (!$uname) { $uname=$env{'user.name'}; }
 4349:    my $uhome=&homeserver($uname,$udomain);
 4350:    my $items='';
 4351:    foreach my $key (keys(%$storehash)) {
 4352:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4353:    }
 4354:    $items=~s/\&$//;
 4355:    my $esc_symb=&escape($symb);
 4356:    my $esc_v=&escape($version);
 4357:    my $reply =
 4358:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4359: 	      $uhome);
 4360:    if ($reply eq 'unknown_cmd') {
 4361:        # gfall back to way things use to be done
 4362:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4363: 			    $uname);
 4364:    }
 4365:    return $reply;
 4366: }
 4367: 
 4368: sub old_putstore {
 4369:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4370:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4371:     if (!$uname) { $uname=$env{'user.name'}; }
 4372:     my $uhome=&homeserver($uname,$udomain);
 4373:     my %newstorehash;
 4374:     foreach my $item (keys(%$storehash)) {
 4375: 	my $key = $version.':'.&escape($symb).':'.$item;
 4376: 	$newstorehash{$key} = $storehash->{$item};
 4377:     }
 4378:     my $items='';
 4379:     my %allitems = ();
 4380:     foreach my $item (keys(%newstorehash)) {
 4381: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4382: 	    my $key = $1.':keys:'.$2;
 4383: 	    $allitems{$key} .= $3.':';
 4384: 	}
 4385: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4386:     }
 4387:     foreach my $item (keys(%allitems)) {
 4388: 	$allitems{$item} =~ s/\:$//;
 4389: 	$items.= $item.'='.$allitems{$item}.'&';
 4390:     }
 4391:     $items=~s/\&$//;
 4392:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4393: }
 4394: 
 4395: # ------------------------------------------------------ critical put interface
 4396: 
 4397: sub cput {
 4398:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4399:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4400:    if (!$uname) { $uname=$env{'user.name'}; }
 4401:    my $uhome=&homeserver($uname,$udomain);
 4402:    my $items='';
 4403:    foreach my $item (keys(%$storehash)) {
 4404:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4405:    }
 4406:    $items=~s/\&$//;
 4407:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4408: }
 4409: 
 4410: # -------------------------------------------------------------- eget interface
 4411: 
 4412: sub eget {
 4413:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4414:    my $items='';
 4415:    foreach my $item (@$storearr) {
 4416:        $items.=&escape($item).'&';
 4417:    }
 4418:    $items=~s/\&$//;
 4419:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4420:    if (!$uname) { $uname=$env{'user.name'}; }
 4421:    my $uhome=&homeserver($uname,$udomain);
 4422:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4423:    my @pairs=split(/\&/,$rep);
 4424:    my %returnhash=();
 4425:    my $i=0;
 4426:    foreach my $item (@$storearr) {
 4427:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4428:       $i++;
 4429:    }
 4430:    return %returnhash;
 4431: }
 4432: 
 4433: # ------------------------------------------------------------ tmpput interface
 4434: sub tmpput {
 4435:     my ($storehash,$server,$context)=@_;
 4436:     my $items='';
 4437:     foreach my $item (keys(%$storehash)) {
 4438: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4439:     }
 4440:     $items=~s/\&$//;
 4441:     if (defined($context)) {
 4442:         $items .= ':'.&escape($context);
 4443:     }
 4444:     return &reply("tmpput:$items",$server);
 4445: }
 4446: 
 4447: # ------------------------------------------------------------ tmpget interface
 4448: sub tmpget {
 4449:     my ($token,$server)=@_;
 4450:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4451:     my $rep=&reply("tmpget:$token",$server);
 4452:     my %returnhash;
 4453:     foreach my $item (split(/\&/,$rep)) {
 4454: 	my ($key,$value)=split(/=/,$item);
 4455:         next if ($key =~ /^error: 2 /);
 4456: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4457:     }
 4458:     return %returnhash;
 4459: }
 4460: 
 4461: # ------------------------------------------------------------ tmpget interface
 4462: sub tmpdel {
 4463:     my ($token,$server)=@_;
 4464:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4465:     return &reply("tmpdel:$token",$server);
 4466: }
 4467: 
 4468: # -------------------------------------------------- portfolio access checking
 4469: 
 4470: sub portfolio_access {
 4471:     my ($requrl) = @_;
 4472:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4473:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4474:     if ($result) {
 4475:         my %setters;
 4476:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4477:             my ($startblock,$endblock) =
 4478:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4479:             if ($startblock && $endblock) {
 4480:                 return 'B';
 4481:             }
 4482:         } else {
 4483:             my ($startblock,$endblock) =
 4484:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4485:             if ($startblock && $endblock) {
 4486:                 return 'B';
 4487:             }
 4488:         }
 4489:     }
 4490:     if ($result eq 'ok') {
 4491:        return 'F';
 4492:     } elsif ($result =~ /^[^:]+:guest_/) {
 4493:        return 'A';
 4494:     }
 4495:     return '';
 4496: }
 4497: 
 4498: sub get_portfolio_access {
 4499:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4500: 
 4501:     if (!ref($access_hash)) {
 4502: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4503: 	my %access_controls = &get_access_controls($current_perms,$group,
 4504: 						   $file_name);
 4505: 	$access_hash = $access_controls{$file_name};
 4506:     }
 4507: 
 4508:     my ($public,$guest,@domains,@users,@courses,@groups);
 4509:     my $now = time;
 4510:     if (ref($access_hash) eq 'HASH') {
 4511:         foreach my $key (keys(%{$access_hash})) {
 4512:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4513:             if ($start > $now) {
 4514:                 next;
 4515:             }
 4516:             if ($end && $end<$now) {
 4517:                 next;
 4518:             }
 4519:             if ($scope eq 'public') {
 4520:                 $public = $key;
 4521:                 last;
 4522:             } elsif ($scope eq 'guest') {
 4523:                 $guest = $key;
 4524:             } elsif ($scope eq 'domains') {
 4525:                 push(@domains,$key);
 4526:             } elsif ($scope eq 'users') {
 4527:                 push(@users,$key);
 4528:             } elsif ($scope eq 'course') {
 4529:                 push(@courses,$key);
 4530:             } elsif ($scope eq 'group') {
 4531:                 push(@groups,$key);
 4532:             }
 4533:         }
 4534:         if ($public) {
 4535:             return 'ok';
 4536:         }
 4537:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4538:             if ($guest) {
 4539:                 return $guest;
 4540:             }
 4541:         } else {
 4542:             if (@domains > 0) {
 4543:                 foreach my $domkey (@domains) {
 4544:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4545:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4546:                             return 'ok';
 4547:                         }
 4548:                     }
 4549:                 }
 4550:             }
 4551:             if (@users > 0) {
 4552:                 foreach my $userkey (@users) {
 4553:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4554:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4555:                             if (ref($item) eq 'HASH') {
 4556:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4557:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4558:                                     return 'ok';
 4559:                                 }
 4560:                             }
 4561:                         }
 4562:                     } 
 4563:                 }
 4564:             }
 4565:             my %roleshash;
 4566:             my @courses_and_groups = @courses;
 4567:             push(@courses_and_groups,@groups); 
 4568:             if (@courses_and_groups > 0) {
 4569:                 my (%allgroups,%allroles); 
 4570:                 my ($start,$end,$role,$sec,$group);
 4571:                 foreach my $envkey (%env) {
 4572:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4573:                         my $cid = $2.'_'.$3; 
 4574:                         if ($1 eq 'gr') {
 4575:                             $group = $4;
 4576:                             $allgroups{$cid}{$group} = $env{$envkey};
 4577:                         } else {
 4578:                             if ($4 eq '') {
 4579:                                 $sec = 'none';
 4580:                             } else {
 4581:                                 $sec = $4;
 4582:                             }
 4583:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4584:                         }
 4585:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4586:                         my $cid = $2.'_'.$3;
 4587:                         if ($4 eq '') {
 4588:                             $sec = 'none';
 4589:                         } else {
 4590:                             $sec = $4;
 4591:                         }
 4592:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4593:                     }
 4594:                 }
 4595:                 if (keys(%allroles) == 0) {
 4596:                     return;
 4597:                 }
 4598:                 foreach my $key (@courses_and_groups) {
 4599:                     my %content = %{$$access_hash{$key}};
 4600:                     my $cnum = $content{'number'};
 4601:                     my $cdom = $content{'domain'};
 4602:                     my $cid = $cdom.'_'.$cnum;
 4603:                     if (!exists($allroles{$cid})) {
 4604:                         next;
 4605:                     }    
 4606:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4607:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4608:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4609:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4610:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4611:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4612:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4613:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4614:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4615:                                         if (grep/^all$/,@sections) {
 4616:                                             return 'ok';
 4617:                                         } else {
 4618:                                             if (grep/^$sec$/,@sections) {
 4619:                                                 return 'ok';
 4620:                                             }
 4621:                                         }
 4622:                                     }
 4623:                                 }
 4624:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4625:                                     if (grep/^none$/,@groups) {
 4626:                                         return 'ok';
 4627:                                     }
 4628:                                 } else {
 4629:                                     if (grep/^all$/,@groups) {
 4630:                                         return 'ok';
 4631:                                     } 
 4632:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4633:                                         if (grep/^$group$/,@groups) {
 4634:                                             return 'ok';
 4635:                                         }
 4636:                                     }
 4637:                                 } 
 4638:                             }
 4639:                         }
 4640:                     }
 4641:                 }
 4642:             }
 4643:             if ($guest) {
 4644:                 return $guest;
 4645:             }
 4646:         }
 4647:     }
 4648:     return;
 4649: }
 4650: 
 4651: sub course_group_datechecker {
 4652:     my ($dates,$now,$status) = @_;
 4653:     my ($start,$end) = split(/\./,$dates);
 4654:     if (!$start && !$end) {
 4655:         return 'ok';
 4656:     }
 4657:     if (grep/^active$/,@{$status}) {
 4658:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4659:             return 'ok';
 4660:         }
 4661:     }
 4662:     if (grep/^previous$/,@{$status}) {
 4663:         if ($end > $now ) {
 4664:             return 'ok';
 4665:         }
 4666:     }
 4667:     if (grep/^future$/,@{$status}) {
 4668:         if ($start > $now) {
 4669:             return 'ok';
 4670:         }
 4671:     }
 4672:     return; 
 4673: }
 4674: 
 4675: sub parse_portfolio_url {
 4676:     my ($url) = @_;
 4677: 
 4678:     my ($type,$udom,$unum,$group,$file_name);
 4679:     
 4680:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4681: 	$type = 1;
 4682:         $udom = $1;
 4683:         $unum = $2;
 4684:         $file_name = $3;
 4685:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4686: 	$type = 2;
 4687:         $udom = $1;
 4688:         $unum = $2;
 4689:         $group = $3;
 4690:         $file_name = $3.'/'.$4;
 4691:     }
 4692:     if (wantarray) {
 4693: 	return ($type,$udom,$unum,$file_name,$group);
 4694:     }
 4695:     return $type;
 4696: }
 4697: 
 4698: sub is_portfolio_url {
 4699:     my ($url) = @_;
 4700:     return scalar(&parse_portfolio_url($url));
 4701: }
 4702: 
 4703: sub is_portfolio_file {
 4704:     my ($file) = @_;
 4705:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4706:         return 1;
 4707:     }
 4708:     return;
 4709: }
 4710: 
 4711: sub usertools_access {
 4712:     my ($uname,$udom,$tool,$action,$context) = @_;
 4713:     my ($access,%tools);
 4714:     if ($context eq '') {
 4715:         $context = 'tools';
 4716:     }
 4717:     if ($context eq 'requestcourses') {
 4718:         %tools = (
 4719:                       official   => 1,
 4720:                       unofficial => 1,
 4721:                       community  => 1,
 4722:                  );
 4723:     } else {
 4724:         %tools = (
 4725:                       aboutme   => 1,
 4726:                       blog      => 1,
 4727:                       portfolio => 1,
 4728:                  );
 4729:     }
 4730:     return if (!defined($tools{$tool}));
 4731: 
 4732:     if ((!defined($udom)) || (!defined($uname))) {
 4733:         $udom = $env{'user.domain'};
 4734:         $uname = $env{'user.name'};
 4735:     }
 4736: 
 4737:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4738:         if ($action ne 'reload') {
 4739:             if ($context eq 'requestcourses') {
 4740:                 return $env{'environment.canrequest.'.$tool};
 4741:             } else {
 4742:                 return $env{'environment.availabletools.'.$tool};
 4743:             }
 4744:         }
 4745:     }
 4746: 
 4747:     my ($toolstatus,$inststatus);
 4748: 
 4749:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4750:          ($action ne 'reload')) {
 4751:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4752:         $inststatus = $env{'environment.inststatus'};
 4753:     } else {
 4754:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 4755:         $toolstatus = $userenv{$context.'.'.$tool};
 4756:         $inststatus = $userenv{'inststatus'};
 4757:     }
 4758: 
 4759:     if ($toolstatus ne '') {
 4760:         if ($toolstatus) {
 4761:             $access = 1;
 4762:         } else {
 4763:             $access = 0;
 4764:         }
 4765:         return $access;
 4766:     }
 4767: 
 4768:     my $is_adv = &is_advanced_user($udom,$uname);
 4769:     my %domdef = &get_domain_defaults($udom);
 4770:     if (ref($domdef{$tool}) eq 'HASH') {
 4771:         if ($is_adv) {
 4772:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4773:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4774:                     $access = 1;
 4775:                 } else {
 4776:                     $access = 0;
 4777:                 }
 4778:                 return $access;
 4779:             }
 4780:         }
 4781:         if ($inststatus ne '') {
 4782:             my ($hasaccess,$hasnoaccess);
 4783:             foreach my $affiliation (split(/:/,$inststatus)) {
 4784:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4785:                     if ($domdef{$tool}{$affiliation}) {
 4786:                         $hasaccess = 1;
 4787:                     } else {
 4788:                         $hasnoaccess = 1;
 4789:                     }
 4790:                 }
 4791:             }
 4792:             if ($hasaccess || $hasnoaccess) {
 4793:                 if ($hasaccess) {
 4794:                     $access = 1;
 4795:                 } elsif ($hasnoaccess) {
 4796:                     $access = 0; 
 4797:                 }
 4798:                 return $access;
 4799:             }
 4800:         } else {
 4801:             if ($domdef{$tool}{'default'} ne '') {
 4802:                 if ($domdef{$tool}{'default'}) {
 4803:                     $access = 1;
 4804:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4805:                     $access = 0;
 4806:                 }
 4807:                 return $access;
 4808:             }
 4809:         }
 4810:     } else {
 4811:         if ($context eq 'tools') {
 4812:             $access = 1;
 4813:         } else {
 4814:             $access = 0;
 4815:         }
 4816:         return $access;
 4817:     }
 4818: }
 4819: 
 4820: sub is_advanced_user {
 4821:     my ($udom,$uname) = @_;
 4822:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4823:     my %allroles;
 4824:     my $is_adv;
 4825:     foreach my $role (keys(%roleshash)) {
 4826:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4827:         my $area = '/'.$tdomain.'/'.$trest;
 4828:         if ($sec ne '') {
 4829:             $area .= '/'.$sec;
 4830:         }
 4831:         if (($area ne '') && ($trole ne '')) {
 4832:             my $spec=$trole.'.'.$area;
 4833:             if ($trole =~ /^cr\//) {
 4834:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4835:             } elsif ($trole ne 'gr') {
 4836:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4837:             }
 4838:         }
 4839:     }
 4840:     foreach my $role (keys(%allroles)) {
 4841:         last if ($is_adv);
 4842:         foreach my $item (split(/:/,$allroles{$role})) {
 4843:             if ($item ne '') {
 4844:                 my ($privilege,$restrictions)=split(/&/,$item);
 4845:                 if ($privilege eq 'adv') {
 4846:                     $is_adv = 1;
 4847:                     last;
 4848:                 }
 4849:             }
 4850:         }
 4851:     }
 4852:     return $is_adv;
 4853: }
 4854: 
 4855: sub check_can_request {
 4856:     my ($dom,$can_request,$request_domains) = @_;
 4857:     my $canreq = 0;
 4858:     my ($types,$typename) = &Apache::loncommon::course_types();
 4859:     my @options = ('approval','validate','autolimit');
 4860:     my $optregex = join('|',@options);
 4861:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 4862:         foreach my $type (@{$types}) {
 4863:             if (&usertools_access($env{'user.name'},
 4864:                                   $env{'user.domain'},
 4865:                                   $type,undef,'requestcourses')) {
 4866:                 $canreq ++;
 4867:                 if (ref($request_domains) eq 'HASH') {
 4868:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 4869:                 }
 4870:                 if ($dom eq $env{'user.domain'}) {
 4871:                     $can_request->{$type} = 1;
 4872:                 }
 4873:             }
 4874:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 4875:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 4876:                 if (@curr > 0) {
 4877:                     foreach my $item (@curr) {
 4878:                         if (ref($request_domains) eq 'HASH') {
 4879:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 4880:                             if ($otherdom ne '') {
 4881:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 4882:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 4883:                                         push(@{$request_domains->{$type}},$otherdom);
 4884:                                     }
 4885:                                 } else {
 4886:                                     push(@{$request_domains->{$type}},$otherdom);
 4887:                                 }
 4888:                             }
 4889:                         }
 4890:                     }
 4891:                     unless($dom eq $env{'user.domain'}) {
 4892:                         $canreq ++;
 4893:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 4894:                             $can_request->{$type} = 1;
 4895:                         }
 4896:                     }
 4897:                 }
 4898:             }
 4899:         }
 4900:     }
 4901:     return $canreq;
 4902: }
 4903: 
 4904: # ---------------------------------------------- Custom access rule evaluation
 4905: 
 4906: sub customaccess {
 4907:     my ($priv,$uri)=@_;
 4908:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4909:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4910:     $udom = &LONCAPA::clean_domain($udom);
 4911:     $ucrs = &LONCAPA::clean_username($ucrs);
 4912:     my $access=0;
 4913:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4914: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4915: 	if ($type eq 'user') {
 4916: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4917: 		my ($tdom,$tuname)=split(m{/},$scope);
 4918: 		if ($tdom) {
 4919: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4920: 		}
 4921: 		if ($tuname) {
 4922: 		    if ($tuname ne $env{'user.name'}) { next; }
 4923: 		}
 4924: 		$access=($effect eq 'allow');
 4925: 		last;
 4926: 	    }
 4927: 	} else {
 4928: 	    if ($role) {
 4929: 		if ($role ne $urole) { next; }
 4930: 	    }
 4931: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4932: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4933: 		if ($tdom) {
 4934: 		    if ($tdom ne $udom) { next; }
 4935: 		}
 4936: 		if ($tcrs) {
 4937: 		    if ($tcrs ne $ucrs) { next; }
 4938: 		}
 4939: 		if ($tsec) {
 4940: 		    if ($tsec ne $usec) { next; }
 4941: 		}
 4942: 		$access=($effect eq 'allow');
 4943: 		last;
 4944: 	    }
 4945: 	    if ($realm eq '' && $role eq '') {
 4946: 		$access=($effect eq 'allow');
 4947: 	    }
 4948: 	}
 4949:     }
 4950:     return $access;
 4951: }
 4952: 
 4953: # ------------------------------------------------- Check for a user privilege
 4954: 
 4955: sub allowed {
 4956:     my ($priv,$uri,$symb,$role)=@_;
 4957:     my $ver_orguri=$uri;
 4958:     $uri=&deversion($uri);
 4959:     my $orguri=$uri;
 4960:     $uri=&declutter($uri);
 4961: 
 4962:     if ($priv eq 'evb') {
 4963: # Evade communication block restrictions for specified role in a course
 4964:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4965:             return $1;
 4966:         } else {
 4967:             return;
 4968:         }
 4969:     }
 4970: 
 4971:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4972: # Free bre access to adm and meta resources
 4973:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4974: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4975: 	&& ($priv eq 'bre')) {
 4976: 	return 'F';
 4977:     }
 4978: 
 4979: # Free bre access to user's own portfolio contents
 4980:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4981:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4982: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4983:         my %setters;
 4984:         my ($startblock,$endblock) = 
 4985:             &Apache::loncommon::blockcheck(\%setters,'port');
 4986:         if ($startblock && $endblock) {
 4987:             return 'B';
 4988:         } else {
 4989:             return 'F';
 4990:         }
 4991:     }
 4992: 
 4993: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4994:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4995:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4996:         if (exists($env{'request.course.id'})) {
 4997:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4998:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4999:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5000:                 my $courseprivid=$env{'request.course.id'};
 5001:                 $courseprivid=~s/\_/\//;
 5002:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5003:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5004:                     return $1; 
 5005:                 } else {
 5006:                     if ($env{'request.course.sec'}) {
 5007:                         $courseprivid.='/'.$env{'request.course.sec'};
 5008:                     }
 5009:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5010:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5011:                         return $2;
 5012:                     }
 5013:                 }
 5014:             }
 5015:         }
 5016:     }
 5017: 
 5018: # Free bre to public access
 5019: 
 5020:     if ($priv eq 'bre') {
 5021:         my $copyright=&metadata($uri,'copyright');
 5022: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5023:            return 'F'; 
 5024:         }
 5025:         if ($copyright eq 'priv') {
 5026:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5027: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5028: 		return '';
 5029:             }
 5030:         }
 5031:         if ($copyright eq 'domain') {
 5032:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5033: 	    unless (($env{'user.domain'} eq $1) ||
 5034:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5035: 		return '';
 5036:             }
 5037:         }
 5038:         if ($env{'request.role'}=~ /li\.\//) {
 5039:             # Library role, so allow browsing of resources in this domain.
 5040:             return 'F';
 5041:         }
 5042:         if ($copyright eq 'custom') {
 5043: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5044:         }
 5045:     }
 5046:     # Domain coordinator is trying to create a course
 5047:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5048:         # uri is the requested domain in this case.
 5049:         # comparison to 'request.role.domain' shows if the user has selected
 5050:         # a role of dc for the domain in question.
 5051:         return 'F' if ($uri eq $env{'request.role.domain'});
 5052:     }
 5053: 
 5054:     my $thisallowed='';
 5055:     my $statecond=0;
 5056:     my $courseprivid='';
 5057: 
 5058:     my $ownaccess;
 5059:     # Community Coordinator or Assistant Co-author browsing resource space.
 5060:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5061:         if ($uri eq '') {
 5062:             $ownaccess = 1;
 5063:         } else {
 5064:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5065:                 my $udom = $env{'user.domain'};
 5066:                 my $uname = $env{'user.name'};
 5067:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5068:                     $ownaccess = 1;
 5069:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5070:                     unless ($uri =~ m{\.\./}) {
 5071:                         $ownaccess = 1;
 5072:                     }
 5073:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5074:                     my $now = time;
 5075:                     if ($uri =~ m{^([^/]+)/?$}) {
 5076:                         my $adom = $1;
 5077:                         foreach my $key (keys(%env)) {
 5078:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5079:                                 my ($start,$end) = split('.',$env{$key});
 5080:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5081:                                     $ownaccess = 1;
 5082:                                     last;
 5083:                                 }
 5084:                             }
 5085:                         }
 5086:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5087:                         my $adom = $1;
 5088:                         my $aname = $2;
 5089:                         foreach my $role ('ca','aa') { 
 5090:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5091:                                 my ($start,$end) =
 5092:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5093:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5094:                                     $ownaccess = 1;
 5095:                                     last;
 5096:                                 }
 5097:                             }
 5098:                         }
 5099:                     }
 5100:                 }
 5101:             }
 5102:         }
 5103:     }
 5104: 
 5105: # Course
 5106: 
 5107:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5108:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5109:             $thisallowed.=$1;
 5110:         }
 5111:     }
 5112: 
 5113: # Domain
 5114: 
 5115:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5116:        =~/\Q$priv\E\&([^\:]*)/) {
 5117:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5118:             $thisallowed.=$1;
 5119:         }
 5120:     }
 5121: 
 5122: # Course: uri itself is a course
 5123:     my $courseuri=$uri;
 5124:     $courseuri=~s/\_(\d)/\/$1/;
 5125:     $courseuri=~s/^([^\/])/\/$1/;
 5126: 
 5127:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5128:        =~/\Q$priv\E\&([^\:]*)/) {
 5129:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5130:             $thisallowed.=$1;
 5131:         }
 5132:     }
 5133: 
 5134: # URI is an uploaded document for this course, default permissions don't matter
 5135: # not allowing 'edit' access (editupload) to uploaded course docs
 5136:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5137: 	$thisallowed='';
 5138:         my ($match)=&is_on_map($uri);
 5139:         if ($match) {
 5140:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5141:                   =~/\Q$priv\E\&([^\:]*)/) {
 5142:                 $thisallowed.=$1;
 5143:             }
 5144:         } else {
 5145:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5146:             if ($refuri) {
 5147:                 if ($refuri =~ m|^/adm/|) {
 5148:                     $thisallowed='F';
 5149:                 } else {
 5150:                     $refuri=&declutter($refuri);
 5151:                     my ($match) = &is_on_map($refuri);
 5152:                     if ($match) {
 5153:                         $thisallowed='F';
 5154:                     }
 5155:                 }
 5156:             }
 5157:         }
 5158:     }
 5159: 
 5160:     if ($priv eq 'bre'
 5161: 	&& $thisallowed ne 'F' 
 5162: 	&& $thisallowed ne '2'
 5163: 	&& &is_portfolio_url($uri)) {
 5164: 	$thisallowed = &portfolio_access($uri);
 5165:     }
 5166:     
 5167: # Full access at system, domain or course-wide level? Exit.
 5168:     if ($thisallowed=~/F/) {
 5169: 	return 'F';
 5170:     }
 5171: 
 5172: # If this is generating or modifying users, exit with special codes
 5173: 
 5174:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5175: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5176: 	    my ($audom,$auname)=split('/',$uri);
 5177: # no author name given, so this just checks on the general right to make a co-author in this domain
 5178: 	    unless ($auname) { return $thisallowed; }
 5179: # an author name is given, so we are about to actually make a co-author for a certain account
 5180: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5181: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5182: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5183: 	}
 5184: 	return $thisallowed;
 5185:     }
 5186: #
 5187: # Gathered so far: system, domain and course wide privileges
 5188: #
 5189: # Course: See if uri or referer is an individual resource that is part of 
 5190: # the course
 5191: 
 5192:     if ($env{'request.course.id'}) {
 5193: 
 5194:        $courseprivid=$env{'request.course.id'};
 5195:        if ($env{'request.course.sec'}) {
 5196:           $courseprivid.='/'.$env{'request.course.sec'};
 5197:        }
 5198:        $courseprivid=~s/\_/\//;
 5199:        my $checkreferer=1;
 5200:        my ($match,$cond)=&is_on_map($uri);
 5201:        if ($match) {
 5202:            $statecond=$cond;
 5203:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5204:                =~/\Q$priv\E\&([^\:]*)/) {
 5205:                $thisallowed.=$1;
 5206:                $checkreferer=0;
 5207:            }
 5208:        }
 5209:        
 5210:        if ($checkreferer) {
 5211: 	  my $refuri=$env{'httpref.'.$orguri};
 5212:             unless ($refuri) {
 5213:                 foreach my $key (keys(%env)) {
 5214: 		    if ($key=~/^httpref\..*\*/) {
 5215: 			my $pattern=$key;
 5216:                         $pattern=~s/^httpref\.\/res\///;
 5217:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5218:                         $pattern=~s/\//\\\//g;
 5219:                         if ($orguri=~/$pattern/) {
 5220: 			    $refuri=$env{$key};
 5221:                         }
 5222:                     }
 5223:                 }
 5224:             }
 5225: 
 5226:          if ($refuri) { 
 5227: 	  $refuri=&declutter($refuri);
 5228:           my ($match,$cond)=&is_on_map($refuri);
 5229:             if ($match) {
 5230:               my $refstatecond=$cond;
 5231:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5232:                   =~/\Q$priv\E\&([^\:]*)/) {
 5233:                   $thisallowed.=$1;
 5234:                   $uri=$refuri;
 5235:                   $statecond=$refstatecond;
 5236:               }
 5237:           }
 5238:         }
 5239:        }
 5240:    }
 5241: 
 5242: #
 5243: # Gathered now: all privileges that could apply, and condition number
 5244: # 
 5245: #
 5246: # Full or no access?
 5247: #
 5248: 
 5249:     if ($thisallowed=~/F/) {
 5250: 	return 'F';
 5251:     }
 5252: 
 5253:     unless ($thisallowed) {
 5254:         return '';
 5255:     }
 5256: 
 5257: # Restrictions exist, deal with them
 5258: #
 5259: #   C:according to course preferences
 5260: #   R:according to resource settings
 5261: #   L:unless locked
 5262: #   X:according to user session state
 5263: #
 5264: 
 5265: # Possibly locked functionality, check all courses
 5266: # Locks might take effect only after 10 minutes cache expiration for other
 5267: # courses, and 2 minutes for current course
 5268: 
 5269:     my $envkey;
 5270:     if ($thisallowed=~/L/) {
 5271:         foreach $envkey (keys(%env)) {
 5272:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5273:                my $courseid=$2;
 5274:                my $roleid=$1.'.'.$2;
 5275:                $courseid=~s/^\///;
 5276:                my $expiretime=600;
 5277:                if ($env{'request.role'} eq $roleid) {
 5278: 		  $expiretime=120;
 5279:                }
 5280: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5281:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5282:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5283: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5284:                }
 5285:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5286:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5287: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5288:                        &log($env{'user.domain'},$env{'user.name'},
 5289:                             $env{'user.home'},
 5290:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5291:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5292:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5293: 		       return '';
 5294:                    }
 5295:                }
 5296:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5297:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5298: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5299:                        &log($env{'user.domain'},$env{'user.name'},
 5300:                             $env{'user.home'},
 5301:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5302:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5303:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5304: 		       return '';
 5305:                    }
 5306:                }
 5307: 	   }
 5308:        }
 5309:     }
 5310:    
 5311: #
 5312: # Rest of the restrictions depend on selected course
 5313: #
 5314: 
 5315:     unless ($env{'request.course.id'}) {
 5316: 	if ($thisallowed eq 'A') {
 5317: 	    return 'A';
 5318:         } elsif ($thisallowed eq 'B') {
 5319:             return 'B';
 5320: 	} else {
 5321: 	    return '1';
 5322: 	}
 5323:     }
 5324: 
 5325: #
 5326: # Now user is definitely in a course
 5327: #
 5328: 
 5329: 
 5330: # Course preferences
 5331: 
 5332:    if ($thisallowed=~/C/) {
 5333:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5334:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5335:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5336: 	   =~/\Q$rolecode\E/) {
 5337: 	   if ($priv ne 'pch') { 
 5338: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5339: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5340: 			$env{'request.course.id'});
 5341: 	   }
 5342:            return '';
 5343:        }
 5344: 
 5345:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5346: 	   =~/\Q$unamedom\E/) {
 5347: 	   if ($priv ne 'pch') { 
 5348: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5349: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5350: 			$env{'request.course.id'});
 5351: 	   }
 5352:            return '';
 5353:        }
 5354:    }
 5355: 
 5356: # Resource preferences
 5357: 
 5358:    if ($thisallowed=~/R/) {
 5359:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5360:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5361: 	   if ($priv ne 'pch') { 
 5362: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5363: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5364: 	   }
 5365: 	   return '';
 5366:        }
 5367:    }
 5368: 
 5369: # Restricted by state or randomout?
 5370: 
 5371:    if ($thisallowed=~/X/) {
 5372:       if ($env{'acc.randomout'}) {
 5373: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5374:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5375:             return ''; 
 5376:          }
 5377:       }
 5378:       if (&condval($statecond)) {
 5379: 	 return '2';
 5380:       } else {
 5381:          return '';
 5382:       }
 5383:    }
 5384: 
 5385:     if ($thisallowed eq 'A') {
 5386: 	return 'A';
 5387:     } elsif ($thisallowed eq 'B') {
 5388:         return 'B';
 5389:     }
 5390:    return 'F';
 5391: }
 5392: 
 5393: sub split_uri_for_cond {
 5394:     my $uri=&deversion(&declutter(shift));
 5395:     my @uriparts=split(/\//,$uri);
 5396:     my $filename=pop(@uriparts);
 5397:     my $pathname=join('/',@uriparts);
 5398:     return ($pathname,$filename);
 5399: }
 5400: # --------------------------------------------------- Is a resource on the map?
 5401: 
 5402: sub is_on_map {
 5403:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5404:     #Trying to find the conditional for the file
 5405:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5406: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5407:     if ($match) {
 5408: 	return (1,$1);
 5409:     } else {
 5410: 	return (0,0);
 5411:     }
 5412: }
 5413: 
 5414: # --------------------------------------------------------- Get symb from alias
 5415: 
 5416: sub get_symb_from_alias {
 5417:     my $symb=shift;
 5418:     my ($map,$resid,$url)=&decode_symb($symb);
 5419: # Already is a symb
 5420:     if ($url) { return $symb; }
 5421: # Must be an alias
 5422:     my $aliassymb='';
 5423:     my %bighash;
 5424:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5425:                             &GDBM_READER(),0640)) {
 5426:         my $rid=$bighash{'mapalias_'.$symb};
 5427: 	if ($rid) {
 5428: 	    my ($mapid,$resid)=split(/\./,$rid);
 5429: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5430: 				    $resid,$bighash{'src_'.$rid});
 5431: 	}
 5432:         untie %bighash;
 5433:     }
 5434:     return $aliassymb;
 5435: }
 5436: 
 5437: # ----------------------------------------------------------------- Define Role
 5438: 
 5439: sub definerole {
 5440:   if (allowed('mcr','/')) {
 5441:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5442:     foreach my $role (split(':',$sysrole)) {
 5443: 	my ($crole,$cqual)=split(/\&/,$role);
 5444:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5445:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5446: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5447:                return "refused:s:$crole&$cqual"; 
 5448:             }
 5449:         }
 5450:     }
 5451:     foreach my $role (split(':',$domrole)) {
 5452: 	my ($crole,$cqual)=split(/\&/,$role);
 5453:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5454:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5455: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5456:                return "refused:d:$crole&$cqual"; 
 5457:             }
 5458:         }
 5459:     }
 5460:     foreach my $role (split(':',$courole)) {
 5461: 	my ($crole,$cqual)=split(/\&/,$role);
 5462:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5463:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5464: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5465:                return "refused:c:$crole&$cqual"; 
 5466:             }
 5467:         }
 5468:     }
 5469:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5470:                 "$env{'user.domain'}:$env{'user.name'}:".
 5471: 	        "rolesdef_$rolename=".
 5472:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5473:     return reply($command,$env{'user.home'});
 5474:   } else {
 5475:     return 'refused';
 5476:   }
 5477: }
 5478: 
 5479: # ---------------- Make a metadata query against the network of library servers
 5480: 
 5481: sub metadata_query {
 5482:     my ($query,$custom,$customshow,$server_array)=@_;
 5483:     my %rhash;
 5484:     my %libserv = &all_library();
 5485:     my @server_list = (defined($server_array) ? @$server_array
 5486:                                               : keys(%libserv) );
 5487:     for my $server (@server_list) {
 5488: 	unless ($custom or $customshow) {
 5489: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5490: 	    $rhash{$server}=$reply;
 5491: 	}
 5492: 	else {
 5493: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5494: 			     &escape($custom).':'.&escape($customshow),
 5495: 			     $server);
 5496: 	    $rhash{$server}=$reply;
 5497: 	}
 5498:     }
 5499:     return \%rhash;
 5500: }
 5501: 
 5502: # ----------------------------------------- Send log queries and wait for reply
 5503: 
 5504: sub log_query {
 5505:     my ($uname,$udom,$query,%filters)=@_;
 5506:     my $uhome=&homeserver($uname,$udom);
 5507:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5508:     my $uhost=&hostname($uhome);
 5509:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5510:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5511:                        $uhome);
 5512:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5513:     return get_query_reply($queryid);
 5514: }
 5515: 
 5516: # -------------------------- Update MySQL table for portfolio file
 5517: 
 5518: sub update_portfolio_table {
 5519:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5520:     if ($group ne '') {
 5521:         $file_name =~s /^\Q$group\E//;
 5522:     }
 5523:     my $homeserver = &homeserver($uname,$udom);
 5524:     my $queryid=
 5525:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5526:                ':'.&escape($file_name).':'.$action,$homeserver);
 5527:     my $reply = &get_query_reply($queryid);
 5528:     return $reply;
 5529: }
 5530: 
 5531: # -------------------------- Update MySQL allusers table
 5532: 
 5533: sub update_allusers_table {
 5534:     my ($uname,$udom,$names) = @_;
 5535:     my $homeserver = &homeserver($uname,$udom);
 5536:     my $queryid=
 5537:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5538:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5539:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5540:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5541:                'generation='.&escape($names->{'generation'}).'%%'.
 5542:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5543:                'id='.&escape($names->{'id'}),$homeserver);
 5544:     my $reply = &get_query_reply($queryid);
 5545:     return $reply;
 5546: }
 5547: 
 5548: # ------- Request retrieval of institutional classlists for course(s)
 5549: 
 5550: sub fetch_enrollment_query {
 5551:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5552:     my $homeserver;
 5553:     my $maxtries = 1;
 5554:     if ($context eq 'automated') {
 5555:         $homeserver = $perlvar{'lonHostID'};
 5556:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5557:     } else {
 5558:         $homeserver = &homeserver($cnum,$dom);
 5559:     }
 5560:     my $host=&hostname($homeserver);
 5561:     my $cmd = '';
 5562:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5563:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5564:     }
 5565:     $cmd =~ s/%%$//;
 5566:     $cmd = &escape($cmd);
 5567:     my $query = 'fetchenrollment';
 5568:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5569:     unless ($queryid=~/^\Q$host\E\_/) { 
 5570:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5571:         return 'error: '.$queryid;
 5572:     }
 5573:     my $reply = &get_query_reply($queryid);
 5574:     my $tries = 1;
 5575:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5576:         $reply = &get_query_reply($queryid);
 5577:         $tries ++;
 5578:     }
 5579:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5580:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5581:     } else {
 5582:         my @responses = split(/:/,$reply);
 5583:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5584:             foreach my $line (@responses) {
 5585:                 my ($key,$value) = split(/=/,$line,2);
 5586:                 $$replyref{$key} = $value;
 5587:             }
 5588:         } else {
 5589:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5590:             foreach my $line (@responses) {
 5591:                 my ($key,$value) = split(/=/,$line);
 5592:                 $$replyref{$key} = $value;
 5593:                 if ($value > 0) {
 5594:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5595:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5596:                         my $destname = $pathname.'/'.$filename;
 5597:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5598:                         if ($xml_classlist =~ /^error/) {
 5599:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5600:                         } else {
 5601:                             if ( open(FILE,">$destname") ) {
 5602:                                 print FILE &unescape($xml_classlist);
 5603:                                 close(FILE);
 5604:                             } else {
 5605:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5606:                             }
 5607:                         }
 5608:                     }
 5609:                 }
 5610:             }
 5611:         }
 5612:         return 'ok';
 5613:     }
 5614:     return 'error';
 5615: }
 5616: 
 5617: sub get_query_reply {
 5618:     my $queryid=shift;
 5619:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5620:     my $reply='';
 5621:     for (1..100) {
 5622: 	sleep 2;
 5623:         if (-e $replyfile.'.end') {
 5624: 	    if (open(my $fh,$replyfile)) {
 5625: 		$reply = join('',<$fh>);
 5626: 		close($fh);
 5627: 	   } else { return 'error: reply_file_error'; }
 5628:            return &unescape($reply);
 5629: 	}
 5630:     }
 5631:     return 'timeout:'.$queryid;
 5632: }
 5633: 
 5634: sub courselog_query {
 5635: #
 5636: # possible filters:
 5637: # url: url or symb
 5638: # username
 5639: # domain
 5640: # action: view, submit, grade
 5641: # start: timestamp
 5642: # end: timestamp
 5643: #
 5644:     my (%filters)=@_;
 5645:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5646:     if ($filters{'url'}) {
 5647: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5648:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5649:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5650:     }
 5651:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5652:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5653:     return &log_query($cname,$cdom,'courselog',%filters);
 5654: }
 5655: 
 5656: sub userlog_query {
 5657: #
 5658: # possible filters:
 5659: # action: log check role
 5660: # start: timestamp
 5661: # end: timestamp
 5662: #
 5663:     my ($uname,$udom,%filters)=@_;
 5664:     return &log_query($uname,$udom,'userlog',%filters);
 5665: }
 5666: 
 5667: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5668: 
 5669: sub auto_run {
 5670:     my ($cnum,$cdom) = @_;
 5671:     my $response = 0;
 5672:     my $settings;
 5673:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5674:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5675:         $settings = $domconfig{'autoenroll'};
 5676:         if ($settings->{'run'} eq '1') {
 5677:             $response = 1;
 5678:         }
 5679:     } else {
 5680:         my $homeserver;
 5681:         if (&is_course($cdom,$cnum)) {
 5682:             $homeserver = &homeserver($cnum,$cdom);
 5683:         } else {
 5684:             $homeserver = &domain($cdom,'primary');
 5685:         }
 5686:         if ($homeserver ne 'no_host') {
 5687:             $response = &reply('autorun:'.$cdom,$homeserver);
 5688:         }
 5689:     }
 5690:     return $response;
 5691: }
 5692: 
 5693: sub auto_get_sections {
 5694:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5695:     my $homeserver;
 5696:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5697:         $homeserver = &homeserver($cnum,$cdom);
 5698:     }
 5699:     if (!defined($homeserver)) { 
 5700:         if ($cdom =~ /^$match_domain$/) {
 5701:             $homeserver = &domain($cdom,'primary');
 5702:         }
 5703:     }
 5704:     my @secs;
 5705:     if (defined($homeserver)) {
 5706:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5707:         unless ($response eq 'refused') {
 5708:             @secs = split(/:/,$response);
 5709:         }
 5710:     }
 5711:     return @secs;
 5712: }
 5713: 
 5714: sub auto_new_course {
 5715:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5716:     my $homeserver = &homeserver($cnum,$cdom);
 5717:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5718:     return $response;
 5719: }
 5720: 
 5721: sub auto_validate_courseID {
 5722:     my ($cnum,$cdom,$inst_course_id) = @_;
 5723:     my $homeserver = &homeserver($cnum,$cdom);
 5724:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5725:     return $response;
 5726: }
 5727: 
 5728: sub auto_validate_instcode {
 5729:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5730:     my ($homeserver,$response);
 5731:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5732:         $homeserver = &homeserver($cnum,$cdom);
 5733:     }
 5734:     if (!defined($homeserver)) {
 5735:         if ($cdom =~ /^$match_domain$/) {
 5736:             $homeserver = &domain($cdom,'primary');
 5737:         }
 5738:     }
 5739:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5740:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5741:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 5742:     return ($outcome,$description);
 5743: }
 5744: 
 5745: sub auto_create_password {
 5746:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5747:     my ($homeserver,$response);
 5748:     my $create_passwd = 0;
 5749:     my $authchk = '';
 5750:     if ($udom =~ /^$match_domain$/) {
 5751:         $homeserver = &domain($udom,'primary');
 5752:     }
 5753:     if ($homeserver eq '') {
 5754:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5755:             $homeserver = &homeserver($cnum,$cdom);
 5756:         }
 5757:     }
 5758:     if ($homeserver eq '') {
 5759:         $authchk = 'nodomain';
 5760:     } else {
 5761:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5762:         if ($response eq 'refused') {
 5763:             $authchk = 'refused';
 5764:         } else {
 5765:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5766:         }
 5767:     }
 5768:     return ($authparam,$create_passwd,$authchk);
 5769: }
 5770: 
 5771: sub auto_photo_permission {
 5772:     my ($cnum,$cdom,$students) = @_;
 5773:     my $homeserver = &homeserver($cnum,$cdom);
 5774:     my ($outcome,$perm_reqd,$conditions) = 
 5775: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5776:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5777: 	return (undef,undef);
 5778:     }
 5779:     return ($outcome,$perm_reqd,$conditions);
 5780: }
 5781: 
 5782: sub auto_checkphotos {
 5783:     my ($uname,$udom,$pid) = @_;
 5784:     my $homeserver = &homeserver($uname,$udom);
 5785:     my ($result,$resulttype);
 5786:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5787: 				   &escape($uname).':'.&escape($pid),
 5788: 				   $homeserver));
 5789:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5790: 	return (undef,undef);
 5791:     }
 5792:     if ($outcome) {
 5793:         ($result,$resulttype) = split(/:/,$outcome);
 5794:     } 
 5795:     return ($result,$resulttype);
 5796: }
 5797: 
 5798: sub auto_photochoice {
 5799:     my ($cnum,$cdom) = @_;
 5800:     my $homeserver = &homeserver($cnum,$cdom);
 5801:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5802: 						       &escape($cdom),
 5803: 						       $homeserver)));
 5804:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5805: 	return (undef,undef);
 5806:     }
 5807:     return ($update,$comment);
 5808: }
 5809: 
 5810: sub auto_photoupdate {
 5811:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5812:     my $homeserver = &homeserver($cnum,$dom);
 5813:     my $host=&hostname($homeserver);
 5814:     my $cmd = '';
 5815:     my $maxtries = 1;
 5816:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5817:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5818:     }
 5819:     $cmd =~ s/%%$//;
 5820:     $cmd = &escape($cmd);
 5821:     my $query = 'institutionalphotos';
 5822:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5823:     unless ($queryid=~/^\Q$host\E\_/) {
 5824:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5825:         return 'error: '.$queryid;
 5826:     }
 5827:     my $reply = &get_query_reply($queryid);
 5828:     my $tries = 1;
 5829:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5830:         $reply = &get_query_reply($queryid);
 5831:         $tries ++;
 5832:     }
 5833:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5834:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5835:     } else {
 5836:         my @responses = split(/:/,$reply);
 5837:         my $outcome = shift(@responses); 
 5838:         foreach my $item (@responses) {
 5839:             my ($key,$value) = split(/=/,$item);
 5840:             $$photo{$key} = $value;
 5841:         }
 5842:         return $outcome;
 5843:     }
 5844:     return 'error';
 5845: }
 5846: 
 5847: sub auto_instcode_format {
 5848:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5849: 	$cat_order) = @_;
 5850:     my $courses = '';
 5851:     my @homeservers;
 5852:     if ($caller eq 'global') {
 5853: 	my %servers = &get_servers($codedom,'library');
 5854: 	foreach my $tryserver (keys(%servers)) {
 5855: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5856: 		push(@homeservers,$tryserver);
 5857: 	    }
 5858:         }
 5859:     } elsif ($caller eq 'requests') {
 5860:         if ($codedom =~ /^$match_domain$/) {
 5861:             my $chome = &domain($codedom,'primary');
 5862:             unless ($chome eq 'no_host') {
 5863:                 push(@homeservers,$chome);
 5864:             }
 5865:         }
 5866:     } else {
 5867:         push(@homeservers,&homeserver($caller,$codedom));
 5868:     }
 5869:     foreach my $code (keys(%{$instcodes})) {
 5870:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5871:     }
 5872:     chop($courses);
 5873:     my $ok_response = 0;
 5874:     my $response;
 5875:     while (@homeservers > 0 && $ok_response == 0) {
 5876:         my $server = shift(@homeservers); 
 5877:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5878:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5879:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5880: 		split(/:/,$response);
 5881:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5882:             push(@{$codetitles},&str2array($codetitles_str));
 5883:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5884:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5885:             $ok_response = 1;
 5886:         }
 5887:     }
 5888:     if ($ok_response) {
 5889:         return 'ok';
 5890:     } else {
 5891:         return $response;
 5892:     }
 5893: }
 5894: 
 5895: sub auto_instcode_defaults {
 5896:     my ($domain,$returnhash,$code_order) = @_;
 5897:     my @homeservers;
 5898: 
 5899:     my %servers = &get_servers($domain,'library');
 5900:     foreach my $tryserver (keys(%servers)) {
 5901: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5902: 	    push(@homeservers,$tryserver);
 5903: 	}
 5904:     }
 5905: 
 5906:     my $response;
 5907:     foreach my $server (@homeservers) {
 5908:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5909:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5910: 	
 5911: 	foreach my $pair (split(/\&/,$response)) {
 5912: 	    my ($name,$value)=split(/\=/,$pair);
 5913: 	    if ($name eq 'code_order') {
 5914: 		@{$code_order} = split(/\&/,&unescape($value));
 5915: 	    } else {
 5916: 		$returnhash->{&unescape($name)}=&unescape($value);
 5917: 	    }
 5918: 	}
 5919: 	return 'ok';
 5920:     }
 5921: 
 5922:     return $response;
 5923: }
 5924: 
 5925: sub auto_possible_instcodes {
 5926:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 5927:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 5928:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 5929:         return;
 5930:     }
 5931:     my (@homeservers,$uhome);
 5932:     if (defined(&domain($domain,'primary'))) {
 5933:         $uhome=&domain($domain,'primary');
 5934:         push(@homeservers,&domain($domain,'primary'));
 5935:     } else {
 5936:         my %servers = &get_servers($domain,'library');
 5937:         foreach my $tryserver (keys(%servers)) {
 5938:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5939:                 push(@homeservers,$tryserver);
 5940:             }
 5941:         }
 5942:     }
 5943:     my $response;
 5944:     foreach my $server (@homeservers) {
 5945:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 5946:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5947:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 5948:             split(':',$response);
 5949:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 5950:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 5951:         foreach my $item (split('&',$cat_title)) {   
 5952:             my ($name,$value)=split('=',$item);
 5953:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 5954:         }
 5955:         foreach my $item (split('&',$cat_order)) {
 5956:             my ($name,$value)=split('=',$item);
 5957:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 5958:         }
 5959:         return 'ok';
 5960:     }
 5961:     return $response;
 5962: }
 5963: 
 5964: sub auto_courserequest_checks {
 5965:     my ($dom) = @_;
 5966:     my ($homeserver,%validations);
 5967:     if ($dom =~ /^$match_domain$/) {
 5968:         $homeserver = &domain($dom,'primary');
 5969:     }
 5970:     unless ($homeserver eq 'no_host') {
 5971:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 5972:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 5973:             my @items = split(/&/,$response);
 5974:             foreach my $item (@items) {
 5975:                 my ($key,$value) = split('=',$item);
 5976:                 $validations{&unescape($key)} = &thaw_unescape($value);
 5977:             }
 5978:         }
 5979:     }
 5980:     return %validations; 
 5981: }
 5982: 
 5983: sub auto_courserequest_validation {
 5984:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 5985:     my ($homeserver,$response);
 5986:     if ($dom =~ /^$match_domain$/) {
 5987:         $homeserver = &domain($dom,'primary');
 5988:     }
 5989:     unless ($homeserver eq 'no_host') {  
 5990:           
 5991:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 5992:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 5993:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 5994:                                     $homeserver));
 5995:     }
 5996:     return $response;
 5997: }
 5998: 
 5999: sub auto_validate_class_sec {
 6000:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 6001:     my $homeserver = &homeserver($cnum,$cdom);
 6002:     my $ownerlist;
 6003:     if (ref($owners) eq 'ARRAY') {
 6004:         $ownerlist = join(',',@{$owners});
 6005:     } else {
 6006:         $ownerlist = $owners;
 6007:     }
 6008:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6009:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6010:     return $response;
 6011: }
 6012: 
 6013: # ------------------------------------------------------- Course Group routines
 6014: 
 6015: sub get_coursegroups {
 6016:     my ($cdom,$cnum,$group,$namespace) = @_;
 6017:     return(&dump($namespace,$cdom,$cnum,$group));
 6018: }
 6019: 
 6020: sub modify_coursegroup {
 6021:     my ($cdom,$cnum,$groupsettings) = @_;
 6022:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6023: }
 6024: 
 6025: sub toggle_coursegroup_status {
 6026:     my ($cdom,$cnum,$group,$action) = @_;
 6027:     my ($from_namespace,$to_namespace);
 6028:     if ($action eq 'delete') {
 6029:         $from_namespace = 'coursegroups';
 6030:         $to_namespace = 'deleted_groups';
 6031:     } else {
 6032:         $from_namespace = 'deleted_groups';
 6033:         $to_namespace = 'coursegroups';
 6034:     }
 6035:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6036:     if (my $tmp = &error(%curr_group)) {
 6037:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6038:         return ('read error',$tmp);
 6039:     } else {
 6040:         my %savedsettings = %curr_group; 
 6041:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6042:         my $deloutcome;
 6043:         if ($result eq 'ok') {
 6044:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6045:         } else {
 6046:             return ('write error',$result);
 6047:         }
 6048:         if ($deloutcome eq 'ok') {
 6049:             return 'ok';
 6050:         } else {
 6051:             return ('delete error',$deloutcome);
 6052:         }
 6053:     }
 6054: }
 6055: 
 6056: sub modify_group_roles {
 6057:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6058:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6059:     my $role = 'gr/'.&escape($userprivs);
 6060:     my ($uname,$udom) = split(/:/,$user);
 6061:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6062:     if ($result eq 'ok') {
 6063:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6064:     }
 6065:     return $result;
 6066: }
 6067: 
 6068: sub modify_coursegroup_membership {
 6069:     my ($cdom,$cnum,$membership) = @_;
 6070:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6071:     return $result;
 6072: }
 6073: 
 6074: sub get_active_groups {
 6075:     my ($udom,$uname,$cdom,$cnum) = @_;
 6076:     my $now = time;
 6077:     my %groups = ();
 6078:     foreach my $key (keys(%env)) {
 6079:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6080:             my ($start,$end) = split(/\./,$env{$key});
 6081:             if (($end!=0) && ($end<$now)) { next; }
 6082:             if (($start!=0) && ($start>$now)) { next; }
 6083:             if ($1 eq $cdom && $2 eq $cnum) {
 6084:                 $groups{$3} = $env{$key} ;
 6085:             }
 6086:         }
 6087:     }
 6088:     return %groups;
 6089: }
 6090: 
 6091: sub get_group_membership {
 6092:     my ($cdom,$cnum,$group) = @_;
 6093:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6094: }
 6095: 
 6096: sub get_users_groups {
 6097:     my ($udom,$uname,$courseid) = @_;
 6098:     my @usersgroups;
 6099:     my $cachetime=1800;
 6100: 
 6101:     my $hashid="$udom:$uname:$courseid";
 6102:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6103:     if (defined($cached)) {
 6104:         @usersgroups = split(/:/,$grouplist);
 6105:     } else {  
 6106:         $grouplist = '';
 6107:         my $courseurl = &courseid_to_courseurl($courseid);
 6108:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 6109:         my $access_end = $env{'course.'.$courseid.
 6110:                               '.default_enrollment_end_date'};
 6111:         my $now = time;
 6112:         foreach my $key (keys(%roleshash)) {
 6113:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6114:                 my $group = $1;
 6115:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6116:                     my $start = $2;
 6117:                     my $end = $1;
 6118:                     if ($start == -1) { next; } # deleted from group
 6119:                     if (($start!=0) && ($start>$now)) { next; }
 6120:                     if (($end!=0) && ($end<$now)) {
 6121:                         if ($access_end && $access_end < $now) {
 6122:                             if ($access_end - $end < 86400) {
 6123:                                 push(@usersgroups,$group);
 6124:                             }
 6125:                         }
 6126:                         next;
 6127:                     }
 6128:                     push(@usersgroups,$group);
 6129:                 }
 6130:             }
 6131:         }
 6132:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6133:         $grouplist = join(':',@usersgroups);
 6134:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6135:     }
 6136:     return @usersgroups;
 6137: }
 6138: 
 6139: sub devalidate_getgroups_cache {
 6140:     my ($udom,$uname,$cdom,$cnum)=@_;
 6141:     my $courseid = $cdom.'_'.$cnum;
 6142: 
 6143:     my $hashid="$udom:$uname:$courseid";
 6144:     &devalidate_cache_new('getgroups',$hashid);
 6145: }
 6146: 
 6147: # ------------------------------------------------------------------ Plain Text
 6148: 
 6149: sub plaintext {
 6150:     my ($short,$type,$cid,$forcedefault) = @_;
 6151:     if ($short =~ m{^cr/}) {
 6152: 	return (split('/',$short))[-1];
 6153:     }
 6154:     if (!defined($cid)) {
 6155:         $cid = $env{'request.course.id'};
 6156:     }
 6157:     my %rolenames = (
 6158:                       Course    => 'std',
 6159:                       Community => 'alt1',
 6160:                     );
 6161:     if ($cid ne '') {
 6162:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6163:             unless ($forcedefault) {
 6164:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6165:                 &Apache::lonlocal::mt_escape(\$roletext);
 6166:                 return &Apache::lonlocal::mt($roletext);
 6167:             }
 6168:         }
 6169:     }
 6170:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6171:         (defined($rolenames{$type})) && 
 6172:         (defined($prp{$short}{$rolenames{$type}}))) {
 6173:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6174:     } elsif ($cid ne '') {
 6175:         my $crstype = $env{'course.'.$cid.'.type'};
 6176:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6177:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 6178:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 6179:         }
 6180:     }
 6181:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 6182: }
 6183: 
 6184: # ----------------------------------------------------------------- Assign Role
 6185: 
 6186: sub assignrole {
 6187:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6188:         $context)=@_;
 6189:     my $mrole;
 6190:     if ($role =~ /^cr\//) {
 6191:         my $cwosec=$url;
 6192:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6193: 	unless (&allowed('ccr',$cwosec)) {
 6194:            my $refused = 1;
 6195:            if ($context eq 'requestcourses') {
 6196:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 6197:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 6198:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 6199:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6200:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6201:                            if ($crsenv{'internal.courseowner'} eq
 6202:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 6203:                                $refused = '';
 6204:                            }
 6205:                        }
 6206:                    }
 6207:                }
 6208:            }
 6209:            if ($refused) {
 6210:                &logthis('Refused custom assignrole: '.
 6211:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 6212:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 6213:                return 'refused';
 6214:            }
 6215:         }
 6216:         $mrole='cr';
 6217:     } elsif ($role =~ /^gr\//) {
 6218:         my $cwogrp=$url;
 6219:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 6220:         unless (&allowed('mdg',$cwogrp)) {
 6221:             &logthis('Refused group assignrole: '.
 6222:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6223:                     $env{'user.name'}.' at '.$env{'user.domain'});
 6224:             return 'refused';
 6225:         }
 6226:         $mrole='gr';
 6227:     } else {
 6228:         my $cwosec=$url;
 6229:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6230:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 6231:             my $refused;
 6232:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 6233:                 if (!(&allowed('c'.$role,$url))) {
 6234:                     $refused = 1;
 6235:                 }
 6236:             } else {
 6237:                 $refused = 1;
 6238:             }
 6239:             if ($refused) {
 6240:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6241:                 if (!$selfenroll && $context eq 'course') {
 6242:                     my %crsenv;
 6243:                     if ($role eq 'cc' || $role eq 'co') {
 6244:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6245:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 6246:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 6247:                                 if ($crsenv{'internal.courseowner'} eq 
 6248:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6249:                                     $refused = '';
 6250:                                 }
 6251:                             }
 6252:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 6253:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 6254:                                 if ($crsenv{'internal.courseowner'} eq 
 6255:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6256:                                     $refused = '';
 6257:                                 }
 6258:                             }
 6259:                         }
 6260:                     }
 6261:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6262:                     $refused = '';
 6263:                 } elsif ($context eq 'requestcourses') {
 6264:                     my @possroles = ('st','ta','ep','in','cc','co');
 6265:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 6266:                         my $wrongcc;
 6267:                         if ($cnum =~ /^$match_community$/) {
 6268:                             $wrongcc = 1 if ($role eq 'cc');
 6269:                         } else {
 6270:                             $wrongcc = 1 if ($role eq 'co');
 6271:                         }
 6272:                         unless ($wrongcc) {
 6273:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6274:                             if ($crsenv{'internal.courseowner'} eq 
 6275:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 6276:                                 $refused = '';
 6277:                             }
 6278:                         }
 6279:                     }
 6280:                 }
 6281:                 if ($refused) {
 6282:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6283:                              ' '.$role.' '.$end.' '.$start.' by '.
 6284: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6285:                     return 'refused';
 6286:                 }
 6287:             }
 6288:         }
 6289:         $mrole=$role;
 6290:     }
 6291:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6292:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6293:     if ($end) { $command.='_'.$end; }
 6294:     if ($start) {
 6295: 	if ($end) { 
 6296:            $command.='_'.$start; 
 6297:         } else {
 6298:            $command.='_0_'.$start;
 6299:         }
 6300:     }
 6301:     my $origstart = $start;
 6302:     my $origend = $end;
 6303:     my $delflag;
 6304: # actually delete
 6305:     if ($deleteflag) {
 6306: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6307: # modify command to delete the role
 6308:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6309:                 "$udom:$uname:$url".'_'."$mrole";
 6310: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6311: # set start and finish to negative values for userrolelog
 6312:            $start=-1;
 6313:            $end=-1;
 6314:            $delflag = 1;
 6315:         }
 6316:     }
 6317: # send command
 6318:     my $answer=&reply($command,&homeserver($uname,$udom));
 6319: # log new user role if status is ok
 6320:     if ($answer eq 'ok') {
 6321: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6322: # for course roles, perform group memberships changes triggered by role change.
 6323:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6324:         unless ($role =~ /^gr/) {
 6325:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6326:                                              $origstart,$selfenroll,$context);
 6327:         }
 6328:     }
 6329:     return $answer;
 6330: }
 6331: 
 6332: # -------------------------------------------------- Modify user authentication
 6333: # Overrides without validation
 6334: 
 6335: sub modifyuserauth {
 6336:     my ($udom,$uname,$umode,$upass)=@_;
 6337:     my $uhome=&homeserver($uname,$udom);
 6338:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6339:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6340:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6341:              ' in domain '.$env{'request.role.domain'});  
 6342:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6343: 		     &escape($upass),$uhome);
 6344:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6345:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6346:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6347:     &log($udom,,$uname,$uhome,
 6348:         'Authentication changed by '.$env{'user.domain'}.', '.
 6349:                                      $env{'user.name'}.', '.$umode.
 6350:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6351:     unless ($reply eq 'ok') {
 6352:         &logthis('Authentication mode error: '.$reply);
 6353: 	return 'error: '.$reply;
 6354:     }   
 6355:     return 'ok';
 6356: }
 6357: 
 6358: # --------------------------------------------------------------- Modify a user
 6359: 
 6360: sub modifyuser {
 6361:     my ($udom,    $uname, $uid,
 6362:         $umode,   $upass, $first,
 6363:         $middle,  $last,  $gene,
 6364:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6365:     $udom= &LONCAPA::clean_domain($udom);
 6366:     $uname=&LONCAPA::clean_username($uname);
 6367:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6368:              $umode.', '.$first.', '.$middle.', '.
 6369: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6370:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6371:                                      ' desiredhome not specified'). 
 6372:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6373:              ' in domain '.$env{'request.role.domain'});
 6374:     my $uhome=&homeserver($uname,$udom,'true');
 6375: # ----------------------------------------------------------------- Create User
 6376:     if (($uhome eq 'no_host') && 
 6377: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6378:         my $unhome='';
 6379:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6380:             $unhome = $desiredhome;
 6381: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6382: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6383:         } else { # load balancing routine for determining $unhome
 6384:             my $loadm=10000000;
 6385: 	    my %servers = &get_servers($udom,'library');
 6386: 	    foreach my $tryserver (keys(%servers)) {
 6387: 		my $answer=reply('load',$tryserver);
 6388: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6389: 		    $loadm=$answer;
 6390: 		    $unhome=$tryserver;
 6391: 		}
 6392: 	    }
 6393:         }
 6394:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6395: 	    return 'error: unable to find a home server for '.$uname.
 6396:                    ' in domain '.$udom;
 6397:         }
 6398:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6399:                          &escape($upass),$unhome);
 6400: 	unless ($reply eq 'ok') {
 6401:             return 'error: '.$reply;
 6402:         }   
 6403:         $uhome=&homeserver($uname,$udom,'true');
 6404:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6405: 	    return 'error: unable verify users home machine.';
 6406:         }
 6407:     }   # End of creation of new user
 6408: # ---------------------------------------------------------------------- Add ID
 6409:     if ($uid) {
 6410:        $uid=~tr/A-Z/a-z/;
 6411:        my %uidhash=&idrget($udom,$uname);
 6412:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6413:          && (!$forceid)) {
 6414: 	  unless ($uid eq $uidhash{$uname}) {
 6415: 	      return 'error: user id "'.$uid.'" does not match '.
 6416:                   'current user id "'.$uidhash{$uname}.'".';
 6417:           }
 6418:        } else {
 6419: 	  &idput($udom,($uname => $uid));
 6420:        }
 6421:     }
 6422: # -------------------------------------------------------------- Add names, etc
 6423:     my @tmp=&get('environment',
 6424: 		   ['firstname','middlename','lastname','generation','id',
 6425:                     'permanentemail','inststatus'],
 6426: 		   $udom,$uname);
 6427:     my %names;
 6428:     if ($tmp[0] =~ m/^error:.*/) { 
 6429:         %names=(); 
 6430:     } else {
 6431:         %names = @tmp;
 6432:     }
 6433: #
 6434: # Make sure to not trash student environment if instructor does not bother
 6435: # to supply name and email information
 6436: #
 6437:     if ($first)  { $names{'firstname'}  = $first; }
 6438:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6439:     if ($last)   { $names{'lastname'}   = $last; }
 6440:     if (defined($gene))   { $names{'generation'} = $gene; }
 6441:     if ($email) {
 6442:        $email=~s/[^\w\@\.\-\,]//gs;
 6443:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6444:     }
 6445:     if ($uid) { $names{'id'}  = $uid; }
 6446:     if (defined($inststatus)) {
 6447:         $names{'inststatus'} = '';
 6448:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6449:         if (ref($usertypes) eq 'HASH') {
 6450:             my @okstatuses; 
 6451:             foreach my $item (split(/:/,$inststatus)) {
 6452:                 if (defined($usertypes->{$item})) {
 6453:                     push(@okstatuses,$item);  
 6454:                 }
 6455:             }
 6456:             if (@okstatuses) {
 6457:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6458:             }
 6459:         }
 6460:     }
 6461:     my $reply = &put('environment', \%names, $udom,$uname);
 6462:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6463:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6464:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6465:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6466:                  $umode.', '.$first.', '.$middle.', '.
 6467: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6468:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6469:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6470:     } else {
 6471:         $logmsg .= ' during self creation';
 6472:     }
 6473:     &logthis($logmsg);
 6474:     return 'ok';
 6475: }
 6476: 
 6477: # -------------------------------------------------------------- Modify student
 6478: 
 6479: sub modifystudent {
 6480:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6481:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6482:         $selfenroll,$context,$inststatus)=@_;
 6483:     if (!$cid) {
 6484: 	unless ($cid=$env{'request.course.id'}) {
 6485: 	    return 'not_in_class';
 6486: 	}
 6487:     }
 6488: # --------------------------------------------------------------- Make the user
 6489:     my $reply=&modifyuser
 6490: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6491:          $desiredhome,$email,$inststatus);
 6492:     unless ($reply eq 'ok') { return $reply; }
 6493:     # This will cause &modify_student_enrollment to get the uid from the
 6494:     # students environment
 6495:     $uid = undef if (!$forceid);
 6496:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6497: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6498:     return $reply;
 6499: }
 6500: 
 6501: sub modify_student_enrollment {
 6502:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6503:     my ($cdom,$cnum,$chome);
 6504:     if (!$cid) {
 6505: 	unless ($cid=$env{'request.course.id'}) {
 6506: 	    return 'not_in_class';
 6507: 	}
 6508: 	$cdom=$env{'course.'.$cid.'.domain'};
 6509: 	$cnum=$env{'course.'.$cid.'.num'};
 6510:     } else {
 6511: 	($cdom,$cnum)=split(/_/,$cid);
 6512:     }
 6513:     $chome=$env{'course.'.$cid.'.home'};
 6514:     if (!$chome) {
 6515: 	$chome=&homeserver($cnum,$cdom);
 6516:     }
 6517:     if (!$chome) { return 'unknown_course'; }
 6518:     # Make sure the user exists
 6519:     my $uhome=&homeserver($uname,$udom);
 6520:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6521: 	return 'error: no such user';
 6522:     }
 6523:     # Get student data if we were not given enough information
 6524:     if (!defined($first)  || $first  eq '' || 
 6525:         !defined($last)   || $last   eq '' || 
 6526:         !defined($uid)    || $uid    eq '' || 
 6527:         !defined($middle) || $middle eq '' || 
 6528:         !defined($gene)   || $gene   eq '') {
 6529:         # They did not supply us with enough data to enroll the student, so
 6530:         # we need to pick up more information.
 6531:         my %tmp = &get('environment',
 6532:                        ['firstname','middlename','lastname', 'generation','id']
 6533:                        ,$udom,$uname);
 6534: 
 6535:         #foreach my $key (keys(%tmp)) {
 6536:         #    &logthis("key $key = ".$tmp{$key});
 6537:         #}
 6538:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6539:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6540:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6541:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6542:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6543:     }
 6544:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6545:     my $reply=cput('classlist',
 6546: 		   {"$uname:$udom" => 
 6547: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6548: 		   $cdom,$cnum);
 6549:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6550: 	return 'error: '.$reply;
 6551:     } else {
 6552: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6553:     }
 6554:     # Add student role to user
 6555:     my $uurl='/'.$cid;
 6556:     $uurl=~s/\_/\//g;
 6557:     if ($usec) {
 6558: 	$uurl.='/'.$usec;
 6559:     }
 6560:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6561: }
 6562: 
 6563: sub format_name {
 6564:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6565:     my $name;
 6566:     if ($first ne 'lastname') {
 6567: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6568:     } else {
 6569: 	if ($lastname=~/\S/) {
 6570: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6571: 	    $name=~s/\s+,/,/;
 6572: 	} else {
 6573: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6574: 	}
 6575:     }
 6576:     $name=~s/^\s+//;
 6577:     $name=~s/\s+$//;
 6578:     $name=~s/\s+/ /g;
 6579:     return $name;
 6580: }
 6581: 
 6582: # ------------------------------------------------- Write to course preferences
 6583: 
 6584: sub writecoursepref {
 6585:     my ($courseid,%prefs)=@_;
 6586:     $courseid=~s/^\///;
 6587:     $courseid=~s/\_/\//g;
 6588:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6589:     my $chome=homeserver($cnum,$cdomain);
 6590:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6591: 	return 'error: no such course';
 6592:     }
 6593:     my $cstring='';
 6594:     foreach my $pref (keys(%prefs)) {
 6595: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6596:     }
 6597:     $cstring=~s/\&$//;
 6598:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6599: }
 6600: 
 6601: # ---------------------------------------------------------- Make/modify course
 6602: 
 6603: sub createcourse {
 6604:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6605:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 6606:     $url=&declutter($url);
 6607:     my $cid='';
 6608:     if ($context eq 'requestcourses') {
 6609:         my $can_create = 0;
 6610:         my ($ownername,$ownerdom) = split(':',$course_owner);
 6611:         if ($udom eq $ownerdom) {
 6612:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 6613:                                   $context)) {
 6614:                 $can_create = 1;
 6615:             }
 6616:         } else {
 6617:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 6618:                                            $category);
 6619:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 6620:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 6621:                 if (@curr > 0) {
 6622:                     my @options = qw(approval validate autolimit);
 6623:                     my $optregex = join('|',@options);
 6624:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 6625:                         $can_create = 1;
 6626:                     }
 6627:                 }
 6628:             }
 6629:         }
 6630:         if ($can_create) {
 6631:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 6632:                 unless (&allowed('ccc',$udom)) {
 6633:                     return 'refused'; 
 6634:                 }
 6635:             }
 6636:         } else {
 6637:             return 'refused';
 6638:         }
 6639:     } elsif (!&allowed('ccc',$udom)) {
 6640:         return 'refused';
 6641:     }
 6642: # --------------------------------------------------------------- Get Unique ID
 6643:     my $uname;
 6644:     if ($cnum =~ /^$match_courseid$/) {
 6645:         my $chome=&homeserver($cnum,$udom,'true');
 6646:         if (($chome eq '') || ($chome eq 'no_host')) {
 6647:             $uname = $cnum;
 6648:         } else {
 6649:             $uname = &generate_coursenum($udom,$crstype);
 6650:         }
 6651:     } else {
 6652:         $uname = &generate_coursenum($udom,$crstype);
 6653:     }
 6654:     return $uname if ($uname =~ /^error/);
 6655: # -------------------------------------------------- Check supplied server name
 6656:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6657:     if (! &is_library($course_server)) {
 6658:         return 'error:bad server name '.$course_server;
 6659:     }
 6660: # ------------------------------------------------------------- Make the course
 6661:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6662:                       $course_server);
 6663:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6664:     my $uhome=&homeserver($uname,$udom,'true');
 6665:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6666: 	return 'error: no such course';
 6667:     }
 6668: # ----------------------------------------------------------------- Course made
 6669: # log existence
 6670:     my $now = time;
 6671:     my $newcourse = {
 6672:                     $udom.'_'.$uname => {
 6673:                                      description => $description,
 6674:                                      inst_code   => $inst_code,
 6675:                                      owner       => $course_owner,
 6676:                                      type        => $crstype,
 6677:                                      creator     => $env{'user.name'}.':'.
 6678:                                                     $env{'user.domain'},
 6679:                                      created     => $now,
 6680:                                      context     => $context,
 6681:                                                 },
 6682:                     };
 6683:     &courseidput($udom,$newcourse,$uhome,'notime');
 6684: # set toplevel url
 6685:     my $topurl=$url;
 6686:     unless ($nonstandard) {
 6687: # ------------------------------------------ For standard courses, make top url
 6688:         my $mapurl=&clutter($url);
 6689:         if ($mapurl eq '/res/') { $mapurl=''; }
 6690:         $env{'form.initmap'}=(<<ENDINITMAP);
 6691: <map>
 6692: <resource id="1" type="start"></resource>
 6693: <resource id="2" src="$mapurl"></resource>
 6694: <resource id="3" type="finish"></resource>
 6695: <link index="1" from="1" to="2"></link>
 6696: <link index="2" from="2" to="3"></link>
 6697: </map>
 6698: ENDINITMAP
 6699:         $topurl=&declutter(
 6700:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6701:                           );
 6702:     }
 6703: # ----------------------------------------------------------- Write preferences
 6704:     &writecoursepref($udom.'_'.$uname,
 6705:                      ('description' => $description,
 6706:                       'url'         => $topurl));
 6707:     return '/'.$udom.'/'.$uname;
 6708: }
 6709: 
 6710: # ------------------------------------------------------------------- Create ID
 6711: sub generate_coursenum {
 6712:     my ($udom,$crstype) = @_;
 6713:     my $domdesc = &domain($udom);
 6714:     return 'error: invalid domain' if ($domdesc eq '');
 6715:     my $first;
 6716:     if ($crstype eq 'Community') {
 6717:         $first = '0';
 6718:     } else {
 6719:         $first = int(1+rand(9)); 
 6720:     } 
 6721:     my $uname=$first.
 6722:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6723:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6724:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6725: # ----------------------------------------------- Make sure that does not exist
 6726:     my $uhome=&homeserver($uname,$udom,'true');
 6727:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6728:         if ($crstype eq 'Community') {
 6729:             $first = '0';
 6730:         } else {
 6731:             $first = int(1+rand(9));
 6732:         }
 6733:         $uname=$first.
 6734:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6735:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6736:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6737:         $uhome=&homeserver($uname,$udom,'true');
 6738:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6739:             return 'error: unable to generate unique course-ID';
 6740:         }
 6741:     }
 6742:     return $uname;
 6743: }
 6744: 
 6745: sub is_course {
 6746:     my ($cdom,$cnum) = @_;
 6747:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6748: 				undef,'.');
 6749:     if (exists($courses{$cdom.'_'.$cnum})) {
 6750:         return 1;
 6751:     }
 6752:     return 0;
 6753: }
 6754: 
 6755: sub store_userdata {
 6756:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 6757:     my $result;
 6758:     if ($datakey ne '') {
 6759:         if (ref($storehash) eq 'HASH') {
 6760:             if ($udom eq '' || $uname eq '') {
 6761:                 $udom = $env{'user.domain'};
 6762:                 $uname = $env{'user.name'};
 6763:             }
 6764:             my $uhome=&homeserver($uname,$udom);
 6765:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 6766:                 $result = 'error: no_host';
 6767:             } else {
 6768:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 6769:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 6770: 
 6771:                 my $namevalue='';
 6772:                 foreach my $key (keys(%{$storehash})) {
 6773:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6774:                 }
 6775:                 $namevalue=~s/\&$//;
 6776:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
 6777:                                   "$namespace:$datakey:$namevalue",$uhome);
 6778:             }
 6779:         } else {
 6780:             $result = 'error: data to store was not a hash reference'; 
 6781:         }
 6782:     } else {
 6783:         $result= 'error: invalid requestkey'; 
 6784:     }
 6785:     return $result;
 6786: }
 6787: 
 6788: # ---------------------------------------------------------- Assign Custom Role
 6789: 
 6790: sub assigncustomrole {
 6791:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6792:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6793:                        $end,$start,$deleteflag,$selfenroll,$context);
 6794: }
 6795: 
 6796: # ----------------------------------------------------------------- Revoke Role
 6797: 
 6798: sub revokerole {
 6799:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6800:     my $now=time;
 6801:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6802: }
 6803: 
 6804: # ---------------------------------------------------------- Revoke Custom Role
 6805: 
 6806: sub revokecustomrole {
 6807:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6808:     my $now=time;
 6809:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6810:            $deleteflag,$selfenroll,$context);
 6811: }
 6812: 
 6813: # ------------------------------------------------------------ Disk usage
 6814: sub diskusage {
 6815:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6816:     $directorypath =~ s/\/$//;
 6817:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6818:                        .&escape($getpropath).':'.&escape($uname).':'
 6819:                        .&escape($udom),homeserver($uname,$udom));
 6820:     if ($listing eq 'unknown_cmd') {
 6821:         if ($getpropath) {
 6822:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6823:         }
 6824:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6825:     }
 6826:     return $listing;
 6827: }
 6828: 
 6829: sub is_locked {
 6830:     my ($file_name, $domain, $user) = @_;
 6831:     my @check;
 6832:     my $is_locked;
 6833:     push @check, $file_name;
 6834:     my %locked = &get('file_permissions',\@check,
 6835: 		      $env{'user.domain'},$env{'user.name'});
 6836:     my ($tmp)=keys(%locked);
 6837:     if ($tmp=~/^error:/) { undef(%locked); }
 6838:     
 6839:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6840:         $is_locked = 'false';
 6841:         foreach my $entry (@{$locked{$file_name}}) {
 6842:            if (ref($entry) eq 'ARRAY') { 
 6843:                $is_locked = 'true';
 6844:                last;
 6845:            }
 6846:        }
 6847:     } else {
 6848:         $is_locked = 'false';
 6849:     }
 6850: }
 6851: 
 6852: sub declutter_portfile {
 6853:     my ($file) = @_;
 6854:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6855:     return $file;
 6856: }
 6857: 
 6858: # ------------------------------------------------------------- Mark as Read Only
 6859: 
 6860: sub mark_as_readonly {
 6861:     my ($domain,$user,$files,$what) = @_;
 6862:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6863:     my ($tmp)=keys(%current_permissions);
 6864:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6865:     foreach my $file (@{$files}) {
 6866: 	$file = &declutter_portfile($file);
 6867:         push(@{$current_permissions{$file}},$what);
 6868:     }
 6869:     &put('file_permissions',\%current_permissions,$domain,$user);
 6870:     return;
 6871: }
 6872: 
 6873: # ------------------------------------------------------------Save Selected Files
 6874: 
 6875: sub save_selected_files {
 6876:     my ($user, $path, @files) = @_;
 6877:     my $filename = $user."savedfiles";
 6878:     my @other_files = &files_not_in_path($user, $path);
 6879:     open (OUT, '>'.$tmpdir.$filename);
 6880:     foreach my $file (@files) {
 6881:         print (OUT $env{'form.currentpath'}.$file."\n");
 6882:     }
 6883:     foreach my $file (@other_files) {
 6884:         print (OUT $file."\n");
 6885:     }
 6886:     close (OUT);
 6887:     return 'ok';
 6888: }
 6889: 
 6890: sub clear_selected_files {
 6891:     my ($user) = @_;
 6892:     my $filename = $user."savedfiles";
 6893:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6894:     print (OUT undef);
 6895:     close (OUT);
 6896:     return ("ok");    
 6897: }
 6898: 
 6899: sub files_in_path {
 6900:     my ($user, $path) = @_;
 6901:     my $filename = $user."savedfiles";
 6902:     my %return_files;
 6903:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6904:     while (my $line_in = <IN>) {
 6905:         chomp ($line_in);
 6906:         my @paths_and_file = split (m!/!, $line_in);
 6907:         my $file_part = pop (@paths_and_file);
 6908:         my $path_part = join ('/', @paths_and_file);
 6909:         $path_part.='/';
 6910:         my $path_and_file = $path_part.$file_part;
 6911:         if ($path_part eq $path) {
 6912:             $return_files{$file_part}= 'selected';
 6913:         }
 6914:     }
 6915:     close (IN);
 6916:     return (\%return_files);
 6917: }
 6918: 
 6919: # called in portfolio select mode, to show files selected NOT in current directory
 6920: sub files_not_in_path {
 6921:     my ($user, $path) = @_;
 6922:     my $filename = $user."savedfiles";
 6923:     my @return_files;
 6924:     my $path_part;
 6925:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6926:     while (my $line = <IN>) {
 6927:         #ok, I know it's clunky, but I want it to work
 6928:         my @paths_and_file = split(m|/|, $line);
 6929:         my $file_part = pop(@paths_and_file);
 6930:         chomp($file_part);
 6931:         my $path_part = join('/', @paths_and_file);
 6932:         $path_part .= '/';
 6933:         my $path_and_file = $path_part.$file_part;
 6934:         if ($path_part ne $path) {
 6935:             push(@return_files, ($path_and_file));
 6936:         }
 6937:     }
 6938:     close(OUT);
 6939:     return (@return_files);
 6940: }
 6941: 
 6942: #----------------------------------------------Get portfolio file permissions
 6943: 
 6944: sub get_portfile_permissions {
 6945:     my ($domain,$user) = @_;
 6946:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6947:     my ($tmp)=keys(%current_permissions);
 6948:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6949:     return \%current_permissions;
 6950: }
 6951: 
 6952: #---------------------------------------------Get portfolio file access controls
 6953: 
 6954: sub get_access_controls {
 6955:     my ($current_permissions,$group,$file) = @_;
 6956:     my %access;
 6957:     my $real_file = $file;
 6958:     $file =~ s/\.meta$//;
 6959:     if (defined($file)) {
 6960:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6961:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6962:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6963:             }
 6964:         }
 6965:     } else {
 6966:         foreach my $key (keys(%{$current_permissions})) {
 6967:             if ($key =~ /\0accesscontrol$/) {
 6968:                 if (defined($group)) {
 6969:                     if ($key !~ m-^\Q$group\E/-) {
 6970:                         next;
 6971:                     }
 6972:                 }
 6973:                 my ($fullpath) = split(/\0/,$key);
 6974:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6975:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6976:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6977:                     }
 6978:                 }
 6979:             }
 6980:         }
 6981:     }
 6982:     return %access;
 6983: }
 6984: 
 6985: sub modify_access_controls {
 6986:     my ($file_name,$changes,$domain,$user)=@_;
 6987:     my ($outcome,$deloutcome);
 6988:     my %store_permissions;
 6989:     my %new_values;
 6990:     my %new_control;
 6991:     my %translation;
 6992:     my @deletions = ();
 6993:     my $now = time;
 6994:     if (exists($$changes{'activate'})) {
 6995:         if (ref($$changes{'activate'}) eq 'HASH') {
 6996:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6997:             my $numnew = scalar(@newitems);
 6998:             for (my $i=0; $i<$numnew; $i++) {
 6999:                 my $newkey = $newitems[$i];
 7000:                 my $newid = &Apache::loncommon::get_cgi_id();
 7001:                 if ($newkey =~ /^\d+:/) { 
 7002:                     $newkey =~ s/^(\d+)/$newid/;
 7003:                     $translation{$1} = $newid;
 7004:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 7005:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 7006:                     $translation{$1} = $newid;
 7007:                 }
 7008:                 $new_values{$file_name."\0".$newkey} = 
 7009:                                           $$changes{'activate'}{$newitems[$i]};
 7010:                 $new_control{$newkey} = $now;
 7011:             }
 7012:         }
 7013:     }
 7014:     my %todelete;
 7015:     my %changed_items;
 7016:     foreach my $action ('delete','update') {
 7017:         if (exists($$changes{$action})) {
 7018:             if (ref($$changes{$action}) eq 'HASH') {
 7019:                 foreach my $key (keys(%{$$changes{$action}})) {
 7020:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 7021:                     if ($action eq 'delete') { 
 7022:                         $todelete{$itemnum} = 1;
 7023:                     } else {
 7024:                         $changed_items{$itemnum} = $key;
 7025:                     }
 7026:                 }
 7027:             }
 7028:         }
 7029:     }
 7030:     # get lock on access controls for file.
 7031:     my $lockhash = {
 7032:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 7033:                                                        ':'.$env{'user.domain'},
 7034:                    }; 
 7035:     my $tries = 0;
 7036:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7037:    
 7038:     while (($gotlock ne 'ok') && $tries <3) {
 7039:         $tries ++;
 7040:         sleep 1;
 7041:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7042:     }
 7043:     if ($gotlock eq 'ok') {
 7044:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 7045:         my ($tmp)=keys(%curr_permissions);
 7046:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 7047:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 7048:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 7049:             if (ref($curr_controls) eq 'HASH') {
 7050:                 foreach my $control_item (keys(%{$curr_controls})) {
 7051:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 7052:                     if (defined($todelete{$itemnum})) {
 7053:                         push(@deletions,$file_name."\0".$control_item);
 7054:                     } else {
 7055:                         if (defined($changed_items{$itemnum})) {
 7056:                             $new_control{$changed_items{$itemnum}} = $now;
 7057:                             push(@deletions,$file_name."\0".$control_item);
 7058:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 7059:                         } else {
 7060:                             $new_control{$control_item} = $$curr_controls{$control_item};
 7061:                         }
 7062:                     }
 7063:                 }
 7064:             }
 7065:         }
 7066:         my ($group);
 7067:         if (&is_course($domain,$user)) {
 7068:             ($group,my $file) = split(/\//,$file_name,2);
 7069:         }
 7070:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 7071:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 7072:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 7073:         #  remove lock
 7074:         my @del_lock = ($file_name."\0".'locked_access_records');
 7075:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 7076:         my $sqlresult =
 7077:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 7078:                                     $group);
 7079:     } else {
 7080:         $outcome = "error: could not obtain lockfile\n";  
 7081:     }
 7082:     return ($outcome,$deloutcome,\%new_values,\%translation);
 7083: }
 7084: 
 7085: sub make_public_indefinitely {
 7086:     my ($requrl) = @_;
 7087:     my $now = time;
 7088:     my $action = 'activate';
 7089:     my $aclnum = 0;
 7090:     if (&is_portfolio_url($requrl)) {
 7091:         my (undef,$udom,$unum,$file_name,$group) =
 7092:             &parse_portfolio_url($requrl);
 7093:         my $current_perms = &get_portfile_permissions($udom,$unum);
 7094:         my %access_controls = &get_access_controls($current_perms,
 7095:                                                    $group,$file_name);
 7096:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 7097:             my ($num,$scope,$end,$start) = 
 7098:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7099:             if ($scope eq 'public') {
 7100:                 if ($start <= $now && $end == 0) {
 7101:                     $action = 'none';
 7102:                 } else {
 7103:                     $action = 'update';
 7104:                     $aclnum = $num;
 7105:                 }
 7106:                 last;
 7107:             }
 7108:         }
 7109:         if ($action eq 'none') {
 7110:              return 'ok';
 7111:         } else {
 7112:             my %changes;
 7113:             my $newend = 0;
 7114:             my $newstart = $now;
 7115:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 7116:             $changes{$action}{$newkey} = {
 7117:                 type => 'public',
 7118:                 time => {
 7119:                     start => $newstart,
 7120:                     end   => $newend,
 7121:                 },
 7122:             };
 7123:             my ($outcome,$deloutcome,$new_values,$translation) =
 7124:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 7125:             return $outcome;
 7126:         }
 7127:     } else {
 7128:         return 'invalid';
 7129:     }
 7130: }
 7131: 
 7132: #------------------------------------------------------Get Marked as Read Only
 7133: 
 7134: sub get_marked_as_readonly {
 7135:     my ($domain,$user,$what,$group) = @_;
 7136:     my $current_permissions = &get_portfile_permissions($domain,$user);
 7137:     my @readonly_files;
 7138:     my $cmp1=$what;
 7139:     if (ref($what)) { $cmp1=join('',@{$what}) };
 7140:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7141:         if (defined($group)) {
 7142:             if ($file_name !~ m-^\Q$group\E/-) {
 7143:                 next;
 7144:             }
 7145:         }
 7146:         if (ref($value) eq "ARRAY"){
 7147:             foreach my $stored_what (@{$value}) {
 7148:                 my $cmp2=$stored_what;
 7149:                 if (ref($stored_what) eq 'ARRAY') {
 7150:                     $cmp2=join('',@{$stored_what});
 7151:                 }
 7152:                 if ($cmp1 eq $cmp2) {
 7153:                     push(@readonly_files, $file_name);
 7154:                     last;
 7155:                 } elsif (!defined($what)) {
 7156:                     push(@readonly_files, $file_name);
 7157:                     last;
 7158:                 }
 7159:             }
 7160:         }
 7161:     }
 7162:     return @readonly_files;
 7163: }
 7164: #-----------------------------------------------------------Get Marked as Read Only Hash
 7165: 
 7166: sub get_marked_as_readonly_hash {
 7167:     my ($current_permissions,$group,$what) = @_;
 7168:     my %readonly_files;
 7169:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7170:         if (defined($group)) {
 7171:             if ($file_name !~ m-^\Q$group\E/-) {
 7172:                 next;
 7173:             }
 7174:         }
 7175:         if (ref($value) eq "ARRAY"){
 7176:             foreach my $stored_what (@{$value}) {
 7177:                 if (ref($stored_what) eq 'ARRAY') {
 7178:                     foreach my $lock_descriptor(@{$stored_what}) {
 7179:                         if ($lock_descriptor eq 'graded') {
 7180:                             $readonly_files{$file_name} = 'graded';
 7181:                         } elsif ($lock_descriptor eq 'handback') {
 7182:                             $readonly_files{$file_name} = 'handback';
 7183:                         } else {
 7184:                             if (!exists($readonly_files{$file_name})) {
 7185:                                 $readonly_files{$file_name} = 'locked';
 7186:                             }
 7187:                         }
 7188:                     }
 7189:                 } 
 7190:             }
 7191:         } 
 7192:     }
 7193:     return %readonly_files;
 7194: }
 7195: # ------------------------------------------------------------ Unmark as Read Only
 7196: 
 7197: sub unmark_as_readonly {
 7198:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 7199:     # for portfolio submissions, $what contains [$symb,$crsid] 
 7200:     my ($domain,$user,$what,$file_name,$group) = @_;
 7201:     $file_name = &declutter_portfile($file_name);
 7202:     my $symb_crs = $what;
 7203:     if (ref($what)) { $symb_crs=join('',@$what); }
 7204:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 7205:     my ($tmp)=keys(%current_permissions);
 7206:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7207:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 7208:     foreach my $file (@readonly_files) {
 7209: 	my $clean_file = &declutter_portfile($file);
 7210: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 7211: 	my $current_locks = $current_permissions{$file};
 7212:         my @new_locks;
 7213:         my @del_keys;
 7214:         if (ref($current_locks) eq "ARRAY"){
 7215:             foreach my $locker (@{$current_locks}) {
 7216:                 my $compare=$locker;
 7217:                 if (ref($locker) eq 'ARRAY') {
 7218:                     $compare=join('',@{$locker});
 7219:                     if ($compare ne $symb_crs) {
 7220:                         push(@new_locks, $locker);
 7221:                     }
 7222:                 }
 7223:             }
 7224:             if (scalar(@new_locks) > 0) {
 7225:                 $current_permissions{$file} = \@new_locks;
 7226:             } else {
 7227:                 push(@del_keys, $file);
 7228:                 &del('file_permissions',\@del_keys, $domain, $user);
 7229:                 delete($current_permissions{$file});
 7230:             }
 7231:         }
 7232:     }
 7233:     &put('file_permissions',\%current_permissions,$domain,$user);
 7234:     return;
 7235: }
 7236: 
 7237: # ------------------------------------------------------------ Directory lister
 7238: 
 7239: sub dirlist {
 7240:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 7241:     $uri=~s/^\///;
 7242:     $uri=~s/\/$//;
 7243:     my ($udom, $uname);
 7244:     if ($getuserdir) {
 7245:         $udom = $userdomain;
 7246:         $uname = $username;
 7247:     } else {
 7248:         (undef,$udom,$uname)=split(/\//,$uri);
 7249:         if(defined($userdomain)) {
 7250:             $udom = $userdomain;
 7251:         }
 7252:         if(defined($username)) {
 7253:             $uname = $username;
 7254:         }
 7255:     }
 7256:     my ($dirRoot,$listing,@listing_results);
 7257: 
 7258:     $dirRoot = $perlvar{'lonDocRoot'};
 7259:     if (defined($getpropath)) {
 7260:         $dirRoot = &propath($udom,$uname);
 7261:         $dirRoot =~ s/\/$//;
 7262:     } elsif (defined($getuserdir)) {
 7263:         my $subdir=$uname.'__';
 7264:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 7265:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 7266:                    ."/$udom/$subdir/$uname";
 7267:     } elsif (defined($alternateRoot)) {
 7268:         $dirRoot = $alternateRoot;
 7269:     }
 7270: 
 7271:     if($udom) {
 7272:         if($uname) {
 7273:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 7274:                               .$getuserdir.':'.&escape($dirRoot)
 7275:                               .':'.&escape($uname).':'.&escape($udom),
 7276:                               &homeserver($uname,$udom));
 7277:             if ($listing eq 'unknown_cmd') {
 7278:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 7279:                                   &homeserver($uname,$udom));
 7280:             } else {
 7281:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7282:             }
 7283:             if ($listing eq 'unknown_cmd') {
 7284:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 7285: 				  &homeserver($uname,$udom));
 7286:                 @listing_results = split(/:/,$listing);
 7287:             } else {
 7288:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7289:             }
 7290:             return @listing_results;
 7291:         } elsif(!$alternateRoot) {
 7292:             my %allusers;
 7293: 	    my %servers = &get_servers($udom,'library');
 7294:  	    foreach my $tryserver (keys(%servers)) {
 7295:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 7296:                                   &escape($udom),$tryserver);
 7297:                 if ($listing eq 'unknown_cmd') {
 7298: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 7299: 				      $udom, $tryserver);
 7300:                 } else {
 7301:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 7302:                 }
 7303: 		if ($listing eq 'unknown_cmd') {
 7304: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 7305: 				      $udom, $tryserver);
 7306: 		    @listing_results = split(/:/,$listing);
 7307: 		} else {
 7308: 		    @listing_results =
 7309: 			map { &unescape($_); } split(/:/,$listing);
 7310: 		}
 7311: 		if ($listing_results[0] ne 'no_such_dir' && 
 7312: 		    $listing_results[0] ne 'empty'       &&
 7313: 		    $listing_results[0] ne 'con_lost') {
 7314: 		    foreach my $line (@listing_results) {
 7315: 			my ($entry) = split(/&/,$line,2);
 7316: 			$allusers{$entry} = 1;
 7317: 		    }
 7318: 		}
 7319:             }
 7320:             my $alluserstr='';
 7321:             foreach my $user (sort(keys(%allusers))) {
 7322:                 $alluserstr.=$user.'&user:';
 7323:             }
 7324:             $alluserstr=~s/:$//;
 7325:             return split(/:/,$alluserstr);
 7326:         } else {
 7327:             return ('missing user name');
 7328:         }
 7329:     } elsif(!defined($getpropath)) {
 7330:         my @all_domains = sort(&all_domains());
 7331:         foreach my $domain (@all_domains) {
 7332:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 7333:         }
 7334:         return @all_domains;
 7335:     } else {
 7336:         return ('missing domain');
 7337:     }
 7338: }
 7339: 
 7340: # --------------------------------------------- GetFileTimestamp
 7341: # This function utilizes dirlist and returns the date stamp for
 7342: # when it was last modified.  It will also return an error of -1
 7343: # if an error occurs
 7344: 
 7345: sub GetFileTimestamp {
 7346:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 7347:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 7348:     $studentName   = &LONCAPA::clean_username($studentName);
 7349:     my ($fileStat) = 
 7350:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 7351:                                  undef,$getuserdir);
 7352:     my @stats = split('&', $fileStat);
 7353:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7354:         # @stats contains first the filename, then the stat output
 7355:         return $stats[10]; # so this is 10 instead of 9.
 7356:     } else {
 7357:         return -1;
 7358:     }
 7359: }
 7360: 
 7361: sub stat_file {
 7362:     my ($uri) = @_;
 7363:     $uri = &clutter_with_no_wrapper($uri);
 7364: 
 7365:     my ($udom,$uname,$file);
 7366:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7367: 	($udom,$uname,$file) =
 7368: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7369: 	$file = 'userfiles/'.$file;
 7370:     }
 7371:     if ($uri =~ m-^/res/-) {
 7372: 	($udom,$uname) = 
 7373: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7374: 	$file = $uri;
 7375:     }
 7376: 
 7377:     if (!$udom || !$uname || !$file) {
 7378: 	# unable to handle the uri
 7379: 	return ();
 7380:     }
 7381:     my $getpropath;
 7382:     if ($file =~ /^userfiles\//) {
 7383:         $getpropath = 1;
 7384:     }
 7385:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7386:     my @stats = split('&', $result);
 7387:     
 7388:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7389: 	shift(@stats); #filename is first
 7390: 	return @stats;
 7391:     }
 7392:     return ();
 7393: }
 7394: 
 7395: # -------------------------------------------------------- Value of a Condition
 7396: 
 7397: # gets the value of a specific preevaluated condition
 7398: #    stored in the string  $env{user.state.<cid>}
 7399: # or looks up a condition reference in the bighash and if if hasn't
 7400: # already been evaluated recurses into docondval to get the value of
 7401: # the condition, then memoizing it to 
 7402: #   $env{user.state.<cid>.<condition>}
 7403: sub directcondval {
 7404:     my $number=shift;
 7405:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7406: 	&Apache::lonuserstate::evalstate();
 7407:     }
 7408:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7409: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7410:     } elsif ($number =~ /^_/) {
 7411: 	my $sub_condition;
 7412: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7413: 		&GDBM_READER(),0640)) {
 7414: 	    $sub_condition=$bighash{'conditions'.$number};
 7415: 	    untie(%bighash);
 7416: 	}
 7417: 	my $value = &docondval($sub_condition);
 7418: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7419: 	return $value;
 7420:     }
 7421:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7422:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7423:     } else {
 7424:        return 2;
 7425:     }
 7426: }
 7427: 
 7428: # get the collection of conditions for this resource
 7429: sub condval {
 7430:     my $condidx=shift;
 7431:     my $allpathcond='';
 7432:     foreach my $cond (split(/\|/,$condidx)) {
 7433: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7434: 	    $allpathcond.=
 7435: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7436: 	}
 7437:     }
 7438:     $allpathcond=~s/\|$//;
 7439:     return &docondval($allpathcond);
 7440: }
 7441: 
 7442: #evaluates an expression of conditions
 7443: sub docondval {
 7444:     my ($allpathcond) = @_;
 7445:     my $result=0;
 7446:     if ($env{'request.course.id'}
 7447: 	&& defined($allpathcond)) {
 7448: 	my $operand='|';
 7449: 	my @stack;
 7450: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7451: 	    if ($chunk eq '(') {
 7452: 		push @stack,($operand,$result);
 7453: 	    } elsif ($chunk eq ')') {
 7454: 		my $before=pop @stack;
 7455: 		if (pop @stack eq '&') {
 7456: 		    $result=$result>$before?$before:$result;
 7457: 		} else {
 7458: 		    $result=$result>$before?$result:$before;
 7459: 		}
 7460: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7461: 		$operand=$chunk;
 7462: 	    } else {
 7463: 		my $new=directcondval($chunk);
 7464: 		if ($operand eq '&') {
 7465: 		    $result=$result>$new?$new:$result;
 7466: 		} else {
 7467: 		    $result=$result>$new?$result:$new;
 7468: 		}
 7469: 	    }
 7470: 	}
 7471:     }
 7472:     return $result;
 7473: }
 7474: 
 7475: # ---------------------------------------------------- Devalidate courseresdata
 7476: 
 7477: sub devalidatecourseresdata {
 7478:     my ($coursenum,$coursedomain)=@_;
 7479:     my $hashid=$coursenum.':'.$coursedomain;
 7480:     &devalidate_cache_new('courseres',$hashid);
 7481: }
 7482: 
 7483: 
 7484: # --------------------------------------------------- Course Resourcedata Query
 7485: #
 7486: #  Parameters:
 7487: #      $coursenum    - Number of the course.
 7488: #      $coursedomain - Domain at which the course was created.
 7489: #  Returns:
 7490: #     A hash of the course parameters along (I think) with timestamps
 7491: #     and version info.
 7492: 
 7493: sub get_courseresdata {
 7494:     my ($coursenum,$coursedomain)=@_;
 7495:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7496:     my $hashid=$coursenum.':'.$coursedomain;
 7497:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7498:     my %dumpreply;
 7499:     unless (defined($cached)) {
 7500: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7501: 	$result=\%dumpreply;
 7502: 	my ($tmp) = keys(%dumpreply);
 7503: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7504: 	    &do_cache_new('courseres',$hashid,$result,600);
 7505: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7506: 	    return $tmp;
 7507: 	} elsif ($tmp =~ /^(error)/) {
 7508: 	    $result=undef;
 7509: 	    &do_cache_new('courseres',$hashid,$result,600);
 7510: 	}
 7511:     }
 7512:     return $result;
 7513: }
 7514: 
 7515: sub devalidateuserresdata {
 7516:     my ($uname,$udom)=@_;
 7517:     my $hashid="$udom:$uname";
 7518:     &devalidate_cache_new('userres',$hashid);
 7519: }
 7520: 
 7521: sub get_userresdata {
 7522:     my ($uname,$udom)=@_;
 7523:     #most student don\'t have any data set, check if there is some data
 7524:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7525: 
 7526:     my $hashid="$udom:$uname";
 7527:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7528:     if (!defined($cached)) {
 7529: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7530: 	$result=\%resourcedata;
 7531: 	&do_cache_new('userres',$hashid,$result,600);
 7532:     }
 7533:     my ($tmp)=keys(%$result);
 7534:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7535: 	return $result;
 7536:     }
 7537:     #error 2 occurs when the .db doesn't exist
 7538:     if ($tmp!~/error: 2 /) {
 7539: 	&logthis("<font color=\"blue\">WARNING:".
 7540: 		 " Trying to get resource data for ".
 7541: 		 $uname." at ".$udom.": ".
 7542: 		 $tmp."</font>");
 7543:     } elsif ($tmp=~/error: 2 /) {
 7544: 	#&EXT_cache_set($udom,$uname);
 7545: 	&do_cache_new('userres',$hashid,undef,600);
 7546: 	undef($tmp); # not really an error so don't send it back
 7547:     }
 7548:     return $tmp;
 7549: }
 7550: #----------------------------------------------- resdata - return resource data
 7551: #  Purpose:
 7552: #    Return resource data for either users or for a course.
 7553: #  Parameters:
 7554: #     $name      - Course/user name.
 7555: #     $domain    - Name of the domain the user/course is registered on.
 7556: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7557: #     @which     - Array of names of resources desired.
 7558: #  Returns:
 7559: #     The value of the first reasource in @which that is found in the
 7560: #     resource hash.
 7561: #  Exceptional Conditions:
 7562: #     If the $type passed in is not valid (not the string 'course' or 
 7563: #     'user', an undefined  reference is returned.
 7564: #     If none of the resources are found, an undef is returned
 7565: sub resdata {
 7566:     my ($name,$domain,$type,@which)=@_;
 7567:     my $result;
 7568:     if ($type eq 'course') {
 7569: 	$result=&get_courseresdata($name,$domain);
 7570:     } elsif ($type eq 'user') {
 7571: 	$result=&get_userresdata($name,$domain);
 7572:     }
 7573:     if (!ref($result)) { return $result; }    
 7574:     foreach my $item (@which) {
 7575: 	if (defined($result->{$item->[0]})) {
 7576: 	    return [$result->{$item->[0]},$item->[1]];
 7577: 	}
 7578:     }
 7579:     return undef;
 7580: }
 7581: 
 7582: #
 7583: # EXT resource caching routines
 7584: #
 7585: 
 7586: sub clear_EXT_cache_status {
 7587:     &delenv('cache.EXT.');
 7588: }
 7589: 
 7590: sub EXT_cache_status {
 7591:     my ($target_domain,$target_user) = @_;
 7592:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7593:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7594:         # We know already the user has no data
 7595:         return 1;
 7596:     } else {
 7597:         return 0;
 7598:     }
 7599: }
 7600: 
 7601: sub EXT_cache_set {
 7602:     my ($target_domain,$target_user) = @_;
 7603:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7604:     #&appenv({$cachename => time});
 7605: }
 7606: 
 7607: # --------------------------------------------------------- Value of a Variable
 7608: sub EXT {
 7609: 
 7610:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7611:     unless ($varname) { return ''; }
 7612:     #get real user name/domain, courseid and symb
 7613:     my $courseid;
 7614:     my $publicuser;
 7615:     if ($symbparm) {
 7616: 	$symbparm=&get_symb_from_alias($symbparm);
 7617:     }
 7618:     if (!($uname && $udom)) {
 7619:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7620:       if (!$symbparm) {	$symbparm=$cursymb; }
 7621:     } else {
 7622: 	$courseid=$env{'request.course.id'};
 7623:     }
 7624:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7625:     my $rest;
 7626:     if (defined($therest[0])) {
 7627:        $rest=join('.',@therest);
 7628:     } else {
 7629:        $rest='';
 7630:     }
 7631: 
 7632:     my $qualifierrest=$qualifier;
 7633:     if ($rest) { $qualifierrest.='.'.$rest; }
 7634:     my $spacequalifierrest=$space;
 7635:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7636:     if ($realm eq 'user') {
 7637: # --------------------------------------------------------------- user.resource
 7638: 	if ($space eq 'resource') {
 7639: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7640: 		  || defined($Apache::lonhomework::parsing_a_task))
 7641: 		 &&
 7642: 		 ($symbparm eq &symbread()) ) {	
 7643: 		# if we are in the middle of processing the resource the
 7644: 		# get the value we are planning on committing
 7645:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7646:                     return $Apache::lonhomework::results{$qualifierrest};
 7647:                 } else {
 7648:                     return $Apache::lonhomework::history{$qualifierrest};
 7649:                 }
 7650: 	    } else {
 7651: 		my %restored;
 7652: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7653: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7654: 		} else {
 7655: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7656: 		}
 7657: 		return $restored{$qualifierrest};
 7658: 	    }
 7659: # ----------------------------------------------------------------- user.access
 7660:         } elsif ($space eq 'access') {
 7661: 	    # FIXME - not supporting calls for a specific user
 7662:             return &allowed($qualifier,$rest);
 7663: # ------------------------------------------ user.preferences, user.environment
 7664:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7665: 	    if (($uname eq $env{'user.name'}) &&
 7666: 		($udom eq $env{'user.domain'})) {
 7667: 		return $env{join('.',('environment',$qualifierrest))};
 7668: 	    } else {
 7669: 		my %returnhash;
 7670: 		if (!$publicuser) {
 7671: 		    %returnhash=&userenvironment($udom,$uname,
 7672: 						 $qualifierrest);
 7673: 		}
 7674: 		return $returnhash{$qualifierrest};
 7675: 	    }
 7676: # ----------------------------------------------------------------- user.course
 7677:         } elsif ($space eq 'course') {
 7678: 	    # FIXME - not supporting calls for a specific user
 7679:             return $env{join('.',('request.course',$qualifier))};
 7680: # ------------------------------------------------------------------- user.role
 7681:         } elsif ($space eq 'role') {
 7682: 	    # FIXME - not supporting calls for a specific user
 7683:             my ($role,$where)=split(/\./,$env{'request.role'});
 7684:             if ($qualifier eq 'value') {
 7685: 		return $role;
 7686:             } elsif ($qualifier eq 'extent') {
 7687:                 return $where;
 7688:             }
 7689: # ----------------------------------------------------------------- user.domain
 7690:         } elsif ($space eq 'domain') {
 7691:             return $udom;
 7692: # ------------------------------------------------------------------- user.name
 7693:         } elsif ($space eq 'name') {
 7694:             return $uname;
 7695: # ---------------------------------------------------- Any other user namespace
 7696:         } else {
 7697: 	    my %reply;
 7698: 	    if (!$publicuser) {
 7699: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7700: 	    }
 7701: 	    return $reply{$qualifierrest};
 7702:         }
 7703:     } elsif ($realm eq 'query') {
 7704: # ---------------------------------------------- pull stuff out of query string
 7705:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7706: 						[$spacequalifierrest]);
 7707: 	return $env{'form.'.$spacequalifierrest}; 
 7708:    } elsif ($realm eq 'request') {
 7709: # ------------------------------------------------------------- request.browser
 7710:         if ($space eq 'browser') {
 7711: 	    if ($qualifier eq 'textremote') {
 7712: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7713: 		    return 1;
 7714: 		} else {
 7715: 		    return 0;
 7716: 		}
 7717: 	    } else {
 7718: 		return $env{'browser.'.$qualifier};
 7719: 	    }
 7720: # ------------------------------------------------------------ request.filename
 7721:         } else {
 7722:             return $env{'request.'.$spacequalifierrest};
 7723:         }
 7724:     } elsif ($realm eq 'course') {
 7725: # ---------------------------------------------------------- course.description
 7726:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7727:     } elsif ($realm eq 'resource') {
 7728: 
 7729: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7730: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7731: 	}
 7732: 
 7733: 	if ($space eq 'title') {
 7734: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7735: 	    return &gettitle($symbparm);
 7736: 	}
 7737: 	
 7738: 	if ($space eq 'map') {
 7739: 	    my ($map) = &decode_symb($symbparm);
 7740: 	    return &symbread($map);
 7741: 	}
 7742: 	if ($space eq 'filename') {
 7743: 	    if ($symbparm) {
 7744: 		return &clutter((&decode_symb($symbparm))[2]);
 7745: 	    }
 7746: 	    return &hreflocation('',$env{'request.filename'});
 7747: 	}
 7748: 
 7749: 	my ($section, $group, @groups);
 7750: 	my ($courselevelm,$courselevel);
 7751: 	if ($symbparm && defined($courseid) && 
 7752: 	    $courseid eq $env{'request.course.id'}) {
 7753: 
 7754: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7755: 
 7756: # ----------------------------------------------------- Cascading lookup scheme
 7757: 	    my $symbp=$symbparm;
 7758: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7759: 
 7760: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7761: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7762: 
 7763: 	    if (($env{'user.name'} eq $uname) &&
 7764: 		($env{'user.domain'} eq $udom)) {
 7765: 		$section=$env{'request.course.sec'};
 7766:                 @groups = split(/:/,$env{'request.course.groups'});  
 7767:                 @groups=&sort_course_groups($courseid,@groups); 
 7768: 	    } else {
 7769: 		if (! defined($usection)) {
 7770: 		    $section=&getsection($udom,$uname,$courseid);
 7771: 		} else {
 7772: 		    $section = $usection;
 7773: 		}
 7774:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7775: 	    }
 7776: 
 7777: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7778: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7779: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7780: 
 7781: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7782: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7783: 	    $courselevelm=$courseid.'.'.$mapparm;
 7784: 
 7785: # ----------------------------------------------------------- first, check user
 7786: 
 7787: 	    my $userreply=&resdata($uname,$udom,'user',
 7788: 				       ([$courselevelr,'resource'],
 7789: 					[$courselevelm,'map'     ],
 7790: 					[$courselevel, 'course'  ]));
 7791: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7792: 
 7793: # ------------------------------------------------ second, check some of course
 7794:             my $coursereply;
 7795:             if (@groups > 0) {
 7796:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7797:                                        $mapparm,$spacequalifierrest);
 7798:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7799:             }
 7800: 
 7801: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7802: 				  $env{'course.'.$courseid.'.domain'},
 7803: 				  'course',
 7804: 				  ([$seclevelr,   'resource'],
 7805: 				   [$seclevelm,   'map'     ],
 7806: 				   [$seclevel,    'course'  ],
 7807: 				   [$courselevelr,'resource']));
 7808: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7809: 
 7810: # ------------------------------------------------------ third, check map parms
 7811: 	    my %parmhash=();
 7812: 	    my $thisparm='';
 7813: 	    if (tie(%parmhash,'GDBM_File',
 7814: 		    $env{'request.course.fn'}.'_parms.db',
 7815: 		    &GDBM_READER(),0640)) {
 7816: 		$thisparm=$parmhash{$symbparm};
 7817: 		untie(%parmhash);
 7818: 	    }
 7819: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7820: 	}
 7821: # ------------------------------------------ fourth, look in resource metadata
 7822: 
 7823: 	$spacequalifierrest=~s/\./\_/;
 7824: 	my $filename;
 7825: 	if (!$symbparm) { $symbparm=&symbread(); }
 7826: 	if ($symbparm) {
 7827: 	    $filename=(&decode_symb($symbparm))[2];
 7828: 	} else {
 7829: 	    $filename=$env{'request.filename'};
 7830: 	}
 7831: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7832: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7833: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7834: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7835: 
 7836: # ---------------------------------------------- fourth, look in rest of course
 7837: 	if ($symbparm && defined($courseid) && 
 7838: 	    $courseid eq $env{'request.course.id'}) {
 7839: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7840: 				     $env{'course.'.$courseid.'.domain'},
 7841: 				     'course',
 7842: 				     ([$courselevelm,'map'   ],
 7843: 				      [$courselevel, 'course']));
 7844: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7845: 	}
 7846: # ------------------------------------------------------------------ Cascade up
 7847: 	unless ($space eq '0') {
 7848: 	    my @parts=split(/_/,$space);
 7849: 	    my $id=pop(@parts);
 7850: 	    my $part=join('_',@parts);
 7851: 	    if ($part eq '') { $part='0'; }
 7852: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7853: 				 $symbparm,$udom,$uname,$section,1);
 7854: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7855: 	}
 7856: 	if ($recurse) { return undef; }
 7857: 	my $pack_def=&packages_tab_default($filename,$varname);
 7858: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7859: # ---------------------------------------------------- Any other user namespace
 7860:     } elsif ($realm eq 'environment') {
 7861: # ----------------------------------------------------------------- environment
 7862: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7863: 	    return $env{'environment.'.$spacequalifierrest};
 7864: 	} else {
 7865: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7866: 		return '';
 7867: 	    }
 7868: 	    my %returnhash=&userenvironment($udom,$uname,
 7869: 					    $spacequalifierrest);
 7870: 	    return $returnhash{$spacequalifierrest};
 7871: 	}
 7872:     } elsif ($realm eq 'system') {
 7873: # ----------------------------------------------------------------- system.time
 7874: 	if ($space eq 'time') {
 7875: 	    return time;
 7876:         }
 7877:     } elsif ($realm eq 'server') {
 7878: # ----------------------------------------------------------------- system.time
 7879: 	if ($space eq 'name') {
 7880: 	    return $ENV{'SERVER_NAME'};
 7881:         }
 7882:     }
 7883:     return '';
 7884: }
 7885: 
 7886: sub get_reply {
 7887:     my ($reply_value) = @_;
 7888:     if (ref($reply_value) eq 'ARRAY') {
 7889:         if (wantarray) {
 7890: 	    return @$reply_value;
 7891:         }
 7892:         return $reply_value->[0];
 7893:     } else {
 7894:         return $reply_value;
 7895:     }
 7896: }
 7897: 
 7898: sub check_group_parms {
 7899:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7900:     my @groupitems = ();
 7901:     my $resultitem;
 7902:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7903:     foreach my $group (@{$groups}) {
 7904:         foreach my $level (@levels) {
 7905:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7906:              push(@groupitems,[$item,$level->[1]]);
 7907:         }
 7908:     }
 7909:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7910:                             $env{'course.'.$courseid.'.domain'},
 7911:                                      'course',@groupitems);
 7912:     return $coursereply;
 7913: }
 7914: 
 7915: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7916:     my ($courseid,@groups) = @_;
 7917:     @groups = sort(@groups);
 7918:     return @groups;
 7919: }
 7920: 
 7921: sub packages_tab_default {
 7922:     my ($uri,$varname)=@_;
 7923:     my (undef,$part,$name)=split(/\./,$varname);
 7924: 
 7925:     my (@extension,@specifics,$do_default);
 7926:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7927: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7928: 	if ($pack_type eq 'default') {
 7929: 	    $do_default=1;
 7930: 	} elsif ($pack_type eq 'extension') {
 7931: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7932: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7933: 	    # only look at packages defaults for packages that this id is
 7934: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7935: 	}
 7936:     }
 7937:     # first look for a package that matches the requested part id
 7938:     foreach my $package (@specifics) {
 7939: 	my (undef,$pack_type,$pack_part)=@{$package};
 7940: 	next if ($pack_part ne $part);
 7941: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7942: 	    return $packagetab{"$pack_type&$name&default"};
 7943: 	}
 7944:     }
 7945:     # look for any possible matching non extension_ package
 7946:     foreach my $package (@specifics) {
 7947: 	my (undef,$pack_type,$pack_part)=@{$package};
 7948: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7949: 	    return $packagetab{"$pack_type&$name&default"};
 7950: 	}
 7951: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7952: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7953: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7954: 	}
 7955:     }
 7956:     # look for any posible extension_ match
 7957:     foreach my $package (@extension) {
 7958: 	my ($package,$pack_type)=@{$package};
 7959: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7960: 	    return $packagetab{"$pack_type&$name&default"};
 7961: 	}
 7962: 	if (defined($packagetab{$package."&$name&default"})) {
 7963: 	    return $packagetab{$package."&$name&default"};
 7964: 	}
 7965:     }
 7966:     # look for a global default setting
 7967:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7968: 	return $packagetab{"default&$name&default"};
 7969:     }
 7970:     return undef;
 7971: }
 7972: 
 7973: sub add_prefix_and_part {
 7974:     my ($prefix,$part)=@_;
 7975:     my $keyroot;
 7976:     if (defined($prefix) && $prefix !~ /^__/) {
 7977: 	# prefix that has a part already
 7978: 	$keyroot=$prefix;
 7979:     } elsif (defined($prefix)) {
 7980: 	# prefix that is missing a part
 7981: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7982:     } else {
 7983: 	# no prefix at all
 7984: 	if (defined($part)) { $keyroot='_'.$part; }
 7985:     }
 7986:     return $keyroot;
 7987: }
 7988: 
 7989: # ---------------------------------------------------------------- Get metadata
 7990: 
 7991: my %metaentry;
 7992: sub metadata {
 7993:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7994:     $uri=&declutter($uri);
 7995:     # if it is a non metadata possible uri return quickly
 7996:     if (($uri eq '') || 
 7997: 	(($uri =~ m|^/*adm/|) && 
 7998: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7999:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 8000: 	return undef;
 8001:     }
 8002:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 8003: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 8004: 	return undef;
 8005:     }
 8006:     my $filename=$uri;
 8007:     $uri=~s/\.meta$//;
 8008: #
 8009: # Is the metadata already cached?
 8010: # Look at timestamp of caching
 8011: # Everything is cached by the main uri, libraries are never directly cached
 8012: #
 8013:     if (!defined($liburi)) {
 8014: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 8015: 	if (defined($cached)) { return $result->{':'.$what}; }
 8016:     }
 8017:     {
 8018: #
 8019: # Is this a recursive call for a library?
 8020: #
 8021: #	if (! exists($metacache{$uri})) {
 8022: #	    $metacache{$uri}={};
 8023: #	}
 8024: 	my $cachetime = 60*60;
 8025:         if ($liburi) {
 8026: 	    $liburi=&declutter($liburi);
 8027:             $filename=$liburi;
 8028:         } else {
 8029: 	    &devalidate_cache_new('meta',$uri);
 8030: 	    undef(%metaentry);
 8031: 	}
 8032:         my %metathesekeys=();
 8033:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 8034: 	my $metastring;
 8035: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 8036: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 8037: 	    $metastring = 
 8038: 		&Apache::lonnet::ssi_body($which,
 8039: 					  ('grade_target' => 'meta'));
 8040: 	    $cachetime = 1; # only want this cached in the child not long term
 8041: 	} elsif ($uri !~ m -^(editupload)/-) {
 8042: 	    my $file=&filelocation('',&clutter($filename));
 8043: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 8044: 	    $metastring=&getfile($file);
 8045: 	}
 8046:         my $parser=HTML::LCParser->new(\$metastring);
 8047:         my $token;
 8048:         undef %metathesekeys;
 8049:         while ($token=$parser->get_token) {
 8050: 	    if ($token->[0] eq 'S') {
 8051: 		if (defined($token->[2]->{'package'})) {
 8052: #
 8053: # This is a package - get package info
 8054: #
 8055: 		    my $package=$token->[2]->{'package'};
 8056: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8057: 		    if (defined($token->[2]->{'id'})) { 
 8058: 			$keyroot.='_'.$token->[2]->{'id'}; 
 8059: 		    }
 8060: 		    if ($metaentry{':packages'}) {
 8061: 			$metaentry{':packages'}.=','.$package.$keyroot;
 8062: 		    } else {
 8063: 			$metaentry{':packages'}=$package.$keyroot;
 8064: 		    }
 8065: 		    foreach my $pack_entry (keys(%packagetab)) {
 8066: 			my $part=$keyroot;
 8067: 			$part=~s/^\_//;
 8068: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 8069: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 8070: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 8071: 			    # ignore package.tab specified default values
 8072:                             # here &package_tab_default() will fetch those
 8073: 			    if ($subp eq 'default') { next; }
 8074: 			    my $value=$packagetab{$pack_entry};
 8075: 			    my $unikey;
 8076: 			    if ($pack =~ /_0$/) {
 8077: 				$unikey='parameter_0_'.$name;
 8078: 				$part=0;
 8079: 			    } else {
 8080: 				$unikey='parameter'.$keyroot.'_'.$name;
 8081: 			    }
 8082: 			    if ($subp eq 'display') {
 8083: 				$value.=' [Part: '.$part.']';
 8084: 			    }
 8085: 			    $metaentry{':'.$unikey.'.part'}=$part;
 8086: 			    $metathesekeys{$unikey}=1;
 8087: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8088: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 8089: 			    }
 8090: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 8091: 				$metaentry{':'.$unikey}=
 8092: 				    $metaentry{':'.$unikey.'.default'};
 8093: 			    }
 8094: 			}
 8095: 		    }
 8096: 		} else {
 8097: #
 8098: # This is not a package - some other kind of start tag
 8099: #
 8100: 		    my $entry=$token->[1];
 8101: 		    my $unikey;
 8102: 		    if ($entry eq 'import') {
 8103: 			$unikey='';
 8104: 		    } else {
 8105: 			$unikey=$entry;
 8106: 		    }
 8107: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8108: 
 8109: 		    if (defined($token->[2]->{'id'})) { 
 8110: 			$unikey.='_'.$token->[2]->{'id'}; 
 8111: 		    }
 8112: 
 8113: 		    if ($entry eq 'import') {
 8114: #
 8115: # Importing a library here
 8116: #
 8117: 			if ($depthcount<20) {
 8118: 			    my $location=$parser->get_text('/import');
 8119: 			    my $dir=$filename;
 8120: 			    $dir=~s|[^/]*$||;
 8121: 			    $location=&filelocation($dir,$location);
 8122: 			    my $metadata = 
 8123: 				&metadata($uri,'keys', $location,$unikey,
 8124: 					  $depthcount+1);
 8125: 			    foreach my $meta (split(',',$metadata)) {
 8126: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 8127: 				$metathesekeys{$meta}=1;
 8128: 			    }
 8129: 			}
 8130: 		    } else { 
 8131: 			
 8132: 			if (defined($token->[2]->{'name'})) { 
 8133: 			    $unikey.='_'.$token->[2]->{'name'}; 
 8134: 			}
 8135: 			$metathesekeys{$unikey}=1;
 8136: 			foreach my $param (@{$token->[3]}) {
 8137: 			    $metaentry{':'.$unikey.'.'.$param} =
 8138: 				$token->[2]->{$param};
 8139: 			}
 8140: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 8141: 			my $default=$metaentry{':'.$unikey.'.default'};
 8142: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 8143: 		 # only ws inside the tag, and not in default, so use default
 8144: 		 # as value
 8145: 			    $metaentry{':'.$unikey}=$default;
 8146: 			} elsif ( $internaltext =~ /\S/ ) {
 8147: 		  # something interesting inside the tag
 8148: 			    $metaentry{':'.$unikey}=$internaltext;
 8149: 			} else {
 8150: 		  # no interesting values, don't set a default
 8151: 			}
 8152: # end of not-a-package not-a-library import
 8153: 		    }
 8154: # end of not-a-package start tag
 8155: 		}
 8156: # the next is the end of "start tag"
 8157: 	    }
 8158: 	}
 8159: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 8160: 	$extension = lc($extension);
 8161: 	if ($extension eq 'htm') { $extension='html'; }
 8162: 
 8163: 	foreach my $key (keys(%packagetab)) {
 8164: 	    #no specific packages #how's our extension
 8165: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 8166: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 8167: 					 \%metathesekeys);
 8168: 	}
 8169: 
 8170: 	if (!exists($metaentry{':packages'})
 8171: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 8172: 	    foreach my $key (keys(%packagetab)) {
 8173: 		#no specific packages well let's get default then
 8174: 		if ($key!~/^default&/) { next; }
 8175: 		&metadata_create_package_def($uri,$key,'default',
 8176: 					     \%metathesekeys);
 8177: 	    }
 8178: 	}
 8179: # are there custom rights to evaluate
 8180: 	if ($metaentry{':copyright'} eq 'custom') {
 8181: 
 8182:     #
 8183:     # Importing a rights file here
 8184:     #
 8185: 	    unless ($depthcount) {
 8186: 		my $location=$metaentry{':customdistributionfile'};
 8187: 		my $dir=$filename;
 8188: 		$dir=~s|[^/]*$||;
 8189: 		$location=&filelocation($dir,$location);
 8190: 		my $rights_metadata =
 8191: 		    &metadata($uri,'keys',$location,'_rights',
 8192: 			      $depthcount+1);
 8193: 		foreach my $rights (split(',',$rights_metadata)) {
 8194: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 8195: 		    $metathesekeys{$rights}=1;
 8196: 		}
 8197: 	    }
 8198: 	}
 8199: 	# uniqifiy package listing
 8200: 	my %seen;
 8201: 	my @uniq_packages =
 8202: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 8203: 	$metaentry{':packages'} = join(',',@uniq_packages);
 8204: 
 8205: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 8206: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 8207: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 8208: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 8209: # this is the end of "was not already recently cached
 8210:     }
 8211:     return $metaentry{':'.$what};
 8212: }
 8213: 
 8214: sub metadata_create_package_def {
 8215:     my ($uri,$key,$package,$metathesekeys)=@_;
 8216:     my ($pack,$name,$subp)=split(/\&/,$key);
 8217:     if ($subp eq 'default') { next; }
 8218:     
 8219:     if (defined($metaentry{':packages'})) {
 8220: 	$metaentry{':packages'}.=','.$package;
 8221:     } else {
 8222: 	$metaentry{':packages'}=$package;
 8223:     }
 8224:     my $value=$packagetab{$key};
 8225:     my $unikey;
 8226:     $unikey='parameter_0_'.$name;
 8227:     $metaentry{':'.$unikey.'.part'}=0;
 8228:     $$metathesekeys{$unikey}=1;
 8229:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8230: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 8231:     }
 8232:     if (defined($metaentry{':'.$unikey.'.default'})) {
 8233: 	$metaentry{':'.$unikey}=
 8234: 	    $metaentry{':'.$unikey.'.default'};
 8235:     }
 8236: }
 8237: 
 8238: sub metadata_generate_part0 {
 8239:     my ($metadata,$metacache,$uri) = @_;
 8240:     my %allnames;
 8241:     foreach my $metakey (keys(%$metadata)) {
 8242: 	if ($metakey=~/^parameter\_(.*)/) {
 8243: 	  my $part=$$metacache{':'.$metakey.'.part'};
 8244: 	  my $name=$$metacache{':'.$metakey.'.name'};
 8245: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 8246: 	    $allnames{$name}=$part;
 8247: 	  }
 8248: 	}
 8249:     }
 8250:     foreach my $name (keys(%allnames)) {
 8251:       $$metadata{"parameter_0_$name"}=1;
 8252:       my $key=":parameter_0_$name";
 8253:       $$metacache{"$key.part"}='0';
 8254:       $$metacache{"$key.name"}=$name;
 8255:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 8256: 					   $allnames{$name}.'_'.$name.
 8257: 					   '.type'};
 8258:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 8259: 			     '.display'};
 8260:       my $expr='[Part: '.$allnames{$name}.']';
 8261:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 8262:       $$metacache{"$key.display"}=$olddis;
 8263:     }
 8264: }
 8265: 
 8266: # ------------------------------------------------------ Devalidate title cache
 8267: 
 8268: sub devalidate_title_cache {
 8269:     my ($url)=@_;
 8270:     if (!$env{'request.course.id'}) { return; }
 8271:     my $symb=&symbread($url);
 8272:     if (!$symb) { return; }
 8273:     my $key=$env{'request.course.id'}."\0".$symb;
 8274:     &devalidate_cache_new('title',$key);
 8275: }
 8276: 
 8277: # ------------------------------------------------- Get the title of a course
 8278: 
 8279: sub current_course_title {
 8280:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 8281: }
 8282: # ------------------------------------------------- Get the title of a resource
 8283: 
 8284: sub gettitle {
 8285:     my $urlsymb=shift;
 8286:     my $symb=&symbread($urlsymb);
 8287:     if ($symb) {
 8288: 	my $key=$env{'request.course.id'}."\0".$symb;
 8289: 	my ($result,$cached)=&is_cached_new('title',$key);
 8290: 	if (defined($cached)) { 
 8291: 	    return $result;
 8292: 	}
 8293: 	my ($map,$resid,$url)=&decode_symb($symb);
 8294: 	my $title='';
 8295: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 8296: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 8297: 	} else {
 8298: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8299: 		    &GDBM_READER(),0640)) {
 8300: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 8301: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 8302: 		untie(%bighash);
 8303: 	    }
 8304: 	}
 8305: 	$title=~s/\&colon\;/\:/gs;
 8306: 	if ($title) {
 8307: 	    return &do_cache_new('title',$key,$title,600);
 8308: 	}
 8309: 	$urlsymb=$url;
 8310:     }
 8311:     my $title=&metadata($urlsymb,'title');
 8312:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 8313:     return $title;
 8314: }
 8315: 
 8316: sub get_slot {
 8317:     my ($which,$cnum,$cdom)=@_;
 8318:     if (!$cnum || !$cdom) {
 8319: 	(undef,my $courseid)=&whichuser();
 8320: 	$cdom=$env{'course.'.$courseid.'.domain'};
 8321: 	$cnum=$env{'course.'.$courseid.'.num'};
 8322:     }
 8323:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 8324:     my %slotinfo;
 8325:     if (exists($remembered{$key})) {
 8326: 	$slotinfo{$which} = $remembered{$key};
 8327:     } else {
 8328: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 8329: 	&Apache::lonhomework::showhash(%slotinfo);
 8330: 	my ($tmp)=keys(%slotinfo);
 8331: 	if ($tmp=~/^error:/) { return (); }
 8332: 	$remembered{$key} = $slotinfo{$which};
 8333:     }
 8334:     if (ref($slotinfo{$which}) eq 'HASH') {
 8335: 	return %{$slotinfo{$which}};
 8336:     }
 8337:     return $slotinfo{$which};
 8338: }
 8339: # ------------------------------------------------- Update symbolic store links
 8340: 
 8341: sub symblist {
 8342:     my ($mapname,%newhash)=@_;
 8343:     $mapname=&deversion(&declutter($mapname));
 8344:     my %hash;
 8345:     if (($env{'request.course.fn'}) && (%newhash)) {
 8346:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8347:                       &GDBM_WRCREAT(),0640)) {
 8348: 	    foreach my $url (keys(%newhash)) {
 8349: 		next if ($url eq 'last_known'
 8350: 			 && $env{'form.no_update_last_known'});
 8351: 		$hash{declutter($url)}=&encode_symb($mapname,
 8352: 						    $newhash{$url}->[1],
 8353: 						    $newhash{$url}->[0]);
 8354:             }
 8355:             if (untie(%hash)) {
 8356: 		return 'ok';
 8357:             }
 8358:         }
 8359:     }
 8360:     return 'error';
 8361: }
 8362: 
 8363: # --------------------------------------------------------------- Verify a symb
 8364: 
 8365: sub symbverify {
 8366:     my ($symb,$thisurl)=@_;
 8367:     my $thisfn=$thisurl;
 8368:     $thisfn=&declutter($thisfn);
 8369: # direct jump to resource in page or to a sequence - will construct own symbs
 8370:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8371: # check URL part
 8372:     my ($map,$resid,$url)=&decode_symb($symb);
 8373: 
 8374:     unless ($url eq $thisfn) { return 0; }
 8375: 
 8376:     $symb=&symbclean($symb);
 8377:     $thisurl=&deversion($thisurl);
 8378:     $thisfn=&deversion($thisfn);
 8379: 
 8380:     my %bighash;
 8381:     my $okay=0;
 8382: 
 8383:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8384:                             &GDBM_READER(),0640)) {
 8385:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 8386:             $thisurl =~ s/\?.+$//;
 8387:         }
 8388:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8389:         unless ($ids) { 
 8390:            $ids=$bighash{'ids_/'.$thisurl};
 8391:         }
 8392:         if ($ids) {
 8393: # ------------------------------------------------------------------- Has ID(s)
 8394: 	    foreach my $id (split(/\,/,$ids)) {
 8395: 	       my ($mapid,$resid)=split(/\./,$id);
 8396:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 8397:                    $symb =~ s/\?.+$//;
 8398:                }
 8399:                if (
 8400:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8401:    eq $symb) { 
 8402: 		   if (($env{'request.role.adv'}) ||
 8403: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8404: 		       $okay=1; 
 8405: 		   }
 8406: 	       }
 8407: 	   }
 8408:         }
 8409: 	untie(%bighash);
 8410:     }
 8411:     return $okay;
 8412: }
 8413: 
 8414: # --------------------------------------------------------------- Clean-up symb
 8415: 
 8416: sub symbclean {
 8417:     my $symb=shift;
 8418:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8419: # remove version from map
 8420:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8421: 
 8422: # remove version from URL
 8423:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8424: 
 8425: # remove wrapper
 8426: 
 8427:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8428:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8429:     return $symb;
 8430: }
 8431: 
 8432: # ---------------------------------------------- Split symb to find map and url
 8433: 
 8434: sub encode_symb {
 8435:     my ($map,$resid,$url)=@_;
 8436:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8437: }
 8438: 
 8439: sub decode_symb {
 8440:     my $symb=shift;
 8441:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8442:     my ($map,$resid,$url)=split(/___/,$symb);
 8443:     return (&fixversion($map),$resid,&fixversion($url));
 8444: }
 8445: 
 8446: sub fixversion {
 8447:     my $fn=shift;
 8448:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8449:     my %bighash;
 8450:     my $uri=&clutter($fn);
 8451:     my $key=$env{'request.course.id'}.'_'.$uri;
 8452: # is this cached?
 8453:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8454:     if (defined($cached)) { return $result; }
 8455: # unfortunately not cached, or expired
 8456:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8457: 	    &GDBM_READER(),0640)) {
 8458:  	if ($bighash{'version_'.$uri}) {
 8459:  	    my $version=$bighash{'version_'.$uri};
 8460:  	    unless (($version eq 'mostrecent') || 
 8461: 		    ($version==&getversion($uri))) {
 8462:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8463:  	    }
 8464:  	}
 8465:  	untie %bighash;
 8466:     }
 8467:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8468: }
 8469: 
 8470: sub deversion {
 8471:     my $url=shift;
 8472:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8473:     return $url;
 8474: }
 8475: 
 8476: # ------------------------------------------------------ Return symb list entry
 8477: 
 8478: sub symbread {
 8479:     my ($thisfn,$donotrecurse)=@_;
 8480:     my $cache_str='request.symbread.cached.'.$thisfn;
 8481:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8482: # no filename provided? try from environment
 8483:     unless ($thisfn) {
 8484:         if ($env{'request.symb'}) {
 8485: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8486: 	}
 8487: 	$thisfn=$env{'request.filename'};
 8488:     }
 8489:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8490: # is that filename actually a symb? Verify, clean, and return
 8491:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8492: 	if (&symbverify($thisfn,$1)) {
 8493: 	    return $env{$cache_str}=&symbclean($thisfn);
 8494: 	}
 8495:     }
 8496:     $thisfn=declutter($thisfn);
 8497:     my %hash;
 8498:     my %bighash;
 8499:     my $syval='';
 8500:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8501:         my $targetfn = $thisfn;
 8502:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8503:             $targetfn = 'adm/wrapper/'.$thisfn;
 8504:         }
 8505: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8506: 	    $targetfn=$1;
 8507: 	}
 8508:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8509:                       &GDBM_READER(),0640)) {
 8510: 	    $syval=$hash{$targetfn};
 8511:             untie(%hash);
 8512:         }
 8513: # ---------------------------------------------------------- There was an entry
 8514:         if ($syval) {
 8515: 	    #unless ($syval=~/\_\d+$/) {
 8516: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8517: 		    #&appenv({'request.ambiguous' => $thisfn});
 8518: 		    #return $env{$cache_str}='';
 8519: 		#}    
 8520: 		#$syval.=$1;
 8521: 	    #}
 8522:         } else {
 8523: # ------------------------------------------------------- Was not in symb table
 8524:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8525:                             &GDBM_READER(),0640)) {
 8526: # ---------------------------------------------- Get ID(s) for current resource
 8527:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8528:               unless ($ids) { 
 8529:                  $ids=$bighash{'ids_/'.$thisfn};
 8530:               }
 8531:               unless ($ids) {
 8532: # alias?
 8533: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8534:               }
 8535:               if ($ids) {
 8536: # ------------------------------------------------------------------- Has ID(s)
 8537:                  my @possibilities=split(/\,/,$ids);
 8538:                  if ($#possibilities==0) {
 8539: # ----------------------------------------------- There is only one possibility
 8540: 		     my ($mapid,$resid)=split(/\./,$ids);
 8541: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8542: 						    $resid,$thisfn);
 8543:                  } elsif (!$donotrecurse) {
 8544: # ------------------------------------------ There is more than one possibility
 8545:                      my $realpossible=0;
 8546:                      foreach my $id (@possibilities) {
 8547: 			 my $file=$bighash{'src_'.$id};
 8548:                          if (&allowed('bre',$file)) {
 8549:          		    my ($mapid,$resid)=split(/\./,$id);
 8550:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8551: 				$realpossible++;
 8552:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8553: 						    $resid,$thisfn);
 8554:                             }
 8555: 			 }
 8556:                      }
 8557: 		     if ($realpossible!=1) { $syval=''; }
 8558:                  } else {
 8559:                      $syval='';
 8560:                  }
 8561: 	      }
 8562:               untie(%bighash)
 8563:            }
 8564:         }
 8565:         if ($syval) {
 8566: 	    return $env{$cache_str}=$syval;
 8567:         }
 8568:     }
 8569:     &appenv({'request.ambiguous' => $thisfn});
 8570:     return $env{$cache_str}='';
 8571: }
 8572: 
 8573: # ---------------------------------------------------------- Return random seed
 8574: 
 8575: sub numval {
 8576:     my $txt=shift;
 8577:     $txt=~tr/A-J/0-9/;
 8578:     $txt=~tr/a-j/0-9/;
 8579:     $txt=~tr/K-T/0-9/;
 8580:     $txt=~tr/k-t/0-9/;
 8581:     $txt=~tr/U-Z/0-5/;
 8582:     $txt=~tr/u-z/0-5/;
 8583:     $txt=~s/\D//g;
 8584:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8585:     return int($txt);
 8586: }
 8587: 
 8588: sub numval2 {
 8589:     my $txt=shift;
 8590:     $txt=~tr/A-J/0-9/;
 8591:     $txt=~tr/a-j/0-9/;
 8592:     $txt=~tr/K-T/0-9/;
 8593:     $txt=~tr/k-t/0-9/;
 8594:     $txt=~tr/U-Z/0-5/;
 8595:     $txt=~tr/u-z/0-5/;
 8596:     $txt=~s/\D//g;
 8597:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8598:     my $total;
 8599:     foreach my $val (@txts) { $total+=$val; }
 8600:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8601:     return int($total);
 8602: }
 8603: 
 8604: sub numval3 {
 8605:     use integer;
 8606:     my $txt=shift;
 8607:     $txt=~tr/A-J/0-9/;
 8608:     $txt=~tr/a-j/0-9/;
 8609:     $txt=~tr/K-T/0-9/;
 8610:     $txt=~tr/k-t/0-9/;
 8611:     $txt=~tr/U-Z/0-5/;
 8612:     $txt=~tr/u-z/0-5/;
 8613:     $txt=~s/\D//g;
 8614:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8615:     my $total;
 8616:     foreach my $val (@txts) { $total+=$val; }
 8617:     if ($_64bit) { $total=(($total<<32)>>32); }
 8618:     return $total;
 8619: }
 8620: 
 8621: sub digest {
 8622:     my ($data)=@_;
 8623:     my $digest=&Digest::MD5::md5($data);
 8624:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8625:     my ($e,$f);
 8626:     {
 8627:         use integer;
 8628:         $e=($a+$b);
 8629:         $f=($c+$d);
 8630:         if ($_64bit) {
 8631:             $e=(($e<<32)>>32);
 8632:             $f=(($f<<32)>>32);
 8633:         }
 8634:     }
 8635:     if (wantarray) {
 8636: 	return ($e,$f);
 8637:     } else {
 8638: 	my $g;
 8639: 	{
 8640: 	    use integer;
 8641: 	    $g=($e+$f);
 8642: 	    if ($_64bit) {
 8643: 		$g=(($g<<32)>>32);
 8644: 	    }
 8645: 	}
 8646: 	return $g;
 8647:     }
 8648: }
 8649: 
 8650: sub latest_rnd_algorithm_id {
 8651:     return '64bit5';
 8652: }
 8653: 
 8654: sub get_rand_alg {
 8655:     my ($courseid)=@_;
 8656:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8657:     if ($courseid) {
 8658: 	return $env{"course.$courseid.rndseed"};
 8659:     }
 8660:     return &latest_rnd_algorithm_id();
 8661: }
 8662: 
 8663: sub validCODE {
 8664:     my ($CODE)=@_;
 8665:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8666:     return 0;
 8667: }
 8668: 
 8669: sub getCODE {
 8670:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8671:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8672: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8673: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8674: 	return $Apache::lonhomework::history{'resource.CODE'};
 8675:     }
 8676:     return undef;
 8677: }
 8678: 
 8679: sub rndseed {
 8680:     my ($symb,$courseid,$domain,$username)=@_;
 8681:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8682:     if (!defined($symb)) {
 8683: 	unless ($symb=$wsymb) { return time; }
 8684:     }
 8685:     if (!$courseid) { $courseid=$wcourseid; }
 8686:     if (!$domain) { $domain=$wdomain; }
 8687:     if (!$username) { $username=$wusername }
 8688:     my $which=&get_rand_alg();
 8689: 
 8690:     if (defined(&getCODE())) {
 8691: 	if ($which eq '64bit5') {
 8692: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8693: 	} elsif ($which eq '64bit4') {
 8694: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8695: 	} else {
 8696: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8697: 	}
 8698:     } elsif ($which eq '64bit5') {
 8699: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8700:     } elsif ($which eq '64bit4') {
 8701: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8702:     } elsif ($which eq '64bit3') {
 8703: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8704:     } elsif ($which eq '64bit2') {
 8705: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8706:     } elsif ($which eq '64bit') {
 8707: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8708:     }
 8709:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8710: }
 8711: 
 8712: sub rndseed_32bit {
 8713:     my ($symb,$courseid,$domain,$username)=@_;
 8714:     {
 8715: 	use integer;
 8716: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8717: 	my $symbseed=numval($symb) << 22;
 8718: 	my $namechck=unpack("%32C*",$username) << 17;
 8719: 	my $nameseed=numval($username) << 12;
 8720: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8721: 	my $courseseed=unpack("%32C*",$courseid);
 8722: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8723: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8724: 	#&logthis("rndseed :$num:$symb");
 8725: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8726: 	return $num;
 8727:     }
 8728: }
 8729: 
 8730: sub rndseed_64bit {
 8731:     my ($symb,$courseid,$domain,$username)=@_;
 8732:     {
 8733: 	use integer;
 8734: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8735: 	my $symbseed=numval($symb) << 10;
 8736: 	my $namechck=unpack("%32S*",$username);
 8737: 	
 8738: 	my $nameseed=numval($username) << 21;
 8739: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8740: 	my $courseseed=unpack("%32S*",$courseid);
 8741: 	
 8742: 	my $num1=$symbchck+$symbseed+$namechck;
 8743: 	my $num2=$nameseed+$domainseed+$courseseed;
 8744: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8745: 	#&logthis("rndseed :$num:$symb");
 8746: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8747: 	return "$num1,$num2";
 8748:     }
 8749: }
 8750: 
 8751: sub rndseed_64bit2 {
 8752:     my ($symb,$courseid,$domain,$username)=@_;
 8753:     {
 8754: 	use integer;
 8755: 	# strings need to be an even # of cahracters long, it it is odd the
 8756:         # last characters gets thrown away
 8757: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8758: 	my $symbseed=numval($symb) << 10;
 8759: 	my $namechck=unpack("%32S*",$username.' ');
 8760: 	
 8761: 	my $nameseed=numval($username) << 21;
 8762: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8763: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8764: 	
 8765: 	my $num1=$symbchck+$symbseed+$namechck;
 8766: 	my $num2=$nameseed+$domainseed+$courseseed;
 8767: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8768: 	#&logthis("rndseed :$num:$symb");
 8769: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8770: 	return "$num1,$num2";
 8771:     }
 8772: }
 8773: 
 8774: sub rndseed_64bit3 {
 8775:     my ($symb,$courseid,$domain,$username)=@_;
 8776:     {
 8777: 	use integer;
 8778: 	# strings need to be an even # of cahracters long, it it is odd the
 8779:         # last characters gets thrown away
 8780: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8781: 	my $symbseed=numval2($symb) << 10;
 8782: 	my $namechck=unpack("%32S*",$username.' ');
 8783: 	
 8784: 	my $nameseed=numval2($username) << 21;
 8785: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8786: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8787: 	
 8788: 	my $num1=$symbchck+$symbseed+$namechck;
 8789: 	my $num2=$nameseed+$domainseed+$courseseed;
 8790: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8791: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8792: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8793: 	
 8794: 	return "$num1:$num2";
 8795:     }
 8796: }
 8797: 
 8798: sub rndseed_64bit4 {
 8799:     my ($symb,$courseid,$domain,$username)=@_;
 8800:     {
 8801: 	use integer;
 8802: 	# strings need to be an even # of cahracters long, it it is odd the
 8803:         # last characters gets thrown away
 8804: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8805: 	my $symbseed=numval3($symb) << 10;
 8806: 	my $namechck=unpack("%32S*",$username.' ');
 8807: 	
 8808: 	my $nameseed=numval3($username) << 21;
 8809: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8810: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8811: 	
 8812: 	my $num1=$symbchck+$symbseed+$namechck;
 8813: 	my $num2=$nameseed+$domainseed+$courseseed;
 8814: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8815: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8816: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8817: 	
 8818: 	return "$num1:$num2";
 8819:     }
 8820: }
 8821: 
 8822: sub rndseed_64bit5 {
 8823:     my ($symb,$courseid,$domain,$username)=@_;
 8824:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8825:     return "$num1:$num2";
 8826: }
 8827: 
 8828: sub rndseed_CODE_64bit {
 8829:     my ($symb,$courseid,$domain,$username)=@_;
 8830:     {
 8831: 	use integer;
 8832: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8833: 	my $symbseed=numval2($symb);
 8834: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8835: 	my $CODEseed=numval(&getCODE());
 8836: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8837: 	my $num1=$symbseed+$CODEchck;
 8838: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8839: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8840: 	#&logthis("rndseed :$num1:$num2:$symb");
 8841: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8842: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8843: 	return "$num1:$num2";
 8844:     }
 8845: }
 8846: 
 8847: sub rndseed_CODE_64bit4 {
 8848:     my ($symb,$courseid,$domain,$username)=@_;
 8849:     {
 8850: 	use integer;
 8851: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8852: 	my $symbseed=numval3($symb);
 8853: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8854: 	my $CODEseed=numval3(&getCODE());
 8855: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8856: 	my $num1=$symbseed+$CODEchck;
 8857: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8858: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8859: 	#&logthis("rndseed :$num1:$num2:$symb");
 8860: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8861: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8862: 	return "$num1:$num2";
 8863:     }
 8864: }
 8865: 
 8866: sub rndseed_CODE_64bit5 {
 8867:     my ($symb,$courseid,$domain,$username)=@_;
 8868:     my $code = &getCODE();
 8869:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8870:     return "$num1:$num2";
 8871: }
 8872: 
 8873: sub setup_random_from_rndseed {
 8874:     my ($rndseed)=@_;
 8875:     if ($rndseed =~/([,:])/) {
 8876: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8877: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8878:     } else {
 8879: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8880:     }
 8881: }
 8882: 
 8883: sub latest_receipt_algorithm_id {
 8884:     return 'receipt3';
 8885: }
 8886: 
 8887: sub recunique {
 8888:     my $fucourseid=shift;
 8889:     my $unique;
 8890:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8891: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8892: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8893:     } else {
 8894: 	$unique=$perlvar{'lonReceipt'};
 8895:     }
 8896:     return unpack("%32C*",$unique);
 8897: }
 8898: 
 8899: sub recprefix {
 8900:     my $fucourseid=shift;
 8901:     my $prefix;
 8902:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8903: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8904: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8905:     } else {
 8906: 	$prefix=$perlvar{'lonHostID'};
 8907:     }
 8908:     return unpack("%32C*",$prefix);
 8909: }
 8910: 
 8911: sub ireceipt {
 8912:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8913: 
 8914:     my $return =&recprefix($fucourseid).'-';
 8915: 
 8916:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8917: 	$env{'request.state'} eq 'construct') {
 8918: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8919: 	return $return;
 8920:     }
 8921: 
 8922:     my $cuname=unpack("%32C*",$funame);
 8923:     my $cudom=unpack("%32C*",$fudom);
 8924:     my $cucourseid=unpack("%32C*",$fucourseid);
 8925:     my $cusymb=unpack("%32C*",$fusymb);
 8926:     my $cunique=&recunique($fucourseid);
 8927:     my $cpart=unpack("%32S*",$part);
 8928:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8929: 
 8930: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8931: 			       
 8932: 	$return.= ($cunique%$cuname+
 8933: 		   $cunique%$cudom+
 8934: 		   $cusymb%$cuname+
 8935: 		   $cusymb%$cudom+
 8936: 		   $cucourseid%$cuname+
 8937: 		   $cucourseid%$cudom+
 8938: 		   $cpart%$cuname+
 8939: 		   $cpart%$cudom);
 8940:     } else {
 8941: 	$return.= ($cunique%$cuname+
 8942: 		   $cunique%$cudom+
 8943: 		   $cusymb%$cuname+
 8944: 		   $cusymb%$cudom+
 8945: 		   $cucourseid%$cuname+
 8946: 		   $cucourseid%$cudom);
 8947:     }
 8948:     return $return;
 8949: }
 8950: 
 8951: sub receipt {
 8952:     my ($part)=@_;
 8953:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8954:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8955: }
 8956: 
 8957: sub whichuser {
 8958:     my ($passedsymb)=@_;
 8959:     my ($symb,$courseid,$domain,$name,$publicuser);
 8960:     if (defined($env{'form.grade_symb'})) {
 8961: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8962: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8963: 	if (!$allowed &&
 8964: 	    exists($env{'request.course.sec'}) &&
 8965: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8966: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8967: 			      '/'.$env{'request.course.sec'});
 8968: 	}
 8969: 	if ($allowed) {
 8970: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8971: 	    $courseid=$tmp_courseid;
 8972: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8973: 	    ($name)=&get_env_multiple('form.grade_username');
 8974: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8975: 	}
 8976:     }
 8977:     if (!$passedsymb) {
 8978: 	$symb=&symbread();
 8979:     } else {
 8980: 	$symb=$passedsymb;
 8981:     }
 8982:     $courseid=$env{'request.course.id'};
 8983:     $domain=$env{'user.domain'};
 8984:     $name=$env{'user.name'};
 8985:     if ($name eq 'public' && $domain eq 'public') {
 8986: 	if (!defined($env{'form.username'})) {
 8987: 	    $env{'form.username'}.=time.rand(10000000);
 8988: 	}
 8989: 	$name.=$env{'form.username'};
 8990:     }
 8991:     return ($symb,$courseid,$domain,$name,$publicuser);
 8992: 
 8993: }
 8994: 
 8995: # ------------------------------------------------------------ Serves up a file
 8996: # returns either the contents of the file or 
 8997: # -1 if the file doesn't exist
 8998: #
 8999: # if the target is a file that was uploaded via DOCS, 
 9000: # a check will be made to see if a current copy exists on the local server,
 9001: # if it does this will be served, otherwise a copy will be retrieved from
 9002: # the home server for the course and stored in /home/httpd/html/userfiles on
 9003: # the local server.   
 9004: 
 9005: sub getfile {
 9006:     my ($file) = @_;
 9007:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9008:     &repcopy($file);
 9009:     return &readfile($file);
 9010: }
 9011: 
 9012: sub repcopy_userfile {
 9013:     my ($file)=@_;
 9014:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9015:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 9016:     my ($cdom,$cnum,$filename) = 
 9017: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 9018:     my $uri="/uploaded/$cdom/$cnum/$filename";
 9019:     if (-e "$file") {
 9020: # we already have a local copy, check it out
 9021: 	my @fileinfo = stat($file);
 9022: 	my $rtncode;
 9023: 	my $info;
 9024: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 9025: 	if ($lwpresp ne 'ok') {
 9026: # there is no such file anymore, even though we had a local copy
 9027: 	    if ($rtncode eq '404') {
 9028: 		unlink($file);
 9029: 	    }
 9030: 	    return -1;
 9031: 	}
 9032: 	if ($info < $fileinfo[9]) {
 9033: # nice, the file we have is up-to-date, just say okay
 9034: 	    return 'ok';
 9035: 	} else {
 9036: # the file is outdated, get rid of it
 9037: 	    unlink($file);
 9038: 	}
 9039:     }
 9040: # one way or the other, at this point, we don't have the file
 9041: # construct the correct path for the file
 9042:     my @parts = ($cdom,$cnum); 
 9043:     if ($filename =~ m|^(.+)/[^/]+$|) {
 9044: 	push @parts, split(/\//,$1);
 9045:     }
 9046:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 9047:     foreach my $part (@parts) {
 9048: 	$path .= '/'.$part;
 9049: 	if (!-e $path) {
 9050: 	    mkdir($path,0770);
 9051: 	}
 9052:     }
 9053: # now the path exists for sure
 9054: # get a user agent
 9055:     my $ua=new LWP::UserAgent;
 9056:     my $transferfile=$file.'.in.transfer';
 9057: # FIXME: this should flock
 9058:     if (-e $transferfile) { return 'ok'; }
 9059:     my $request;
 9060:     $uri=~s/^\///;
 9061:     my $homeserver = &homeserver($cnum,$cdom);
 9062:     my $protocol = $protocol{$homeserver};
 9063:     $protocol = 'http' if ($protocol ne 'https');
 9064:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 9065:     my $response=$ua->request($request,$transferfile);
 9066: # did it work?
 9067:     if ($response->is_error()) {
 9068: 	unlink($transferfile);
 9069: 	&logthis("Userfile repcopy failed for $uri");
 9070: 	return -1;
 9071:     }
 9072: # worked, rename the transfer file
 9073:     rename($transferfile,$file);
 9074:     return 'ok';
 9075: }
 9076: 
 9077: sub tokenwrapper {
 9078:     my $uri=shift;
 9079:     $uri=~s|^https?\://([^/]+)||;
 9080:     $uri=~s|^/||;
 9081:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 9082:     my $token=$1;
 9083:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 9084:     if ($udom && $uname && $file) {
 9085: 	$file=~s|(\?\.*)*$||;
 9086:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 9087:         my $homeserver = &homeserver($uname,$udom);
 9088:         my $protocol = $protocol{$homeserver};
 9089:         $protocol = 'http' if ($protocol ne 'https');
 9090:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 9091:                (($uri=~/\?/)?'&':'?').'token='.$token.
 9092:                                '&tokenissued='.$perlvar{'lonHostID'};
 9093:     } else {
 9094:         return '/adm/notfound.html';
 9095:     }
 9096: }
 9097: 
 9098: # call with reqtype HEAD: get last modification time
 9099: # call with reqtype GET: get the file contents
 9100: # Do not call this with reqtype GET for large files! It loads everything into memory
 9101: #
 9102: sub getuploaded {
 9103:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 9104:     $uri=~s/^\///;
 9105:     my $homeserver = &homeserver($cnum,$cdom);
 9106:     my $protocol = $protocol{$homeserver};
 9107:     $protocol = 'http' if ($protocol ne 'https');
 9108:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 9109:     my $ua=new LWP::UserAgent;
 9110:     my $request=new HTTP::Request($reqtype,$uri);
 9111:     my $response=$ua->request($request);
 9112:     $$rtncode = $response->code;
 9113:     if (! $response->is_success()) {
 9114: 	return 'failed';
 9115:     }      
 9116:     if ($reqtype eq 'HEAD') {
 9117: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 9118:     } elsif ($reqtype eq 'GET') {
 9119: 	$$info = $response->content;
 9120:     }
 9121:     return 'ok';
 9122: }
 9123: 
 9124: sub readfile {
 9125:     my $file = shift;
 9126:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 9127:     my $fh;
 9128:     open($fh,"<$file");
 9129:     my $a='';
 9130:     while (my $line = <$fh>) { $a .= $line; }
 9131:     return $a;
 9132: }
 9133: 
 9134: sub filelocation {
 9135:     my ($dir,$file) = @_;
 9136:     my $location;
 9137:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 9138: 
 9139:     if ($file =~ m-^/adm/-) {
 9140: 	$file=~s-^/adm/wrapper/-/-;
 9141: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9142:     }
 9143: 
 9144:     if ($file=~m:^/~:) { # is a contruction space reference
 9145:         $location = $file;
 9146:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 9147:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 9148: 	# is a correct contruction space reference
 9149:         $location = $file;
 9150:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 9151:         $location = $file;
 9152:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 9153:         my ($udom,$uname,$filename)=
 9154:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 9155:         my $home=&homeserver($uname,$udom);
 9156:         my $is_me=0;
 9157:         my @ids=&current_machine_ids();
 9158:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 9159:         if ($is_me) {
 9160:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 9161:         } else {
 9162:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 9163:   	      $udom.'/'.$uname.'/'.$filename;
 9164:         }
 9165:     } elsif ($file =~ m-^/adm/-) {
 9166: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 9167:     } else {
 9168:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9169:         $file=~s:^/res/:/:;
 9170:         if ( !( $file =~ m:^/:) ) {
 9171:             $location = $dir. '/'.$file;
 9172:         } else {
 9173:             $location = '/home/httpd/html/res'.$file;
 9174:         }
 9175:     }
 9176:     $location=~s://+:/:g; # remove duplicate /
 9177:     while ($location=~m{/\.\./}) {
 9178: 	if ($location =~ m{/[^/]+/\.\./}) {
 9179: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 9180: 	} else {
 9181: 	    $location=~ s{/\.\./}{/}g;
 9182: 	}
 9183:     } #remove dir/..
 9184:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 9185:     return $location;
 9186: }
 9187: 
 9188: sub hreflocation {
 9189:     my ($dir,$file)=@_;
 9190:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 9191: 	$file=filelocation($dir,$file);
 9192:     } elsif ($file=~m-^/adm/-) {
 9193: 	$file=~s-^/adm/wrapper/-/-;
 9194: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9195:     }
 9196:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 9197: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 9198:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 9199: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 9200:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 9201: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 9202: 	    -/uploaded/$1/$2/-x;
 9203:     }
 9204:     if ($file=~ m{^/userfiles/}) {
 9205: 	$file =~ s{^/userfiles/}{/uploaded/};
 9206:     }
 9207:     return $file;
 9208: }
 9209: 
 9210: sub current_machine_domains {
 9211:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 9212: }
 9213: 
 9214: sub machine_domains {
 9215:     my ($hostname) = @_;
 9216:     my @domains;
 9217:     my %hostname = &all_hostnames();
 9218:     while( my($id, $name) = each(%hostname)) {
 9219: #	&logthis("-$id-$name-$hostname-");
 9220: 	if ($hostname eq $name) {
 9221: 	    push(@domains,&host_domain($id));
 9222: 	}
 9223:     }
 9224:     return @domains;
 9225: }
 9226: 
 9227: sub current_machine_ids {
 9228:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 9229: }
 9230: 
 9231: sub machine_ids {
 9232:     my ($hostname) = @_;
 9233:     $hostname ||= &hostname($perlvar{'lonHostID'});
 9234:     my @ids;
 9235:     my %name_to_host = &all_names();
 9236:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 9237: 	return @{ $name_to_host{$hostname} };
 9238:     }
 9239:     return;
 9240: }
 9241: 
 9242: sub additional_machine_domains {
 9243:     my @domains;
 9244:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 9245:     while( my $line = <$fh>) {
 9246:         $line =~ s/\s//g;
 9247:         push(@domains,$line);
 9248:     }
 9249:     return @domains;
 9250: }
 9251: 
 9252: sub default_login_domain {
 9253:     my $domain = $perlvar{'lonDefDomain'};
 9254:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 9255:     foreach my $posdom (&current_machine_domains(),
 9256:                         &additional_machine_domains()) {
 9257:         if (lc($posdom) eq lc($testdomain)) {
 9258:             $domain=$posdom;
 9259:             last;
 9260:         }
 9261:     }
 9262:     return $domain;
 9263: }
 9264: 
 9265: # ------------------------------------------------------------- Declutters URLs
 9266: 
 9267: sub declutter {
 9268:     my $thisfn=shift;
 9269:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9270:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9271:     $thisfn=~s/^\///;
 9272:     $thisfn=~s|^adm/wrapper/||;
 9273:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 9274:     $thisfn=~s/^res\///;
 9275:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
 9276:         $thisfn=~s/\?.+$//;
 9277:     }
 9278:     return $thisfn;
 9279: }
 9280: 
 9281: # ------------------------------------------------------------- Clutter up URLs
 9282: 
 9283: sub clutter {
 9284:     my $thisfn='/'.&declutter(shift);
 9285:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 9286: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 9287:        $thisfn='/res'.$thisfn; 
 9288:     }
 9289:     if ($thisfn !~m|^/adm|) {
 9290: 	if ($thisfn =~ m|^/ext/|) {
 9291: 	    $thisfn='/adm/wrapper'.$thisfn;
 9292: 	} else {
 9293: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 9294: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 9295: 	    if ($embstyle eq 'ssi'
 9296: 		|| ($embstyle eq 'hdn')
 9297: 		|| ($embstyle eq 'rat')
 9298: 		|| ($embstyle eq 'prv')
 9299: 		|| ($embstyle eq 'ign')) {
 9300: 		#do nothing with these
 9301: 	    } elsif (($embstyle eq 'img') 
 9302: 		|| ($embstyle eq 'emb')
 9303: 		|| ($embstyle eq 'wrp')) {
 9304: 		$thisfn='/adm/wrapper'.$thisfn;
 9305: 	    } elsif ($embstyle eq 'unk'
 9306: 		     && $thisfn!~/\.(sequence|page)$/) {
 9307: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 9308: 	    } else {
 9309: #		&logthis("Got a blank emb style");
 9310: 	    }
 9311: 	}
 9312:     }
 9313:     return $thisfn;
 9314: }
 9315: 
 9316: sub clutter_with_no_wrapper {
 9317:     my $uri = &clutter(shift);
 9318:     if ($uri =~ m-^/adm/-) {
 9319: 	$uri =~ s-^/adm/wrapper/-/-;
 9320: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 9321:     }
 9322:     return $uri;
 9323: }
 9324: 
 9325: sub freeze_escape {
 9326:     my ($value)=@_;
 9327:     if (ref($value)) {
 9328: 	$value=&nfreeze($value);
 9329: 	return '__FROZEN__'.&escape($value);
 9330:     }
 9331:     return &escape($value);
 9332: }
 9333: 
 9334: 
 9335: sub thaw_unescape {
 9336:     my ($value)=@_;
 9337:     if ($value =~ /^__FROZEN__/) {
 9338: 	substr($value,0,10,undef);
 9339: 	$value=&unescape($value);
 9340: 	return &thaw($value);
 9341:     }
 9342:     return &unescape($value);
 9343: }
 9344: 
 9345: sub correct_line_ends {
 9346:     my ($result)=@_;
 9347:     $$result =~s/\r\n/\n/mg;
 9348:     $$result =~s/\r/\n/mg;
 9349: }
 9350: # ================================================================ Main Program
 9351: 
 9352: sub goodbye {
 9353:    &logthis("Starting Shut down");
 9354: #not converted to using infrastruture and probably shouldn't be
 9355:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 9356: #converted
 9357: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 9358:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 9359: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 9360: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 9361: #1.1 only
 9362: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 9363: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 9364: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 9365: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 9366:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 9367:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 9368:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 9369:    &flushcourselogs();
 9370:    &logthis("Shutting down");
 9371: }
 9372: 
 9373: sub get_dns {
 9374:     my ($url,$func,$ignore_cache) = @_;
 9375:     if (!$ignore_cache) {
 9376: 	my ($content,$cached)=
 9377: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9378: 	if ($cached) {
 9379: 	    &$func($content);
 9380: 	    return;
 9381: 	}
 9382:     }
 9383: 
 9384:     my %alldns;
 9385:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9386:     foreach my $dns (<$config>) {
 9387: 	next if ($dns !~ /^\^(\S*)/x);
 9388:         my $line = $1;
 9389:         my ($host,$protocol) = split(/:/,$line);
 9390:         if ($protocol ne 'https') {
 9391:             $protocol = 'http';
 9392:         }
 9393: 	$alldns{$host} = $protocol;
 9394:     }
 9395:     while (%alldns) {
 9396: 	my ($dns) = keys(%alldns);
 9397: 	my $ua=new LWP::UserAgent;
 9398: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9399: 	my $response=$ua->request($request);
 9400:         delete($alldns{$dns});
 9401: 	next if ($response->is_error());
 9402: 	my @content = split("\n",$response->content);
 9403: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9404: 	&$func(\@content);
 9405: 	return;
 9406:     }
 9407:     close($config);
 9408:     my $which = (split('/',$url))[3];
 9409:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9410:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9411:     my @content = <$config>;
 9412:     &$func(\@content);
 9413:     return;
 9414: }
 9415: # ------------------------------------------------------------ Read domain file
 9416: {
 9417:     my $loaded;
 9418:     my %domain;
 9419: 
 9420:     sub parse_domain_tab {
 9421: 	my ($lines) = @_;
 9422: 	foreach my $line (@$lines) {
 9423: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9424: 
 9425: 	    chomp($line);
 9426: 	    my ($name,@elements) = split(/:/,$line,9);
 9427: 	    my %this_domain;
 9428: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9429: 			       'lang_def', 'city', 'longi', 'lati',
 9430: 			       'primary') {
 9431: 		$this_domain{$field} = shift(@elements);
 9432: 	    }
 9433: 	    $domain{$name} = \%this_domain;
 9434: 	}
 9435:     }
 9436: 
 9437:     sub reset_domain_info {
 9438: 	undef($loaded);
 9439: 	undef(%domain);
 9440:     }
 9441: 
 9442:     sub load_domain_tab {
 9443: 	my ($ignore_cache) = @_;
 9444: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9445: 	my $fh;
 9446: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9447: 	    my @lines = <$fh>;
 9448: 	    &parse_domain_tab(\@lines);
 9449: 	}
 9450: 	close($fh);
 9451: 	$loaded = 1;
 9452:     }
 9453: 
 9454:     sub domain {
 9455: 	&load_domain_tab() if (!$loaded);
 9456: 
 9457: 	my ($name,$what) = @_;
 9458: 	return if ( !exists($domain{$name}) );
 9459: 
 9460: 	if (!$what) {
 9461: 	    return $domain{$name}{'description'};
 9462: 	}
 9463: 	return $domain{$name}{$what};
 9464:     }
 9465: 
 9466:     sub domain_info {
 9467:         &load_domain_tab() if (!$loaded);
 9468:         return %domain;
 9469:     }
 9470: 
 9471: }
 9472: 
 9473: 
 9474: # ------------------------------------------------------------- Read hosts file
 9475: {
 9476:     my %hostname;
 9477:     my %hostdom;
 9478:     my %libserv;
 9479:     my $loaded;
 9480:     my %name_to_host;
 9481: 
 9482:     sub parse_hosts_tab {
 9483: 	my ($file) = @_;
 9484: 	foreach my $configline (@$file) {
 9485: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9486: 	    next if ($configline =~ /^\^/);
 9487: 	    chomp($configline);
 9488: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9489: 	    $name=~s/\s//g;
 9490: 	    if ($id && $domain && $role && $name) {
 9491: 		$hostname{$id}=$name;
 9492: 		push(@{$name_to_host{$name}}, $id);
 9493: 		$hostdom{$id}=$domain;
 9494: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9495:                 if (defined($protocol)) {
 9496:                     if ($protocol eq 'https') {
 9497:                         $protocol{$id} = $protocol;
 9498:                     } else {
 9499:                         $protocol{$id} = 'http'; 
 9500:                     }
 9501:                 } else {
 9502:                     $protocol{$id} = 'http';
 9503:                 }
 9504: 	    }
 9505: 	}
 9506:     }
 9507:     
 9508:     sub reset_hosts_info {
 9509: 	&purge_remembered();
 9510: 	&reset_domain_info();
 9511: 	&reset_hosts_ip_info();
 9512: 	undef(%name_to_host);
 9513: 	undef(%hostname);
 9514: 	undef(%hostdom);
 9515: 	undef(%libserv);
 9516: 	undef($loaded);
 9517:     }
 9518: 
 9519:     sub load_hosts_tab {
 9520: 	my ($ignore_cache) = @_;
 9521: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9522: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9523: 	my @config = <$config>;
 9524: 	&parse_hosts_tab(\@config);
 9525: 	close($config);
 9526: 	$loaded=1;
 9527:     }
 9528: 
 9529:     sub hostname {
 9530: 	&load_hosts_tab() if (!$loaded);
 9531: 
 9532: 	my ($lonid) = @_;
 9533: 	return $hostname{$lonid};
 9534:     }
 9535: 
 9536:     sub all_hostnames {
 9537: 	&load_hosts_tab() if (!$loaded);
 9538: 
 9539: 	return %hostname;
 9540:     }
 9541: 
 9542:     sub all_names {
 9543: 	&load_hosts_tab() if (!$loaded);
 9544: 
 9545: 	return %name_to_host;
 9546:     }
 9547: 
 9548:     sub all_host_domain {
 9549:         &load_hosts_tab() if (!$loaded);
 9550:         return %hostdom;
 9551:     }
 9552: 
 9553:     sub is_library {
 9554: 	&load_hosts_tab() if (!$loaded);
 9555: 
 9556: 	return exists($libserv{$_[0]});
 9557:     }
 9558: 
 9559:     sub all_library {
 9560: 	&load_hosts_tab() if (!$loaded);
 9561: 
 9562: 	return %libserv;
 9563:     }
 9564: 
 9565:     sub get_servers {
 9566: 	&load_hosts_tab() if (!$loaded);
 9567: 
 9568: 	my ($domain,$type) = @_;
 9569: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9570: 	                                          : %hostname;
 9571: 	my %result;
 9572: 	if (ref($domain) eq 'ARRAY') {
 9573: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9574: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9575: 		    $result{$host} = $hostname;
 9576: 		}
 9577: 	    }
 9578: 	} else {
 9579: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9580: 		if ($hostdom{$host} eq $domain) {
 9581: 		    $result{$host} = $hostname;
 9582: 		}
 9583: 	    }
 9584: 	}
 9585: 	return %result;
 9586:     }
 9587: 
 9588:     sub host_domain {
 9589: 	&load_hosts_tab() if (!$loaded);
 9590: 
 9591: 	my ($lonid) = @_;
 9592: 	return $hostdom{$lonid};
 9593:     }
 9594: 
 9595:     sub all_domains {
 9596: 	&load_hosts_tab() if (!$loaded);
 9597: 
 9598: 	my %seen;
 9599: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9600: 	return @uniq;
 9601:     }
 9602: }
 9603: 
 9604: { 
 9605:     my %iphost;
 9606:     my %name_to_ip;
 9607:     my %lonid_to_ip;
 9608: 
 9609:     sub get_hosts_from_ip {
 9610: 	my ($ip) = @_;
 9611: 	my %iphosts = &get_iphost();
 9612: 	if (ref($iphosts{$ip})) {
 9613: 	    return @{$iphosts{$ip}};
 9614: 	}
 9615: 	return;
 9616:     }
 9617:     
 9618:     sub reset_hosts_ip_info {
 9619: 	undef(%iphost);
 9620: 	undef(%name_to_ip);
 9621: 	undef(%lonid_to_ip);
 9622:     }
 9623: 
 9624:     sub get_host_ip {
 9625: 	my ($lonid) = @_;
 9626: 	if (exists($lonid_to_ip{$lonid})) {
 9627: 	    return $lonid_to_ip{$lonid};
 9628: 	}
 9629: 	my $name=&hostname($lonid);
 9630:    	my $ip = gethostbyname($name);
 9631: 	return if (!$ip || length($ip) ne 4);
 9632: 	$ip=inet_ntoa($ip);
 9633: 	$name_to_ip{$name}   = $ip;
 9634: 	$lonid_to_ip{$lonid} = $ip;
 9635: 	return $ip;
 9636:     }
 9637:     
 9638:     sub get_iphost {
 9639: 	my ($ignore_cache) = @_;
 9640: 
 9641: 	if (!$ignore_cache) {
 9642: 	    if (%iphost) {
 9643: 		return %iphost;
 9644: 	    }
 9645: 	    my ($ip_info,$cached)=
 9646: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9647: 	    if ($cached) {
 9648: 		%iphost      = %{$ip_info->[0]};
 9649: 		%name_to_ip  = %{$ip_info->[1]};
 9650: 		%lonid_to_ip = %{$ip_info->[2]};
 9651: 		return %iphost;
 9652: 	    }
 9653: 	}
 9654: 
 9655: 	# get yesterday's info for fallback
 9656: 	my %old_name_to_ip;
 9657: 	my ($ip_info,$cached)=
 9658: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9659: 	if ($cached) {
 9660: 	    %old_name_to_ip = %{$ip_info->[1]};
 9661: 	}
 9662: 
 9663: 	my %name_to_host = &all_names();
 9664: 	foreach my $name (keys(%name_to_host)) {
 9665: 	    my $ip;
 9666: 	    if (!exists($name_to_ip{$name})) {
 9667: 		$ip = gethostbyname($name);
 9668: 		if (!$ip || length($ip) ne 4) {
 9669: 		    if (defined($old_name_to_ip{$name})) {
 9670: 			$ip = $old_name_to_ip{$name};
 9671: 			&logthis("Can't find $name defaulting to old $ip");
 9672: 		    } else {
 9673: 			&logthis("Name $name no IP found");
 9674: 			next;
 9675: 		    }
 9676: 		} else {
 9677: 		    $ip=inet_ntoa($ip);
 9678: 		}
 9679: 		$name_to_ip{$name} = $ip;
 9680: 	    } else {
 9681: 		$ip = $name_to_ip{$name};
 9682: 	    }
 9683: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9684: 		$lonid_to_ip{$id} = $ip;
 9685: 	    }
 9686: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9687: 	}
 9688: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9689: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9690: 				      48*60*60);
 9691: 
 9692: 	return %iphost;
 9693:     }
 9694: 
 9695:     #
 9696:     #  Given a DNS returns the loncapa host name for that DNS 
 9697:     # 
 9698:     sub host_from_dns {
 9699:         my ($dns) = @_;
 9700:         my @hosts;
 9701:         my $ip;
 9702: 
 9703:         if (exists($name_to_ip{$dns})) {
 9704:             $ip = $name_to_ip{$dns};
 9705:         }
 9706:         if (!$ip) {
 9707:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9708:             if (length($ip) == 4) { 
 9709: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9710:             }
 9711:         }
 9712:         if ($ip) {
 9713: 	    @hosts = get_hosts_from_ip($ip);
 9714: 	    return $hosts[0];
 9715:         }
 9716:         return undef;
 9717:     }
 9718: 
 9719: }
 9720: 
 9721: BEGIN {
 9722: 
 9723: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9724:     unless ($readit) {
 9725: {
 9726:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9727:     %perlvar = (%perlvar,%{$configvars});
 9728: }
 9729: 
 9730: 
 9731: # ------------------------------------------------------ Read spare server file
 9732: {
 9733:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9734: 
 9735:     while (my $configline=<$config>) {
 9736:        chomp($configline);
 9737:        if ($configline) {
 9738: 	   my ($host,$type) = split(':',$configline,2);
 9739: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9740: 	   push(@{ $spareid{$type} }, $host);
 9741:        }
 9742:     }
 9743:     close($config);
 9744: }
 9745: # ------------------------------------------------------------ Read permissions
 9746: {
 9747:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9748: 
 9749:     while (my $configline=<$config>) {
 9750: 	chomp($configline);
 9751: 	if ($configline) {
 9752: 	    my ($role,$perm)=split(/ /,$configline);
 9753: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9754: 	}
 9755:     }
 9756:     close($config);
 9757: }
 9758: 
 9759: # -------------------------------------------- Read plain texts for permissions
 9760: {
 9761:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9762: 
 9763:     while (my $configline=<$config>) {
 9764: 	chomp($configline);
 9765: 	if ($configline) {
 9766: 	    my ($short,@plain)=split(/:/,$configline);
 9767:             %{$prp{$short}} = ();
 9768: 	    if (@plain > 0) {
 9769:                 $prp{$short}{'std'} = $plain[0];
 9770:                 for (my $i=1; $i<@plain; $i++) {
 9771:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9772:                 }
 9773:             }
 9774: 	}
 9775:     }
 9776:     close($config);
 9777: }
 9778: 
 9779: # ---------------------------------------------------------- Read package table
 9780: {
 9781:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9782: 
 9783:     while (my $configline=<$config>) {
 9784: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9785: 	chomp($configline);
 9786: 	my ($short,$plain)=split(/:/,$configline);
 9787: 	my ($pack,$name)=split(/\&/,$short);
 9788: 	if ($plain ne '') {
 9789: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9790: 	    $packagetab{$short}=$plain; 
 9791: 	}
 9792:     }
 9793:     close($config);
 9794: }
 9795: 
 9796: # ------------- set up temporary directory
 9797: {
 9798:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9799: 
 9800: }
 9801: 
 9802: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9803: 				'compress_threshold'=> 20_000,
 9804:  			        });
 9805: 
 9806: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9807: $dumpcount=0;
 9808: $locknum=0;
 9809: 
 9810: &logtouch();
 9811: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9812: $readit=1;
 9813:     {
 9814: 	use integer;
 9815: 	my $test=(2**32)+1;
 9816: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9817: 	&logthis(" Detected 64bit platform ($_64bit)");
 9818:     }
 9819: }
 9820: }
 9821: 
 9822: 1;
 9823: __END__
 9824: 
 9825: =pod
 9826: 
 9827: =head1 NAME
 9828: 
 9829: Apache::lonnet - Subroutines to ask questions about things in the network.
 9830: 
 9831: =head1 SYNOPSIS
 9832: 
 9833: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9834: 
 9835:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9836: 
 9837: Common parameters:
 9838: 
 9839: =over 4
 9840: 
 9841: =item *
 9842: 
 9843: $uname : an internal username (if $cname expecting a course Id specifically)
 9844: 
 9845: =item *
 9846: 
 9847: $udom : a domain (if $cdom expecting a course's domain specifically)
 9848: 
 9849: =item *
 9850: 
 9851: $symb : a resource instance identifier
 9852: 
 9853: =item *
 9854: 
 9855: $namespace : the name of a .db file that contains the data needed or
 9856: being set.
 9857: 
 9858: =back
 9859: 
 9860: =head1 OVERVIEW
 9861: 
 9862: lonnet provides subroutines which interact with the
 9863: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9864: about classes, users, and resources.
 9865: 
 9866: For many of these objects you can also use this to store data about
 9867: them or modify them in various ways.
 9868: 
 9869: =head2 Symbs
 9870: 
 9871: To identify a specific instance of a resource, LON-CAPA uses symbols
 9872: or "symbs"X<symb>. These identifiers are built from the URL of the
 9873: map, the resource number of the resource in the map, and the URL of
 9874: the resource itself. The latter is somewhat redundant, but might help
 9875: if maps change.
 9876: 
 9877: An example is
 9878: 
 9879:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9880: 
 9881: The respective map entry is
 9882: 
 9883:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9884:   title="Problem 2">
 9885:  </resource>
 9886: 
 9887: Symbs are used by the random number generator, as well as to store and
 9888: restore data specific to a certain instance of for example a problem.
 9889: 
 9890: =head2 Storing And Retrieving Data
 9891: 
 9892: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9893: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9894: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9895: is is the non-critical message twin of cstore. These functions are for
 9896: handlers to store a perl hash to a user's permanent data space in an
 9897: easy manner, and to retrieve it again on another call. It is expected
 9898: that a handler would use this once at the beginning to retrieve data,
 9899: and then again once at the end to send only the new data back.
 9900: 
 9901: The data is stored in the user's data directory on the user's
 9902: homeserver under the ID of the course.
 9903: 
 9904: The hash that is returned by restore will have all of the previous
 9905: value for all of the elements of the hash.
 9906: 
 9907: Example:
 9908: 
 9909:  #creating a hash
 9910:  my %hash;
 9911:  $hash{'foo'}='bar';
 9912: 
 9913:  #storing it
 9914:  &Apache::lonnet::cstore(\%hash);
 9915: 
 9916:  #changing a value
 9917:  $hash{'foo'}='notbar';
 9918: 
 9919:  #adding a new value
 9920:  $hash{'bar'}='foo';
 9921:  &Apache::lonnet::cstore(\%hash);
 9922: 
 9923:  #retrieving the hash
 9924:  my %history=&Apache::lonnet::restore();
 9925: 
 9926:  #print the hash
 9927:  foreach my $key (sort(keys(%history))) {
 9928:    print("\%history{$key} = $history{$key}");
 9929:  }
 9930: 
 9931: Will print out:
 9932: 
 9933:  %history{1:foo} = bar
 9934:  %history{1:keys} = foo:timestamp
 9935:  %history{1:timestamp} = 990455579
 9936:  %history{2:bar} = foo
 9937:  %history{2:foo} = notbar
 9938:  %history{2:keys} = foo:bar:timestamp
 9939:  %history{2:timestamp} = 990455580
 9940:  %history{bar} = foo
 9941:  %history{foo} = notbar
 9942:  %history{timestamp} = 990455580
 9943:  %history{version} = 2
 9944: 
 9945: Note that the special hash entries C<keys>, C<version> and
 9946: C<timestamp> were added to the hash. C<version> will be equal to the
 9947: total number of versions of the data that have been stored. The
 9948: C<timestamp> attribute will be the UNIX time the hash was
 9949: stored. C<keys> is available in every historical section to list which
 9950: keys were added or changed at a specific historical revision of a
 9951: hash.
 9952: 
 9953: B<Warning>: do not store the hash that restore returns directly. This
 9954: will cause a mess since it will restore the historical keys as if the
 9955: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9956: 
 9957: Calling convention:
 9958: 
 9959:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9960:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9961: 
 9962: For more detailed information, see lonnet specific documentation.
 9963: 
 9964: =head1 RETURN MESSAGES
 9965: 
 9966: =over 4
 9967: 
 9968: =item * B<con_lost>: unable to contact remote host
 9969: 
 9970: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9971: when the connection is brought back up
 9972: 
 9973: =item * B<con_failed>: unable to contact remote host and unable to save message
 9974: for later delivery
 9975: 
 9976: =item * B<error:>: an error a occurred, a description of the error follows the :
 9977: 
 9978: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9979: that was requested
 9980: 
 9981: =back
 9982: 
 9983: =head1 PUBLIC SUBROUTINES
 9984: 
 9985: =head2 Session Environment Functions
 9986: 
 9987: =over 4
 9988: 
 9989: =item * 
 9990: X<appenv()>
 9991: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9992: the user envirnoment file, and will be restored for each access this
 9993: user makes during this session, also modifies the %env for the current
 9994: process. Optional rolesarrayref - if defined contains a reference to an array
 9995: of roles which are exempt from the restriction on modifying user.role entries 
 9996: in the user's environment.db and in %env.    
 9997: 
 9998: =item *
 9999: X<delenv()>
10000: B<delenv($delthis,$regexp)>: removes all items from the session
10001: environment file that begin with $delthis. If the 
10002: optional second arg - $regexp - is true, $delthis is treated as a 
10003: regular expression, otherwise \Q$delthis\E is used. 
10004: The values are also deleted from the current processes %env.
10005: 
10006: =item * get_env_multiple($name) 
10007: 
10008: gets $name from the %env hash, it seemlessly handles the cases where multiple
10009: values may be defined and end up as an array ref.
10010: 
10011: returns an array of values
10012: 
10013: =back
10014: 
10015: =head2 User Information
10016: 
10017: =over 4
10018: 
10019: =item *
10020: X<queryauthenticate()>
10021: B<queryauthenticate($uname,$udom)>: try to determine user's current 
10022: authentication scheme
10023: 
10024: =item *
10025: X<authenticate()>
10026: B<authenticate($uname,$upass,$udom)>: try to
10027: authenticate user from domain's lib servers (first use the current
10028: one). C<$upass> should be the users password.
10029: 
10030: =item *
10031: X<homeserver()>
10032: B<homeserver($uname,$udom)>: find the server which has
10033: the user's directory and files (there must be only one), this caches
10034: the answer, and also caches if there is a borken connection.
10035: 
10036: =item *
10037: X<idget()>
10038: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10039: (IDs are a unique resource in a domain, there must be only 1 ID per
10040: username, and only 1 username per ID in a specific domain) (returns
10041: hash: id=>name,id=>name)
10042: 
10043: =item *
10044: X<idrget()>
10045: B<idrget($udom,@unames)>: find the IDs behind a list of
10046: usernames (returns hash: name=>id,name=>id)
10047: 
10048: =item *
10049: X<idput()>
10050: B<idput($udom,%ids)>: store away a list of names and associated IDs
10051: 
10052: =item *
10053: X<rolesinit()>
10054: B<rolesinit($udom,$username,$authhost)>: get user privileges
10055: 
10056: =item *
10057: X<getsection()>
10058: B<getsection($udom,$uname,$cname)>: finds the section of student in the
10059: course $cname, return section name/number or '' for "not in course"
10060: and '-1' for "no section"
10061: 
10062: =item *
10063: X<userenvironment()>
10064: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
10065: passed in @what from the requested user's environment, returns a hash
10066: 
10067: =item * 
10068: X<userlog_query()>
10069: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10070: activity.log file. %filters defines filters applied when parsing the
10071: log file. These can be start or end timestamps, or the type of action
10072: - log to look for Login or Logout events, check for Checkin or
10073: Checkout, role for role selection. The response is in the form
10074: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
10075: escaped strings of the action recorded in the activity.log file.
10076: 
10077: =back
10078: 
10079: =head2 User Roles
10080: 
10081: =over 4
10082: 
10083: =item *
10084: 
10085: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
10086:  F: full access
10087:  U,I,K: authentication modes (cxx only)
10088:  '': forbidden
10089:  1: user needs to choose course
10090:  2: browse allowed
10091:  A: passphrase authentication needed
10092: 
10093: =item *
10094: 
10095: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10096: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10097: and course level
10098: 
10099: =item *
10100: 
10101: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
10102: (rolesplain.tab); plain text explanation of a user role term.
10103: $type is Course (default) or Community.
10104: If $forcedefault evaluates to true, text returned will be default 
10105: text for $type. Otherwise, if this is a course, the text returned 
10106: will be a custom name for the role (if defined in the course's 
10107: environment).  If no custom name is defined the default is returned.
10108:    
10109: =item *
10110: 
10111: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
10112: All arguments are optional. Returns a hash of a roles, either for
10113: co-author/assistant author roles for a user's Construction Space
10114: (default), or if $context is 'userroles', roles for the user himself,
10115: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10116: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10117: For each key, value is set to colon-separated start and end times for
10118: the role.  If no username and domain are specified, will default to
10119: current user/domain. Types, roles, and roledoms are references to arrays
10120: of role statuses (active, future or previous), roles 
10121: (e.g., cc,in, st etc.) and domains of the roles which can be used
10122: to restrict the list of roles reported. If no array ref is 
10123: provided for types, will default to return only active roles.
10124: 
10125: =back
10126: 
10127: =head2 User Modification
10128: 
10129: =over 4
10130: 
10131: =item *
10132: 
10133: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10134: user for the level given by URL.  Optional start and end dates (leave empty
10135: string or zero for "no date")
10136: 
10137: =item *
10138: 
10139: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10140: change a users, password, possible return values are: ok,
10141: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10142: refused
10143: 
10144: =item *
10145: 
10146: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10147: 
10148: =item *
10149: 
10150: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
10151:            $forceid,$desiredhome,$email,$inststatus) : 
10152: modify user
10153: 
10154: =item *
10155: 
10156: modifystudent
10157: 
10158: modify a student's enrollment and identification information.
10159: The course id is resolved based on the current users environment.  
10160: This means the envoking user must be a course coordinator or otherwise
10161: associated with a course.
10162: 
10163: This call is essentially a wrapper for lonnet::modifyuser and
10164: lonnet::modify_student_enrollment
10165: 
10166: Inputs: 
10167: 
10168: =over 4
10169: 
10170: =item B<$udom> Student's loncapa domain
10171: 
10172: =item B<$uname> Student's loncapa login name
10173: 
10174: =item B<$uid> Student/Employee ID
10175: 
10176: =item B<$umode> Student's authentication mode
10177: 
10178: =item B<$upass> Student's password
10179: 
10180: =item B<$first> Student's first name
10181: 
10182: =item B<$middle> Student's middle name
10183: 
10184: =item B<$last> Student's last name
10185: 
10186: =item B<$gene> Student's generation
10187: 
10188: =item B<$usec> Student's section in course
10189: 
10190: =item B<$end> Unix time of the roles expiration
10191: 
10192: =item B<$start> Unix time of the roles start date
10193: 
10194: =item B<$forceid> If defined, allow $uid to be changed
10195: 
10196: =item B<$desiredhome> server to use as home server for student
10197: 
10198: =item B<$email> Student's permanent e-mail address
10199: 
10200: =item B<$type> Type of enrollment (auto or manual)
10201: 
10202: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
10203: 
10204: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10205: 
10206: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10207: 
10208: =item B<$context> role change context (shown in User Management Logs display in a course)
10209: 
10210: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
10211: 
10212: =back
10213: 
10214: =item *
10215: 
10216: modify_student_enrollment
10217: 
10218: Change a students enrollment status in a class.  The environment variable
10219: 'role.request.course' must be defined for this function to proceed.
10220: 
10221: Inputs:
10222: 
10223: =over 4
10224: 
10225: =item $udom, students domain
10226: 
10227: =item $uname, students name
10228: 
10229: =item $uid, students user id
10230: 
10231: =item $first, students first name
10232: 
10233: =item $middle
10234: 
10235: =item $last
10236: 
10237: =item $gene
10238: 
10239: =item $usec
10240: 
10241: =item $end
10242: 
10243: =item $start
10244: 
10245: =item $type
10246: 
10247: =item $locktype
10248: 
10249: =item $cid
10250: 
10251: =item $selfenroll
10252: 
10253: =item $context
10254: 
10255: =back
10256: 
10257: 
10258: =item *
10259: 
10260: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10261: custom role; give a custom role to a user for the level given by URL.  Specify
10262: name and domain of role author, and role name
10263: 
10264: =item *
10265: 
10266: revokerole($udom,$uname,$url,$role) : revoke a role for url
10267: 
10268: =item *
10269: 
10270: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10271: 
10272: =back
10273: 
10274: =head2 Course Infomation
10275: 
10276: =over 4
10277: 
10278: =item *
10279: 
10280: coursedescription($courseid) : returns a hash of information about the
10281: specified course id, including all environment settings for the
10282: course, the description of the course will be in the hash under the
10283: key 'description'
10284: 
10285: =item *
10286: 
10287: resdata($name,$domain,$type,@which) : request for current parameter
10288: setting for a specific $type, where $type is either 'course' or 'user',
10289: @what should be a list of parameters to ask about. This routine caches
10290: answers for 5 minutes.
10291: 
10292: =item *
10293: 
10294: get_courseresdata($courseid, $domain) : dump the entire course resource
10295: data base, returning a hash that is keyed by the resource name and has
10296: values that are the resource value.  I believe that the timestamps and
10297: versions are also returned.
10298: 
10299: 
10300: =back
10301: 
10302: =head2 Course Modification
10303: 
10304: =over 4
10305: 
10306: =item *
10307: 
10308: writecoursepref($courseid,%prefs) : write preferences (environment
10309: database) for a course
10310: 
10311: =item *
10312: 
10313: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10314: 
10315: =item *
10316: 
10317: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
10318: 
10319: =back
10320: 
10321: =head2 Resource Subroutines
10322: 
10323: =over 4
10324: 
10325: =item *
10326: 
10327: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10328: 
10329: =item *
10330: 
10331: repcopy($filename) : subscribes to the requested file, and attempts to
10332: replicate from the owning library server, Might return
10333: 'unavailable', 'not_found', 'forbidden', 'ok', or
10334: 'bad_request', also attempts to grab the metadata for the
10335: resource. Expects the local filesystem pathname
10336: (/home/httpd/html/res/....)
10337: 
10338: =back
10339: 
10340: =head2 Resource Information
10341: 
10342: =over 4
10343: 
10344: =item *
10345: 
10346: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10347: a vairety of different possible values, $varname should be a request
10348: string, and the other parameters can be used to specify who and what
10349: one is asking about.
10350: 
10351: Possible values for $varname are environment.lastname (or other item
10352: from the envirnment hash), user.name (or someother aspect about the
10353: user), resource.0.maxtries (or some other part and parameter of a
10354: resource)
10355: 
10356: =item *
10357: 
10358: directcondval($number) : get current value of a condition; reads from a state
10359: string
10360: 
10361: =item *
10362: 
10363: condval($condidx) : value of condition index based on state
10364: 
10365: =item *
10366: 
10367: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10368: resource's metadata, $what should be either a specific key, or either
10369: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10370: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10371: 
10372: this function automatically caches all requests
10373: 
10374: =item *
10375: 
10376: metadata_query($query,$custom,$customshow) : make a metadata query against the
10377: network of library servers; returns file handle of where SQL and regex results
10378: will be stored for query
10379: 
10380: =item *
10381: 
10382: symbread($filename) : return symbolic list entry (filename argument optional);
10383: returns the data handle
10384: 
10385: =item *
10386: 
10387: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10388: a possible symb for the URL in $thisfn, and if is an encryypted
10389: resource that the user accessed using /enc/ returns a 1 on success, 0
10390: on failure, user must be in a course, as it assumes the existance of
10391: the course initial hash, and uses $env('request.course.id'}
10392: 
10393: 
10394: =item *
10395: 
10396: symbclean($symb) : removes versions numbers from a symb, returns the
10397: cleaned symb
10398: 
10399: =item *
10400: 
10401: is_on_map($uri) : checks if the $uri is somewhere on the current
10402: course map, user must be in a course for it to work.
10403: 
10404: =item *
10405: 
10406: numval($salt) : return random seed value (addend for rndseed)
10407: 
10408: =item *
10409: 
10410: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10411: a random seed, all arguments are optional, if they aren't sent it uses the
10412: environment to derive them. Note: if symb isn't sent and it can't get one
10413: from &symbread it will use the current time as its return value
10414: 
10415: =item *
10416: 
10417: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10418: unfakeable, receipt
10419: 
10420: =item *
10421: 
10422: receipt() : API to ireceipt working off of env values; given out to users
10423: 
10424: =item *
10425: 
10426: countacc($url) : count the number of accesses to a given URL
10427: 
10428: =item *
10429: 
10430: 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
10431: 
10432: =item *
10433: 
10434: 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)
10435: 
10436: =item *
10437: 
10438: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10439: 
10440: =item *
10441: 
10442: devalidate($symb) : devalidate temporary spreadsheet calculations,
10443: forcing spreadsheet to reevaluate the resource scores next time.
10444: 
10445: =back
10446: 
10447: =head2 Storing/Retreiving Data
10448: 
10449: =over 4
10450: 
10451: =item *
10452: 
10453: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10454: for this url; hashref needs to be given and should be a \%hashname; the
10455: remaining args aren't required and if they aren't passed or are '' they will
10456: be derived from the env
10457: 
10458: =item *
10459: 
10460: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10461: uses critical subroutine
10462: 
10463: =item *
10464: 
10465: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10466: all args are optional
10467: 
10468: =item *
10469: 
10470: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10471: dumps the complete (or key matching regexp) namespace into a hash
10472: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10473: normally &store()ed into
10474: 
10475: $range should be either an integer '100' (give me the first 100
10476:                                            matching records)
10477:               or be  two integers sperated by a - with no spaces
10478:                  '30-50' (give me the 30th through the 50th matching
10479:                           records)
10480: 
10481: 
10482: =item *
10483: 
10484: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10485: replaces a &store() version of data with a replacement set of data
10486: for a particular resource in a namespace passed in the $storehash hash 
10487: reference
10488: 
10489: =item *
10490: 
10491: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10492: works very similar to store/cstore, but all data is stored in a
10493: temporary location and can be reset using tmpreset, $storehash should
10494: be a hash reference, returns nothing on success
10495: 
10496: =item *
10497: 
10498: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10499: similar to restore, but all data is stored in a temporary location and
10500: can be reset using tmpreset. Returns a hash of values on success,
10501: error string otherwise.
10502: 
10503: =item *
10504: 
10505: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10506: deltes all keys for $symb form the temporary storage hash.
10507: 
10508: =item *
10509: 
10510: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10511: reference filled in from namesp ($udom and $uname are optional)
10512: 
10513: =item *
10514: 
10515: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10516: namesp ($udom and $uname are optional)
10517: 
10518: =item *
10519: 
10520: dump($namespace,$udom,$uname,$regexp,$range) : 
10521: dumps the complete (or key matching regexp) namespace into a hash
10522: ($udom, $uname, $regexp, $range are optional)
10523: 
10524: $range should be either an integer '100' (give me the first 100
10525:                                            matching records)
10526:               or be  two integers sperated by a - with no spaces
10527:                  '30-50' (give me the 30th through the 50th matching
10528:                           records)
10529: =item *
10530: 
10531: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10532: $store can be a scalar, an array reference, or if the amount to be 
10533: incremented is > 1, a hash reference.
10534: 
10535: ($udom and $uname are optional)
10536: 
10537: =item *
10538: 
10539: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10540: ($udom and $uname are optional)
10541: 
10542: =item *
10543: 
10544: cput($namespace,$storehash,$udom,$uname) : critical put
10545: ($udom and $uname are optional)
10546: 
10547: =item *
10548: 
10549: newput($namespace,$storehash,$udom,$uname) :
10550: 
10551: Attempts to store the items in the $storehash, but only if they don't
10552: currently exist, if this succeeds you can be certain that you have 
10553: successfully created a new key value pair in the $namespace db.
10554: 
10555: 
10556: Args:
10557:  $namespace: name of database to store values to
10558:  $storehash: hashref to store to the db
10559:  $udom: (optional) domain of user containing the db
10560:  $uname: (optional) name of user caontaining the db
10561: 
10562: Returns:
10563:  'ok' -> succeeded in storing all keys of $storehash
10564:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10565:                         least <key> already existed in the db (other
10566:                         requested keys may also already exist)
10567:  'error: <msg>' -> unable to tie the DB or other error occurred
10568:  'con_lost' -> unable to contact request server
10569:  'refused' -> action was not allowed by remote machine
10570: 
10571: 
10572: =item *
10573: 
10574: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10575: reference filled in from namesp (encrypts the return communication)
10576: ($udom and $uname are optional)
10577: 
10578: =item *
10579: 
10580: log($udom,$name,$home,$message) : write to permanent log for user; use
10581: critical subroutine
10582: 
10583: =item *
10584: 
10585: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10586: array reference filled in from namespace found in domain level on either
10587: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10588: 
10589: =item *
10590: 
10591: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10592: domain level either on specified domain server ($uhome) or primary domain 
10593: server ($udom and $uhome are optional)
10594: 
10595: =item * 
10596: 
10597: get_domain_defaults($target_domain) : returns hash with defaults for
10598: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10599: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10600: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10601: Values are retrieved from cache (if current), or from domain's configuration.db
10602: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10603: or lonTabs/domain.tab. 
10604: 
10605: %domdefaults = &get_auth_defaults($target_domain);
10606: 
10607: =back
10608: 
10609: =head2 Network Status Functions
10610: 
10611: =over 4
10612: 
10613: =item *
10614: 
10615: dirlist($uri) : return directory list based on URI
10616: 
10617: =item *
10618: 
10619: spareserver() : find server with least workload from spare.tab
10620: 
10621: 
10622: =item *
10623: 
10624: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10625: if there is no corresponding loncapa host.
10626: 
10627: =back
10628: 
10629: 
10630: =head2 Apache Request
10631: 
10632: =over 4
10633: 
10634: =item *
10635: 
10636: ssi($url,%hash) : server side include, does a complete request cycle on url to
10637: localhost, posts hash
10638: 
10639: =back
10640: 
10641: =head2 Data to String to Data
10642: 
10643: =over 4
10644: 
10645: =item *
10646: 
10647: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10648: and '&' separators, supports elements that are arrayrefs and hashrefs
10649: 
10650: =item *
10651: 
10652: hashref2str($hashref) : convert a hashref into a string complete with
10653: escaping and '=' and '&' separators, supports elements that are
10654: arrayrefs and hashrefs
10655: 
10656: =item *
10657: 
10658: arrayref2str($arrayref) : convert an arrayref into a string complete
10659: with escaping and '&' separators, supports elements that are arrayrefs
10660: and hashrefs
10661: 
10662: =item *
10663: 
10664: str2hash($string) : convert string to hash using unescaping and
10665: splitting on '=' and '&', supports elements that are arrayrefs and
10666: hashrefs
10667: 
10668: =item *
10669: 
10670: str2array($string) : convert string to hash using unescaping and
10671: splitting on '&', supports elements that are arrayrefs and hashrefs
10672: 
10673: =back
10674: 
10675: =head2 Logging Routines
10676: 
10677: =over 4
10678: 
10679: These routines allow one to make log messages in the lonnet.log and
10680: lonnet.perm logfiles.
10681: 
10682: =item *
10683: 
10684: logtouch() : make sure the logfile, lonnet.log, exists
10685: 
10686: =item *
10687: 
10688: logthis() : append message to the normal lonnet.log file, it gets
10689: preiodically rolled over and deleted.
10690: 
10691: =item *
10692: 
10693: logperm() : append a permanent message to lonnet.perm.log, this log
10694: file never gets deleted by any automated portion of the system, only
10695: messages of critical importance should go in here.
10696: 
10697: =back
10698: 
10699: =head2 General File Helper Routines
10700: 
10701: =over 4
10702: 
10703: =item *
10704: 
10705: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10706: (a) files in /uploaded
10707:   (i) If a local copy of the file exists - 
10708:       compares modification date of local copy with last-modified date for 
10709:       definitive version stored on home server for course. If local copy is 
10710:       stale, requests a new version from the home server and stores it. 
10711:       If the original has been removed from the home server, then local copy 
10712:       is unlinked.
10713:   (ii) If local copy does not exist -
10714:       requests the file from the home server and stores it. 
10715:   
10716:   If $caller is 'uploadrep':  
10717:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10718:     for request for files originally uploaded via DOCS. 
10719:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10720:   
10721:   Otherwise:
10722:      This indicates a call from the content generation phase of the request.
10723:      -  returns the entire contents of the file or -1.
10724:      
10725: (b) files in /res
10726:    - returns the entire contents of a file or -1; 
10727:    it properly subscribes to and replicates the file if neccessary.
10728: 
10729: 
10730: =item *
10731: 
10732: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10733:                   reference
10734: 
10735: returns either a stat() list of data about the file or an empty list
10736: if the file doesn't exist or couldn't find out about it (connection
10737: problems or user unknown)
10738: 
10739: =item *
10740: 
10741: filelocation($dir,$file) : returns file system location of a file
10742: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10743: directory that relative $file lookups are to looked in ($dir of /a/dir
10744: and a file of ../bob will become /a/bob)
10745: 
10746: =item *
10747: 
10748: hreflocation($dir,$file) : returns file system location or a URL; same as
10749: filelocation except for hrefs
10750: 
10751: =item *
10752: 
10753: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10754: 
10755: =back
10756: 
10757: =head2 Usererfile file routines (/uploaded*)
10758: 
10759: =over 4
10760: 
10761: =item *
10762: 
10763: userfileupload(): main rotine for putting a file in a user or course's
10764:                   filespace, arguments are,
10765: 
10766:  formname - required - this is the name of the element in $env where the
10767:            filename, and the contents of the file to create/modifed exist
10768:            the filename is in $env{'form.'.$formname.'.filename'} and the
10769:            contents of the file is located in $env{'form.'.$formname}
10770:  coursedoc - if true, store the file in the course of the active role
10771:              of the current user
10772:  subdir - required - subdirectory to put the file in under ../userfiles/
10773:          if undefined, it will be placed in "unknown"
10774: 
10775:  (This routine calls clean_filename() to remove any dangerous
10776:  characters from the filename, and then calls finuserfileupload() to
10777:  complete the transaction)
10778: 
10779:  returns either the url of the uploaded file (/uploaded/....) if successful
10780:  and /adm/notfound.html if unsuccessful
10781: 
10782: =item *
10783: 
10784: clean_filename(): routine for cleaing a filename up for storage in
10785:                  userfile space, argument is:
10786: 
10787:  filename - proposed filename
10788: 
10789: returns: the new clean filename
10790: 
10791: =item *
10792: 
10793: finishuserfileupload(): routine that creaes and sends the file to
10794: userspace, probably shouldn't be called directly
10795: 
10796:   docuname: username or courseid of destination for the file
10797:   docudom: domain of user/course of destination for the file
10798:   formname: same as for userfileupload()
10799:   fname: filename (inculding subdirectories) for the file
10800: 
10801:  returns either the url of the uploaded file (/uploaded/....) if successful
10802:  and /adm/notfound.html if unsuccessful
10803: 
10804: =item *
10805: 
10806: renameuserfile(): renames an existing userfile to a new name
10807: 
10808:   Args:
10809:    docuname: username or courseid of destination for the file
10810:    docudom: domain of user/course of destination for the file
10811:    old: current file name (including any subdirs under userfiles)
10812:    new: desired file name (including any subdirs under userfiles)
10813: 
10814: =item *
10815: 
10816: mkdiruserfile(): creates a directory is a userfiles dir
10817: 
10818:   Args:
10819:    docuname: username or courseid of destination for the file
10820:    docudom: domain of user/course of destination for the file
10821:    dir: dir to create (including any subdirs under userfiles)
10822: 
10823: =item *
10824: 
10825: removeuserfile(): removes a file that exists in userfiles
10826: 
10827:   Args:
10828:    docuname: username or courseid of destination for the file
10829:    docudom: domain of user/course of destination for the file
10830:    fname: filname to delete (including any subdirs under userfiles)
10831: 
10832: =item *
10833: 
10834: removeuploadedurl(): convience function for removeuserfile()
10835: 
10836:   Args:
10837:    url:  a full /uploaded/... url to delete
10838: 
10839: =item * 
10840: 
10841: get_portfile_permissions():
10842:   Args:
10843:     domain: domain of user or course contain the portfolio files
10844:     user: name of user or num of course contain the portfolio files
10845:   Returns:
10846:     hashref of a dump of the proper file_permissions.db
10847:    
10848: 
10849: =item * 
10850: 
10851: get_access_controls():
10852: 
10853: Args:
10854:   current_permissions: the hash ref returned from get_portfile_permissions()
10855:   group: (optional) the group you want the files associated with
10856:   file: (optional) the file you want access info on
10857: 
10858: Returns:
10859:     a hash (keys are file names) of hashes containing
10860:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10861:         values are XML containing access control settings (see below) 
10862: 
10863: Internal notes:
10864: 
10865:  access controls are stored in file_permissions.db as key=value pairs.
10866:     key -> path to file/file_name\0uniqueID:scope_end_start
10867:         where scope -> public,guest,course,group,domains or users.
10868:               end -> UNIX time for end of access (0 -> no end date)
10869:               start -> UNIX time for start of access
10870: 
10871:     value -> XML description of access control
10872:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10873:             <start></start>
10874:             <end></end>
10875: 
10876:             <password></password>  for scope type = guest
10877: 
10878:             <domain></domain>     for scope type = course or group
10879:             <number></number>
10880:             <roles id="">
10881:              <role></role>
10882:              <access></access>
10883:              <section></section>
10884:              <group></group>
10885:             </roles>
10886: 
10887:             <dom></dom>         for scope type = domains
10888: 
10889:             <users>             for scope type = users
10890:              <user>
10891:               <uname></uname>
10892:               <udom></udom>
10893:              </user>
10894:             </users>
10895:            </scope> 
10896:               
10897:  Access data is also aggregated for each file in an additional key=value pair:
10898:  key -> path to file/file_name\0accesscontrol 
10899:  value -> reference to hash
10900:           hash contains key = value pairs
10901:           where key = uniqueID:scope_end_start
10902:                 value = UNIX time record was last updated
10903: 
10904:           Used to improve speed of look-ups of access controls for each file.  
10905:  
10906:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10907: 
10908: modify_access_controls():
10909: 
10910: Modifies access controls for a portfolio file
10911: Args
10912: 1. file name
10913: 2. reference to hash of required changes,
10914: 3. domain
10915: 4. username
10916:   where domain,username are the domain of the portfolio owner 
10917:   (either a user or a course) 
10918: 
10919: Returns:
10920: 1. result of additions or updates ('ok' or 'error', with error message). 
10921: 2. result of deletions ('ok' or 'error', with error message).
10922: 3. reference to hash of any new or updated access controls.
10923: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10924:    key = integer (inbound ID)
10925:    value = uniqueID  
10926: 
10927: =back
10928: 
10929: =head2 HTTP Helper Routines
10930: 
10931: =over 4
10932: 
10933: =item *
10934: 
10935: escape() : unpack non-word characters into CGI-compatible hex codes
10936: 
10937: =item *
10938: 
10939: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10940: 
10941: =back
10942: 
10943: =head1 PRIVATE SUBROUTINES
10944: 
10945: =head2 Underlying communication routines (Shouldn't call)
10946: 
10947: =over 4
10948: 
10949: =item *
10950: 
10951: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10952: 
10953: =item *
10954: 
10955: reply() : uses subreply to send a message to remote machine, logs all failures
10956: 
10957: =item *
10958: 
10959: critical() : passes a critical message to another server; if cannot
10960: get through then place message in connection buffer directory and
10961: returns con_delayed, if incapable of saving message, returns
10962: con_failed
10963: 
10964: =item *
10965: 
10966: reconlonc() : tries to reconnect lonc client processes.
10967: 
10968: =back
10969: 
10970: =head2 Resource Access Logging
10971: 
10972: =over 4
10973: 
10974: =item *
10975: 
10976: flushcourselogs() : flush (save) buffer logs and access logs
10977: 
10978: =item *
10979: 
10980: courselog($what) : save message for course in hash
10981: 
10982: =item *
10983: 
10984: courseacclog($what) : save message for course using &courselog().  Perform
10985: special processing for specific resource types (problems, exams, quizzes, etc).
10986: 
10987: =item *
10988: 
10989: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10990: as a PerlChildExitHandler
10991: 
10992: =back
10993: 
10994: =head2 Other
10995: 
10996: =over 4
10997: 
10998: =item *
10999: 
11000: symblist($mapname,%newhash) : update symbolic storage links
11001: 
11002: =back
11003: 
11004: =cut
11005: 

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