File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1023: download - view: text, annotated - select for diffs
Mon Aug 24 20:08:40 2009 UTC (14 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Reverse changes in lond 1.420.
- &newput_dom(), &dump_dom and &del_dom in lonnet.pm now use the corresponding routines for user files - &newput, &del and &dump - with domain db data stored in .db files belonging to the domainconfig user.
- new routine: &get_domainconfiguser() provides the username of the domainconfig user.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1023 2009/08/24 20:08:40 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol);
   80: 
   81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   84:     %courseownerbuf, %coursetypebuf,$locknum);
   85: 
   86: use IO::Socket;
   87: use GDBM_File;
   88: use HTML::LCParser;
   89: use Fcntl qw(:flock);
   90: use Storable qw(thaw nfreeze);
   91: use Time::HiRes qw( gettimeofday tv_interval );
   92: use Cache::Memcached;
   93: use Digest::MD5;
   94: use Math::Random;
   95: use LONCAPA qw(:DEFAULT :match);
   96: use LONCAPA::Configuration;
   97: 
   98: my $readit;
   99: my $max_connection_retries = 10;     # Or some such value.
  100: 
  101: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  102: 
  103: require Exporter;
  104: 
  105: our @ISA = qw (Exporter);
  106: our @EXPORT = qw(%env);
  107: 
  108: 
  109: # --------------------------------------------------------------------- Logging
  110: {
  111:     my $logid;
  112:     sub instructor_log {
  113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  114:         if (($cnum eq '') || ($cdom eq '')) {
  115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  117:         }
  118: 	$logid++;
  119:         my $now = time();
  120: 	my $id=$now.'00000'.$$.'00000'.$logid;
  121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  122: 				    { $id => {
  123: 					'exe_uname' => $env{'user.name'},
  124: 					'exe_udom'  => $env{'user.domain'},
  125: 					'exe_time'  => $now,
  126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  127: 					'delflag'   => $delflag,
  128: 					'logentry'  => $storehash,
  129: 					'uname'     => $uname,
  130: 					'udom'      => $udom,
  131: 				    }
  132: 				  },$cdom,$cnum);
  133:     }
  134: }
  135: 
  136: sub logtouch {
  137:     my $execdir=$perlvar{'lonDaemons'};
  138:     unless (-e "$execdir/logs/lonnet.log") {	
  139: 	open(my $fh,">>$execdir/logs/lonnet.log");
  140: 	close $fh;
  141:     }
  142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  144: }
  145: 
  146: sub logthis {
  147:     my $message=shift;
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     my $now=time;
  150:     my $local=localtime($now);
  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  153: 	print $fh $logstring;
  154: 	close($fh);
  155:     }
  156:     return 1;
  157: }
  158: 
  159: sub logperm {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  165: 	print $fh "$now:$message:$local\n";
  166: 	close($fh);
  167:     }
  168:     return 1;
  169: }
  170: 
  171: sub create_connection {
  172:     my ($hostname,$lonid) = @_;
  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  174: 				     Type    => SOCK_STREAM,
  175: 				     Timeout => 10);
  176:     return 0 if (!$client);
  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  178:     my $result = <$client>;
  179:     chomp($result);
  180:     return 1 if ($result eq 'done');
  181:     return 0;
  182: }
  183: 
  184: sub get_server_timezone {
  185:     my ($cnum,$cdom) = @_;
  186:     my $home=&homeserver($cnum,$cdom);
  187:     if ($home ne 'no_host') {
  188:         my $cachetime = 24*3600;
  189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  190:         if (defined($cached)) {
  191:             return $timezone;
  192:         } else {
  193:             my $timezone = &reply('servertimezone',$home);
  194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  195:         }
  196:     }
  197: }
  198: 
  199: sub get_server_loncaparev {
  200:     my ($dom,$lonhost) = @_;
  201:     if (defined($lonhost)) {
  202:         if (!defined(&hostname($lonhost))) {
  203:             undef($lonhost);
  204:         }
  205:     }
  206:     if (!defined($lonhost)) {
  207:         if (defined(&domain($dom,'primary'))) {
  208:             $lonhost=&domain($dom,'primary');
  209:             if ($lonhost eq 'no_host') {
  210:                 undef($lonhost);
  211:             }
  212:         }
  213:     }
  214:     if (defined($lonhost)) {
  215:         my $cachetime = 24*3600;
  216:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  217:         if (defined($cached)) {
  218:             return $loncaparev;
  219:         } else {
  220:             my $loncaparev = &reply('serverloncaparev',$lonhost);
  221:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  222:         }
  223:     }
  224: }
  225: 
  226: # -------------------------------------------------- Non-critical communication
  227: sub subreply {
  228:     my ($cmd,$server)=@_;
  229:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  230:     #
  231:     #  With loncnew process trimming, there's a timing hole between lonc server
  232:     #  process exit and the master server picking up the listen on the AF_UNIX
  233:     #  socket.  In that time interval, a lock file will exist:
  234: 
  235:     my $lockfile=$peerfile.".lock";
  236:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  237: 	sleep(1);
  238:     }
  239:     # At this point, either a loncnew parent is listening or an old lonc
  240:     # or loncnew child is listening so we can connect or everything's dead.
  241:     #
  242:     #   We'll give the connection a few tries before abandoning it.  If
  243:     #   connection is not possible, we'll con_lost back to the client.
  244:     #   
  245:     my $client;
  246:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  247: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  248: 				      Type    => SOCK_STREAM,
  249: 				      Timeout => 10);
  250: 	if ($client) {
  251: 	    last;		# Connected!
  252: 	} else {
  253: 	    &create_connection(&hostname($server),$server);
  254: 	}
  255:         sleep(1);		# Try again later if failed connection.
  256:     }
  257:     my $answer;
  258:     if ($client) {
  259: 	print $client "sethost:$server:$cmd\n";
  260: 	$answer=<$client>;
  261: 	if (!$answer) { $answer="con_lost"; }
  262: 	chomp($answer);
  263:     } else {
  264: 	$answer = 'con_lost';	# Failed connection.
  265:     }
  266:     return $answer;
  267: }
  268: 
  269: sub reply {
  270:     my ($cmd,$server)=@_;
  271:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  272:     my $answer=subreply($cmd,$server);
  273:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  274:        &logthis("<font color=\"blue\">WARNING:".
  275:                 " $cmd to $server returned $answer</font>");
  276:     }
  277:     return $answer;
  278: }
  279: 
  280: # ----------------------------------------------------------- Send USR1 to lonc
  281: 
  282: sub reconlonc {
  283:     my ($lonid) = @_;
  284:     my $hostname = &hostname($lonid);
  285:     if ($lonid) {
  286: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  287: 	if ($hostname && -e $peerfile) {
  288: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  289: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  290: 					     Type    => SOCK_STREAM,
  291: 					     Timeout => 10);
  292: 	    if ($client) {
  293: 		print $client ("reset_retries\n");
  294: 		my $answer=<$client>;
  295: 		#reset just this one.
  296: 	    }
  297: 	}
  298: 	return;
  299:     }
  300: 
  301:     &logthis("Trying to reconnect lonc");
  302:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  303:     if (open(my $fh,"<$loncfile")) {
  304: 	my $loncpid=<$fh>;
  305:         chomp($loncpid);
  306:         if (kill 0 => $loncpid) {
  307: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  308:             kill USR1 => $loncpid;
  309:             sleep 1;
  310:          } else {
  311: 	    &logthis(
  312:                "<font color=\"blue\">WARNING:".
  313:                " lonc at pid $loncpid not responding, giving up</font>");
  314:         }
  315:     } else {
  316: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  317:     }
  318: }
  319: 
  320: # ------------------------------------------------------ Critical communication
  321: 
  322: sub critical {
  323:     my ($cmd,$server)=@_;
  324:     unless (&hostname($server)) {
  325:         &logthis("<font color=\"blue\">WARNING:".
  326:                " Critical message to unknown server ($server)</font>");
  327:         return 'no_such_host';
  328:     }
  329:     my $answer=reply($cmd,$server);
  330:     if ($answer eq 'con_lost') {
  331: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  332: 	my $answer=reply($cmd,$server);
  333:         if ($answer eq 'con_lost') {
  334:             my $now=time;
  335:             my $middlename=$cmd;
  336:             $middlename=substr($middlename,0,16);
  337:             $middlename=~s/\W//g;
  338:             my $dfilename=
  339:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  340:             $dumpcount++;
  341:             {
  342: 		my $dfh;
  343: 		if (open($dfh,">$dfilename")) {
  344: 		    print $dfh "$cmd\n"; 
  345: 		    close($dfh);
  346: 		}
  347:             }
  348:             sleep 2;
  349:             my $wcmd='';
  350:             {
  351: 		my $dfh;
  352: 		if (open($dfh,"<$dfilename")) {
  353: 		    $wcmd=<$dfh>; 
  354: 		    close($dfh);
  355: 		}
  356:             }
  357:             chomp($wcmd);
  358:             if ($wcmd eq $cmd) {
  359: 		&logthis("<font color=\"blue\">WARNING: ".
  360:                          "Connection buffer $dfilename: $cmd</font>");
  361:                 &logperm("D:$server:$cmd");
  362: 	        return 'con_delayed';
  363:             } else {
  364:                 &logthis("<font color=\"red\">CRITICAL:"
  365:                         ." Critical connection failed: $server $cmd</font>");
  366:                 &logperm("F:$server:$cmd");
  367:                 return 'con_failed';
  368:             }
  369:         }
  370:     }
  371:     return $answer;
  372: }
  373: 
  374: # ------------------------------------------- check if return value is an error
  375: 
  376: sub error {
  377:     my ($result) = @_;
  378:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  379: 	if ($2 == 2) { return undef; }
  380: 	return $1;
  381:     }
  382:     return undef;
  383: }
  384: 
  385: sub convert_and_load_session_env {
  386:     my ($lonidsdir,$handle)=@_;
  387:     my @profile;
  388:     {
  389: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  390: 	if (!$opened) {
  391: 	    return 0;
  392: 	}
  393: 	flock($idf,LOCK_SH);
  394: 	@profile=<$idf>;
  395: 	close($idf);
  396:     }
  397:     my %temp_env;
  398:     foreach my $line (@profile) {
  399: 	if ($line !~ m/=/) {
  400: 	    return 0;
  401: 	}
  402: 	chomp($line);
  403: 	my ($envname,$envvalue)=split(/=/,$line,2);
  404: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  405:     }
  406:     unlink("$lonidsdir/$handle.id");
  407:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  408: 	    0640)) {
  409: 	%disk_env = %temp_env;
  410: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  411: 	untie(%disk_env);
  412:     }
  413:     return 1;
  414: }
  415: 
  416: # ------------------------------------------- Transfer profile into environment
  417: my $env_loaded;
  418: sub transfer_profile_to_env {
  419:     my ($lonidsdir,$handle,$force_transfer) = @_;
  420:     if (!$force_transfer && $env_loaded) { return; } 
  421: 
  422:     if (!defined($lonidsdir)) {
  423: 	$lonidsdir = $perlvar{'lonIDsDir'};
  424:     }
  425:     if (!defined($handle)) {
  426:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  427:     }
  428: 
  429:     my $convert;
  430:     {
  431:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  432: 	if (!$opened) {
  433: 	    return;
  434: 	}
  435: 	flock($idf,LOCK_SH);
  436: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  437: 		&GDBM_READER(),0640)) {
  438: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  439: 	    untie(%disk_env);
  440: 	} else {
  441: 	    $convert = 1;
  442: 	}
  443:     }
  444:     if ($convert) {
  445: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  446: 	    &logthis("Failed to load session, or convert session.");
  447: 	}
  448:     }
  449: 
  450:     my %remove;
  451:     while ( my $envname = each(%env) ) {
  452:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  453:             if ($time < time-300) {
  454:                 $remove{$key}++;
  455:             }
  456:         }
  457:     }
  458: 
  459:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  460:     $env_loaded=1;
  461:     foreach my $expired_key (keys(%remove)) {
  462:         &delenv($expired_key);
  463:     }
  464: }
  465: 
  466: # ---------------------------------------------------- Check for valid session 
  467: sub check_for_valid_session {
  468:     my ($r) = @_;
  469:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  470:     my $lonid=$cookies{'lonID'};
  471:     return undef if (!$lonid);
  472: 
  473:     my $handle=&LONCAPA::clean_handle($lonid->value);
  474:     my $lonidsdir=$r->dir_config('lonIDsDir');
  475:     return undef if (!-e "$lonidsdir/$handle.id");
  476: 
  477:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  478:     return undef if (!$opened);
  479: 
  480:     flock($idf,LOCK_SH);
  481:     my %disk_env;
  482:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  483: 	    &GDBM_READER(),0640)) {
  484: 	return undef;	
  485:     }
  486: 
  487:     if (!defined($disk_env{'user.name'})
  488: 	|| !defined($disk_env{'user.domain'})) {
  489: 	return undef;
  490:     }
  491:     return $handle;
  492: }
  493: 
  494: sub timed_flock {
  495:     my ($file,$lock_type) = @_;
  496:     my $failed=0;
  497:     eval {
  498: 	local $SIG{__DIE__}='DEFAULT';
  499: 	local $SIG{ALRM}=sub {
  500: 	    $failed=1;
  501: 	    die("failed lock");
  502: 	};
  503: 	alarm(13);
  504: 	flock($file,$lock_type);
  505: 	alarm(0);
  506:     };
  507:     if ($failed) {
  508: 	return undef;
  509:     } else {
  510: 	return 1;
  511:     }
  512: }
  513: 
  514: # ---------------------------------------------------------- Append Environment
  515: 
  516: sub appenv {
  517:     my ($newenv,$roles) = @_;
  518:     if (ref($newenv) eq 'HASH') {
  519:         foreach my $key (keys(%{$newenv})) {
  520:             my $refused = 0;
  521: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  522:                 $refused = 1;
  523:                 if (ref($roles) eq 'ARRAY') {
  524:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  525:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  526:                         $refused = 0;
  527:                     }
  528:                 }
  529:             }
  530:             if ($refused) {
  531:                 &logthis("<font color=\"blue\">WARNING: ".
  532:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  533:                          .'</font>');
  534: 	        delete($newenv->{$key});
  535:             } else {
  536:                 $env{$key}=$newenv->{$key};
  537:             }
  538:         }
  539:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  540:         if ($opened
  541: 	    && &timed_flock($env_file,LOCK_EX)
  542: 	    &&
  543: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  544: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  545: 	    while (my ($key,$value) = each(%{$newenv})) {
  546: 	        $disk_env{$key} = $value;
  547: 	    }
  548: 	    untie(%disk_env);
  549:         }
  550:     }
  551:     return 'ok';
  552: }
  553: # ----------------------------------------------------- Delete from Environment
  554: 
  555: sub delenv {
  556:     my ($delthis,$regexp) = @_;
  557:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  558:         &logthis("<font color=\"blue\">WARNING: ".
  559:                 "Attempt to delete from environment ".$delthis);
  560:         return 'error';
  561:     }
  562:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  563:     if ($opened
  564: 	&& &timed_flock($env_file,LOCK_EX)
  565: 	&&
  566: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  567: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  568: 	foreach my $key (keys(%disk_env)) {
  569: 	    if ($regexp) {
  570:                 if ($key=~/^$delthis/) {
  571:                     delete($env{$key});
  572:                     delete($disk_env{$key});
  573:                 } 
  574:             } else {
  575:                 if ($key=~/^\Q$delthis\E/) {
  576: 		    delete($env{$key});
  577: 		    delete($disk_env{$key});
  578: 	        }
  579:             }
  580: 	}
  581: 	untie(%disk_env);
  582:     }
  583:     return 'ok';
  584: }
  585: 
  586: sub get_env_multiple {
  587:     my ($name) = @_;
  588:     my @values;
  589:     if (defined($env{$name})) {
  590:         # exists is it an array
  591:         if (ref($env{$name})) {
  592:             @values=@{ $env{$name} };
  593:         } else {
  594:             $values[0]=$env{$name};
  595:         }
  596:     }
  597:     return(@values);
  598: }
  599: 
  600: # ------------------------------------------------------------------- Locking
  601: 
  602: sub set_lock {
  603:     my ($text)=@_;
  604:     $locknum++;
  605:     my $id=$$.'-'.$locknum;
  606:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  607:              'session.lock.'.$id => $text});
  608:     return $id;
  609: }
  610: 
  611: sub get_locks {
  612:     my $num=0;
  613:     my %texts=();
  614:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  615:        if ($lock=~/\w/) {
  616:           $num++;
  617:           $texts{$lock}=$env{'session.lock.'.$lock};
  618:        }
  619:    }
  620:    return ($num,%texts);
  621: }
  622: 
  623: sub remove_lock {
  624:     my ($id)=@_;
  625:     my $newlocks='';
  626:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  627:        if (($lock=~/\w/) && ($lock ne $id)) {
  628:           $newlocks.=','.$lock;
  629:        }
  630:     }
  631:     &appenv({'session.locks' => $newlocks});
  632:     &delenv('session.lock.'.$id);
  633: }
  634: 
  635: sub remove_all_locks {
  636:     my $activelocks=$env{'session.locks'};
  637:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  638:        if ($lock=~/\w/) {
  639:           &remove_lock($lock);
  640:        }
  641:     }
  642: }
  643: 
  644: 
  645: # ------------------------------------------ Find out current server userload
  646: sub userload {
  647:     my $numusers=0;
  648:     {
  649: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  650: 	my $filename;
  651: 	my $curtime=time;
  652: 	while ($filename=readdir(LONIDS)) {
  653: 	    next if ($filename eq '.' || $filename eq '..');
  654: 	    next if ($filename =~ /publicuser_\d+\.id/);
  655: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  656: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  657: 	}
  658: 	closedir(LONIDS);
  659:     }
  660:     my $userloadpercent=0;
  661:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  662:     if ($maxuserload) {
  663: 	$userloadpercent=100*$numusers/$maxuserload;
  664:     }
  665:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  666:     return $userloadpercent;
  667: }
  668: 
  669: # ------------------------------------------ Fight off request when overloaded
  670: 
  671: sub overloaderror {
  672:     my ($r,$checkserver)=@_;
  673:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  674:     my $loadavg;
  675:     if ($checkserver eq $perlvar{'lonHostID'}) {
  676:        open(my $loadfile,'/proc/loadavg');
  677:        $loadavg=<$loadfile>;
  678:        $loadavg =~ s/\s.*//g;
  679:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  680:        close($loadfile);
  681:     } else {
  682:        $loadavg=&reply('load',$checkserver);
  683:     }
  684:     my $overload=$loadavg-100;
  685:     if ($overload>0) {
  686: 	$r->err_headers_out->{'Retry-After'}=$overload;
  687:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  688:         return 413;
  689:     }    
  690:     return '';
  691: }
  692: 
  693: # ------------------------------ Find server with least workload from spare.tab
  694: 
  695: sub spareserver {
  696:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  697:     my $spare_server;
  698:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  699:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  700:                                                      :  $userloadpercent;
  701:     
  702:     foreach my $try_server (@{ $spareid{'primary'} }) {
  703: 	($spare_server, $lowest_load) =
  704: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  705:     }
  706: 
  707:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  708: 
  709:     if (!$found_server) {
  710: 	foreach my $try_server (@{ $spareid{'default'} }) {
  711: 	    ($spare_server, $lowest_load) =
  712: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  713: 	}
  714:     }
  715: 
  716:     if (!$want_server_name) {
  717:         my $protocol = 'http';
  718:         if ($protocol{$spare_server} eq 'https') {
  719:             $protocol = $protocol{$spare_server};
  720:         }
  721:         if (defined($spare_server)) {
  722:             my $hostname = &hostname($spare_server);
  723:             if (defined($hostname)) {  
  724: 	        $spare_server = $protocol.'://'.$hostname;
  725:             }
  726:         }
  727:     }
  728:     return $spare_server;
  729: }
  730: 
  731: sub compare_server_load {
  732:     my ($try_server, $spare_server, $lowest_load) = @_;
  733: 
  734:     my $loadans     = &reply('load',    $try_server);
  735:     my $userloadans = &reply('userload',$try_server);
  736: 
  737:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  738: 	next; #didn't get a number from the server
  739:     }
  740: 
  741:     my $load;
  742:     if ($loadans =~ /\d/) {
  743: 	if ($userloadans =~ /\d/) {
  744: 	    #both are numbers, pick the bigger one
  745: 	    $load = ($loadans > $userloadans) ? $loadans 
  746: 		                              : $userloadans;
  747: 	} else {
  748: 	    $load = $loadans;
  749: 	}
  750:     } else {
  751: 	$load = $userloadans;
  752:     }
  753: 
  754:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  755: 	$spare_server = $try_server;
  756: 	$lowest_load  = $load;
  757:     }
  758:     return ($spare_server,$lowest_load);
  759: }
  760: 
  761: # --------------------------- ask offload servers if user already has a session
  762: sub find_existing_session {
  763:     my ($udom,$uname) = @_;
  764:     foreach my $try_server (@{ $spareid{'primary'} },
  765: 			    @{ $spareid{'default'} }) {
  766: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  767:     }
  768:     return;
  769: }
  770: 
  771: # -------------------------------- ask if server already has a session for user
  772: sub has_user_session {
  773:     my ($lonid,$udom,$uname) = @_;
  774:     my $result = &reply(join(':','userhassession',
  775: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  776:     return 1 if ($result eq 'ok');
  777: 
  778:     return 0;
  779: }
  780: 
  781: # --------------------------------------------- Try to change a user's password
  782: 
  783: sub changepass {
  784:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  785:     $currentpass = &escape($currentpass);
  786:     $newpass     = &escape($newpass);
  787:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  788: 		       $server);
  789:     if (! $answer) {
  790: 	&logthis("No reply on password change request to $server ".
  791: 		 "by $uname in domain $udom.");
  792:     } elsif ($answer =~ "^ok") {
  793:         &logthis("$uname in $udom successfully changed their password ".
  794: 		 "on $server.");
  795:     } elsif ($answer =~ "^pwchange_failure") {
  796: 	&logthis("$uname in $udom was unable to change their password ".
  797: 		 "on $server.  The action was blocked by either lcpasswd ".
  798: 		 "or pwchange");
  799:     } elsif ($answer =~ "^non_authorized") {
  800:         &logthis("$uname in $udom did not get their password correct when ".
  801: 		 "attempting to change it on $server.");
  802:     } elsif ($answer =~ "^auth_mode_error") {
  803:         &logthis("$uname in $udom attempted to change their password despite ".
  804: 		 "not being locally or internally authenticated on $server.");
  805:     } elsif ($answer =~ "^unknown_user") {
  806:         &logthis("$uname in $udom attempted to change their password ".
  807: 		 "on $server but were unable to because $server is not ".
  808: 		 "their home server.");
  809:     } elsif ($answer =~ "^refused") {
  810: 	&logthis("$server refused to change $uname in $udom password because ".
  811: 		 "it was sent an unencrypted request to change the password.");
  812:     }
  813:     return $answer;
  814: }
  815: 
  816: # ----------------------- Try to determine user's current authentication scheme
  817: 
  818: sub queryauthenticate {
  819:     my ($uname,$udom)=@_;
  820:     my $uhome=&homeserver($uname,$udom);
  821:     if (!$uhome) {
  822: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  823: 	return 'no_host';
  824:     }
  825:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  826:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  827: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  828:     }
  829:     return $answer;
  830: }
  831: 
  832: # --------- Try to authenticate user from domain's lib servers (first this one)
  833: 
  834: sub authenticate {
  835:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  836:     $upass=&escape($upass);
  837:     $uname= &LONCAPA::clean_username($uname);
  838:     my $uhome=&homeserver($uname,$udom,1);
  839:     my $newhome;
  840:     if ((!$uhome) || ($uhome eq 'no_host')) {
  841: # Maybe the machine was offline and only re-appeared again recently?
  842:         &reconlonc();
  843: # One more
  844: 	$uhome=&homeserver($uname,$udom,1);
  845:         if (($uhome eq 'no_host') && $checkdefauth) {
  846:             if (defined(&domain($udom,'primary'))) {
  847:                 $newhome=&domain($udom,'primary');
  848:             }
  849:             if ($newhome ne '') {
  850:                 $uhome = $newhome;
  851:             }
  852:         }
  853: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  854: 	    &logthis("User $uname at $udom is unknown in authenticate");
  855: 	    return 'no_host';
  856:         }
  857:     }
  858:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  859:     if ($answer eq 'authorized') {
  860:         if ($newhome) {
  861:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  862:             return 'no_account_on_host'; 
  863:         } else {
  864:             &logthis("User $uname at $udom authorized by $uhome");
  865:             return $uhome;
  866:         }
  867:     }
  868:     if ($answer eq 'non_authorized') {
  869: 	&logthis("User $uname at $udom rejected by $uhome");
  870: 	return 'no_host'; 
  871:     }
  872:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  873:     return 'no_host';
  874: }
  875: 
  876: # ---------------------- Find the homebase for a user from domain's lib servers
  877: 
  878: my %homecache;
  879: sub homeserver {
  880:     my ($uname,$udom,$ignoreBadCache)=@_;
  881:     my $index="$uname:$udom";
  882: 
  883:     if (exists($homecache{$index})) { return $homecache{$index}; }
  884: 
  885:     my %servers = &get_servers($udom,'library');
  886:     foreach my $tryserver (keys(%servers)) {
  887:         next if ($ignoreBadCache ne 'true' && 
  888: 		 exists($badServerCache{$tryserver}));
  889: 
  890: 	my $answer=reply("home:$udom:$uname",$tryserver);
  891: 	if ($answer eq 'found') {
  892: 	    delete($badServerCache{$tryserver}); 
  893: 	    return $homecache{$index}=$tryserver;
  894: 	} elsif ($answer eq 'no_host') {
  895: 	    $badServerCache{$tryserver}=1;
  896: 	}
  897:     }    
  898:     return 'no_host';
  899: }
  900: 
  901: # ------------------------------------- Find the usernames behind a list of IDs
  902: 
  903: sub idget {
  904:     my ($udom,@ids)=@_;
  905:     my %returnhash=();
  906:     
  907:     my %servers = &get_servers($udom,'library');
  908:     foreach my $tryserver (keys(%servers)) {
  909: 	my $idlist=join('&',@ids);
  910: 	$idlist=~tr/A-Z/a-z/; 
  911: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  912: 	my @answer=();
  913: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  914: 	    @answer=split(/\&/,$reply);
  915: 	}                    ;
  916: 	my $i;
  917: 	for ($i=0;$i<=$#ids;$i++) {
  918: 	    if ($answer[$i]) {
  919: 		$returnhash{$ids[$i]}=$answer[$i];
  920: 	    } 
  921: 	}
  922:     } 
  923:     return %returnhash;
  924: }
  925: 
  926: # ------------------------------------- Find the IDs behind a list of usernames
  927: 
  928: sub idrget {
  929:     my ($udom,@unames)=@_;
  930:     my %returnhash=();
  931:     foreach my $uname (@unames) {
  932:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  933:     }
  934:     return %returnhash;
  935: }
  936: 
  937: # ------------------------------- Store away a list of names and associated IDs
  938: 
  939: sub idput {
  940:     my ($udom,%ids)=@_;
  941:     my %servers=();
  942:     foreach my $uname (keys(%ids)) {
  943: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  944:         my $uhom=&homeserver($uname,$udom);
  945:         if ($uhom ne 'no_host') {
  946:             my $id=&escape($ids{$uname});
  947:             $id=~tr/A-Z/a-z/;
  948:             my $esc_unam=&escape($uname);
  949: 	    if ($servers{$uhom}) {
  950: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  951:             } else {
  952:                 $servers{$uhom}=$id.'='.$esc_unam;
  953:             }
  954:         }
  955:     }
  956:     foreach my $server (keys(%servers)) {
  957:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  958:     }
  959: }
  960: 
  961: # ------------------------------dump from db file owned by domainconfig user
  962: sub dump_dom {
  963:     my ($namespace,$udom,$regexp,$range)=@_;
  964:     if (!$udom) {
  965:         $udom=$env{'user.domain'};
  966:     }
  967:     my %returnhash;
  968:     if ($udom) {
  969:         my $uname = &get_domainconfiguser($udom);
  970:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
  971:     }
  972:     return %returnhash;
  973: }
  974: 
  975: # ------------------------------------------ get items from domain db files   
  976: 
  977: sub get_dom {
  978:     my ($namespace,$storearr,$udom,$uhome)=@_;
  979:     my $items='';
  980:     foreach my $item (@$storearr) {
  981:         $items.=&escape($item).'&';
  982:     }
  983:     $items=~s/\&$//;
  984:     if (!$udom) {
  985:         $udom=$env{'user.domain'};
  986:         if (defined(&domain($udom,'primary'))) {
  987:             $uhome=&domain($udom,'primary');
  988:         } else {
  989:             undef($uhome);
  990:         }
  991:     } else {
  992:         if (!$uhome) {
  993:             if (defined(&domain($udom,'primary'))) {
  994:                 $uhome=&domain($udom,'primary');
  995:             }
  996:         }
  997:     }
  998:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  999:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1000:         my %returnhash;
 1001:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1002:             return %returnhash;
 1003:         }
 1004:         my @pairs=split(/\&/,$rep);
 1005:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1006:             return @pairs;
 1007:         }
 1008:         my $i=0;
 1009:         foreach my $item (@$storearr) {
 1010:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1011:             $i++;
 1012:         }
 1013:         return %returnhash;
 1014:     } else {
 1015:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1016:     }
 1017: }
 1018: 
 1019: # -------------------------------------------- put items in domain db files 
 1020: 
 1021: sub put_dom {
 1022:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1023:     if (!$udom) {
 1024:         $udom=$env{'user.domain'};
 1025:         if (defined(&domain($udom,'primary'))) {
 1026:             $uhome=&domain($udom,'primary');
 1027:         } else {
 1028:             undef($uhome);
 1029:         }
 1030:     } else {
 1031:         if (!$uhome) {
 1032:             if (defined(&domain($udom,'primary'))) {
 1033:                 $uhome=&domain($udom,'primary');
 1034:             }
 1035:         }
 1036:     } 
 1037:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1038:         my $items='';
 1039:         foreach my $item (keys(%$storehash)) {
 1040:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1041:         }
 1042:         $items=~s/\&$//;
 1043:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1044:     } else {
 1045:         &logthis("put_dom failed - no homeserver and/or domain");
 1046:     }
 1047: }
 1048: 
 1049: # --------------------- newput for items in db file owned by domainconfig user
 1050: sub newput_dom {
 1051:     my ($namespace,$storehash,$udom) = @_;
 1052:     my $result;
 1053:     if (!$udom) {
 1054:         $udom=$env{'user.domain'};
 1055:     }
 1056:     if ($udom) {
 1057:         my $uname = &get_domainconfiguser($udom);
 1058:         $result = &newput($namespace,$storehash,$udom,$uname);
 1059:     }
 1060:     return $result;
 1061: }
 1062: 
 1063: # --------------------- delete for items in db file owned by domainconfig user
 1064: sub del_dom {
 1065:     my ($namespace,$storearr,$udom)=@_;
 1066:     if (ref($storearr) eq 'ARRAY') {
 1067:         if (!$udom) {
 1068:             $udom=$env{'user.domain'};
 1069:         }
 1070:         if ($udom) {
 1071:             my $uname = &get_domainconfiguser($udom); 
 1072:             return &del($namespace,$storearr,$udom,$uname);
 1073:         }
 1074:     }
 1075: }
 1076: 
 1077: # ----------------------------------construct domainconfig user for a domain 
 1078: sub get_domainconfiguser {
 1079:     my ($udom) = @_;
 1080:     return $udom.'-domainconfig';
 1081: }
 1082: 
 1083: sub retrieve_inst_usertypes {
 1084:     my ($udom) = @_;
 1085:     my (%returnhash,@order);
 1086:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1087:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1088:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1089:         %returnhash = %{$domdefs{'inststatustypes'}};
 1090:         @order = @{$domdefs{'inststatusorder'}};
 1091:     } else {
 1092:         if (defined(&domain($udom,'primary'))) {
 1093:             my $uhome=&domain($udom,'primary');
 1094:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1095:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1096:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1097:                 return (\%returnhash,\@order);
 1098:             }
 1099:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1100:             my @pairs=split(/\&/,$hashitems);
 1101:             foreach my $item (@pairs) {
 1102:                 my ($key,$value)=split(/=/,$item,2);
 1103:                 $key = &unescape($key);
 1104:                 next if ($key =~ /^error: 2 /);
 1105:                 $returnhash{$key}=&thaw_unescape($value);
 1106:             }
 1107:             my @esc_order = split(/\&/,$orderitems);
 1108:             foreach my $item (@esc_order) {
 1109:                 push(@order,&unescape($item));
 1110:             }
 1111:         } else {
 1112:             &logthis("get_dom failed - no primary domain server for $udom");
 1113:         }
 1114:     }
 1115:     return (\%returnhash,\@order);
 1116: }
 1117: 
 1118: sub is_domainimage {
 1119:     my ($url) = @_;
 1120:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1121:         if (&domain($1) ne '') {
 1122:             return '1';
 1123:         }
 1124:     }
 1125:     return;
 1126: }
 1127: 
 1128: sub inst_directory_query {
 1129:     my ($srch) = @_;
 1130:     my $udom = $srch->{'srchdomain'};
 1131:     my %results;
 1132:     my $homeserver = &domain($udom,'primary');
 1133:     my $outcome;
 1134:     if ($homeserver ne '') {
 1135: 	my $queryid=&reply("querysend:instdirsearch:".
 1136: 			   &escape($srch->{'srchby'}).':'.
 1137: 			   &escape($srch->{'srchterm'}).':'.
 1138: 			   &escape($srch->{'srchtype'}),$homeserver);
 1139: 	my $host=&hostname($homeserver);
 1140: 	if ($queryid !~/^\Q$host\E\_/) {
 1141: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1142: 	    return;
 1143: 	}
 1144: 	my $response = &get_query_reply($queryid);
 1145: 	my $maxtries = 5;
 1146: 	my $tries = 1;
 1147: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1148: 	    $response = &get_query_reply($queryid);
 1149: 	    $tries ++;
 1150: 	}
 1151: 
 1152:         if (!&error($response) && $response ne 'refused') {
 1153:             if ($response eq 'unavailable') {
 1154:                 $outcome = $response;
 1155:             } else {
 1156:                 $outcome = 'ok';
 1157:                 my @matches = split(/\n/,$response);
 1158:                 foreach my $match (@matches) {
 1159:                     my ($key,$value) = split(/=/,$match);
 1160:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1161:                 }
 1162:             }
 1163:         }
 1164:     }
 1165:     return ($outcome,%results);
 1166: }
 1167: 
 1168: sub usersearch {
 1169:     my ($srch) = @_;
 1170:     my $dom = $srch->{'srchdomain'};
 1171:     my %results;
 1172:     my %libserv = &all_library();
 1173:     my $query = 'usersearch';
 1174:     foreach my $tryserver (keys(%libserv)) {
 1175:         if (&host_domain($tryserver) eq $dom) {
 1176:             my $host=&hostname($tryserver);
 1177:             my $queryid=
 1178:                 &reply("querysend:".&escape($query).':'.
 1179:                        &escape($srch->{'srchby'}).':'.
 1180:                        &escape($srch->{'srchtype'}).':'.
 1181:                        &escape($srch->{'srchterm'}),$tryserver);
 1182:             if ($queryid !~/^\Q$host\E\_/) {
 1183:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1184:                 next;
 1185:             }
 1186:             my $reply = &get_query_reply($queryid);
 1187:             my $maxtries = 1;
 1188:             my $tries = 1;
 1189:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1190:                 $reply = &get_query_reply($queryid);
 1191:                 $tries ++;
 1192:             }
 1193:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1194:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1195:             } else {
 1196:                 my @matches;
 1197:                 if ($reply =~ /\n/) {
 1198:                     @matches = split(/\n/,$reply);
 1199:                 } else {
 1200:                     @matches = split(/\&/,$reply);
 1201:                 }
 1202:                 foreach my $match (@matches) {
 1203:                     my ($uname,$udom,%userhash);
 1204:                     foreach my $entry (split(/:/,$match)) {
 1205:                         my ($key,$value) =
 1206:                             map {&unescape($_);} split(/=/,$entry);
 1207:                         $userhash{$key} = $value;
 1208:                         if ($key eq 'username') {
 1209:                             $uname = $value;
 1210:                         } elsif ($key eq 'domain') {
 1211:                             $udom = $value;
 1212:                         }
 1213:                     }
 1214:                     $results{$uname.':'.$udom} = \%userhash;
 1215:                 }
 1216:             }
 1217:         }
 1218:     }
 1219:     return %results;
 1220: }
 1221: 
 1222: sub get_instuser {
 1223:     my ($udom,$uname,$id) = @_;
 1224:     my $homeserver = &domain($udom,'primary');
 1225:     my ($outcome,%results);
 1226:     if ($homeserver ne '') {
 1227:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1228:                            &escape($id).':'.&escape($udom),$homeserver);
 1229:         my $host=&hostname($homeserver);
 1230:         if ($queryid !~/^\Q$host\E\_/) {
 1231:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1232:             return;
 1233:         }
 1234:         my $response = &get_query_reply($queryid);
 1235:         my $maxtries = 5;
 1236:         my $tries = 1;
 1237:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1238:             $response = &get_query_reply($queryid);
 1239:             $tries ++;
 1240:         }
 1241:         if (!&error($response) && $response ne 'refused') {
 1242:             if ($response eq 'unavailable') {
 1243:                 $outcome = $response;
 1244:             } else {
 1245:                 $outcome = 'ok';
 1246:                 my @matches = split(/\n/,$response);
 1247:                 foreach my $match (@matches) {
 1248:                     my ($key,$value) = split(/=/,$match);
 1249:                     $results{&unescape($key)} = &thaw_unescape($value);
 1250:                 }
 1251:             }
 1252:         }
 1253:     }
 1254:     my %userinfo;
 1255:     if (ref($results{$uname}) eq 'HASH') {
 1256:         %userinfo = %{$results{$uname}};
 1257:     } 
 1258:     return ($outcome,%userinfo);
 1259: }
 1260: 
 1261: sub inst_rulecheck {
 1262:     my ($udom,$uname,$id,$item,$rules) = @_;
 1263:     my %returnhash;
 1264:     if ($udom ne '') {
 1265:         if (ref($rules) eq 'ARRAY') {
 1266:             @{$rules} = map {&escape($_);} (@{$rules});
 1267:             my $rulestr = join(':',@{$rules});
 1268:             my $homeserver=&domain($udom,'primary');
 1269:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1270:                 my $response;
 1271:                 if ($item eq 'username') {                
 1272:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1273:                                               ':'.&escape($uname).':'.$rulestr,
 1274:                                               $homeserver));
 1275:                 } elsif ($item eq 'id') {
 1276:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1277:                                               ':'.&escape($id).':'.$rulestr,
 1278:                                               $homeserver));
 1279:                 } elsif ($item eq 'selfcreate') {
 1280:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1281:                                                &escape($udom).':'.&escape($uname).
 1282:                                               ':'.$rulestr,$homeserver));
 1283:                 }
 1284:                 if ($response ne 'refused') {
 1285:                     my @pairs=split(/\&/,$response);
 1286:                     foreach my $item (@pairs) {
 1287:                         my ($key,$value)=split(/=/,$item,2);
 1288:                         $key = &unescape($key);
 1289:                         next if ($key =~ /^error: 2 /);
 1290:                         $returnhash{$key}=&thaw_unescape($value);
 1291:                     }
 1292:                 }
 1293:             }
 1294:         }
 1295:     }
 1296:     return %returnhash;
 1297: }
 1298: 
 1299: sub inst_userrules {
 1300:     my ($udom,$check) = @_;
 1301:     my (%ruleshash,@ruleorder);
 1302:     if ($udom ne '') {
 1303:         my $homeserver=&domain($udom,'primary');
 1304:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1305:             my $response;
 1306:             if ($check eq 'id') {
 1307:                 $response=&reply('instidrules:'.&escape($udom),
 1308:                                  $homeserver);
 1309:             } elsif ($check eq 'email') {
 1310:                 $response=&reply('instemailrules:'.&escape($udom),
 1311:                                  $homeserver);
 1312:             } else {
 1313:                 $response=&reply('instuserrules:'.&escape($udom),
 1314:                                  $homeserver);
 1315:             }
 1316:             if (($response ne 'refused') && ($response ne 'error') && 
 1317:                 ($response ne 'unknown_cmd') && 
 1318:                 ($response ne 'no_such_host')) {
 1319:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1320:                 my @pairs=split(/\&/,$hashitems);
 1321:                 foreach my $item (@pairs) {
 1322:                     my ($key,$value)=split(/=/,$item,2);
 1323:                     $key = &unescape($key);
 1324:                     next if ($key =~ /^error: 2 /);
 1325:                     $ruleshash{$key}=&thaw_unescape($value);
 1326:                 }
 1327:                 my @esc_order = split(/\&/,$orderitems);
 1328:                 foreach my $item (@esc_order) {
 1329:                     push(@ruleorder,&unescape($item));
 1330:                 }
 1331:             }
 1332:         }
 1333:     }
 1334:     return (\%ruleshash,\@ruleorder);
 1335: }
 1336: 
 1337: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1338: 
 1339: sub get_domain_defaults {
 1340:     my ($domain) = @_;
 1341:     my $cachetime = 60*60*24;
 1342:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1343:     if (defined($cached)) {
 1344:         if (ref($result) eq 'HASH') {
 1345:             return %{$result};
 1346:         }
 1347:     }
 1348:     my %domdefaults;
 1349:     my %domconfig =
 1350:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1351:                                   'requestcourses','inststatus'],$domain);
 1352:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1353:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1354:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1355:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1356:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1357:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1358:     } else {
 1359:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1360:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1361:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1362:     }
 1363:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1364:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1365:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1366:         } else {
 1367:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1368:         } 
 1369:         my @usertools = ('aboutme','blog','portfolio');
 1370:         foreach my $item (@usertools) {
 1371:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1372:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1373:             }
 1374:         }
 1375:     }
 1376:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1377:         foreach my $item ('official','unofficial','community') {
 1378:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1379:         }
 1380:     }
 1381:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1382:         foreach my $item ('inststatustypes','inststatusorder') {
 1383:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1384:         }
 1385:     }
 1386:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1387:                                   $cachetime);
 1388:     return %domdefaults;
 1389: }
 1390: 
 1391: # --------------------------------------------------- Assign a key to a student
 1392: 
 1393: sub assign_access_key {
 1394: #
 1395: # a valid key looks like uname:udom#comments
 1396: # comments are being appended
 1397: #
 1398:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1399:     $kdom=
 1400:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1401:     $knum=
 1402:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1403:     $cdom=
 1404:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1405:     $cnum=
 1406:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1407:     $udom=$env{'user.name'} unless (defined($udom));
 1408:     $uname=$env{'user.domain'} unless (defined($uname));
 1409:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1410:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1411:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1412:                                                   # assigned to this person
 1413:                                                   # - this should not happen,
 1414:                                                   # unless something went wrong
 1415:                                                   # the first time around
 1416: # ready to assign
 1417:         $logentry=$1.'; '.$logentry;
 1418:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1419:                                                  $kdom,$knum) eq 'ok') {
 1420: # key now belongs to user
 1421: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1422:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1423:                 &appenv({'environment.'.$envkey => $ckey});
 1424:                 return 'ok';
 1425:             } else {
 1426:                 return 
 1427:   'error: Count not permanently assign key, will need to be re-entered later.';
 1428: 	    }
 1429:         } else {
 1430:             return 'error: Could not assign key, try again later.';
 1431:         }
 1432:     } elsif (!$existing{$ckey}) {
 1433: # the key does not exist
 1434: 	return 'error: The key does not exist';
 1435:     } else {
 1436: # the key is somebody else's
 1437: 	return 'error: The key is already in use';
 1438:     }
 1439: }
 1440: 
 1441: # ------------------------------------------ put an additional comment on a key
 1442: 
 1443: sub comment_access_key {
 1444: #
 1445: # a valid key looks like uname:udom#comments
 1446: # comments are being appended
 1447: #
 1448:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1449:     $cdom=
 1450:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1451:     $cnum=
 1452:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1453:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1454:     if ($existing{$ckey}) {
 1455:         $existing{$ckey}.='; '.$logentry;
 1456: # ready to assign
 1457:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1458:                                                  $cdom,$cnum) eq 'ok') {
 1459: 	    return 'ok';
 1460:         } else {
 1461: 	    return 'error: Count not store comment.';
 1462:         }
 1463:     } else {
 1464: # the key does not exist
 1465: 	return 'error: The key does not exist';
 1466:     }
 1467: }
 1468: 
 1469: # ------------------------------------------------------ Generate a set of keys
 1470: 
 1471: sub generate_access_keys {
 1472:     my ($number,$cdom,$cnum,$logentry)=@_;
 1473:     $cdom=
 1474:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1475:     $cnum=
 1476:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1477:     unless (&allowed('mky',$cdom)) { return 0; }
 1478:     unless (($cdom) && ($cnum)) { return 0; }
 1479:     if ($number>10000) { return 0; }
 1480:     sleep(2); # make sure don't get same seed twice
 1481:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1482:     my $total=0;
 1483:     for (my $i=1;$i<=$number;$i++) {
 1484:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1485:                   sprintf("%lx",int(100000*rand)).'-'.
 1486:                   sprintf("%lx",int(100000*rand));
 1487:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1488:        $newkey=~s/0/h/g; # and also 0 and O
 1489:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1490:        if ($existing{$newkey}) {
 1491:            $i--;
 1492:        } else {
 1493: 	  if (&put('accesskeys',
 1494:               { $newkey => '# generated '.localtime().
 1495:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1496:                            '; '.$logentry },
 1497: 		   $cdom,$cnum) eq 'ok') {
 1498:               $total++;
 1499: 	  }
 1500:        }
 1501:     }
 1502:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1503:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1504:     return $total;
 1505: }
 1506: 
 1507: # ------------------------------------------------------- Validate an accesskey
 1508: 
 1509: sub validate_access_key {
 1510:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1511:     $cdom=
 1512:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1513:     $cnum=
 1514:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1515:     $udom=$env{'user.domain'} unless (defined($udom));
 1516:     $uname=$env{'user.name'} unless (defined($uname));
 1517:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1518:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1519: }
 1520: 
 1521: # ------------------------------------- Find the section of student in a course
 1522: sub devalidate_getsection_cache {
 1523:     my ($udom,$unam,$courseid)=@_;
 1524:     my $hashid="$udom:$unam:$courseid";
 1525:     &devalidate_cache_new('getsection',$hashid);
 1526: }
 1527: 
 1528: sub courseid_to_courseurl {
 1529:     my ($courseid) = @_;
 1530:     #already url style courseid
 1531:     return $courseid if ($courseid =~ m{^/});
 1532: 
 1533:     if (exists($env{'course.'.$courseid.'.num'})) {
 1534: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1535: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1536: 	return "/$cdom/$cnum";
 1537:     }
 1538: 
 1539:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1540:     if (exists($courseinfo{'num'})) {
 1541: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1542:     }
 1543: 
 1544:     return undef;
 1545: }
 1546: 
 1547: sub getsection {
 1548:     my ($udom,$unam,$courseid)=@_;
 1549:     my $cachetime=1800;
 1550: 
 1551:     my $hashid="$udom:$unam:$courseid";
 1552:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1553:     if (defined($cached)) { return $result; }
 1554: 
 1555:     my %Pending; 
 1556:     my %Expired;
 1557:     #
 1558:     # Each role can either have not started yet (pending), be active, 
 1559:     #    or have expired.
 1560:     #
 1561:     # If there is an active role, we are done.
 1562:     #
 1563:     # If there is more than one role which has not started yet, 
 1564:     #     choose the one which will start sooner
 1565:     # If there is one role which has not started yet, return it.
 1566:     #
 1567:     # If there is more than one expired role, choose the one which ended last.
 1568:     # If there is a role which has expired, return it.
 1569:     #
 1570:     $courseid = &courseid_to_courseurl($courseid);
 1571:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1572:     foreach my $key (keys(%roleshash)) {
 1573:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1574:         my $section=$1;
 1575:         if ($key eq $courseid.'_st') { $section=''; }
 1576:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1577:         my $now=time;
 1578:         if (defined($end) && $end && ($now > $end)) {
 1579:             $Expired{$end}=$section;
 1580:             next;
 1581:         }
 1582:         if (defined($start) && $start && ($now < $start)) {
 1583:             $Pending{$start}=$section;
 1584:             next;
 1585:         }
 1586:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1587:     }
 1588:     #
 1589:     # Presumedly there will be few matching roles from the above
 1590:     # loop and the sorting time will be negligible.
 1591:     if (scalar(keys(%Pending))) {
 1592:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1593:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1594:     } 
 1595:     if (scalar(keys(%Expired))) {
 1596:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1597:         my $time = pop(@sorted);
 1598:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1599:     }
 1600:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1601: }
 1602: 
 1603: sub save_cache {
 1604:     &purge_remembered();
 1605:     #&Apache::loncommon::validate_page();
 1606:     undef(%env);
 1607:     undef($env_loaded);
 1608: }
 1609: 
 1610: my $to_remember=-1;
 1611: my %remembered;
 1612: my %accessed;
 1613: my $kicks=0;
 1614: my $hits=0;
 1615: sub make_key {
 1616:     my ($name,$id) = @_;
 1617:     if (length($id) > 65 
 1618: 	&& length(&escape($id)) > 200) {
 1619: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1620:     }
 1621:     return &escape($name.':'.$id);
 1622: }
 1623: 
 1624: sub devalidate_cache_new {
 1625:     my ($name,$id,$debug) = @_;
 1626:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1627:     $id=&make_key($name,$id);
 1628:     $memcache->delete($id);
 1629:     delete($remembered{$id});
 1630:     delete($accessed{$id});
 1631: }
 1632: 
 1633: sub is_cached_new {
 1634:     my ($name,$id,$debug) = @_;
 1635:     $id=&make_key($name,$id);
 1636:     if (exists($remembered{$id})) {
 1637: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1638: 	$accessed{$id}=[&gettimeofday()];
 1639: 	$hits++;
 1640: 	return ($remembered{$id},1);
 1641:     }
 1642:     my $value = $memcache->get($id);
 1643:     if (!(defined($value))) {
 1644: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1645: 	return (undef,undef);
 1646:     }
 1647:     if ($value eq '__undef__') {
 1648: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1649: 	$value=undef;
 1650:     }
 1651:     &make_room($id,$value,$debug);
 1652:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1653:     return ($value,1);
 1654: }
 1655: 
 1656: sub do_cache_new {
 1657:     my ($name,$id,$value,$time,$debug) = @_;
 1658:     $id=&make_key($name,$id);
 1659:     my $setvalue=$value;
 1660:     if (!defined($setvalue)) {
 1661: 	$setvalue='__undef__';
 1662:     }
 1663:     if (!defined($time) ) {
 1664: 	$time=600;
 1665:     }
 1666:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1667:     my $result = $memcache->set($id,$setvalue,$time);
 1668:     if (! $result) {
 1669: 	&logthis("caching of id -> $id  failed");
 1670: 	$memcache->disconnect_all();
 1671:     }
 1672:     # need to make a copy of $value
 1673:     &make_room($id,$value,$debug);
 1674:     return $value;
 1675: }
 1676: 
 1677: sub make_room {
 1678:     my ($id,$value,$debug)=@_;
 1679: 
 1680:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1681:                                     : $value;
 1682:     if ($to_remember<0) { return; }
 1683:     $accessed{$id}=[&gettimeofday()];
 1684:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1685:     my $to_kick;
 1686:     my $max_time=0;
 1687:     foreach my $other (keys(%accessed)) {
 1688: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1689: 	    $to_kick=$other;
 1690: 	    $max_time=&tv_interval($accessed{$other});
 1691: 	}
 1692:     }
 1693:     delete($remembered{$to_kick});
 1694:     delete($accessed{$to_kick});
 1695:     $kicks++;
 1696:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1697:     return;
 1698: }
 1699: 
 1700: sub purge_remembered {
 1701:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1702:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1703:     undef(%remembered);
 1704:     undef(%accessed);
 1705: }
 1706: # ------------------------------------- Read an entry from a user's environment
 1707: 
 1708: sub userenvironment {
 1709:     my ($udom,$unam,@what)=@_;
 1710:     my $items;
 1711:     foreach my $item (@what) {
 1712:         $items.=&escape($item).'&';
 1713:     }
 1714:     $items=~s/\&$//;
 1715:     my %returnhash=();
 1716:     my $uhome = &homeserver($unam,$udom);
 1717:     unless ($uhome eq 'no_host') {
 1718:         my @answer=split(/\&/, 
 1719:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 1720:         my $i;
 1721:         for ($i=0;$i<=$#what;$i++) {
 1722: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 1723:         }
 1724:     }
 1725:     return %returnhash;
 1726: }
 1727: 
 1728: # ---------------------------------------------------------- Get a studentphoto
 1729: sub studentphoto {
 1730:     my ($udom,$unam,$ext) = @_;
 1731:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1732:     if (defined($env{'request.course.id'})) {
 1733:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1734:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1735:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1736:             } else {
 1737:                 my ($result,$perm_reqd)=
 1738: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1739:                 if ($result eq 'ok') {
 1740:                     if (!($perm_reqd eq 'yes')) {
 1741:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1742:                     }
 1743:                 }
 1744:             }
 1745:         }
 1746:     } else {
 1747:         my ($result,$perm_reqd) = 
 1748: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1749:         if ($result eq 'ok') {
 1750:             if (!($perm_reqd eq 'yes')) {
 1751:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1752:             }
 1753:         }
 1754:     }
 1755:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1756: }
 1757: 
 1758: sub retrievestudentphoto {
 1759:     my ($udom,$unam,$ext,$type) = @_;
 1760:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1761:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1762:     if ($ret eq 'ok') {
 1763:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1764:         if ($type eq 'thumbnail') {
 1765:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1766:         }
 1767:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1768:         return $tokenurl;
 1769:     } else {
 1770:         if ($type eq 'thumbnail') {
 1771:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1772:         } else { 
 1773:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1774:         }
 1775:     }
 1776: }
 1777: 
 1778: # -------------------------------------------------------------------- New chat
 1779: 
 1780: sub chatsend {
 1781:     my ($newentry,$anon,$group)=@_;
 1782:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1783:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1784:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1785:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1786: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1787: 		   &escape($newentry)).':'.$group,$chome);
 1788: }
 1789: 
 1790: # ------------------------------------------ Find current version of a resource
 1791: 
 1792: sub getversion {
 1793:     my $fname=&clutter(shift);
 1794:     unless ($fname=~/^\/res\//) { return -1; }
 1795:     return &currentversion(&filelocation('',$fname));
 1796: }
 1797: 
 1798: sub currentversion {
 1799:     my $fname=shift;
 1800:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1801:     if (defined($cached)) { return $result; }
 1802:     my $author=$fname;
 1803:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1804:     my ($udom,$uname)=split(/\//,$author);
 1805:     my $home=homeserver($uname,$udom);
 1806:     if ($home eq 'no_host') { 
 1807:         return -1; 
 1808:     }
 1809:     my $answer=reply("currentversion:$fname",$home);
 1810:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1811: 	return -1;
 1812:     }
 1813:     return &do_cache_new('resversion',$fname,$answer,600);
 1814: }
 1815: 
 1816: # ----------------------------- Subscribe to a resource, return URL if possible
 1817: 
 1818: sub subscribe {
 1819:     my $fname=shift;
 1820:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1821:     $fname=~s/[\n\r]//g;
 1822:     my $author=$fname;
 1823:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1824:     my ($udom,$uname)=split(/\//,$author);
 1825:     my $home=homeserver($uname,$udom);
 1826:     if ($home eq 'no_host') {
 1827:         return 'not_found';
 1828:     }
 1829:     my $answer=reply("sub:$fname",$home);
 1830:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1831: 	$answer.=' by '.$home;
 1832:     }
 1833:     return $answer;
 1834: }
 1835:     
 1836: # -------------------------------------------------------------- Replicate file
 1837: 
 1838: sub repcopy {
 1839:     my $filename=shift;
 1840:     $filename=~s/\/+/\//g;
 1841:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1842:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1843:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1844: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1845: 	return &repcopy_userfile($filename);
 1846:     }
 1847:     $filename=~s/[\n\r]//g;
 1848:     my $transname="$filename.in.transfer";
 1849: # FIXME: this should flock
 1850:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1851:     my $remoteurl=subscribe($filename);
 1852:     if ($remoteurl =~ /^con_lost by/) {
 1853: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1854:            return 'unavailable';
 1855:     } elsif ($remoteurl eq 'not_found') {
 1856: 	   #&logthis("Subscribe returned not_found: $filename");
 1857: 	   return 'not_found';
 1858:     } elsif ($remoteurl =~ /^rejected by/) {
 1859: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1860:            return 'forbidden';
 1861:     } elsif ($remoteurl eq 'directory') {
 1862:            return 'ok';
 1863:     } else {
 1864:         my $author=$filename;
 1865:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1866:         my ($udom,$uname)=split(/\//,$author);
 1867:         my $home=homeserver($uname,$udom);
 1868:         unless ($home eq $perlvar{'lonHostID'}) {
 1869:            my @parts=split(/\//,$filename);
 1870:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1871:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1872:                &logthis("Malconfiguration for replication: $filename");
 1873: 	       return 'bad_request';
 1874:            }
 1875:            my $count;
 1876:            for ($count=5;$count<$#parts;$count++) {
 1877:                $path.="/$parts[$count]";
 1878:                if ((-e $path)!=1) {
 1879: 		   mkdir($path,0777);
 1880:                }
 1881:            }
 1882:            my $ua=new LWP::UserAgent;
 1883:            my $request=new HTTP::Request('GET',"$remoteurl");
 1884:            my $response=$ua->request($request,$transname);
 1885:            if ($response->is_error()) {
 1886: 	       unlink($transname);
 1887:                my $message=$response->status_line;
 1888:                &logthis("<font color=\"blue\">WARNING:"
 1889:                        ." LWP get: $message: $filename</font>");
 1890:                return 'unavailable';
 1891:            } else {
 1892: 	       if ($remoteurl!~/\.meta$/) {
 1893:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1894:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1895:                   if ($mresponse->is_error()) {
 1896: 		      unlink($filename.'.meta');
 1897:                       &logthis(
 1898:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1899:                   }
 1900: 	       }
 1901:                rename($transname,$filename);
 1902:                return 'ok';
 1903:            }
 1904:        }
 1905:     }
 1906: }
 1907: 
 1908: # ------------------------------------------------ Get server side include body
 1909: sub ssi_body {
 1910:     my ($filelink,%form)=@_;
 1911:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1912:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1913:     }
 1914:     my $output='';
 1915:     my $response;
 1916:     if ($filelink=~/^https?\:/) {
 1917:        ($output,$response)=&externalssi($filelink);
 1918:     } else {
 1919:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 1920:        $filelink .= 'inhibitmenu=yes';
 1921:        ($output,$response)=&ssi($filelink,%form);
 1922:     }
 1923:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1924:     $output=~s/^.*?\<body[^\>]*\>//si;
 1925:     $output=~s/\<\/body\s*\>.*?$//si;
 1926:     if (wantarray) {
 1927:         return ($output, $response);
 1928:     } else {
 1929:         return $output;
 1930:     }
 1931: }
 1932: 
 1933: # --------------------------------------------------------- Server Side Include
 1934: 
 1935: sub absolute_url {
 1936:     my ($host_name) = @_;
 1937:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1938:     if ($host_name eq '') {
 1939: 	$host_name = $ENV{'SERVER_NAME'};
 1940:     }
 1941:     return $protocol.$host_name;
 1942: }
 1943: 
 1944: #
 1945: #   Server side include.
 1946: # Parameters:
 1947: #  fn     Possibly encrypted resource name/id.
 1948: #  form   Hash that describes how the rendering should be done
 1949: #         and other things.
 1950: # Returns:
 1951: #   Scalar context: The content of the response.
 1952: #   Array context:  2 element list of the content and the full response object.
 1953: #     
 1954: sub ssi {
 1955: 
 1956:     my ($fn,%form)=@_;
 1957:     my $ua=new LWP::UserAgent;
 1958:     my $request;
 1959: 
 1960:     $form{'no_update_last_known'}=1;
 1961:     &Apache::lonenc::check_encrypt(\$fn);
 1962:     if (%form) {
 1963:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1964:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1965:     } else {
 1966:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1967:     }
 1968: 
 1969:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1970:     my $response=$ua->request($request);
 1971: 
 1972:     if (wantarray) {
 1973: 	return ($response->content, $response);
 1974:     } else {
 1975: 	return $response->content;
 1976:     }
 1977: }
 1978: 
 1979: sub externalssi {
 1980:     my ($url)=@_;
 1981:     my $ua=new LWP::UserAgent;
 1982:     my $request=new HTTP::Request('GET',$url);
 1983:     my $response=$ua->request($request);
 1984:     if (wantarray) {
 1985:         return ($response->content, $response);
 1986:     } else {
 1987:         return $response->content;
 1988:     }
 1989: }
 1990: 
 1991: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1992: 
 1993: sub allowuploaded {
 1994:     my ($srcurl,$url)=@_;
 1995:     $url=&clutter(&declutter($url));
 1996:     my $dir=$url;
 1997:     $dir=~s/\/[^\/]+$//;
 1998:     my %httpref=();
 1999:     my $httpurl=&hreflocation('',$url);
 2000:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2001:     &Apache::lonnet::appenv(\%httpref);
 2002: }
 2003: 
 2004: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2005: # input: action, courseID, current domain, intended
 2006: #        path to file, source of file, instruction to parse file for objects,
 2007: #        ref to hash for embedded objects,
 2008: #        ref to hash for codebase of java objects.
 2009: #
 2010: # output: url to file (if action was uploaddoc), 
 2011: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2012: #
 2013: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2014: # course.
 2015: #
 2016: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2017: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2018: #          course's home server.
 2019: #
 2020: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2021: #          be copied from $source (current location) to 
 2022: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2023: #         and will then be copied to
 2024: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2025: #         course's home server.
 2026: #
 2027: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2028: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2029: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2030: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2031: #         in course's home server.
 2032: #
 2033: 
 2034: sub process_coursefile {
 2035:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 2036:     my $fetchresult;
 2037:     my $home=&homeserver($docuname,$docudom);
 2038:     if ($action eq 'propagate') {
 2039:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2040: 			     $home);
 2041:     } else {
 2042:         my $fpath = '';
 2043:         my $fname = $file;
 2044:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2045:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2046:         my $filepath = &build_filepath($fpath);
 2047:         if ($action eq 'copy') {
 2048:             if ($source eq '') {
 2049:                 $fetchresult = 'no source file';
 2050:                 return $fetchresult;
 2051:             } else {
 2052:                 my $destination = $filepath.'/'.$fname;
 2053:                 rename($source,$destination);
 2054:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2055:                                  $home);
 2056:             }
 2057:         } elsif ($action eq 'uploaddoc') {
 2058:             open(my $fh,'>'.$filepath.'/'.$fname);
 2059:             print $fh $env{'form.'.$source};
 2060:             close($fh);
 2061:             if ($parser eq 'parse') {
 2062:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2063:                 unless ($parse_result eq 'ok') {
 2064:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2065:                 }
 2066:             }
 2067:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2068:                                  $home);
 2069:             if ($fetchresult eq 'ok') {
 2070:                 return '/uploaded/'.$fpath.'/'.$fname;
 2071:             } else {
 2072:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2073:                         ' to host '.$home.': '.$fetchresult);
 2074:                 return '/adm/notfound.html';
 2075:             }
 2076:         }
 2077:     }
 2078:     unless ( $fetchresult eq 'ok') {
 2079:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2080:              ' to host '.$home.': '.$fetchresult);
 2081:     }
 2082:     return $fetchresult;
 2083: }
 2084: 
 2085: sub build_filepath {
 2086:     my ($fpath) = @_;
 2087:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2088:     unless ($fpath eq '') {
 2089:         my @parts=split('/',$fpath);
 2090:         foreach my $part (@parts) {
 2091:             $filepath.= '/'.$part;
 2092:             if ((-e $filepath)!=1) {
 2093:                 mkdir($filepath,0777);
 2094:             }
 2095:         }
 2096:     }
 2097:     return $filepath;
 2098: }
 2099: 
 2100: sub store_edited_file {
 2101:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2102:     my $file = $primary_url;
 2103:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2104:     my $fpath = '';
 2105:     my $fname = $file;
 2106:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2107:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2108:     my $filepath = &build_filepath($fpath);
 2109:     open(my $fh,'>'.$filepath.'/'.$fname);
 2110:     print $fh $content;
 2111:     close($fh);
 2112:     my $home=&homeserver($docuname,$docudom);
 2113:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2114: 			  $home);
 2115:     if ($$fetchresult eq 'ok') {
 2116:         return '/uploaded/'.$fpath.'/'.$fname;
 2117:     } else {
 2118:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2119: 		 ' to host '.$home.': '.$$fetchresult);
 2120:         return '/adm/notfound.html';
 2121:     }
 2122: }
 2123: 
 2124: sub clean_filename {
 2125:     my ($fname,$args)=@_;
 2126: # Replace Windows backslashes by forward slashes
 2127:     $fname=~s/\\/\//g;
 2128:     if (!$args->{'keep_path'}) {
 2129:         # Get rid of everything but the actual filename
 2130: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2131:     }
 2132: # Replace spaces by underscores
 2133:     $fname=~s/\s+/\_/g;
 2134: # Replace all other weird characters by nothing
 2135:     $fname=~s{[^/\w\.\-]}{}g;
 2136: # Replace all .\d. sequences with _\d. so they no longer look like version
 2137: # numbers
 2138:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2139:     return $fname;
 2140: }
 2141: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2142: sub resizeImage {
 2143: 	my($img_url) = @_;	
 2144: 	my $ima = Image::Magick->new;                       
 2145:         $ima->Read($img_url);
 2146: 	if($ima->Get('width') > 400)
 2147: 	{
 2148: 		my $factor = $ima->Get('width')/400;
 2149:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2150: 	}
 2151: 	if($ima->Get('height') > 500)
 2152:         {
 2153:         	my $factor = $ima->Get('height')/500;
 2154:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2155:         } 
 2156: 		
 2157: 	$ima->Write($img_url);
 2158: }
 2159: 
 2160: #Wrapper function for userphotoupload
 2161: sub userphotoupload
 2162: {
 2163: 	my($formname,$subdir) = @_;
 2164: 	$upload_photo_form = 1;
 2165: 	return &userfileupload($formname,undef,$subdir);
 2166: }
 2167: 
 2168: # --------------- Take an uploaded file and put it into the userfiles directory
 2169: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2170: #                    the desired filenam is in $env{"form.$formname.filename"}
 2171: #        $coursedoc - if true up to the current course
 2172: #                     if false
 2173: #        $subdir - directory in userfile to store the file into
 2174: #        $parser - instruction to parse file for objects ($parser = parse)    
 2175: #        $allfiles - reference to hash for embedded objects
 2176: #        $codebase - reference to hash for codebase of java objects
 2177: #        $desuname - username for permanent storage of uploaded file
 2178: #        $dsetudom - domain for permanaent storage of uploaded file
 2179: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2180: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2181: # 
 2182: # output: url of file in userspace, or error: <message> 
 2183: #             or /adm/notfound.html if failure to upload occurse
 2184: 
 2185: 
 2186: sub userfileupload {
 2187:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2188:         $destudom,$thumbwidth,$thumbheight)=@_;
 2189:     if (!defined($subdir)) { $subdir='unknown'; }
 2190:     my $fname=$env{'form.'.$formname.'.filename'};
 2191:     $fname=&clean_filename($fname);
 2192: # See if there is anything left
 2193:     unless ($fname) { return 'error: no uploaded file'; }
 2194:     chop($env{'form.'.$formname});
 2195:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2196:         my $now = time;
 2197:         my $filepath = 'tmp/helprequests/'.$now;
 2198:         my @parts=split(/\//,$filepath);
 2199:         my $fullpath = $perlvar{'lonDaemons'};
 2200:         for (my $i=0;$i<@parts;$i++) {
 2201:             $fullpath .= '/'.$parts[$i];
 2202:             if ((-e $fullpath)!=1) {
 2203:                 mkdir($fullpath,0777);
 2204:             }
 2205:         }
 2206:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2207:         print $fh $env{'form.'.$formname};
 2208:         close($fh);
 2209:         return $fullpath.'/'.$fname;
 2210:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2211:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2212:                        '_'.$env{'user.domain'}.'/pending';
 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:     }
 2226:     if ($subdir eq 'scantron') {
 2227:         $fname = 'scantron_orig_'.$fname;
 2228:     } else {   
 2229: # Create the directory if not present
 2230:         $fname="$subdir/$fname";
 2231:     }
 2232:     if ($coursedoc) {
 2233: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2234: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2235:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2236:             return &finishuserfileupload($docuname,$docudom,
 2237: 					 $formname,$fname,$parser,$allfiles,
 2238: 					 $codebase,$thumbwidth,$thumbheight);
 2239:         } else {
 2240:             $fname=$env{'form.folder'}.'/'.$fname;
 2241:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2242: 				       $fname,$formname,$parser,
 2243: 				       $allfiles,$codebase);
 2244:         }
 2245:     } elsif (defined($destuname)) {
 2246:         my $docuname=$destuname;
 2247:         my $docudom=$destudom;
 2248: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2249: 				     $parser,$allfiles,$codebase,
 2250:                                      $thumbwidth,$thumbheight);
 2251:         
 2252:     } else {
 2253:         my $docuname=$env{'user.name'};
 2254:         my $docudom=$env{'user.domain'};
 2255:         if (exists($env{'form.group'})) {
 2256:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2257:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2258:         }
 2259: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2260: 				     $parser,$allfiles,$codebase,
 2261:                                      $thumbwidth,$thumbheight);
 2262:     }
 2263: }
 2264: 
 2265: sub finishuserfileupload {
 2266:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2267:         $thumbwidth,$thumbheight) = @_;
 2268:     my $path=$docudom.'/'.$docuname.'/';
 2269:     my $filepath=$perlvar{'lonDocRoot'};
 2270:   
 2271:     my ($fnamepath,$file,$fetchthumb);
 2272:     $file=$fname;
 2273:     if ($fname=~m|/|) {
 2274:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2275: 	$path.=$fnamepath.'/';
 2276:     }
 2277:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2278:     my $count;
 2279:     for ($count=4;$count<=$#parts;$count++) {
 2280:         $filepath.="/$parts[$count]";
 2281:         if ((-e $filepath)!=1) {
 2282: 	    mkdir($filepath,0777);
 2283:         }
 2284:     }
 2285: 
 2286: # Save the file
 2287:     {
 2288: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2289: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2290: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2291: 	    return '/adm/notfound.html';
 2292: 	}
 2293: 	if (!print FH ($env{'form.'.$formname})) {
 2294: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2295: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2296: 	    return '/adm/notfound.html';
 2297: 	}
 2298: 	close(FH);
 2299: 	if($upload_photo_form==1)
 2300: 	{
 2301: 		resizeImage($filepath.'/'.$file);		
 2302: 		$upload_photo_form = 0;
 2303: 	}
 2304:     }
 2305:     if ($parser eq 'parse') {
 2306:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2307: 						   $codebase);
 2308:         unless ($parse_result eq 'ok') {
 2309:             &logthis('Failed to parse '.$filepath.$file.
 2310: 		     ' for embedded media: '.$parse_result); 
 2311:         }
 2312:     }
 2313:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2314:         my $input = $filepath.'/'.$file;
 2315:         my $output = $filepath.'/'.'tn-'.$file;
 2316:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2317:         system("convert -sample $thumbsize $input $output");
 2318:         if (-e $filepath.'/'.'tn-'.$file) {
 2319:             $fetchthumb  = 1; 
 2320:         }
 2321:     }
 2322:  
 2323: # Notify homeserver to grep it
 2324: #
 2325:     my $docuhome=&homeserver($docuname,$docudom);	
 2326:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2327:     if ($fetchresult eq 'ok') {
 2328:         if ($fetchthumb) {
 2329:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2330:             if ($thumbresult ne 'ok') {
 2331:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2332:                          $docuhome.': '.$thumbresult);
 2333:             }
 2334:         }
 2335: #
 2336: # Return the URL to it
 2337:         return '/uploaded/'.$path.$file;
 2338:     } else {
 2339:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2340: 		 ': '.$fetchresult);
 2341:         return '/adm/notfound.html';
 2342:     }
 2343: }
 2344: 
 2345: sub extract_embedded_items {
 2346:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2347:     my @state = ();
 2348:     my %javafiles = (
 2349:                       codebase => '',
 2350:                       code => '',
 2351:                       archive => ''
 2352:                     );
 2353:     my %mediafiles = (
 2354:                       src => '',
 2355:                       movie => '',
 2356:                      );
 2357:     my $p;
 2358:     if ($content) {
 2359:         $p = HTML::LCParser->new($content);
 2360:     } else {
 2361:         $p = HTML::LCParser->new($fullpath);
 2362:     }
 2363:     while (my $t=$p->get_token()) {
 2364: 	if ($t->[0] eq 'S') {
 2365: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2366: 	    push(@state, $tagname);
 2367:             if (lc($tagname) eq 'allow') {
 2368:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2369:             }
 2370: 	    if (lc($tagname) eq 'img') {
 2371: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2372: 	    }
 2373: 	    if (lc($tagname) eq 'a') {
 2374: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2375: 	    }
 2376:             if (lc($tagname) eq 'script') {
 2377:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2378:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2379:                 } else {
 2380:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2381:                 }
 2382:             }
 2383:             if (lc($tagname) eq 'link') {
 2384:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2385:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2386:                 }
 2387:             }
 2388: 	    if (lc($tagname) eq 'object' ||
 2389: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2390: 		foreach my $item (keys(%javafiles)) {
 2391: 		    $javafiles{$item} = '';
 2392: 		}
 2393: 	    }
 2394: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2395: 		my $name = lc($attr->{'name'});
 2396: 		foreach my $item (keys(%javafiles)) {
 2397: 		    if ($name eq $item) {
 2398: 			$javafiles{$item} = $attr->{'value'};
 2399: 			last;
 2400: 		    }
 2401: 		}
 2402: 		foreach my $item (keys(%mediafiles)) {
 2403: 		    if ($name eq $item) {
 2404: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2405: 			last;
 2406: 		    }
 2407: 		}
 2408: 	    }
 2409: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2410: 		foreach my $item (keys(%javafiles)) {
 2411: 		    if ($attr->{$item}) {
 2412: 			$javafiles{$item} = $attr->{$item};
 2413: 			last;
 2414: 		    }
 2415: 		}
 2416: 		foreach my $item (keys(%mediafiles)) {
 2417: 		    if ($attr->{$item}) {
 2418: 			&add_filetype($allfiles,$attr->{$item},$item);
 2419: 			last;
 2420: 		    }
 2421: 		}
 2422: 	    }
 2423: 	} elsif ($t->[0] eq 'E') {
 2424: 	    my ($tagname) = ($t->[1]);
 2425: 	    if ($javafiles{'codebase'} ne '') {
 2426: 		$javafiles{'codebase'} .= '/';
 2427: 	    }  
 2428: 	    if (lc($tagname) eq 'applet' ||
 2429: 		lc($tagname) eq 'object' ||
 2430: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2431: 		) {
 2432: 		foreach my $item (keys(%javafiles)) {
 2433: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2434: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2435: 			&add_filetype($allfiles,$file,$item);
 2436: 		    }
 2437: 		}
 2438: 	    } 
 2439: 	    pop @state;
 2440: 	}
 2441:     }
 2442:     return 'ok';
 2443: }
 2444: 
 2445: sub add_filetype {
 2446:     my ($allfiles,$file,$type)=@_;
 2447:     if (exists($allfiles->{$file})) {
 2448: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2449: 	    push(@{$allfiles->{$file}}, &escape($type));
 2450: 	}
 2451:     } else {
 2452: 	@{$allfiles->{$file}} = (&escape($type));
 2453:     }
 2454: }
 2455: 
 2456: sub removeuploadedurl {
 2457:     my ($url)=@_;	
 2458:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2459:     return &removeuserfile($uname,$udom,$fname);
 2460: }
 2461: 
 2462: sub removeuserfile {
 2463:     my ($docuname,$docudom,$fname)=@_;
 2464:     my $home=&homeserver($docuname,$docudom);    
 2465:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2466:     if ($result eq 'ok') {	
 2467:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2468:             my $metafile = $fname.'.meta';
 2469:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2470: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2471:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2472:             my $sqlresult = 
 2473:                 &update_portfolio_table($docuname,$docudom,$file,
 2474:                                         'portfolio_metadata',$group,
 2475:                                         'delete');
 2476:         }
 2477:     }
 2478:     return $result;
 2479: }
 2480: 
 2481: sub mkdiruserfile {
 2482:     my ($docuname,$docudom,$dir)=@_;
 2483:     my $home=&homeserver($docuname,$docudom);
 2484:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2485: }
 2486: 
 2487: sub renameuserfile {
 2488:     my ($docuname,$docudom,$old,$new)=@_;
 2489:     my $home=&homeserver($docuname,$docudom);
 2490:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2491:                         &escape("$old").':'.&escape("$new"),$home);
 2492:     if ($result eq 'ok') {
 2493:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2494:             my $oldmeta = $old.'.meta';
 2495:             my $newmeta = $new.'.meta';
 2496:             my $metaresult = 
 2497:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2498: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2499:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2500:             my $sqlresult = 
 2501:                 &update_portfolio_table($docuname,$docudom,$file,
 2502:                                         'portfolio_metadata',$group,
 2503:                                         'delete');
 2504:         }
 2505:     }
 2506:     return $result;
 2507: }
 2508: 
 2509: # ------------------------------------------------------------------------- Log
 2510: 
 2511: sub log {
 2512:     my ($dom,$nam,$hom,$what)=@_;
 2513:     return critical("log:$dom:$nam:$what",$hom);
 2514: }
 2515: 
 2516: # ------------------------------------------------------------------ Course Log
 2517: #
 2518: # This routine flushes several buffers of non-mission-critical nature
 2519: #
 2520: 
 2521: sub flushcourselogs {
 2522:     &logthis('Flushing log buffers');
 2523: #
 2524: # course logs
 2525: # This is a log of all transactions in a course, which can be used
 2526: # for data mining purposes
 2527: #
 2528: # It also collects the courseid database, which lists last transaction
 2529: # times and course titles for all courseids
 2530: #
 2531:     my %courseidbuffer=();
 2532:     foreach my $crsid (keys(%courselogs)) {
 2533:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2534: 		          &escape($courselogs{$crsid}),
 2535: 		          $coursehombuf{$crsid}) eq 'ok') {
 2536: 	    delete $courselogs{$crsid};
 2537:         } else {
 2538:             &logthis('Failed to flush log buffer for '.$crsid);
 2539:             if (length($courselogs{$crsid})>40000) {
 2540:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2541:                         " exceeded maximum size, deleting.</font>");
 2542:                delete $courselogs{$crsid};
 2543:             }
 2544:         }
 2545:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2546:             'description' => $coursedescrbuf{$crsid},
 2547:             'inst_code'    => $courseinstcodebuf{$crsid},
 2548:             'type'        => $coursetypebuf{$crsid},
 2549:             'owner'       => $courseownerbuf{$crsid},
 2550:         };
 2551:     }
 2552: #
 2553: # Write course id database (reverse lookup) to homeserver of courses 
 2554: # Is used in pickcourse
 2555: #
 2556:     foreach my $crs_home (keys(%courseidbuffer)) {
 2557:         my $response = &courseidput(&host_domain($crs_home),
 2558:                                     $courseidbuffer{$crs_home},
 2559:                                     $crs_home,'timeonly');
 2560:     }
 2561: #
 2562: # File accesses
 2563: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2564: #
 2565:     foreach my $entry (keys(%accesshash)) {
 2566:         if ($entry =~ /___count$/) {
 2567:             my ($dom,$name);
 2568:             ($dom,$name,undef)=
 2569: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2570:             if (! defined($dom) || $dom eq '' || 
 2571:                 ! defined($name) || $name eq '') {
 2572:                 my $cid = $env{'request.course.id'};
 2573:                 $dom  = $env{'request.'.$cid.'.domain'};
 2574:                 $name = $env{'request.'.$cid.'.num'};
 2575:             }
 2576:             my $value = $accesshash{$entry};
 2577:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2578:             my %temphash=($url => $value);
 2579:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2580:             if ($result eq 'ok') {
 2581:                 delete $accesshash{$entry};
 2582:             } elsif ($result eq 'unknown_cmd') {
 2583:                 # Target server has old code running on it.
 2584:                 my %temphash=($entry => $value);
 2585:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2586:                     delete $accesshash{$entry};
 2587:                 }
 2588:             }
 2589:         } else {
 2590:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2591:             my %temphash=($entry => $accesshash{$entry});
 2592:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2593:                 delete $accesshash{$entry};
 2594:             }
 2595:         }
 2596:     }
 2597: #
 2598: # Roles
 2599: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2600: #
 2601:     foreach my $entry (keys(%userrolehash)) {
 2602:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2603: 	    split(/\:/,$entry);
 2604:         if (&Apache::lonnet::put('nohist_userroles',
 2605:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2606:                 $rudom,$runame) eq 'ok') {
 2607: 	    delete $userrolehash{$entry};
 2608:         }
 2609:     }
 2610: #
 2611: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2612: #
 2613:     my %domrolebuffer = ();
 2614:     foreach my $entry (keys(%domainrolehash)) {
 2615:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2616:         if ($domrolebuffer{$rudom}) {
 2617:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2618:                       '='.&escape($domainrolehash{$entry});
 2619:         } else {
 2620:             $domrolebuffer{$rudom}.=&escape($entry).
 2621:                       '='.&escape($domainrolehash{$entry});
 2622:         }
 2623:         delete $domainrolehash{$entry};
 2624:     }
 2625:     foreach my $dom (keys(%domrolebuffer)) {
 2626: 	my %servers = &get_servers($dom,'library');
 2627: 	foreach my $tryserver (keys(%servers)) {
 2628: 	    unless (&reply('domroleput:'.$dom.':'.
 2629: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2630: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2631: 	    }
 2632:         }
 2633:     }
 2634:     $dumpcount++;
 2635: }
 2636: 
 2637: sub courselog {
 2638:     my $what=shift;
 2639:     $what=time.':'.$what;
 2640:     unless ($env{'request.course.id'}) { return ''; }
 2641:     $coursedombuf{$env{'request.course.id'}}=
 2642:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2643:     $coursenumbuf{$env{'request.course.id'}}=
 2644:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2645:     $coursehombuf{$env{'request.course.id'}}=
 2646:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2647:     $coursedescrbuf{$env{'request.course.id'}}=
 2648:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2649:     $courseinstcodebuf{$env{'request.course.id'}}=
 2650:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2651:     $courseownerbuf{$env{'request.course.id'}}=
 2652:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2653:     $coursetypebuf{$env{'request.course.id'}}=
 2654:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2655:     if (defined $courselogs{$env{'request.course.id'}}) {
 2656: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2657:     } else {
 2658: 	$courselogs{$env{'request.course.id'}}.=$what;
 2659:     }
 2660:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2661: 	&flushcourselogs();
 2662:     }
 2663: }
 2664: 
 2665: sub courseacclog {
 2666:     my $fnsymb=shift;
 2667:     unless ($env{'request.course.id'}) { return ''; }
 2668:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2669:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2670:         $what.=':POST';
 2671:         # FIXME: Probably ought to escape things....
 2672: 	foreach my $key (keys(%env)) {
 2673:             if ($key=~/^form\.(.*)/) {
 2674:                 my $formitem = $1;
 2675:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2676:                     $what.=':'.$formitem.'='.$env{$key};
 2677:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2678:                     $what.=':'.$formitem.'='.$env{$key};
 2679:                 }
 2680:             }
 2681:         }
 2682:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2683:         # FIXME: We should not be depending on a form parameter that someone
 2684:         # editing lonsearchcat.pm might change in the future.
 2685:         if ($env{'form.phase'} eq 'course_search') {
 2686:             $what.= ':POST';
 2687:             # FIXME: Probably ought to escape things....
 2688:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2689:                                  'crsdiscuss') {
 2690:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2691:             }
 2692:         }
 2693:     }
 2694:     &courselog($what);
 2695: }
 2696: 
 2697: sub countacc {
 2698:     my $url=&declutter(shift);
 2699:     return if (! defined($url) || $url eq '');
 2700:     unless ($env{'request.course.id'}) { return ''; }
 2701:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2702:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2703:     $accesshash{$key}++;
 2704: }
 2705: 
 2706: sub linklog {
 2707:     my ($from,$to)=@_;
 2708:     $from=&declutter($from);
 2709:     $to=&declutter($to);
 2710:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2711:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2712: }
 2713:   
 2714: sub userrolelog {
 2715:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2716:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2717:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2718:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2719:         ($trole=~/^ta/)) {
 2720:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2721:        $userrolehash
 2722:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2723:                     =$tend.':'.$tstart;
 2724:     }
 2725:     if (($env{'request.role'} =~ /dc\./) &&
 2726: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2727: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2728: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2729:        $userrolehash
 2730:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2731:                     =$tend.':'.$tstart;
 2732:     }
 2733:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2734:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2735:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2736:         ($trole=~/^sc/)) {
 2737:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2738:        $domainrolehash
 2739:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2740:                     = $tend.':'.$tstart;
 2741:     }
 2742: }
 2743: 
 2744: sub courserolelog {
 2745:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2746:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2747:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2748:         ($trole eq 'ta') || ($trole eq 'st') ||
 2749:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2750:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2751:             my $cdom = $1;
 2752:             my $cnum = $2;
 2753:             my $sec = $3;
 2754:             my $namespace = 'rolelog';
 2755:             my %storehash = (
 2756:                                role    => $trole,
 2757:                                start   => $tstart,
 2758:                                end     => $tend,
 2759:                                selfenroll => $selfenroll,
 2760:                                context    => $context,
 2761:                             );
 2762:             if ($trole eq 'gr') {
 2763:                 $namespace = 'groupslog';
 2764:                 $storehash{'group'} = $sec;
 2765:             } else {
 2766:                 $storehash{'section'} = $sec;
 2767:             }
 2768:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2769:             if (($trole ne 'st') || ($sec ne '')) {
 2770:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2771:             }
 2772:         }
 2773:     }
 2774:     return;
 2775: }
 2776: 
 2777: sub get_course_adv_roles {
 2778:     my ($cid,$codes) = @_;
 2779:     $cid=$env{'request.course.id'} unless (defined($cid));
 2780:     my %coursehash=&coursedescription($cid);
 2781:     my $crstype = &Apache::loncommon::course_type($cid);
 2782:     my %nothide=();
 2783:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2784:         if ($user !~ /:/) {
 2785: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2786:         } else {
 2787:             $nothide{$user}=1;
 2788:         }
 2789:     }
 2790:     my %returnhash=();
 2791:     my %dumphash=
 2792:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2793:     my $now=time;
 2794:     my %privileged;
 2795:     foreach my $entry (keys(%dumphash)) {
 2796: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2797:         if (($tstart) && ($tstart<0)) { next; }
 2798:         if (($tend) && ($tend<$now)) { next; }
 2799:         if (($tstart) && ($now<$tstart)) { next; }
 2800:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2801: 	if ($username eq '' || $domain eq '') { next; }
 2802:         unless (ref($privileged{$domain}) eq 'HASH') {
 2803:             my %dompersonnel =
 2804:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2805:             $privileged{$domain} = {};
 2806:             foreach my $server (keys(%dompersonnel)) {
 2807:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2808:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2809:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2810:                         $privileged{$udom}{$uname} = 1;
 2811:                     }
 2812:                 }
 2813:             }
 2814:         }
 2815:         if ((exists($privileged{$domain}{$username})) && 
 2816:             (!$nothide{$username.':'.$domain})) { next; }
 2817: 	if ($role eq 'cr') { next; }
 2818:         if ($codes) {
 2819:             if ($section) { $role .= ':'.$section; }
 2820:             if ($returnhash{$role}) {
 2821:                 $returnhash{$role}.=','.$username.':'.$domain;
 2822:             } else {
 2823:                 $returnhash{$role}=$username.':'.$domain;
 2824:             }
 2825:         } else {
 2826:             my $key=&plaintext($role,$crstype);
 2827:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2828:             if ($returnhash{$key}) {
 2829: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2830:             } else {
 2831:                 $returnhash{$key}=$username.':'.$domain;
 2832:             }
 2833:         }
 2834:     }
 2835:     return %returnhash;
 2836: }
 2837: 
 2838: sub get_my_roles {
 2839:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2840:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2841:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2842:     my (%dumphash,%nothide);
 2843:     if ($context eq 'userroles') { 
 2844:         %dumphash = &dump('roles',$udom,$uname);
 2845:     } else {
 2846:         %dumphash=
 2847:             &dump('nohist_userroles',$udom,$uname);
 2848:         if ($hidepriv) {
 2849:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2850:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2851:                 if ($user !~ /:/) {
 2852:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2853:                 } else {
 2854:                     $nothide{$user} = 1;
 2855:                 }
 2856:             }
 2857:         }
 2858:     }
 2859:     my %returnhash=();
 2860:     my $now=time;
 2861:     my %privileged;
 2862:     foreach my $entry (keys(%dumphash)) {
 2863:         my ($role,$tend,$tstart);
 2864:         if ($context eq 'userroles') {
 2865: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2866:         } else {
 2867:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2868:         }
 2869:         if (($tstart) && ($tstart<0)) { next; }
 2870:         my $status = 'active';
 2871:         if (($tend) && ($tend<=$now)) {
 2872:             $status = 'previous';
 2873:         } 
 2874:         if (($tstart) && ($now<$tstart)) {
 2875:             $status = 'future';
 2876:         }
 2877:         if (ref($types) eq 'ARRAY') {
 2878:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2879:                 next;
 2880:             } 
 2881:         } else {
 2882:             if ($status ne 'active') {
 2883:                 next;
 2884:             }
 2885:         }
 2886:         my ($rolecode,$username,$domain,$section,$area);
 2887:         if ($context eq 'userroles') {
 2888:             ($area,$rolecode) = split(/_/,$entry);
 2889:             (undef,$domain,$username,$section) = split(/\//,$area);
 2890:         } else {
 2891:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2892:         }
 2893:         if (ref($roledoms) eq 'ARRAY') {
 2894:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2895:                 next;
 2896:             }
 2897:         }
 2898:         if (ref($roles) eq 'ARRAY') {
 2899:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2900:                 if ($role =~ /^cr\//) {
 2901:                     if (!grep(/^cr$/,@{$roles})) {
 2902:                         next;
 2903:                     }
 2904:                 } else {
 2905:                     next;
 2906:                 }
 2907:             }
 2908:         }
 2909:         if ($hidepriv) {
 2910:             if ($context eq 'userroles') {
 2911:                 if ((&privileged($username,$domain)) &&
 2912:                     (!$nothide{$username.':'.$domain})) {
 2913:                     next;
 2914:                 }
 2915:             } else {
 2916:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2917:                     my %dompersonnel =
 2918:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2919:                     $privileged{$domain} = {};
 2920:                     if (keys(%dompersonnel)) {
 2921:                         foreach my $server (keys(%dompersonnel)) {
 2922:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2923:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2924:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2925:                                     $privileged{$udom}{$uname} = $trole;
 2926:                                 }
 2927:                             }
 2928:                         }
 2929:                     }
 2930:                 }
 2931:                 if (exists($privileged{$domain}{$username})) {
 2932:                     if (!$nothide{$username.':'.$domain}) {
 2933:                         next;
 2934:                     }
 2935:                 }
 2936:             }
 2937:         }
 2938:         if ($withsec) {
 2939:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2940:                 $tstart.':'.$tend;
 2941:         } else {
 2942:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2943:         }
 2944:     }
 2945:     return %returnhash;
 2946: }
 2947: 
 2948: # ----------------------------------------------------- Frontpage Announcements
 2949: #
 2950: #
 2951: 
 2952: sub postannounce {
 2953:     my ($server,$text)=@_;
 2954:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2955:     unless ($text=~/\w/) { $text=''; }
 2956:     return &reply('setannounce:'.&escape($text),$server);
 2957: }
 2958: 
 2959: sub getannounce {
 2960: 
 2961:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2962: 	my $announcement='';
 2963: 	while (my $line = <$fh>) { $announcement .= $line; }
 2964: 	close($fh);
 2965: 	if ($announcement=~/\w/) { 
 2966: 	    return 
 2967:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2968:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2969: 	} else {
 2970: 	    return '';
 2971: 	}
 2972:     } else {
 2973: 	return '';
 2974:     }
 2975: }
 2976: 
 2977: # ---------------------------------------------------------- Course ID routines
 2978: # Deal with domain's nohist_courseid.db files
 2979: #
 2980: 
 2981: sub courseidput {
 2982:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2983:     my $outcome;
 2984:     if ($caller eq 'timeonly') {
 2985:         my $cids = '';
 2986:         foreach my $item (keys(%$storehash)) {
 2987:             $cids.=&escape($item).'&';
 2988:         }
 2989:         $cids=~s/\&$//;
 2990:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2991:                           $coursehome);       
 2992:     } else {
 2993:         my $items = '';
 2994:         foreach my $item (keys(%$storehash)) {
 2995:             $items.= &escape($item).'='.
 2996:                      &freeze_escape($$storehash{$item}).'&';
 2997:         }
 2998:         $items=~s/\&$//;
 2999:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3000:                           $coursehome);
 3001:     }
 3002:     if ($outcome eq 'unknown_cmd') {
 3003:         my $what;
 3004:         foreach my $cid (keys(%$storehash)) {
 3005:             $what .= &escape($cid).'=';
 3006:             foreach my $item ('description','inst_code','owner','type') {
 3007:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3008:             }
 3009:             $what =~ s/\:$/&/;
 3010:         }
 3011:         $what =~ s/\&$//;  
 3012:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3013:     } else {
 3014:         return $outcome;
 3015:     }
 3016: }
 3017: 
 3018: sub courseiddump {
 3019:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3020:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3021:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
 3022:     my $as_hash = 1;
 3023:     my %returnhash;
 3024:     if (!$domfilter) { $domfilter=''; }
 3025:     my %libserv = &all_library();
 3026:     foreach my $tryserver (keys(%libserv)) {
 3027:         if ( (  $hostidflag == 1 
 3028: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3029: 	     || (!defined($hostidflag)) ) {
 3030: 
 3031: 	    if (($domfilter eq '') ||
 3032: 		(&host_domain($tryserver) eq $domfilter)) {
 3033:                 my $rep = 
 3034:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3035:                          $sincefilter.':'.&escape($descfilter).':'.
 3036:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3037:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3038:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3039:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3040:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3041:                          &escape($cc_clone).':'.$cloneonly,$tryserver);
 3042:                 my @pairs=split(/\&/,$rep);
 3043:                 foreach my $item (@pairs) {
 3044:                     my ($key,$value)=split(/\=/,$item,2);
 3045:                     $key = &unescape($key);
 3046:                     next if ($key =~ /^error: 2 /);
 3047:                     my $result = &thaw_unescape($value);
 3048:                     if (ref($result) eq 'HASH') {
 3049:                         $returnhash{$key}=$result;
 3050:                     } else {
 3051:                         my @responses = split(/:/,$value);
 3052:                         my @items = ('description','inst_code','owner','type');
 3053:                         for (my $i=0; $i<@responses; $i++) {
 3054:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3055:                         }
 3056:                     }
 3057:                 }
 3058:             }
 3059:         }
 3060:     }
 3061:     return %returnhash;
 3062: }
 3063: 
 3064: # ---------------------------------------------------------- DC e-mail
 3065: 
 3066: sub dcmailput {
 3067:     my ($domain,$msgid,$message,$server)=@_;
 3068:     my $status = &Apache::lonnet::critical(
 3069:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3070:        &escape($message),$server);
 3071:     return $status;
 3072: }
 3073: 
 3074: sub dcmaildump {
 3075:     my ($dom,$startdate,$enddate,$senders) = @_;
 3076:     my %returnhash=();
 3077: 
 3078:     if (defined(&domain($dom,'primary'))) {
 3079:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3080:                                                          &escape($enddate).':';
 3081: 	my @esc_senders=map { &escape($_)} @$senders;
 3082: 	$cmd.=&escape(join('&',@esc_senders));
 3083: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3084:             my ($key,$value) = split(/\=/,$line,2);
 3085:             if (($key) && ($value)) {
 3086:                 $returnhash{&unescape($key)} = &unescape($value);
 3087:             }
 3088:         }
 3089:     }
 3090:     return %returnhash;
 3091: }
 3092: # ---------------------------------------------------------- Domain roles
 3093: 
 3094: sub get_domain_roles {
 3095:     my ($dom,$roles,$startdate,$enddate)=@_;
 3096:     if ((!defined($startdate)) || ($startdate eq '')) {
 3097:         $startdate = '.';
 3098:     }
 3099:     if ((!defined($enddate)) || ($enddate eq '')) {
 3100:         $enddate = '.';
 3101:     }
 3102:     my $rolelist;
 3103:     if (ref($roles) eq 'ARRAY') {
 3104:         $rolelist = join(':',@{$roles});
 3105:     }
 3106:     my %personnel = ();
 3107: 
 3108:     my %servers = &get_servers($dom,'library');
 3109:     foreach my $tryserver (keys(%servers)) {
 3110: 	%{$personnel{$tryserver}}=();
 3111: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3112: 					    &escape($startdate).':'.
 3113: 					    &escape($enddate).':'.
 3114: 					    &escape($rolelist), $tryserver))) {
 3115: 	    my ($key,$value) = split(/\=/,$line,2);
 3116: 	    if (($key) && ($value)) {
 3117: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3118: 	    }
 3119: 	}
 3120:     }
 3121:     return %personnel;
 3122: }
 3123: 
 3124: # ----------------------------------------------------------- Check out an item
 3125: 
 3126: sub get_first_access {
 3127:     my ($type,$argsymb)=@_;
 3128:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3129:     if ($argsymb) { $symb=$argsymb; }
 3130:     my ($map,$id,$res)=&decode_symb($symb);
 3131:     if ($type eq 'course') {
 3132: 	$res='course';
 3133:     } elsif ($type eq 'map') {
 3134: 	$res=&symbread($map);
 3135:     } else {
 3136: 	$res=$symb;
 3137:     }
 3138:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3139:     return $times{"$courseid\0$res"};
 3140: }
 3141: 
 3142: sub set_first_access {
 3143:     my ($type)=@_;
 3144:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3145:     my ($map,$id,$res)=&decode_symb($symb);
 3146:     if ($type eq 'course') {
 3147: 	$res='course';
 3148:     } elsif ($type eq 'map') {
 3149: 	$res=&symbread($map);
 3150:     } else {
 3151: 	$res=$symb;
 3152:     }
 3153:     my $firstaccess=&get_first_access($type,$symb);
 3154:     if (!$firstaccess) {
 3155: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3156:     }
 3157:     return 'already_set';
 3158: }
 3159: 
 3160: sub checkout {
 3161:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3162:     my $now=time;
 3163:     my $lonhost=$perlvar{'lonHostID'};
 3164:     my $infostr=&escape(
 3165:                  'CHECKOUTTOKEN&'.
 3166:                  $tuname.'&'.
 3167:                  $tudom.'&'.
 3168:                  $tcrsid.'&'.
 3169:                  $symb.'&'.
 3170: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3171:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3172:     if ($token=~/^error\:/) { 
 3173:         &logthis("<font color=\"blue\">WARNING: ".
 3174:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3175:                  "</font>");
 3176:         return ''; 
 3177:     }
 3178: 
 3179:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3180:     $token=~tr/a-z/A-Z/;
 3181: 
 3182:     my %infohash=('resource.0.outtoken' => $token,
 3183:                   'resource.0.checkouttime' => $now,
 3184:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3185: 
 3186:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3187:        return '';
 3188:     } else {
 3189:         &logthis("<font color=\"blue\">WARNING: ".
 3190:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3191:                  "</font>");
 3192:     }    
 3193: 
 3194:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3195:                          &escape('Checkout '.$infostr.' - '.
 3196:                                                  $token)) ne 'ok') {
 3197: 	return '';
 3198:     } else {
 3199:         &logthis("<font color=\"blue\">WARNING: ".
 3200:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3201:                  "</font>");
 3202:     }
 3203:     return $token;
 3204: }
 3205: 
 3206: # ------------------------------------------------------------ Check in an item
 3207: 
 3208: sub checkin {
 3209:     my $token=shift;
 3210:     my $now=time;
 3211:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3212:     $lonhost=~tr/A-Z/a-z/;
 3213:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3214:     $dtoken=~s/\W/\_/g;
 3215:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3216:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3217: 
 3218:     unless (($tuname) && ($tudom)) {
 3219:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3220:         return '';
 3221:     }
 3222:     
 3223:     unless (&allowed('mgr',$tcrsid)) {
 3224:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3225:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3226:         return '';
 3227:     }
 3228: 
 3229:     my %infohash=('resource.0.intoken' => $token,
 3230:                   'resource.0.checkintime' => $now,
 3231:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3232: 
 3233:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3234:        return '';
 3235:     }    
 3236: 
 3237:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3238:                          &escape('Checkin - '.$token)) ne 'ok') {
 3239: 	return '';
 3240:     }
 3241: 
 3242:     return ($symb,$tuname,$tudom,$tcrsid);    
 3243: }
 3244: 
 3245: # --------------------------------------------- Set Expire Date for Spreadsheet
 3246: 
 3247: sub expirespread {
 3248:     my ($uname,$udom,$stype,$usymb)=@_;
 3249:     my $cid=$env{'request.course.id'}; 
 3250:     if ($cid) {
 3251:        my $now=time;
 3252:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3253:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3254:                             $env{'course.'.$cid.'.num'}.
 3255: 	        	    ':nohist_expirationdates:'.
 3256:                             &escape($key).'='.$now,
 3257:                             $env{'course.'.$cid.'.home'})
 3258:     }
 3259:     return 'ok';
 3260: }
 3261: 
 3262: # ----------------------------------------------------- Devalidate Spreadsheets
 3263: 
 3264: sub devalidate {
 3265:     my ($symb,$uname,$udom)=@_;
 3266:     my $cid=$env{'request.course.id'}; 
 3267:     if ($cid) {
 3268:         # delete the stored spreadsheets for
 3269:         # - the student level sheet of this user in course's homespace
 3270:         # - the assessment level sheet for this resource 
 3271:         #   for this user in user's homespace
 3272: 	# - current conditional state info
 3273: 	my $key=$uname.':'.$udom.':';
 3274:         my $status=
 3275: 	    &del('nohist_calculatedsheets',
 3276: 		 [$key.'studentcalc:'],
 3277: 		 $env{'course.'.$cid.'.domain'},
 3278: 		 $env{'course.'.$cid.'.num'})
 3279: 		.' '.
 3280: 	    &del('nohist_calculatedsheets_'.$cid,
 3281: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3282:         unless ($status eq 'ok ok') {
 3283:            &logthis('Could not devalidate spreadsheet '.
 3284:                     $uname.' at '.$udom.' for '.
 3285: 		    $symb.': '.$status);
 3286:         }
 3287: 	&delenv('user.state.'.$cid);
 3288:     }
 3289: }
 3290: 
 3291: sub get_scalar {
 3292:     my ($string,$end) = @_;
 3293:     my $value;
 3294:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3295: 	$value = $1;
 3296:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3297: 	$value = $1;
 3298:     }
 3299:     return &unescape($value);
 3300: }
 3301: 
 3302: sub array2str {
 3303:   my (@array) = @_;
 3304:   my $result=&arrayref2str(\@array);
 3305:   $result=~s/^__ARRAY_REF__//;
 3306:   $result=~s/__END_ARRAY_REF__$//;
 3307:   return $result;
 3308: }
 3309: 
 3310: sub arrayref2str {
 3311:   my ($arrayref) = @_;
 3312:   my $result='__ARRAY_REF__';
 3313:   foreach my $elem (@$arrayref) {
 3314:     if(ref($elem) eq 'ARRAY') {
 3315:       $result.=&arrayref2str($elem).'&';
 3316:     } elsif(ref($elem) eq 'HASH') {
 3317:       $result.=&hashref2str($elem).'&';
 3318:     } elsif(ref($elem)) {
 3319:       #print("Got a ref of ".(ref($elem))." skipping.");
 3320:     } else {
 3321:       $result.=&escape($elem).'&';
 3322:     }
 3323:   }
 3324:   $result=~s/\&$//;
 3325:   $result .= '__END_ARRAY_REF__';
 3326:   return $result;
 3327: }
 3328: 
 3329: sub hash2str {
 3330:   my (%hash) = @_;
 3331:   my $result=&hashref2str(\%hash);
 3332:   $result=~s/^__HASH_REF__//;
 3333:   $result=~s/__END_HASH_REF__$//;
 3334:   return $result;
 3335: }
 3336: 
 3337: sub hashref2str {
 3338:   my ($hashref)=@_;
 3339:   my $result='__HASH_REF__';
 3340:   foreach my $key (sort(keys(%$hashref))) {
 3341:     if (ref($key) eq 'ARRAY') {
 3342:       $result.=&arrayref2str($key).'=';
 3343:     } elsif (ref($key) eq 'HASH') {
 3344:       $result.=&hashref2str($key).'=';
 3345:     } elsif (ref($key)) {
 3346:       $result.='=';
 3347:       #print("Got a ref of ".(ref($key))." skipping.");
 3348:     } else {
 3349: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3350:     }
 3351: 
 3352:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3353:       $result.=&arrayref2str($hashref->{$key}).'&';
 3354:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3355:       $result.=&hashref2str($hashref->{$key}).'&';
 3356:     } elsif(ref($hashref->{$key})) {
 3357:        $result.='&';
 3358:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3359:     } else {
 3360:       $result.=&escape($hashref->{$key}).'&';
 3361:     }
 3362:   }
 3363:   $result=~s/\&$//;
 3364:   $result .= '__END_HASH_REF__';
 3365:   return $result;
 3366: }
 3367: 
 3368: sub str2hash {
 3369:     my ($string)=@_;
 3370:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3371:     return %$hash;
 3372: }
 3373: 
 3374: sub str2hashref {
 3375:   my ($string) = @_;
 3376: 
 3377:   my %hash;
 3378: 
 3379:   if($string !~ /^__HASH_REF__/) {
 3380:       if (! ($string eq '' || !defined($string))) {
 3381: 	  $hash{'error'}='Not hash reference';
 3382:       }
 3383:       return (\%hash, $string);
 3384:   }
 3385: 
 3386:   $string =~ s/^__HASH_REF__//;
 3387: 
 3388:   while($string !~ /^__END_HASH_REF__/) {
 3389:       #key
 3390:       my $key='';
 3391:       if($string =~ /^__HASH_REF__/) {
 3392:           ($key, $string)=&str2hashref($string);
 3393:           if(defined($key->{'error'})) {
 3394:               $hash{'error'}='Bad data';
 3395:               return (\%hash, $string);
 3396:           }
 3397:       } elsif($string =~ /^__ARRAY_REF__/) {
 3398:           ($key, $string)=&str2arrayref($string);
 3399:           if($key->[0] eq 'Array reference error') {
 3400:               $hash{'error'}='Bad data';
 3401:               return (\%hash, $string);
 3402:           }
 3403:       } else {
 3404:           $string =~ s/^(.*?)=//;
 3405: 	  $key=&unescape($1);
 3406:       }
 3407:       $string =~ s/^=//;
 3408: 
 3409:       #value
 3410:       my $value='';
 3411:       if($string =~ /^__HASH_REF__/) {
 3412:           ($value, $string)=&str2hashref($string);
 3413:           if(defined($value->{'error'})) {
 3414:               $hash{'error'}='Bad data';
 3415:               return (\%hash, $string);
 3416:           }
 3417:       } elsif($string =~ /^__ARRAY_REF__/) {
 3418:           ($value, $string)=&str2arrayref($string);
 3419:           if($value->[0] eq 'Array reference error') {
 3420:               $hash{'error'}='Bad data';
 3421:               return (\%hash, $string);
 3422:           }
 3423:       } else {
 3424: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3425:       }
 3426:       $string =~ s/^&//;
 3427: 
 3428:       $hash{$key}=$value;
 3429:   }
 3430: 
 3431:   $string =~ s/^__END_HASH_REF__//;
 3432: 
 3433:   return (\%hash, $string);
 3434: }
 3435: 
 3436: sub str2array {
 3437:     my ($string)=@_;
 3438:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3439:     return @$array;
 3440: }
 3441: 
 3442: sub str2arrayref {
 3443:   my ($string) = @_;
 3444:   my @array;
 3445: 
 3446:   if($string !~ /^__ARRAY_REF__/) {
 3447:       if (! ($string eq '' || !defined($string))) {
 3448: 	  $array[0]='Array reference error';
 3449:       }
 3450:       return (\@array, $string);
 3451:   }
 3452: 
 3453:   $string =~ s/^__ARRAY_REF__//;
 3454: 
 3455:   while($string !~ /^__END_ARRAY_REF__/) {
 3456:       my $value='';
 3457:       if($string =~ /^__HASH_REF__/) {
 3458:           ($value, $string)=&str2hashref($string);
 3459:           if(defined($value->{'error'})) {
 3460:               $array[0] ='Array reference error';
 3461:               return (\@array, $string);
 3462:           }
 3463:       } elsif($string =~ /^__ARRAY_REF__/) {
 3464:           ($value, $string)=&str2arrayref($string);
 3465:           if($value->[0] eq 'Array reference error') {
 3466:               $array[0] ='Array reference error';
 3467:               return (\@array, $string);
 3468:           }
 3469:       } else {
 3470: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3471:       }
 3472:       $string =~ s/^&//;
 3473: 
 3474:       push(@array, $value);
 3475:   }
 3476: 
 3477:   $string =~ s/^__END_ARRAY_REF__//;
 3478: 
 3479:   return (\@array, $string);
 3480: }
 3481: 
 3482: # -------------------------------------------------------------------Temp Store
 3483: 
 3484: sub tmpreset {
 3485:   my ($symb,$namespace,$domain,$stuname) = @_;
 3486:   if (!$symb) {
 3487:     $symb=&symbread();
 3488:     if (!$symb) { $symb= $env{'request.url'}; }
 3489:   }
 3490:   $symb=escape($symb);
 3491: 
 3492:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3493:   $namespace=~s/\//\_/g;
 3494:   $namespace=~s/\W//g;
 3495: 
 3496:   if (!$domain) { $domain=$env{'user.domain'}; }
 3497:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3498:   if ($domain eq 'public' && $stuname eq 'public') {
 3499:       $stuname=$ENV{'REMOTE_ADDR'};
 3500:   }
 3501:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3502:   my %hash;
 3503:   if (tie(%hash,'GDBM_File',
 3504: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3505: 	  &GDBM_WRCREAT(),0640)) {
 3506:     foreach my $key (keys(%hash)) {
 3507:       if ($key=~ /:$symb/) {
 3508: 	delete($hash{$key});
 3509:       }
 3510:     }
 3511:   }
 3512: }
 3513: 
 3514: sub tmpstore {
 3515:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3516: 
 3517:   if (!$symb) {
 3518:     $symb=&symbread();
 3519:     if (!$symb) { $symb= $env{'request.url'}; }
 3520:   }
 3521:   $symb=escape($symb);
 3522: 
 3523:   if (!$namespace) {
 3524:     # I don't think we would ever want to store this for a course.
 3525:     # it seems this will only be used if we don't have a course.
 3526:     #$namespace=$env{'request.course.id'};
 3527:     #if (!$namespace) {
 3528:       $namespace=$env{'request.state'};
 3529:     #}
 3530:   }
 3531:   $namespace=~s/\//\_/g;
 3532:   $namespace=~s/\W//g;
 3533:   if (!$domain) { $domain=$env{'user.domain'}; }
 3534:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3535:   if ($domain eq 'public' && $stuname eq 'public') {
 3536:       $stuname=$ENV{'REMOTE_ADDR'};
 3537:   }
 3538:   my $now=time;
 3539:   my %hash;
 3540:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3541:   if (tie(%hash,'GDBM_File',
 3542: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3543: 	  &GDBM_WRCREAT(),0640)) {
 3544:     $hash{"version:$symb"}++;
 3545:     my $version=$hash{"version:$symb"};
 3546:     my $allkeys=''; 
 3547:     foreach my $key (keys(%$storehash)) {
 3548:       $allkeys.=$key.':';
 3549:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3550:     }
 3551:     $hash{"$version:$symb:timestamp"}=$now;
 3552:     $allkeys.='timestamp';
 3553:     $hash{"$version:keys:$symb"}=$allkeys;
 3554:     if (untie(%hash)) {
 3555:       return 'ok';
 3556:     } else {
 3557:       return "error:$!";
 3558:     }
 3559:   } else {
 3560:     return "error:$!";
 3561:   }
 3562: }
 3563: 
 3564: # -----------------------------------------------------------------Temp Restore
 3565: 
 3566: sub tmprestore {
 3567:   my ($symb,$namespace,$domain,$stuname) = @_;
 3568: 
 3569:   if (!$symb) {
 3570:     $symb=&symbread();
 3571:     if (!$symb) { $symb= $env{'request.url'}; }
 3572:   }
 3573:   $symb=escape($symb);
 3574: 
 3575:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3576: 
 3577:   if (!$domain) { $domain=$env{'user.domain'}; }
 3578:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3579:   if ($domain eq 'public' && $stuname eq 'public') {
 3580:       $stuname=$ENV{'REMOTE_ADDR'};
 3581:   }
 3582:   my %returnhash;
 3583:   $namespace=~s/\//\_/g;
 3584:   $namespace=~s/\W//g;
 3585:   my %hash;
 3586:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3587:   if (tie(%hash,'GDBM_File',
 3588: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3589: 	  &GDBM_READER(),0640)) {
 3590:     my $version=$hash{"version:$symb"};
 3591:     $returnhash{'version'}=$version;
 3592:     my $scope;
 3593:     for ($scope=1;$scope<=$version;$scope++) {
 3594:       my $vkeys=$hash{"$scope:keys:$symb"};
 3595:       my @keys=split(/:/,$vkeys);
 3596:       my $key;
 3597:       $returnhash{"$scope:keys"}=$vkeys;
 3598:       foreach $key (@keys) {
 3599: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3600: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3601:       }
 3602:     }
 3603:     if (!(untie(%hash))) {
 3604:       return "error:$!";
 3605:     }
 3606:   } else {
 3607:     return "error:$!";
 3608:   }
 3609:   return %returnhash;
 3610: }
 3611: 
 3612: # ----------------------------------------------------------------------- Store
 3613: 
 3614: sub store {
 3615:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3616:     my $home='';
 3617: 
 3618:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3619: 
 3620:     $symb=&symbclean($symb);
 3621:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3622: 
 3623:     if (!$domain) { $domain=$env{'user.domain'}; }
 3624:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3625: 
 3626:     &devalidate($symb,$stuname,$domain);
 3627: 
 3628:     $symb=escape($symb);
 3629:     if (!$namespace) { 
 3630:        unless ($namespace=$env{'request.course.id'}) { 
 3631:           return ''; 
 3632:        } 
 3633:     }
 3634:     if (!$home) { $home=$env{'user.home'}; }
 3635: 
 3636:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3637:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3638: 
 3639:     my $namevalue='';
 3640:     foreach my $key (keys(%$storehash)) {
 3641:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3642:     }
 3643:     $namevalue=~s/\&$//;
 3644:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3645:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3646: }
 3647: 
 3648: # -------------------------------------------------------------- Critical Store
 3649: 
 3650: sub cstore {
 3651:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3652:     my $home='';
 3653: 
 3654:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3655: 
 3656:     $symb=&symbclean($symb);
 3657:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3658: 
 3659:     if (!$domain) { $domain=$env{'user.domain'}; }
 3660:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3661: 
 3662:     &devalidate($symb,$stuname,$domain);
 3663: 
 3664:     $symb=escape($symb);
 3665:     if (!$namespace) { 
 3666:        unless ($namespace=$env{'request.course.id'}) { 
 3667:           return ''; 
 3668:        } 
 3669:     }
 3670:     if (!$home) { $home=$env{'user.home'}; }
 3671: 
 3672:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3673:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3674: 
 3675:     my $namevalue='';
 3676:     foreach my $key (keys(%$storehash)) {
 3677:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3678:     }
 3679:     $namevalue=~s/\&$//;
 3680:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3681:     return critical
 3682:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3683: }
 3684: 
 3685: # --------------------------------------------------------------------- Restore
 3686: 
 3687: sub restore {
 3688:     my ($symb,$namespace,$domain,$stuname) = @_;
 3689:     my $home='';
 3690: 
 3691:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3692: 
 3693:     if (!$symb) {
 3694:       unless ($symb=escape(&symbread())) { return ''; }
 3695:     } else {
 3696:       $symb=&escape(&symbclean($symb));
 3697:     }
 3698:     if (!$namespace) { 
 3699:        unless ($namespace=$env{'request.course.id'}) { 
 3700:           return ''; 
 3701:        } 
 3702:     }
 3703:     if (!$domain) { $domain=$env{'user.domain'}; }
 3704:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3705:     if (!$home) { $home=$env{'user.home'}; }
 3706:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3707: 
 3708:     my %returnhash=();
 3709:     foreach my $line (split(/\&/,$answer)) {
 3710: 	my ($name,$value)=split(/\=/,$line);
 3711:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3712:     }
 3713:     my $version;
 3714:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3715:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3716:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3717:        }
 3718:     }
 3719:     return %returnhash;
 3720: }
 3721: 
 3722: # ---------------------------------------------------------- Course Description
 3723: 
 3724: sub coursedescription {
 3725:     my ($courseid,$args)=@_;
 3726:     $courseid=~s/^\///;
 3727:     $courseid=~s/\_/\//g;
 3728:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3729:     my $chome=&homeserver($cnum,$cdomain);
 3730:     my $normalid=$cdomain.'_'.$cnum;
 3731:     # need to always cache even if we get errors otherwise we keep 
 3732:     # trying and trying and trying to get the course description.
 3733:     my %envhash=();
 3734:     my %returnhash=();
 3735:     
 3736:     my $expiretime=600;
 3737:     if ($env{'request.course.id'} eq $normalid) {
 3738: 	$expiretime=120;
 3739:     }
 3740: 
 3741:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3742:     if (!$args->{'freshen_cache'}
 3743: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3744: 	foreach my $key (keys(%env)) {
 3745: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3746: 	    my ($setting) = $1;
 3747: 	    $returnhash{$setting} = $env{$key};
 3748: 	}
 3749: 	return %returnhash;
 3750:     }
 3751: 
 3752:     # get the data agin
 3753:     if (!$args->{'one_time'}) {
 3754: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3755:     }
 3756: 
 3757:     if ($chome ne 'no_host') {
 3758:        %returnhash=&dump('environment',$cdomain,$cnum);
 3759:        if (!exists($returnhash{'con_lost'})) {
 3760:            $returnhash{'home'}= $chome;
 3761: 	   $returnhash{'domain'} = $cdomain;
 3762: 	   $returnhash{'num'} = $cnum;
 3763:            if (!defined($returnhash{'type'})) {
 3764:                $returnhash{'type'} = 'Course';
 3765:            }
 3766:            while (my ($name,$value) = each %returnhash) {
 3767:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3768:            }
 3769:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3770:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3771: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3772:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3773:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3774:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3775:        }
 3776:     }
 3777:     if (!$args->{'one_time'}) {
 3778: 	&appenv(\%envhash);
 3779:     }
 3780:     return %returnhash;
 3781: }
 3782: 
 3783: # -------------------------------------------------See if a user is privileged
 3784: 
 3785: sub privileged {
 3786:     my ($username,$domain)=@_;
 3787:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3788: 			&homeserver($username,$domain));
 3789:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3790:     my $now=time;
 3791:     if ($rolesdump ne '') {
 3792:         foreach my $entry (split(/&/,$rolesdump)) {
 3793: 	    if ($entry!~/^rolesdef_/) {
 3794: 		my ($area,$role)=split(/=/,$entry);
 3795: 		$area=~s/\_\w\w$//;
 3796: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3797: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3798: 		    my $active=1;
 3799: 		    if ($tend) {
 3800: 			if ($tend<$now) { $active=0; }
 3801: 		    }
 3802: 		    if ($tstart) {
 3803: 			if ($tstart>$now) { $active=0; }
 3804: 		    }
 3805: 		    if ($active) { return 1; }
 3806: 		}
 3807: 	    }
 3808: 	}
 3809:     }
 3810:     return 0;
 3811: }
 3812: 
 3813: # -------------------------------------------------------- Get user privileges
 3814: 
 3815: sub rolesinit {
 3816:     my ($domain,$username,$authhost)=@_;
 3817:     my %userroles;
 3818:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3819:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3820:     my %allroles=();
 3821:     my %allgroups=();   
 3822:     my $now=time;
 3823:     %userroles = ('user.login.time' => $now);
 3824:     my $group_privs;
 3825: 
 3826:     if ($rolesdump ne '') {
 3827:         foreach my $entry (split(/&/,$rolesdump)) {
 3828: 	  if ($entry!~/^rolesdef_/) {
 3829:             my ($area,$role)=split(/=/,$entry);
 3830: 	    $area=~s/\_\w\w$//;
 3831:             my ($trole,$tend,$tstart,$group_privs);
 3832: 	    if ($role=~/^cr/) { 
 3833: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3834: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3835: 		    ($tend,$tstart)=split('_',$trest);
 3836: 		} else {
 3837: 		    $trole=$role;
 3838: 		}
 3839:             } elsif ($role =~ m|^gr/|) {
 3840:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3841:                 ($trole,$group_privs) = split(/\//,$trole);
 3842:                 $group_privs = &unescape($group_privs);
 3843: 	    } else {
 3844: 		($trole,$tend,$tstart)=split(/_/,$role);
 3845: 	    }
 3846: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3847: 					 $username);
 3848: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3849:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3850:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3851:             if (($area ne '') && ($trole ne '')) {
 3852: 		my $spec=$trole.'.'.$area;
 3853: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3854: 		if ($trole =~ /^cr\//) {
 3855:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3856:                 } elsif ($trole eq 'gr') {
 3857:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3858: 		} else {
 3859:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3860: 		}
 3861:             }
 3862:           }
 3863:         }
 3864:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3865:         $userroles{'user.adv'}    = $adv;
 3866: 	$userroles{'user.author'} = $author;
 3867:         $env{'user.adv'}=$adv;
 3868:     }
 3869:     return \%userroles;  
 3870: }
 3871: 
 3872: sub set_arearole {
 3873:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3874: # log the associated role with the area
 3875:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3876:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3877: }
 3878: 
 3879: sub custom_roleprivs {
 3880:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3881:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3882:     my $homsvr=homeserver($rauthor,$rdomain);
 3883:     if (&hostname($homsvr) ne '') {
 3884:         my ($rdummy,$roledef)=
 3885:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3886:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3887:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3888:             if (defined($syspriv)) {
 3889:                 $$allroles{'cm./'}.=':'.$syspriv;
 3890:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3891:             }
 3892:             if ($tdomain ne '') {
 3893:                 if (defined($dompriv)) {
 3894:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3895:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3896:                 }
 3897:                 if (($trest ne '') && (defined($coursepriv))) {
 3898:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3899:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3900:                 }
 3901:             }
 3902:         }
 3903:     }
 3904: }
 3905: 
 3906: sub group_roleprivs {
 3907:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3908:     my $access = 1;
 3909:     my $now = time;
 3910:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3911:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3912:     if ($access) {
 3913:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3914:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3915:     }
 3916: }
 3917: 
 3918: sub standard_roleprivs {
 3919:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3920:     if (defined($pr{$trole.':s'})) {
 3921:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3922:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3923:     }
 3924:     if ($tdomain ne '') {
 3925:         if (defined($pr{$trole.':d'})) {
 3926:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3927:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3928:         }
 3929:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3930:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3931:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3932:         }
 3933:     }
 3934: }
 3935: 
 3936: sub set_userprivs {
 3937:     my ($userroles,$allroles,$allgroups) = @_; 
 3938:     my $author=0;
 3939:     my $adv=0;
 3940:     my %grouproles = ();
 3941:     if (keys(%{$allgroups}) > 0) {
 3942:         foreach my $role (keys(%{$allroles})) {
 3943:             my ($trole,$area,$sec,$extendedarea);
 3944:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3945:                 $trole = $1;
 3946:                 $area = $2;
 3947:                 $sec = $3;
 3948:                 $extendedarea = $area.$sec;
 3949:                 if (exists($$allgroups{$area})) {
 3950:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3951:                         my $spec = $trole.'.'.$extendedarea;
 3952:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3953:                                                 $$allgroups{$area}{$group};
 3954:                     }
 3955:                 }
 3956:             }
 3957:         }
 3958:     }
 3959:     foreach my $group (keys(%grouproles)) {
 3960:         $$allroles{$group} = $grouproles{$group};
 3961:     }
 3962:     foreach my $role (keys(%{$allroles})) {
 3963:         my %thesepriv;
 3964:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3965:         foreach my $item (split(/:/,$$allroles{$role})) {
 3966:             if ($item ne '') {
 3967:                 my ($privilege,$restrictions)=split(/&/,$item);
 3968:                 if ($restrictions eq '') {
 3969:                     $thesepriv{$privilege}='F';
 3970:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3971:                     $thesepriv{$privilege}.=$restrictions;
 3972:                 }
 3973:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3974:             }
 3975:         }
 3976:         my $thesestr='';
 3977:         foreach my $priv (keys(%thesepriv)) {
 3978: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3979: 	}
 3980:         $userroles->{'user.priv.'.$role} = $thesestr;
 3981:     }
 3982:     return ($author,$adv);
 3983: }
 3984: 
 3985: sub role_status {
 3986:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 3987:     my @pwhere = ();
 3988:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 3989:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 3990:         unless (!defined($$role) || $$role eq '') {
 3991:             $$where=join('.',@pwhere);
 3992:             $$trolecode=$$role.'.'.$$where;
 3993:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 3994:             $$tstatus='is';
 3995:             if ($$tstart && $$tstart>$then) {
 3996:                 $$tstatus='future';
 3997:                 if ($$tstart && $$tstart>$refresh) {
 3998:                     if ($$tstart<$now) {
 3999:                         if (($$where ne '') && ($$role ne '')) {
 4000:                             my (%allroles,%allgroups,$group_privs);
 4001:                             my %userroles = (
 4002:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4003:                             );
 4004:                             my $spec=$$role.'.'.$$where;
 4005:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4006:                             if ($$role eq 'gr') {
 4007:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4008:                                                     $env{'user.name'})=@_;
 4009:                                 my ($trole) = split('_',$role,1);
 4010:                                 (undef,my $group_privs) = split(/\//,$trole);
 4011:                                 $group_privs = &unescape($group_privs);
 4012:                             }
 4013:                             if ($$role =~ /^cr\//) {
 4014:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4015:                             } elsif ($$role eq 'gr') {
 4016:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4017:                                                     $env{'user.name'});
 4018:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 4019:                                 (undef,my $group_privs) = split(/\//,$trole);
 4020:                                 $group_privs = &unescape($group_privs);
 4021:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4022:                             } else {
 4023:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4024:                             }
 4025:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4026:                             &appenv(\%userroles,[$$role,'cm']);
 4027:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4028:                             $$tstatus = 'is';
 4029:                         }
 4030:                     }
 4031:                 }
 4032:             }
 4033:             if ($$tend) {
 4034:                 if ($$tend<$then) {
 4035:                     $$tstatus='expired';
 4036:                 } elsif ($$tend<$now) {
 4037:                     $$tstatus='will_not';
 4038:                 }
 4039:             }
 4040:         }
 4041:     }
 4042: }
 4043: 
 4044: sub check_adhoc_privs {
 4045:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 4046:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4047:     if ($env{$cckey}) {
 4048:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4049:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4050:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4051:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4052:         }
 4053:     } else {
 4054:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4055:     }
 4056: }
 4057: 
 4058: sub set_adhoc_privileges {
 4059: # role can be cc or ca
 4060:     my ($dcdom,$pickedcourse,$role) = @_;
 4061:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4062:     my $spec = $role.'.'.$area;
 4063:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4064:                                   $env{'user.name'});
 4065:     my %ccrole = ();
 4066:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4067:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4068:     &appenv(\%userroles,[$role,'cm']);
 4069:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4070:     &appenv( {'request.role'        => $spec,
 4071:               'request.role.domain' => $dcdom,
 4072:               'request.course.sec'  => ''
 4073:              }
 4074:            );
 4075:     my $tadv=0;
 4076:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4077:     &appenv({'request.role.adv'    => $tadv});
 4078: }
 4079: 
 4080: # --------------------------------------------------------------- get interface
 4081: 
 4082: sub get {
 4083:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4084:    my $items='';
 4085:    foreach my $item (@$storearr) {
 4086:        $items.=&escape($item).'&';
 4087:    }
 4088:    $items=~s/\&$//;
 4089:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4090:    if (!$uname) { $uname=$env{'user.name'}; }
 4091:    my $uhome=&homeserver($uname,$udomain);
 4092: 
 4093:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4094:    my @pairs=split(/\&/,$rep);
 4095:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4096:      return @pairs;
 4097:    }
 4098:    my %returnhash=();
 4099:    my $i=0;
 4100:    foreach my $item (@$storearr) {
 4101:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4102:       $i++;
 4103:    }
 4104:    return %returnhash;
 4105: }
 4106: 
 4107: # --------------------------------------------------------------- del interface
 4108: 
 4109: sub del {
 4110:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4111:    my $items='';
 4112:    foreach my $item (@$storearr) {
 4113:        $items.=&escape($item).'&';
 4114:    }
 4115: 
 4116:    $items=~s/\&$//;
 4117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4118:    if (!$uname) { $uname=$env{'user.name'}; }
 4119:    my $uhome=&homeserver($uname,$udomain);
 4120:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4121: }
 4122: 
 4123: # -------------------------------------------------------------- dump interface
 4124: 
 4125: sub dump {
 4126:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4127:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4128:     if (!$uname) { $uname=$env{'user.name'}; }
 4129:     my $uhome=&homeserver($uname,$udomain);
 4130:     if ($regexp) {
 4131: 	$regexp=&escape($regexp);
 4132:     } else {
 4133: 	$regexp='.';
 4134:     }
 4135:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4136:     my @pairs=split(/\&/,$rep);
 4137:     my %returnhash=();
 4138:     foreach my $item (@pairs) {
 4139: 	my ($key,$value)=split(/=/,$item,2);
 4140: 	$key = &unescape($key);
 4141: 	next if ($key =~ /^error: 2 /);
 4142: 	$returnhash{$key}=&thaw_unescape($value);
 4143:     }
 4144:     return %returnhash;
 4145: }
 4146: 
 4147: # --------------------------------------------------------- dumpstore interface
 4148: 
 4149: sub dumpstore {
 4150:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4151:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4152:    if (!$uname) { $uname=$env{'user.name'}; }
 4153:    my $uhome=&homeserver($uname,$udomain);
 4154:    if ($regexp) {
 4155:        $regexp=&escape($regexp);
 4156:    } else {
 4157:        $regexp='.';
 4158:    }
 4159:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4160:    my @pairs=split(/\&/,$rep);
 4161:    my %returnhash=();
 4162:    foreach my $item (@pairs) {
 4163:        my ($key,$value)=split(/=/,$item,2);
 4164:        next if ($key =~ /^error: 2 /);
 4165:        $returnhash{$key}=&thaw_unescape($value);
 4166:    }
 4167:    return %returnhash;
 4168: }
 4169: 
 4170: # -------------------------------------------------------------- keys interface
 4171: 
 4172: sub getkeys {
 4173:    my ($namespace,$udomain,$uname)=@_;
 4174:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4175:    if (!$uname) { $uname=$env{'user.name'}; }
 4176:    my $uhome=&homeserver($uname,$udomain);
 4177:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4178:    my @keyarray=();
 4179:    foreach my $key (split(/\&/,$rep)) {
 4180:       next if ($key =~ /^error: 2 /);
 4181:       push(@keyarray,&unescape($key));
 4182:    }
 4183:    return @keyarray;
 4184: }
 4185: 
 4186: # --------------------------------------------------------------- currentdump
 4187: sub currentdump {
 4188:    my ($courseid,$sdom,$sname)=@_;
 4189:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4190:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4191:    $sname    = $env{'user.name'}         if (! defined($sname));
 4192:    my $uhome = &homeserver($sname,$sdom);
 4193:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4194:    return if ($rep =~ /^(error:|no_such_host)/);
 4195:    #
 4196:    my %returnhash=();
 4197:    #
 4198:    if ($rep eq "unknown_cmd") { 
 4199:        # an old lond will not know currentdump
 4200:        # Do a dump and make it look like a currentdump
 4201:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4202:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4203:        my %hash = @tmp;
 4204:        @tmp=();
 4205:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4206:    } else {
 4207:        my @pairs=split(/\&/,$rep);
 4208:        foreach my $pair (@pairs) {
 4209:            my ($key,$value)=split(/=/,$pair,2);
 4210:            my ($symb,$param) = split(/:/,$key);
 4211:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4212:                                                         &thaw_unescape($value);
 4213:        }
 4214:    }
 4215:    return %returnhash;
 4216: }
 4217: 
 4218: sub convert_dump_to_currentdump{
 4219:     my %hash = %{shift()};
 4220:     my %returnhash;
 4221:     # Code ripped from lond, essentially.  The only difference
 4222:     # here is the unescaping done by lonnet::dump().  Conceivably
 4223:     # we might run in to problems with parameter names =~ /^v\./
 4224:     while (my ($key,$value) = each(%hash)) {
 4225:         my ($v,$symb,$param) = split(/:/,$key);
 4226: 	$symb  = &unescape($symb);
 4227: 	$param = &unescape($param);
 4228:         next if ($v eq 'version' || $symb eq 'keys');
 4229:         next if (exists($returnhash{$symb}) &&
 4230:                  exists($returnhash{$symb}->{$param}) &&
 4231:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4232:         $returnhash{$symb}->{$param}=$value;
 4233:         $returnhash{$symb}->{'v.'.$param}=$v;
 4234:     }
 4235:     #
 4236:     # Remove all of the keys in the hashes which keep track of
 4237:     # the version of the parameter.
 4238:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4239:         # use a foreach because we are going to delete from the hash.
 4240:         foreach my $key (keys(%$param_hash)) {
 4241:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4242:         }
 4243:     }
 4244:     return \%returnhash;
 4245: }
 4246: 
 4247: # ------------------------------------------------------ critical inc interface
 4248: 
 4249: sub cinc {
 4250:     return &inc(@_,'critical');
 4251: }
 4252: 
 4253: # --------------------------------------------------------------- inc interface
 4254: 
 4255: sub inc {
 4256:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4257:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4258:     if (!$uname) { $uname=$env{'user.name'}; }
 4259:     my $uhome=&homeserver($uname,$udomain);
 4260:     my $items='';
 4261:     if (! ref($store)) {
 4262:         # got a single value, so use that instead
 4263:         $items = &escape($store).'=&';
 4264:     } elsif (ref($store) eq 'SCALAR') {
 4265:         $items = &escape($$store).'=&';        
 4266:     } elsif (ref($store) eq 'ARRAY') {
 4267:         $items = join('=&',map {&escape($_);} @{$store});
 4268:     } elsif (ref($store) eq 'HASH') {
 4269:         while (my($key,$value) = each(%{$store})) {
 4270:             $items.= &escape($key).'='.&escape($value).'&';
 4271:         }
 4272:     }
 4273:     $items=~s/\&$//;
 4274:     if ($critical) {
 4275: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4276:     } else {
 4277: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4278:     }
 4279: }
 4280: 
 4281: # --------------------------------------------------------------- put interface
 4282: 
 4283: sub put {
 4284:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4285:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4286:    if (!$uname) { $uname=$env{'user.name'}; }
 4287:    my $uhome=&homeserver($uname,$udomain);
 4288:    my $items='';
 4289:    foreach my $item (keys(%$storehash)) {
 4290:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4291:    }
 4292:    $items=~s/\&$//;
 4293:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4294: }
 4295: 
 4296: # ------------------------------------------------------------ newput interface
 4297: 
 4298: sub newput {
 4299:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4300:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4301:    if (!$uname) { $uname=$env{'user.name'}; }
 4302:    my $uhome=&homeserver($uname,$udomain);
 4303:    my $items='';
 4304:    foreach my $key (keys(%$storehash)) {
 4305:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4306:    }
 4307:    $items=~s/\&$//;
 4308:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4309: }
 4310: 
 4311: # ---------------------------------------------------------  putstore interface
 4312: 
 4313: sub putstore {
 4314:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4315:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4316:    if (!$uname) { $uname=$env{'user.name'}; }
 4317:    my $uhome=&homeserver($uname,$udomain);
 4318:    my $items='';
 4319:    foreach my $key (keys(%$storehash)) {
 4320:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4321:    }
 4322:    $items=~s/\&$//;
 4323:    my $esc_symb=&escape($symb);
 4324:    my $esc_v=&escape($version);
 4325:    my $reply =
 4326:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4327: 	      $uhome);
 4328:    if ($reply eq 'unknown_cmd') {
 4329:        # gfall back to way things use to be done
 4330:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4331: 			    $uname);
 4332:    }
 4333:    return $reply;
 4334: }
 4335: 
 4336: sub old_putstore {
 4337:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4338:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4339:     if (!$uname) { $uname=$env{'user.name'}; }
 4340:     my $uhome=&homeserver($uname,$udomain);
 4341:     my %newstorehash;
 4342:     foreach my $item (keys(%$storehash)) {
 4343: 	my $key = $version.':'.&escape($symb).':'.$item;
 4344: 	$newstorehash{$key} = $storehash->{$item};
 4345:     }
 4346:     my $items='';
 4347:     my %allitems = ();
 4348:     foreach my $item (keys(%newstorehash)) {
 4349: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4350: 	    my $key = $1.':keys:'.$2;
 4351: 	    $allitems{$key} .= $3.':';
 4352: 	}
 4353: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4354:     }
 4355:     foreach my $item (keys(%allitems)) {
 4356: 	$allitems{$item} =~ s/\:$//;
 4357: 	$items.= $item.'='.$allitems{$item}.'&';
 4358:     }
 4359:     $items=~s/\&$//;
 4360:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4361: }
 4362: 
 4363: # ------------------------------------------------------ critical put interface
 4364: 
 4365: sub cput {
 4366:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4367:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4368:    if (!$uname) { $uname=$env{'user.name'}; }
 4369:    my $uhome=&homeserver($uname,$udomain);
 4370:    my $items='';
 4371:    foreach my $item (keys(%$storehash)) {
 4372:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4373:    }
 4374:    $items=~s/\&$//;
 4375:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4376: }
 4377: 
 4378: # -------------------------------------------------------------- eget interface
 4379: 
 4380: sub eget {
 4381:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4382:    my $items='';
 4383:    foreach my $item (@$storearr) {
 4384:        $items.=&escape($item).'&';
 4385:    }
 4386:    $items=~s/\&$//;
 4387:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4388:    if (!$uname) { $uname=$env{'user.name'}; }
 4389:    my $uhome=&homeserver($uname,$udomain);
 4390:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4391:    my @pairs=split(/\&/,$rep);
 4392:    my %returnhash=();
 4393:    my $i=0;
 4394:    foreach my $item (@$storearr) {
 4395:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4396:       $i++;
 4397:    }
 4398:    return %returnhash;
 4399: }
 4400: 
 4401: # ------------------------------------------------------------ tmpput interface
 4402: sub tmpput {
 4403:     my ($storehash,$server,$context)=@_;
 4404:     my $items='';
 4405:     foreach my $item (keys(%$storehash)) {
 4406: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4407:     }
 4408:     $items=~s/\&$//;
 4409:     if (defined($context)) {
 4410:         $items .= ':'.&escape($context);
 4411:     }
 4412:     return &reply("tmpput:$items",$server);
 4413: }
 4414: 
 4415: # ------------------------------------------------------------ tmpget interface
 4416: sub tmpget {
 4417:     my ($token,$server)=@_;
 4418:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4419:     my $rep=&reply("tmpget:$token",$server);
 4420:     my %returnhash;
 4421:     foreach my $item (split(/\&/,$rep)) {
 4422: 	my ($key,$value)=split(/=/,$item);
 4423:         next if ($key =~ /^error: 2 /);
 4424: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4425:     }
 4426:     return %returnhash;
 4427: }
 4428: 
 4429: # ------------------------------------------------------------ tmpget interface
 4430: sub tmpdel {
 4431:     my ($token,$server)=@_;
 4432:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4433:     return &reply("tmpdel:$token",$server);
 4434: }
 4435: 
 4436: # -------------------------------------------------- portfolio access checking
 4437: 
 4438: sub portfolio_access {
 4439:     my ($requrl) = @_;
 4440:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4441:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4442:     if ($result) {
 4443:         my %setters;
 4444:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4445:             my ($startblock,$endblock) =
 4446:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4447:             if ($startblock && $endblock) {
 4448:                 return 'B';
 4449:             }
 4450:         } else {
 4451:             my ($startblock,$endblock) =
 4452:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4453:             if ($startblock && $endblock) {
 4454:                 return 'B';
 4455:             }
 4456:         }
 4457:     }
 4458:     if ($result eq 'ok') {
 4459:        return 'F';
 4460:     } elsif ($result =~ /^[^:]+:guest_/) {
 4461:        return 'A';
 4462:     }
 4463:     return '';
 4464: }
 4465: 
 4466: sub get_portfolio_access {
 4467:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4468: 
 4469:     if (!ref($access_hash)) {
 4470: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4471: 	my %access_controls = &get_access_controls($current_perms,$group,
 4472: 						   $file_name);
 4473: 	$access_hash = $access_controls{$file_name};
 4474:     }
 4475: 
 4476:     my ($public,$guest,@domains,@users,@courses,@groups);
 4477:     my $now = time;
 4478:     if (ref($access_hash) eq 'HASH') {
 4479:         foreach my $key (keys(%{$access_hash})) {
 4480:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4481:             if ($start > $now) {
 4482:                 next;
 4483:             }
 4484:             if ($end && $end<$now) {
 4485:                 next;
 4486:             }
 4487:             if ($scope eq 'public') {
 4488:                 $public = $key;
 4489:                 last;
 4490:             } elsif ($scope eq 'guest') {
 4491:                 $guest = $key;
 4492:             } elsif ($scope eq 'domains') {
 4493:                 push(@domains,$key);
 4494:             } elsif ($scope eq 'users') {
 4495:                 push(@users,$key);
 4496:             } elsif ($scope eq 'course') {
 4497:                 push(@courses,$key);
 4498:             } elsif ($scope eq 'group') {
 4499:                 push(@groups,$key);
 4500:             }
 4501:         }
 4502:         if ($public) {
 4503:             return 'ok';
 4504:         }
 4505:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4506:             if ($guest) {
 4507:                 return $guest;
 4508:             }
 4509:         } else {
 4510:             if (@domains > 0) {
 4511:                 foreach my $domkey (@domains) {
 4512:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4513:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4514:                             return 'ok';
 4515:                         }
 4516:                     }
 4517:                 }
 4518:             }
 4519:             if (@users > 0) {
 4520:                 foreach my $userkey (@users) {
 4521:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4522:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4523:                             if (ref($item) eq 'HASH') {
 4524:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4525:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4526:                                     return 'ok';
 4527:                                 }
 4528:                             }
 4529:                         }
 4530:                     } 
 4531:                 }
 4532:             }
 4533:             my %roleshash;
 4534:             my @courses_and_groups = @courses;
 4535:             push(@courses_and_groups,@groups); 
 4536:             if (@courses_and_groups > 0) {
 4537:                 my (%allgroups,%allroles); 
 4538:                 my ($start,$end,$role,$sec,$group);
 4539:                 foreach my $envkey (%env) {
 4540:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4541:                         my $cid = $2.'_'.$3; 
 4542:                         if ($1 eq 'gr') {
 4543:                             $group = $4;
 4544:                             $allgroups{$cid}{$group} = $env{$envkey};
 4545:                         } else {
 4546:                             if ($4 eq '') {
 4547:                                 $sec = 'none';
 4548:                             } else {
 4549:                                 $sec = $4;
 4550:                             }
 4551:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4552:                         }
 4553:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4554:                         my $cid = $2.'_'.$3;
 4555:                         if ($4 eq '') {
 4556:                             $sec = 'none';
 4557:                         } else {
 4558:                             $sec = $4;
 4559:                         }
 4560:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4561:                     }
 4562:                 }
 4563:                 if (keys(%allroles) == 0) {
 4564:                     return;
 4565:                 }
 4566:                 foreach my $key (@courses_and_groups) {
 4567:                     my %content = %{$$access_hash{$key}};
 4568:                     my $cnum = $content{'number'};
 4569:                     my $cdom = $content{'domain'};
 4570:                     my $cid = $cdom.'_'.$cnum;
 4571:                     if (!exists($allroles{$cid})) {
 4572:                         next;
 4573:                     }    
 4574:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4575:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4576:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4577:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4578:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4579:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4580:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4581:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4582:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4583:                                         if (grep/^all$/,@sections) {
 4584:                                             return 'ok';
 4585:                                         } else {
 4586:                                             if (grep/^$sec$/,@sections) {
 4587:                                                 return 'ok';
 4588:                                             }
 4589:                                         }
 4590:                                     }
 4591:                                 }
 4592:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4593:                                     if (grep/^none$/,@groups) {
 4594:                                         return 'ok';
 4595:                                     }
 4596:                                 } else {
 4597:                                     if (grep/^all$/,@groups) {
 4598:                                         return 'ok';
 4599:                                     } 
 4600:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4601:                                         if (grep/^$group$/,@groups) {
 4602:                                             return 'ok';
 4603:                                         }
 4604:                                     }
 4605:                                 } 
 4606:                             }
 4607:                         }
 4608:                     }
 4609:                 }
 4610:             }
 4611:             if ($guest) {
 4612:                 return $guest;
 4613:             }
 4614:         }
 4615:     }
 4616:     return;
 4617: }
 4618: 
 4619: sub course_group_datechecker {
 4620:     my ($dates,$now,$status) = @_;
 4621:     my ($start,$end) = split(/\./,$dates);
 4622:     if (!$start && !$end) {
 4623:         return 'ok';
 4624:     }
 4625:     if (grep/^active$/,@{$status}) {
 4626:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4627:             return 'ok';
 4628:         }
 4629:     }
 4630:     if (grep/^previous$/,@{$status}) {
 4631:         if ($end > $now ) {
 4632:             return 'ok';
 4633:         }
 4634:     }
 4635:     if (grep/^future$/,@{$status}) {
 4636:         if ($start > $now) {
 4637:             return 'ok';
 4638:         }
 4639:     }
 4640:     return; 
 4641: }
 4642: 
 4643: sub parse_portfolio_url {
 4644:     my ($url) = @_;
 4645: 
 4646:     my ($type,$udom,$unum,$group,$file_name);
 4647:     
 4648:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4649: 	$type = 1;
 4650:         $udom = $1;
 4651:         $unum = $2;
 4652:         $file_name = $3;
 4653:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4654: 	$type = 2;
 4655:         $udom = $1;
 4656:         $unum = $2;
 4657:         $group = $3;
 4658:         $file_name = $3.'/'.$4;
 4659:     }
 4660:     if (wantarray) {
 4661: 	return ($type,$udom,$unum,$file_name,$group);
 4662:     }
 4663:     return $type;
 4664: }
 4665: 
 4666: sub is_portfolio_url {
 4667:     my ($url) = @_;
 4668:     return scalar(&parse_portfolio_url($url));
 4669: }
 4670: 
 4671: sub is_portfolio_file {
 4672:     my ($file) = @_;
 4673:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4674:         return 1;
 4675:     }
 4676:     return;
 4677: }
 4678: 
 4679: sub usertools_access {
 4680:     my ($uname,$udom,$tool,$action,$context) = @_;
 4681:     my ($access,%tools);
 4682:     if ($context eq '') {
 4683:         $context = 'tools';
 4684:     }
 4685:     if ($context eq 'requestcourses') {
 4686:         %tools = (
 4687:                       official   => 1,
 4688:                       unofficial => 1,
 4689:                       community  => 1,
 4690:                  );
 4691:     } else {
 4692:         %tools = (
 4693:                       aboutme   => 1,
 4694:                       blog      => 1,
 4695:                       portfolio => 1,
 4696:                  );
 4697:     }
 4698:     return if (!defined($tools{$tool}));
 4699: 
 4700:     if ((!defined($udom)) || (!defined($uname))) {
 4701:         $udom = $env{'user.domain'};
 4702:         $uname = $env{'user.name'};
 4703:     }
 4704: 
 4705:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4706:         if ($action ne 'reload') {
 4707:             if ($context eq 'requestcourses') {
 4708:                 return $env{'environment.canrequest.'.$tool};
 4709:             } else {
 4710:                 return $env{'environment.availabletools.'.$tool};
 4711:             }
 4712:         }
 4713:     }
 4714: 
 4715:     my ($toolstatus,$inststatus);
 4716: 
 4717:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4718:          ($action ne 'reload')) {
 4719:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4720:         $inststatus = $env{'environment.inststatus'};
 4721:     } else {
 4722:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4723:         $toolstatus = $userenv{$context.'.'.$tool};
 4724:         $inststatus = $userenv{'inststatus'};
 4725:     }
 4726: 
 4727:     if ($toolstatus ne '') {
 4728:         if ($toolstatus) {
 4729:             $access = 1;
 4730:         } else {
 4731:             $access = 0;
 4732:         }
 4733:         return $access;
 4734:     }
 4735: 
 4736:     my $is_adv = &is_advanced_user($udom,$uname);
 4737:     my %domdef = &get_domain_defaults($udom);
 4738:     if (ref($domdef{$tool}) eq 'HASH') {
 4739:         if ($is_adv) {
 4740:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4741:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4742:                     $access = 1;
 4743:                 } else {
 4744:                     $access = 0;
 4745:                 }
 4746:                 return $access;
 4747:             }
 4748:         }
 4749:         if ($inststatus ne '') {
 4750:             my ($hasaccess,$hasnoaccess);
 4751:             foreach my $affiliation (split(/:/,$inststatus)) {
 4752:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4753:                     if ($domdef{$tool}{$affiliation}) {
 4754:                         $hasaccess = 1;
 4755:                     } else {
 4756:                         $hasnoaccess = 1;
 4757:                     }
 4758:                 }
 4759:             }
 4760:             if ($hasaccess || $hasnoaccess) {
 4761:                 if ($hasaccess) {
 4762:                     $access = 1;
 4763:                 } elsif ($hasnoaccess) {
 4764:                     $access = 0; 
 4765:                 }
 4766:                 return $access;
 4767:             }
 4768:         } else {
 4769:             if ($domdef{$tool}{'default'} ne '') {
 4770:                 if ($domdef{$tool}{'default'}) {
 4771:                     $access = 1;
 4772:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4773:                     $access = 0;
 4774:                 }
 4775:                 return $access;
 4776:             }
 4777:         }
 4778:     } else {
 4779:         if ($context eq 'tools') {
 4780:             $access = 1;
 4781:         } else {
 4782:             $access = 0;
 4783:         }
 4784:         return $access;
 4785:     }
 4786: }
 4787: 
 4788: sub is_advanced_user {
 4789:     my ($udom,$uname) = @_;
 4790:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4791:     my %allroles;
 4792:     my $is_adv;
 4793:     foreach my $role (keys(%roleshash)) {
 4794:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4795:         my $area = '/'.$tdomain.'/'.$trest;
 4796:         if ($sec ne '') {
 4797:             $area .= '/'.$sec;
 4798:         }
 4799:         if (($area ne '') && ($trole ne '')) {
 4800:             my $spec=$trole.'.'.$area;
 4801:             if ($trole =~ /^cr\//) {
 4802:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4803:             } elsif ($trole ne 'gr') {
 4804:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4805:             }
 4806:         }
 4807:     }
 4808:     foreach my $role (keys(%allroles)) {
 4809:         last if ($is_adv);
 4810:         foreach my $item (split(/:/,$allroles{$role})) {
 4811:             if ($item ne '') {
 4812:                 my ($privilege,$restrictions)=split(/&/,$item);
 4813:                 if ($privilege eq 'adv') {
 4814:                     $is_adv = 1;
 4815:                     last;
 4816:                 }
 4817:             }
 4818:         }
 4819:     }
 4820:     return $is_adv;
 4821: }
 4822: 
 4823: # ---------------------------------------------- Custom access rule evaluation
 4824: 
 4825: sub customaccess {
 4826:     my ($priv,$uri)=@_;
 4827:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4828:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4829:     $udom = &LONCAPA::clean_domain($udom);
 4830:     $ucrs = &LONCAPA::clean_username($ucrs);
 4831:     my $access=0;
 4832:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4833: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4834: 	if ($type eq 'user') {
 4835: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4836: 		my ($tdom,$tuname)=split(m{/},$scope);
 4837: 		if ($tdom) {
 4838: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4839: 		}
 4840: 		if ($tuname) {
 4841: 		    if ($tuname ne $env{'user.name'}) { next; }
 4842: 		}
 4843: 		$access=($effect eq 'allow');
 4844: 		last;
 4845: 	    }
 4846: 	} else {
 4847: 	    if ($role) {
 4848: 		if ($role ne $urole) { next; }
 4849: 	    }
 4850: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4851: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4852: 		if ($tdom) {
 4853: 		    if ($tdom ne $udom) { next; }
 4854: 		}
 4855: 		if ($tcrs) {
 4856: 		    if ($tcrs ne $ucrs) { next; }
 4857: 		}
 4858: 		if ($tsec) {
 4859: 		    if ($tsec ne $usec) { next; }
 4860: 		}
 4861: 		$access=($effect eq 'allow');
 4862: 		last;
 4863: 	    }
 4864: 	    if ($realm eq '' && $role eq '') {
 4865: 		$access=($effect eq 'allow');
 4866: 	    }
 4867: 	}
 4868:     }
 4869:     return $access;
 4870: }
 4871: 
 4872: # ------------------------------------------------- Check for a user privilege
 4873: 
 4874: sub allowed {
 4875:     my ($priv,$uri,$symb,$role)=@_;
 4876:     my $ver_orguri=$uri;
 4877:     $uri=&deversion($uri);
 4878:     my $orguri=$uri;
 4879:     $uri=&declutter($uri);
 4880: 
 4881:     if ($priv eq 'evb') {
 4882: # Evade communication block restrictions for specified role in a course
 4883:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4884:             return $1;
 4885:         } else {
 4886:             return;
 4887:         }
 4888:     }
 4889: 
 4890:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4891: # Free bre access to adm and meta resources
 4892:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4893: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4894: 	&& ($priv eq 'bre')) {
 4895: 	return 'F';
 4896:     }
 4897: 
 4898: # Free bre access to user's own portfolio contents
 4899:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4900:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4901: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4902:         my %setters;
 4903:         my ($startblock,$endblock) = 
 4904:             &Apache::loncommon::blockcheck(\%setters,'port');
 4905:         if ($startblock && $endblock) {
 4906:             return 'B';
 4907:         } else {
 4908:             return 'F';
 4909:         }
 4910:     }
 4911: 
 4912: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4913:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4914:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4915:         if (exists($env{'request.course.id'})) {
 4916:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4917:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4918:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4919:                 my $courseprivid=$env{'request.course.id'};
 4920:                 $courseprivid=~s/\_/\//;
 4921:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4922:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4923:                     return $1; 
 4924:                 } else {
 4925:                     if ($env{'request.course.sec'}) {
 4926:                         $courseprivid.='/'.$env{'request.course.sec'};
 4927:                     }
 4928:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4929:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4930:                         return $2;
 4931:                     }
 4932:                 }
 4933:             }
 4934:         }
 4935:     }
 4936: 
 4937: # Free bre to public access
 4938: 
 4939:     if ($priv eq 'bre') {
 4940:         my $copyright=&metadata($uri,'copyright');
 4941: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4942:            return 'F'; 
 4943:         }
 4944:         if ($copyright eq 'priv') {
 4945:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4946: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4947: 		return '';
 4948:             }
 4949:         }
 4950:         if ($copyright eq 'domain') {
 4951:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4952: 	    unless (($env{'user.domain'} eq $1) ||
 4953:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4954: 		return '';
 4955:             }
 4956:         }
 4957:         if ($env{'request.role'}=~ /li\.\//) {
 4958:             # Library role, so allow browsing of resources in this domain.
 4959:             return 'F';
 4960:         }
 4961:         if ($copyright eq 'custom') {
 4962: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4963:         }
 4964:     }
 4965:     # Domain coordinator is trying to create a course
 4966:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4967:         # uri is the requested domain in this case.
 4968:         # comparison to 'request.role.domain' shows if the user has selected
 4969:         # a role of dc for the domain in question.
 4970:         return 'F' if ($uri eq $env{'request.role.domain'});
 4971:     }
 4972: 
 4973:     my $thisallowed='';
 4974:     my $statecond=0;
 4975:     my $courseprivid='';
 4976: 
 4977: # Course
 4978: 
 4979:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4980:        $thisallowed.=$1;
 4981:     }
 4982: 
 4983: # Domain
 4984: 
 4985:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4986:        =~/\Q$priv\E\&([^\:]*)/) {
 4987:        $thisallowed.=$1;
 4988:     }
 4989: 
 4990: # Course: uri itself is a course
 4991:     my $courseuri=$uri;
 4992:     $courseuri=~s/\_(\d)/\/$1/;
 4993:     $courseuri=~s/^([^\/])/\/$1/;
 4994: 
 4995:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4996:        =~/\Q$priv\E\&([^\:]*)/) {
 4997:        $thisallowed.=$1;
 4998:     }
 4999: 
 5000: # URI is an uploaded document for this course, default permissions don't matter
 5001: # not allowing 'edit' access (editupload) to uploaded course docs
 5002:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5003: 	$thisallowed='';
 5004:         my ($match)=&is_on_map($uri);
 5005:         if ($match) {
 5006:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5007:                   =~/\Q$priv\E\&([^\:]*)/) {
 5008:                 $thisallowed.=$1;
 5009:             }
 5010:         } else {
 5011:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5012:             if ($refuri) {
 5013:                 if ($refuri =~ m|^/adm/|) {
 5014:                     $thisallowed='F';
 5015:                 } else {
 5016:                     $refuri=&declutter($refuri);
 5017:                     my ($match) = &is_on_map($refuri);
 5018:                     if ($match) {
 5019:                         $thisallowed='F';
 5020:                     }
 5021:                 }
 5022:             }
 5023:         }
 5024:     }
 5025: 
 5026:     if ($priv eq 'bre'
 5027: 	&& $thisallowed ne 'F' 
 5028: 	&& $thisallowed ne '2'
 5029: 	&& &is_portfolio_url($uri)) {
 5030: 	$thisallowed = &portfolio_access($uri);
 5031:     }
 5032:     
 5033: # Full access at system, domain or course-wide level? Exit.
 5034:     if ($thisallowed=~/F/) {
 5035: 	return 'F';
 5036:     }
 5037: 
 5038: # If this is generating or modifying users, exit with special codes
 5039: 
 5040:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5041: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5042: 	    my ($audom,$auname)=split('/',$uri);
 5043: # no author name given, so this just checks on the general right to make a co-author in this domain
 5044: 	    unless ($auname) { return $thisallowed; }
 5045: # an author name is given, so we are about to actually make a co-author for a certain account
 5046: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5047: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5048: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5049: 	}
 5050: 	return $thisallowed;
 5051:     }
 5052: #
 5053: # Gathered so far: system, domain and course wide privileges
 5054: #
 5055: # Course: See if uri or referer is an individual resource that is part of 
 5056: # the course
 5057: 
 5058:     if ($env{'request.course.id'}) {
 5059: 
 5060:        $courseprivid=$env{'request.course.id'};
 5061:        if ($env{'request.course.sec'}) {
 5062:           $courseprivid.='/'.$env{'request.course.sec'};
 5063:        }
 5064:        $courseprivid=~s/\_/\//;
 5065:        my $checkreferer=1;
 5066:        my ($match,$cond)=&is_on_map($uri);
 5067:        if ($match) {
 5068:            $statecond=$cond;
 5069:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5070:                =~/\Q$priv\E\&([^\:]*)/) {
 5071:                $thisallowed.=$1;
 5072:                $checkreferer=0;
 5073:            }
 5074:        }
 5075:        
 5076:        if ($checkreferer) {
 5077: 	  my $refuri=$env{'httpref.'.$orguri};
 5078:             unless ($refuri) {
 5079:                 foreach my $key (keys(%env)) {
 5080: 		    if ($key=~/^httpref\..*\*/) {
 5081: 			my $pattern=$key;
 5082:                         $pattern=~s/^httpref\.\/res\///;
 5083:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5084:                         $pattern=~s/\//\\\//g;
 5085:                         if ($orguri=~/$pattern/) {
 5086: 			    $refuri=$env{$key};
 5087:                         }
 5088:                     }
 5089:                 }
 5090:             }
 5091: 
 5092:          if ($refuri) { 
 5093: 	  $refuri=&declutter($refuri);
 5094:           my ($match,$cond)=&is_on_map($refuri);
 5095:             if ($match) {
 5096:               my $refstatecond=$cond;
 5097:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5098:                   =~/\Q$priv\E\&([^\:]*)/) {
 5099:                   $thisallowed.=$1;
 5100:                   $uri=$refuri;
 5101:                   $statecond=$refstatecond;
 5102:               }
 5103:           }
 5104:         }
 5105:        }
 5106:    }
 5107: 
 5108: #
 5109: # Gathered now: all privileges that could apply, and condition number
 5110: # 
 5111: #
 5112: # Full or no access?
 5113: #
 5114: 
 5115:     if ($thisallowed=~/F/) {
 5116: 	return 'F';
 5117:     }
 5118: 
 5119:     unless ($thisallowed) {
 5120:         return '';
 5121:     }
 5122: 
 5123: # Restrictions exist, deal with them
 5124: #
 5125: #   C:according to course preferences
 5126: #   R:according to resource settings
 5127: #   L:unless locked
 5128: #   X:according to user session state
 5129: #
 5130: 
 5131: # Possibly locked functionality, check all courses
 5132: # Locks might take effect only after 10 minutes cache expiration for other
 5133: # courses, and 2 minutes for current course
 5134: 
 5135:     my $envkey;
 5136:     if ($thisallowed=~/L/) {
 5137:         foreach $envkey (keys(%env)) {
 5138:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5139:                my $courseid=$2;
 5140:                my $roleid=$1.'.'.$2;
 5141:                $courseid=~s/^\///;
 5142:                my $expiretime=600;
 5143:                if ($env{'request.role'} eq $roleid) {
 5144: 		  $expiretime=120;
 5145:                }
 5146: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5147:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5148:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5149: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5150:                }
 5151:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5152:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5153: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5154:                        &log($env{'user.domain'},$env{'user.name'},
 5155:                             $env{'user.home'},
 5156:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5157:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5158:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5159: 		       return '';
 5160:                    }
 5161:                }
 5162:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5163:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5164: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5165:                        &log($env{'user.domain'},$env{'user.name'},
 5166:                             $env{'user.home'},
 5167:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5168:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5169:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5170: 		       return '';
 5171:                    }
 5172:                }
 5173: 	   }
 5174:        }
 5175:     }
 5176:    
 5177: #
 5178: # Rest of the restrictions depend on selected course
 5179: #
 5180: 
 5181:     unless ($env{'request.course.id'}) {
 5182: 	if ($thisallowed eq 'A') {
 5183: 	    return 'A';
 5184:         } elsif ($thisallowed eq 'B') {
 5185:             return 'B';
 5186: 	} else {
 5187: 	    return '1';
 5188: 	}
 5189:     }
 5190: 
 5191: #
 5192: # Now user is definitely in a course
 5193: #
 5194: 
 5195: 
 5196: # Course preferences
 5197: 
 5198:    if ($thisallowed=~/C/) {
 5199:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5200:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5201:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5202: 	   =~/\Q$rolecode\E/) {
 5203: 	   if ($priv ne 'pch') { 
 5204: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5205: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5206: 			$env{'request.course.id'});
 5207: 	   }
 5208:            return '';
 5209:        }
 5210: 
 5211:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5212: 	   =~/\Q$unamedom\E/) {
 5213: 	   if ($priv ne 'pch') { 
 5214: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5215: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5216: 			$env{'request.course.id'});
 5217: 	   }
 5218:            return '';
 5219:        }
 5220:    }
 5221: 
 5222: # Resource preferences
 5223: 
 5224:    if ($thisallowed=~/R/) {
 5225:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5226:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5227: 	   if ($priv ne 'pch') { 
 5228: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5229: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5230: 	   }
 5231: 	   return '';
 5232:        }
 5233:    }
 5234: 
 5235: # Restricted by state or randomout?
 5236: 
 5237:    if ($thisallowed=~/X/) {
 5238:       if ($env{'acc.randomout'}) {
 5239: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5240:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5241:             return ''; 
 5242:          }
 5243:       }
 5244:       if (&condval($statecond)) {
 5245: 	 return '2';
 5246:       } else {
 5247:          return '';
 5248:       }
 5249:    }
 5250: 
 5251:     if ($thisallowed eq 'A') {
 5252: 	return 'A';
 5253:     } elsif ($thisallowed eq 'B') {
 5254:         return 'B';
 5255:     }
 5256:    return 'F';
 5257: }
 5258: 
 5259: sub split_uri_for_cond {
 5260:     my $uri=&deversion(&declutter(shift));
 5261:     my @uriparts=split(/\//,$uri);
 5262:     my $filename=pop(@uriparts);
 5263:     my $pathname=join('/',@uriparts);
 5264:     return ($pathname,$filename);
 5265: }
 5266: # --------------------------------------------------- Is a resource on the map?
 5267: 
 5268: sub is_on_map {
 5269:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5270:     #Trying to find the conditional for the file
 5271:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5272: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5273:     if ($match) {
 5274: 	return (1,$1);
 5275:     } else {
 5276: 	return (0,0);
 5277:     }
 5278: }
 5279: 
 5280: # --------------------------------------------------------- Get symb from alias
 5281: 
 5282: sub get_symb_from_alias {
 5283:     my $symb=shift;
 5284:     my ($map,$resid,$url)=&decode_symb($symb);
 5285: # Already is a symb
 5286:     if ($url) { return $symb; }
 5287: # Must be an alias
 5288:     my $aliassymb='';
 5289:     my %bighash;
 5290:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5291:                             &GDBM_READER(),0640)) {
 5292:         my $rid=$bighash{'mapalias_'.$symb};
 5293: 	if ($rid) {
 5294: 	    my ($mapid,$resid)=split(/\./,$rid);
 5295: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5296: 				    $resid,$bighash{'src_'.$rid});
 5297: 	}
 5298:         untie %bighash;
 5299:     }
 5300:     return $aliassymb;
 5301: }
 5302: 
 5303: # ----------------------------------------------------------------- Define Role
 5304: 
 5305: sub definerole {
 5306:   if (allowed('mcr','/')) {
 5307:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5308:     foreach my $role (split(':',$sysrole)) {
 5309: 	my ($crole,$cqual)=split(/\&/,$role);
 5310:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5311:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5312: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5313:                return "refused:s:$crole&$cqual"; 
 5314:             }
 5315:         }
 5316:     }
 5317:     foreach my $role (split(':',$domrole)) {
 5318: 	my ($crole,$cqual)=split(/\&/,$role);
 5319:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5320:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5321: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5322:                return "refused:d:$crole&$cqual"; 
 5323:             }
 5324:         }
 5325:     }
 5326:     foreach my $role (split(':',$courole)) {
 5327: 	my ($crole,$cqual)=split(/\&/,$role);
 5328:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5329:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5330: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5331:                return "refused:c:$crole&$cqual"; 
 5332:             }
 5333:         }
 5334:     }
 5335:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5336:                 "$env{'user.domain'}:$env{'user.name'}:".
 5337: 	        "rolesdef_$rolename=".
 5338:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5339:     return reply($command,$env{'user.home'});
 5340:   } else {
 5341:     return 'refused';
 5342:   }
 5343: }
 5344: 
 5345: # ---------------- Make a metadata query against the network of library servers
 5346: 
 5347: sub metadata_query {
 5348:     my ($query,$custom,$customshow,$server_array)=@_;
 5349:     my %rhash;
 5350:     my %libserv = &all_library();
 5351:     my @server_list = (defined($server_array) ? @$server_array
 5352:                                               : keys(%libserv) );
 5353:     for my $server (@server_list) {
 5354: 	unless ($custom or $customshow) {
 5355: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5356: 	    $rhash{$server}=$reply;
 5357: 	}
 5358: 	else {
 5359: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5360: 			     &escape($custom).':'.&escape($customshow),
 5361: 			     $server);
 5362: 	    $rhash{$server}=$reply;
 5363: 	}
 5364:     }
 5365:     return \%rhash;
 5366: }
 5367: 
 5368: # ----------------------------------------- Send log queries and wait for reply
 5369: 
 5370: sub log_query {
 5371:     my ($uname,$udom,$query,%filters)=@_;
 5372:     my $uhome=&homeserver($uname,$udom);
 5373:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5374:     my $uhost=&hostname($uhome);
 5375:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5376:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5377:                        $uhome);
 5378:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5379:     return get_query_reply($queryid);
 5380: }
 5381: 
 5382: # -------------------------- Update MySQL table for portfolio file
 5383: 
 5384: sub update_portfolio_table {
 5385:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5386:     if ($group ne '') {
 5387:         $file_name =~s /^\Q$group\E//;
 5388:     }
 5389:     my $homeserver = &homeserver($uname,$udom);
 5390:     my $queryid=
 5391:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5392:                ':'.&escape($file_name).':'.$action,$homeserver);
 5393:     my $reply = &get_query_reply($queryid);
 5394:     return $reply;
 5395: }
 5396: 
 5397: # -------------------------- Update MySQL allusers table
 5398: 
 5399: sub update_allusers_table {
 5400:     my ($uname,$udom,$names) = @_;
 5401:     my $homeserver = &homeserver($uname,$udom);
 5402:     my $queryid=
 5403:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5404:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5405:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5406:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5407:                'generation='.&escape($names->{'generation'}).'%%'.
 5408:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5409:                'id='.&escape($names->{'id'}),$homeserver);
 5410:     my $reply = &get_query_reply($queryid);
 5411:     return $reply;
 5412: }
 5413: 
 5414: # ------- Request retrieval of institutional classlists for course(s)
 5415: 
 5416: sub fetch_enrollment_query {
 5417:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5418:     my $homeserver;
 5419:     my $maxtries = 1;
 5420:     if ($context eq 'automated') {
 5421:         $homeserver = $perlvar{'lonHostID'};
 5422:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5423:     } else {
 5424:         $homeserver = &homeserver($cnum,$dom);
 5425:     }
 5426:     my $host=&hostname($homeserver);
 5427:     my $cmd = '';
 5428:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5429:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5430:     }
 5431:     $cmd =~ s/%%$//;
 5432:     $cmd = &escape($cmd);
 5433:     my $query = 'fetchenrollment';
 5434:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5435:     unless ($queryid=~/^\Q$host\E\_/) { 
 5436:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5437:         return 'error: '.$queryid;
 5438:     }
 5439:     my $reply = &get_query_reply($queryid);
 5440:     my $tries = 1;
 5441:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5442:         $reply = &get_query_reply($queryid);
 5443:         $tries ++;
 5444:     }
 5445:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5446:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5447:     } else {
 5448:         my @responses = split(/:/,$reply);
 5449:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5450:             foreach my $line (@responses) {
 5451:                 my ($key,$value) = split(/=/,$line,2);
 5452:                 $$replyref{$key} = $value;
 5453:             }
 5454:         } else {
 5455:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5456:             foreach my $line (@responses) {
 5457:                 my ($key,$value) = split(/=/,$line);
 5458:                 $$replyref{$key} = $value;
 5459:                 if ($value > 0) {
 5460:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5461:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5462:                         my $destname = $pathname.'/'.$filename;
 5463:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5464:                         if ($xml_classlist =~ /^error/) {
 5465:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5466:                         } else {
 5467:                             if ( open(FILE,">$destname") ) {
 5468:                                 print FILE &unescape($xml_classlist);
 5469:                                 close(FILE);
 5470:                             } else {
 5471:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5472:                             }
 5473:                         }
 5474:                     }
 5475:                 }
 5476:             }
 5477:         }
 5478:         return 'ok';
 5479:     }
 5480:     return 'error';
 5481: }
 5482: 
 5483: sub get_query_reply {
 5484:     my $queryid=shift;
 5485:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5486:     my $reply='';
 5487:     for (1..100) {
 5488: 	sleep 2;
 5489:         if (-e $replyfile.'.end') {
 5490: 	    if (open(my $fh,$replyfile)) {
 5491: 		$reply = join('',<$fh>);
 5492: 		close($fh);
 5493: 	   } else { return 'error: reply_file_error'; }
 5494:            return &unescape($reply);
 5495: 	}
 5496:     }
 5497:     return 'timeout:'.$queryid;
 5498: }
 5499: 
 5500: sub courselog_query {
 5501: #
 5502: # possible filters:
 5503: # url: url or symb
 5504: # username
 5505: # domain
 5506: # action: view, submit, grade
 5507: # start: timestamp
 5508: # end: timestamp
 5509: #
 5510:     my (%filters)=@_;
 5511:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5512:     if ($filters{'url'}) {
 5513: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5514:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5515:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5516:     }
 5517:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5518:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5519:     return &log_query($cname,$cdom,'courselog',%filters);
 5520: }
 5521: 
 5522: sub userlog_query {
 5523: #
 5524: # possible filters:
 5525: # action: log check role
 5526: # start: timestamp
 5527: # end: timestamp
 5528: #
 5529:     my ($uname,$udom,%filters)=@_;
 5530:     return &log_query($uname,$udom,'userlog',%filters);
 5531: }
 5532: 
 5533: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5534: 
 5535: sub auto_run {
 5536:     my ($cnum,$cdom) = @_;
 5537:     my $response = 0;
 5538:     my $settings;
 5539:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5540:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5541:         $settings = $domconfig{'autoenroll'};
 5542:         if ($settings->{'run'} eq '1') {
 5543:             $response = 1;
 5544:         }
 5545:     } else {
 5546:         my $homeserver;
 5547:         if (&is_course($cdom,$cnum)) {
 5548:             $homeserver = &homeserver($cnum,$cdom);
 5549:         } else {
 5550:             $homeserver = &domain($cdom,'primary');
 5551:         }
 5552:         if ($homeserver ne 'no_host') {
 5553:             $response = &reply('autorun:'.$cdom,$homeserver);
 5554:         }
 5555:     }
 5556:     return $response;
 5557: }
 5558: 
 5559: sub auto_get_sections {
 5560:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5561:     my $homeserver;
 5562:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5563:         $homeserver = &homeserver($cnum,$cdom);
 5564:     }
 5565:     if (!defined($homeserver)) { 
 5566:         if ($cdom =~ /^$match_domain$/) {
 5567:             $homeserver = &domain($cdom,'primary');
 5568:         }
 5569:     }
 5570:     my @secs;
 5571:     if (defined($homeserver)) {
 5572:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5573:         unless ($response eq 'refused') {
 5574:             @secs = split(/:/,$response);
 5575:         }
 5576:     }
 5577:     return @secs;
 5578: }
 5579: 
 5580: sub auto_new_course {
 5581:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5582:     my $homeserver = &homeserver($cnum,$cdom);
 5583:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5584:     return $response;
 5585: }
 5586: 
 5587: sub auto_validate_courseID {
 5588:     my ($cnum,$cdom,$inst_course_id) = @_;
 5589:     my $homeserver = &homeserver($cnum,$cdom);
 5590:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5591:     return $response;
 5592: }
 5593: 
 5594: sub auto_validate_instcode {
 5595:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5596:     my ($homeserver,$response);
 5597:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5598:         $homeserver = &homeserver($cnum,$cdom);
 5599:     }
 5600:     if (!defined($homeserver)) {
 5601:         if ($cdom =~ /^$match_domain$/) {
 5602:             $homeserver = &domain($cdom,'primary');
 5603:         }
 5604:     }
 5605:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5606:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5607:     return $response;
 5608: }
 5609: 
 5610: sub auto_create_password {
 5611:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5612:     my ($homeserver,$response);
 5613:     my $create_passwd = 0;
 5614:     my $authchk = '';
 5615:     if ($udom =~ /^$match_domain$/) {
 5616:         $homeserver = &domain($udom,'primary');
 5617:     }
 5618:     if ($homeserver eq '') {
 5619:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5620:             $homeserver = &homeserver($cnum,$cdom);
 5621:         }
 5622:     }
 5623:     if ($homeserver eq '') {
 5624:         $authchk = 'nodomain';
 5625:     } else {
 5626:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5627:         if ($response eq 'refused') {
 5628:             $authchk = 'refused';
 5629:         } else {
 5630:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5631:         }
 5632:     }
 5633:     return ($authparam,$create_passwd,$authchk);
 5634: }
 5635: 
 5636: sub auto_photo_permission {
 5637:     my ($cnum,$cdom,$students) = @_;
 5638:     my $homeserver = &homeserver($cnum,$cdom);
 5639:     my ($outcome,$perm_reqd,$conditions) = 
 5640: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5641:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5642: 	return (undef,undef);
 5643:     }
 5644:     return ($outcome,$perm_reqd,$conditions);
 5645: }
 5646: 
 5647: sub auto_checkphotos {
 5648:     my ($uname,$udom,$pid) = @_;
 5649:     my $homeserver = &homeserver($uname,$udom);
 5650:     my ($result,$resulttype);
 5651:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5652: 				   &escape($uname).':'.&escape($pid),
 5653: 				   $homeserver));
 5654:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5655: 	return (undef,undef);
 5656:     }
 5657:     if ($outcome) {
 5658:         ($result,$resulttype) = split(/:/,$outcome);
 5659:     } 
 5660:     return ($result,$resulttype);
 5661: }
 5662: 
 5663: sub auto_photochoice {
 5664:     my ($cnum,$cdom) = @_;
 5665:     my $homeserver = &homeserver($cnum,$cdom);
 5666:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5667: 						       &escape($cdom),
 5668: 						       $homeserver)));
 5669:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5670: 	return (undef,undef);
 5671:     }
 5672:     return ($update,$comment);
 5673: }
 5674: 
 5675: sub auto_photoupdate {
 5676:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5677:     my $homeserver = &homeserver($cnum,$dom);
 5678:     my $host=&hostname($homeserver);
 5679:     my $cmd = '';
 5680:     my $maxtries = 1;
 5681:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5682:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5683:     }
 5684:     $cmd =~ s/%%$//;
 5685:     $cmd = &escape($cmd);
 5686:     my $query = 'institutionalphotos';
 5687:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5688:     unless ($queryid=~/^\Q$host\E\_/) {
 5689:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5690:         return 'error: '.$queryid;
 5691:     }
 5692:     my $reply = &get_query_reply($queryid);
 5693:     my $tries = 1;
 5694:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5695:         $reply = &get_query_reply($queryid);
 5696:         $tries ++;
 5697:     }
 5698:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5699:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5700:     } else {
 5701:         my @responses = split(/:/,$reply);
 5702:         my $outcome = shift(@responses); 
 5703:         foreach my $item (@responses) {
 5704:             my ($key,$value) = split(/=/,$item);
 5705:             $$photo{$key} = $value;
 5706:         }
 5707:         return $outcome;
 5708:     }
 5709:     return 'error';
 5710: }
 5711: 
 5712: sub auto_instcode_format {
 5713:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5714: 	$cat_order) = @_;
 5715:     my $courses = '';
 5716:     my @homeservers;
 5717:     if ($caller eq 'global') {
 5718: 	my %servers = &get_servers($codedom,'library');
 5719: 	foreach my $tryserver (keys(%servers)) {
 5720: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5721: 		push(@homeservers,$tryserver);
 5722: 	    }
 5723:         }
 5724:     } elsif ($caller eq 'requests') {
 5725:         if ($codedom =~ /^$match_domain$/) {
 5726:             my $chome = &domain($codedom,'primary');
 5727:             unless ($chome eq 'no_host') {
 5728:                 push(@homeservers,$chome);
 5729:             }
 5730:         }
 5731:     } else {
 5732:         push(@homeservers,&homeserver($caller,$codedom));
 5733:     }
 5734:     foreach my $code (keys(%{$instcodes})) {
 5735:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5736:     }
 5737:     chop($courses);
 5738:     my $ok_response = 0;
 5739:     my $response;
 5740:     while (@homeservers > 0 && $ok_response == 0) {
 5741:         my $server = shift(@homeservers); 
 5742:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5743:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5744:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5745: 		split(/:/,$response);
 5746:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5747:             push(@{$codetitles},&str2array($codetitles_str));
 5748:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5749:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5750:             $ok_response = 1;
 5751:         }
 5752:     }
 5753:     if ($ok_response) {
 5754:         return 'ok';
 5755:     } else {
 5756:         return $response;
 5757:     }
 5758: }
 5759: 
 5760: sub auto_instcode_defaults {
 5761:     my ($domain,$returnhash,$code_order) = @_;
 5762:     my @homeservers;
 5763: 
 5764:     my %servers = &get_servers($domain,'library');
 5765:     foreach my $tryserver (keys(%servers)) {
 5766: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5767: 	    push(@homeservers,$tryserver);
 5768: 	}
 5769:     }
 5770: 
 5771:     my $response;
 5772:     foreach my $server (@homeservers) {
 5773:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5774:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5775: 	
 5776: 	foreach my $pair (split(/\&/,$response)) {
 5777: 	    my ($name,$value)=split(/\=/,$pair);
 5778: 	    if ($name eq 'code_order') {
 5779: 		@{$code_order} = split(/\&/,&unescape($value));
 5780: 	    } else {
 5781: 		$returnhash->{&unescape($name)}=&unescape($value);
 5782: 	    }
 5783: 	}
 5784: 	return 'ok';
 5785:     }
 5786: 
 5787:     return $response;
 5788: }
 5789: 
 5790: sub auto_possible_instcodes {
 5791:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 5792:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 5793:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 5794:         return;
 5795:     }
 5796:     my (@homeservers,$uhome);
 5797:     if (defined(&domain($domain,'primary'))) {
 5798:         $uhome=&domain($domain,'primary');
 5799:         push(@homeservers,&domain($domain,'primary'));
 5800:     } else {
 5801:         my %servers = &get_servers($domain,'library');
 5802:         foreach my $tryserver (keys(%servers)) {
 5803:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5804:                 push(@homeservers,$tryserver);
 5805:             }
 5806:         }
 5807:     }
 5808:     my $response;
 5809:     foreach my $server (@homeservers) {
 5810:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 5811:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5812:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 5813:             split(':',$response);
 5814:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 5815:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 5816:         foreach my $item (split('&',$cat_title)) {   
 5817:             my ($name,$value)=split('=',$item);
 5818:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 5819:         }
 5820:         foreach my $item (split('&',$cat_order)) {
 5821:             my ($name,$value)=split('=',$item);
 5822:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 5823:         }
 5824:         return 'ok';
 5825:     }
 5826:     return $response;
 5827: }
 5828: 
 5829: sub auto_courserequest_checks {
 5830:     my ($dom) = @_;
 5831:     my ($homeserver,%validations);
 5832:     if ($dom =~ /^$match_domain$/) {
 5833:         $homeserver = &domain($dom,'primary');
 5834:     }
 5835:     unless ($homeserver eq 'no_host') {
 5836:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 5837:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 5838:             my @items = split(/&/,$response);
 5839:             foreach my $item (@items) {
 5840:                 my ($key,$value) = split('=',$item);
 5841:                 $validations{&unescape($key)} = &thaw_unescape($value);
 5842:             }
 5843:         }
 5844:     }
 5845:     return %validations; 
 5846: }
 5847: 
 5848: sub auto_courserequest_validation {
 5849:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 5850:     my ($homeserver,$response);
 5851:     if ($dom =~ /^$match_domain$/) {
 5852:         $homeserver = &domain($dom,'primary');
 5853:     }
 5854:     unless ($homeserver eq 'no_host') {  
 5855:           
 5856:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 5857:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 5858:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 5859:                                     $homeserver));
 5860:     }
 5861:     return $response;
 5862: }
 5863: 
 5864: sub auto_validate_class_sec {
 5865:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5866:     my $homeserver = &homeserver($cnum,$cdom);
 5867:     my $ownerlist;
 5868:     if (ref($owners) eq 'ARRAY') {
 5869:         $ownerlist = join(',',@{$owners});
 5870:     } else {
 5871:         $ownerlist = $owners;
 5872:     }
 5873:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5874:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5875:     return $response;
 5876: }
 5877: 
 5878: # ------------------------------------------------------- Course Group routines
 5879: 
 5880: sub get_coursegroups {
 5881:     my ($cdom,$cnum,$group,$namespace) = @_;
 5882:     return(&dump($namespace,$cdom,$cnum,$group));
 5883: }
 5884: 
 5885: sub modify_coursegroup {
 5886:     my ($cdom,$cnum,$groupsettings) = @_;
 5887:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5888: }
 5889: 
 5890: sub toggle_coursegroup_status {
 5891:     my ($cdom,$cnum,$group,$action) = @_;
 5892:     my ($from_namespace,$to_namespace);
 5893:     if ($action eq 'delete') {
 5894:         $from_namespace = 'coursegroups';
 5895:         $to_namespace = 'deleted_groups';
 5896:     } else {
 5897:         $from_namespace = 'deleted_groups';
 5898:         $to_namespace = 'coursegroups';
 5899:     }
 5900:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5901:     if (my $tmp = &error(%curr_group)) {
 5902:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5903:         return ('read error',$tmp);
 5904:     } else {
 5905:         my %savedsettings = %curr_group; 
 5906:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5907:         my $deloutcome;
 5908:         if ($result eq 'ok') {
 5909:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5910:         } else {
 5911:             return ('write error',$result);
 5912:         }
 5913:         if ($deloutcome eq 'ok') {
 5914:             return 'ok';
 5915:         } else {
 5916:             return ('delete error',$deloutcome);
 5917:         }
 5918:     }
 5919: }
 5920: 
 5921: sub modify_group_roles {
 5922:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5923:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5924:     my $role = 'gr/'.&escape($userprivs);
 5925:     my ($uname,$udom) = split(/:/,$user);
 5926:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5927:     if ($result eq 'ok') {
 5928:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5929:     }
 5930:     return $result;
 5931: }
 5932: 
 5933: sub modify_coursegroup_membership {
 5934:     my ($cdom,$cnum,$membership) = @_;
 5935:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5936:     return $result;
 5937: }
 5938: 
 5939: sub get_active_groups {
 5940:     my ($udom,$uname,$cdom,$cnum) = @_;
 5941:     my $now = time;
 5942:     my %groups = ();
 5943:     foreach my $key (keys(%env)) {
 5944:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5945:             my ($start,$end) = split(/\./,$env{$key});
 5946:             if (($end!=0) && ($end<$now)) { next; }
 5947:             if (($start!=0) && ($start>$now)) { next; }
 5948:             if ($1 eq $cdom && $2 eq $cnum) {
 5949:                 $groups{$3} = $env{$key} ;
 5950:             }
 5951:         }
 5952:     }
 5953:     return %groups;
 5954: }
 5955: 
 5956: sub get_group_membership {
 5957:     my ($cdom,$cnum,$group) = @_;
 5958:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5959: }
 5960: 
 5961: sub get_users_groups {
 5962:     my ($udom,$uname,$courseid) = @_;
 5963:     my @usersgroups;
 5964:     my $cachetime=1800;
 5965: 
 5966:     my $hashid="$udom:$uname:$courseid";
 5967:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5968:     if (defined($cached)) {
 5969:         @usersgroups = split(/:/,$grouplist);
 5970:     } else {  
 5971:         $grouplist = '';
 5972:         my $courseurl = &courseid_to_courseurl($courseid);
 5973:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5974:         my $access_end = $env{'course.'.$courseid.
 5975:                               '.default_enrollment_end_date'};
 5976:         my $now = time;
 5977:         foreach my $key (keys(%roleshash)) {
 5978:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5979:                 my $group = $1;
 5980:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5981:                     my $start = $2;
 5982:                     my $end = $1;
 5983:                     if ($start == -1) { next; } # deleted from group
 5984:                     if (($start!=0) && ($start>$now)) { next; }
 5985:                     if (($end!=0) && ($end<$now)) {
 5986:                         if ($access_end && $access_end < $now) {
 5987:                             if ($access_end - $end < 86400) {
 5988:                                 push(@usersgroups,$group);
 5989:                             }
 5990:                         }
 5991:                         next;
 5992:                     }
 5993:                     push(@usersgroups,$group);
 5994:                 }
 5995:             }
 5996:         }
 5997:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5998:         $grouplist = join(':',@usersgroups);
 5999:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6000:     }
 6001:     return @usersgroups;
 6002: }
 6003: 
 6004: sub devalidate_getgroups_cache {
 6005:     my ($udom,$uname,$cdom,$cnum)=@_;
 6006:     my $courseid = $cdom.'_'.$cnum;
 6007: 
 6008:     my $hashid="$udom:$uname:$courseid";
 6009:     &devalidate_cache_new('getgroups',$hashid);
 6010: }
 6011: 
 6012: # ------------------------------------------------------------------ Plain Text
 6013: 
 6014: sub plaintext {
 6015:     my ($short,$type,$cid,$forcedefault) = @_;
 6016:     if ($short =~ /^cr/) {
 6017: 	return (split('/',$short))[-1];
 6018:     }
 6019:     if (!defined($cid)) {
 6020:         $cid = $env{'request.course.id'};
 6021:     }
 6022:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 6023:         unless ($forcedefault) {
 6024:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6025:             &Apache::lonlocal::mt_escape(\$roletext);
 6026:             return &Apache::lonlocal::mt($roletext);
 6027:         }
 6028:     }
 6029:     my %rolenames = (
 6030:                       Course    => 'std',
 6031:                       Community => 'alt1',
 6032:                     );
 6033:     if (defined($type) && 
 6034:          defined($rolenames{$type}) && 
 6035:          defined($prp{$short}{$rolenames{$type}})) {
 6036:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6037:     } else {
 6038:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 6039:     }
 6040: }
 6041: 
 6042: # ----------------------------------------------------------------- Assign Role
 6043: 
 6044: sub assignrole {
 6045:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6046:         $context)=@_;
 6047:     my $mrole;
 6048:     if ($role =~ /^cr\//) {
 6049:         my $cwosec=$url;
 6050:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6051: 	unless (&allowed('ccr',$cwosec)) {
 6052:            &logthis('Refused custom assignrole: '.
 6053:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6054: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 6055:            return 'refused'; 
 6056:         }
 6057:         $mrole='cr';
 6058:     } elsif ($role =~ /^gr\//) {
 6059:         my $cwogrp=$url;
 6060:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 6061:         unless (&allowed('mdg',$cwogrp)) {
 6062:             &logthis('Refused group assignrole: '.
 6063:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6064:                     $env{'user.name'}.' at '.$env{'user.domain'});
 6065:             return 'refused';
 6066:         }
 6067:         $mrole='gr';
 6068:     } else {
 6069:         my $cwosec=$url;
 6070:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6071:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 6072:             my $refused;
 6073:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 6074:                 if (!(&allowed('c'.$role,$url))) {
 6075:                     $refused = 1;
 6076:                 }
 6077:             } else {
 6078:                 $refused = 1;
 6079:             }
 6080:             if ($refused) {
 6081:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6082:                     $refused = '';
 6083:                 } elsif ($context eq 'requestcourses') {
 6084:                     if (($role eq 'cc') && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 6085:                         my ($cdom,$cnum) = ($cwosec =~ m{^/($match_domain)/($match_courseid)$});
 6086:                         my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6087:                         if ($crsenv{'internal.courseowner'} eq 
 6088:                              $env{'user.name'}.':'.$env{'user.domain'}) {
 6089:                             $refused = '';
 6090:                         }
 6091:                     }
 6092:                 }
 6093:                 if ($refused) {
 6094:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6095:                              ' '.$role.' '.$end.' '.$start.' by '.
 6096: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6097:                     return 'refused';
 6098:                 }
 6099:             }
 6100:         }
 6101:         $mrole=$role;
 6102:     }
 6103:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6104:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6105:     if ($end) { $command.='_'.$end; }
 6106:     if ($start) {
 6107: 	if ($end) { 
 6108:            $command.='_'.$start; 
 6109:         } else {
 6110:            $command.='_0_'.$start;
 6111:         }
 6112:     }
 6113:     my $origstart = $start;
 6114:     my $origend = $end;
 6115:     my $delflag;
 6116: # actually delete
 6117:     if ($deleteflag) {
 6118: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6119: # modify command to delete the role
 6120:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6121:                 "$udom:$uname:$url".'_'."$mrole";
 6122: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6123: # set start and finish to negative values for userrolelog
 6124:            $start=-1;
 6125:            $end=-1;
 6126:            $delflag = 1;
 6127:         }
 6128:     }
 6129: # send command
 6130:     my $answer=&reply($command,&homeserver($uname,$udom));
 6131: # log new user role if status is ok
 6132:     if ($answer eq 'ok') {
 6133: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6134: # for course roles, perform group memberships changes triggered by role change.
 6135:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6136:         unless ($role =~ /^gr/) {
 6137:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6138:                                              $origstart,$selfenroll,$context);
 6139:         }
 6140:     }
 6141:     return $answer;
 6142: }
 6143: 
 6144: # -------------------------------------------------- Modify user authentication
 6145: # Overrides without validation
 6146: 
 6147: sub modifyuserauth {
 6148:     my ($udom,$uname,$umode,$upass)=@_;
 6149:     my $uhome=&homeserver($uname,$udom);
 6150:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6151:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6152:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6153:              ' in domain '.$env{'request.role.domain'});  
 6154:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6155: 		     &escape($upass),$uhome);
 6156:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6157:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6158:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6159:     &log($udom,,$uname,$uhome,
 6160:         'Authentication changed by '.$env{'user.domain'}.', '.
 6161:                                      $env{'user.name'}.', '.$umode.
 6162:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6163:     unless ($reply eq 'ok') {
 6164:         &logthis('Authentication mode error: '.$reply);
 6165: 	return 'error: '.$reply;
 6166:     }   
 6167:     return 'ok';
 6168: }
 6169: 
 6170: # --------------------------------------------------------------- Modify a user
 6171: 
 6172: sub modifyuser {
 6173:     my ($udom,    $uname, $uid,
 6174:         $umode,   $upass, $first,
 6175:         $middle,  $last,  $gene,
 6176:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6177:     $udom= &LONCAPA::clean_domain($udom);
 6178:     $uname=&LONCAPA::clean_username($uname);
 6179:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6180:              $umode.', '.$first.', '.$middle.', '.
 6181: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6182:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6183:                                      ' desiredhome not specified'). 
 6184:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6185:              ' in domain '.$env{'request.role.domain'});
 6186:     my $uhome=&homeserver($uname,$udom,'true');
 6187: # ----------------------------------------------------------------- Create User
 6188:     if (($uhome eq 'no_host') && 
 6189: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6190:         my $unhome='';
 6191:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6192:             $unhome = $desiredhome;
 6193: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6194: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6195:         } else { # load balancing routine for determining $unhome
 6196:             my $loadm=10000000;
 6197: 	    my %servers = &get_servers($udom,'library');
 6198: 	    foreach my $tryserver (keys(%servers)) {
 6199: 		my $answer=reply('load',$tryserver);
 6200: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6201: 		    $loadm=$answer;
 6202: 		    $unhome=$tryserver;
 6203: 		}
 6204: 	    }
 6205:         }
 6206:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6207: 	    return 'error: unable to find a home server for '.$uname.
 6208:                    ' in domain '.$udom;
 6209:         }
 6210:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6211:                          &escape($upass),$unhome);
 6212: 	unless ($reply eq 'ok') {
 6213:             return 'error: '.$reply;
 6214:         }   
 6215:         $uhome=&homeserver($uname,$udom,'true');
 6216:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6217: 	    return 'error: unable verify users home machine.';
 6218:         }
 6219:     }   # End of creation of new user
 6220: # ---------------------------------------------------------------------- Add ID
 6221:     if ($uid) {
 6222:        $uid=~tr/A-Z/a-z/;
 6223:        my %uidhash=&idrget($udom,$uname);
 6224:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6225:          && (!$forceid)) {
 6226: 	  unless ($uid eq $uidhash{$uname}) {
 6227: 	      return 'error: user id "'.$uid.'" does not match '.
 6228:                   'current user id "'.$uidhash{$uname}.'".';
 6229:           }
 6230:        } else {
 6231: 	  &idput($udom,($uname => $uid));
 6232:        }
 6233:     }
 6234: # -------------------------------------------------------------- Add names, etc
 6235:     my @tmp=&get('environment',
 6236: 		   ['firstname','middlename','lastname','generation','id',
 6237:                     'permanentemail','inststatus'],
 6238: 		   $udom,$uname);
 6239:     my %names;
 6240:     if ($tmp[0] =~ m/^error:.*/) { 
 6241:         %names=(); 
 6242:     } else {
 6243:         %names = @tmp;
 6244:     }
 6245: #
 6246: # Make sure to not trash student environment if instructor does not bother
 6247: # to supply name and email information
 6248: #
 6249:     if ($first)  { $names{'firstname'}  = $first; }
 6250:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6251:     if ($last)   { $names{'lastname'}   = $last; }
 6252:     if (defined($gene))   { $names{'generation'} = $gene; }
 6253:     if ($email) {
 6254:        $email=~s/[^\w\@\.\-\,]//gs;
 6255:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6256:     }
 6257:     if ($uid) { $names{'id'}  = $uid; }
 6258:     if (defined($inststatus)) {
 6259:         $names{'inststatus'} = '';
 6260:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6261:         if (ref($usertypes) eq 'HASH') {
 6262:             my @okstatuses; 
 6263:             foreach my $item (split(/:/,$inststatus)) {
 6264:                 if (defined($usertypes->{$item})) {
 6265:                     push(@okstatuses,$item);  
 6266:                 }
 6267:             }
 6268:             if (@okstatuses) {
 6269:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6270:             }
 6271:         }
 6272:     }
 6273:     my $reply = &put('environment', \%names, $udom,$uname);
 6274:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6275:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6276:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6277:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6278:                  $umode.', '.$first.', '.$middle.', '.
 6279: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6280:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6281:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6282:     } else {
 6283:         $logmsg .= ' during self creation';
 6284:     }
 6285:     &logthis($logmsg);
 6286:     return 'ok';
 6287: }
 6288: 
 6289: # -------------------------------------------------------------- Modify student
 6290: 
 6291: sub modifystudent {
 6292:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6293:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6294:         $selfenroll,$context,$inststatus)=@_;
 6295:     if (!$cid) {
 6296: 	unless ($cid=$env{'request.course.id'}) {
 6297: 	    return 'not_in_class';
 6298: 	}
 6299:     }
 6300: # --------------------------------------------------------------- Make the user
 6301:     my $reply=&modifyuser
 6302: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6303:          $desiredhome,$email,$inststatus);
 6304:     unless ($reply eq 'ok') { return $reply; }
 6305:     # This will cause &modify_student_enrollment to get the uid from the
 6306:     # students environment
 6307:     $uid = undef if (!$forceid);
 6308:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6309: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6310:     return $reply;
 6311: }
 6312: 
 6313: sub modify_student_enrollment {
 6314:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6315:     my ($cdom,$cnum,$chome);
 6316:     if (!$cid) {
 6317: 	unless ($cid=$env{'request.course.id'}) {
 6318: 	    return 'not_in_class';
 6319: 	}
 6320: 	$cdom=$env{'course.'.$cid.'.domain'};
 6321: 	$cnum=$env{'course.'.$cid.'.num'};
 6322:     } else {
 6323: 	($cdom,$cnum)=split(/_/,$cid);
 6324:     }
 6325:     $chome=$env{'course.'.$cid.'.home'};
 6326:     if (!$chome) {
 6327: 	$chome=&homeserver($cnum,$cdom);
 6328:     }
 6329:     if (!$chome) { return 'unknown_course'; }
 6330:     # Make sure the user exists
 6331:     my $uhome=&homeserver($uname,$udom);
 6332:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6333: 	return 'error: no such user';
 6334:     }
 6335:     # Get student data if we were not given enough information
 6336:     if (!defined($first)  || $first  eq '' || 
 6337:         !defined($last)   || $last   eq '' || 
 6338:         !defined($uid)    || $uid    eq '' || 
 6339:         !defined($middle) || $middle eq '' || 
 6340:         !defined($gene)   || $gene   eq '') {
 6341:         # They did not supply us with enough data to enroll the student, so
 6342:         # we need to pick up more information.
 6343:         my %tmp = &get('environment',
 6344:                        ['firstname','middlename','lastname', 'generation','id']
 6345:                        ,$udom,$uname);
 6346: 
 6347:         #foreach my $key (keys(%tmp)) {
 6348:         #    &logthis("key $key = ".$tmp{$key});
 6349:         #}
 6350:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6351:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6352:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6353:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6354:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6355:     }
 6356:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6357:     my $reply=cput('classlist',
 6358: 		   {"$uname:$udom" => 
 6359: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6360: 		   $cdom,$cnum);
 6361:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6362: 	return 'error: '.$reply;
 6363:     } else {
 6364: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6365:     }
 6366:     # Add student role to user
 6367:     my $uurl='/'.$cid;
 6368:     $uurl=~s/\_/\//g;
 6369:     if ($usec) {
 6370: 	$uurl.='/'.$usec;
 6371:     }
 6372:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6373: }
 6374: 
 6375: sub format_name {
 6376:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6377:     my $name;
 6378:     if ($first ne 'lastname') {
 6379: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6380:     } else {
 6381: 	if ($lastname=~/\S/) {
 6382: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6383: 	    $name=~s/\s+,/,/;
 6384: 	} else {
 6385: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6386: 	}
 6387:     }
 6388:     $name=~s/^\s+//;
 6389:     $name=~s/\s+$//;
 6390:     $name=~s/\s+/ /g;
 6391:     return $name;
 6392: }
 6393: 
 6394: # ------------------------------------------------- Write to course preferences
 6395: 
 6396: sub writecoursepref {
 6397:     my ($courseid,%prefs)=@_;
 6398:     $courseid=~s/^\///;
 6399:     $courseid=~s/\_/\//g;
 6400:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6401:     my $chome=homeserver($cnum,$cdomain);
 6402:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6403: 	return 'error: no such course';
 6404:     }
 6405:     my $cstring='';
 6406:     foreach my $pref (keys(%prefs)) {
 6407: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6408:     }
 6409:     $cstring=~s/\&$//;
 6410:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6411: }
 6412: 
 6413: # ---------------------------------------------------------- Make/modify course
 6414: 
 6415: sub createcourse {
 6416:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6417:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 6418:     $url=&declutter($url);
 6419:     my $cid='';
 6420:     unless (&allowed('ccc',$udom)) {
 6421:         if ($context eq 'requestcourses') {
 6422:             unless (&usertools_access($course_owner,$udom,$category,undef,$context)) {
 6423:                 return 'refused';
 6424:             }
 6425:         } else {
 6426:             return 'refused';
 6427:         }
 6428:     }
 6429: # --------------------------------------------------------------- Get Unique ID
 6430:     my $uname;
 6431:     if ($cnum =~ /^$match_courseid$/) {
 6432:         my $chome=&homeserver($cnum,$udom,'true');
 6433:         if (($chome eq '') || ($chome eq 'no_host')) {
 6434:             $uname = $cnum;
 6435:         } else {
 6436:             $uname = &generate_coursenum($udom);
 6437:         }
 6438:     } else {
 6439:         $uname = &generate_coursenum($udom);
 6440:     }
 6441:     return $uname if ($uname =~ /^error/);
 6442: # -------------------------------------------------- Check supplied server name
 6443:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6444:     if (! &is_library($course_server)) {
 6445:         return 'error:bad server name '.$course_server;
 6446:     }
 6447: # ------------------------------------------------------------- Make the course
 6448:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6449:                       $course_server);
 6450:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6451:     my $uhome=&homeserver($uname,$udom,'true');
 6452:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6453: 	return 'error: no such course';
 6454:     }
 6455: # ----------------------------------------------------------------- Course made
 6456: # log existence
 6457:     my $newcourse = {
 6458:                     $udom.'_'.$uname => {
 6459:                                      description => $description,
 6460:                                      inst_code   => $inst_code,
 6461:                                      owner       => $course_owner,
 6462:                                      type        => $crstype,
 6463:                                                 },
 6464:                     };
 6465:     &courseidput($udom,$newcourse,$uhome,'notime');
 6466: # set toplevel url
 6467:     my $topurl=$url;
 6468:     unless ($nonstandard) {
 6469: # ------------------------------------------ For standard courses, make top url
 6470:         my $mapurl=&clutter($url);
 6471:         if ($mapurl eq '/res/') { $mapurl=''; }
 6472:         $env{'form.initmap'}=(<<ENDINITMAP);
 6473: <map>
 6474: <resource id="1" type="start"></resource>
 6475: <resource id="2" src="$mapurl"></resource>
 6476: <resource id="3" type="finish"></resource>
 6477: <link index="1" from="1" to="2"></link>
 6478: <link index="2" from="2" to="3"></link>
 6479: </map>
 6480: ENDINITMAP
 6481:         $topurl=&declutter(
 6482:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6483:                           );
 6484:     }
 6485: # ----------------------------------------------------------- Write preferences
 6486:     &writecoursepref($udom.'_'.$uname,
 6487:                      ('description' => $description,
 6488:                       'url'         => $topurl));
 6489:     return '/'.$udom.'/'.$uname;
 6490: }
 6491: 
 6492: # ------------------------------------------------------------------- Create ID
 6493: sub generate_coursenum {
 6494:     my ($udom) = @_;
 6495:     my $domdesc = &domain($udom);
 6496:     return 'error: invalid domain' if ($domdesc eq '');
 6497:     my $uname=int(1+rand(9)).
 6498:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6499:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6500:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6501: # ----------------------------------------------- Make sure that does not exist
 6502:     my $uhome=&homeserver($uname,$udom,'true');
 6503:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6504:         $uname=int(1+rand(9)).
 6505:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6506:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6507:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6508:         $uhome=&homeserver($uname,$udom,'true');
 6509:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6510:             return 'error: unable to generate unique course-ID';
 6511:         }
 6512:     }
 6513:     return $uname;
 6514: }
 6515: 
 6516: sub is_course {
 6517:     my ($cdom,$cnum) = @_;
 6518:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6519: 				undef,'.');
 6520:     if (exists($courses{$cdom.'_'.$cnum})) {
 6521:         return 1;
 6522:     }
 6523:     return 0;
 6524: }
 6525: 
 6526: sub store_userdata {
 6527:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 6528:     my $result;
 6529:     if ($datakey ne '') {
 6530:         if (ref($storehash) eq 'HASH') {
 6531:             if ($udom eq '' || $uname eq '') {
 6532:                 $udom = $env{'user.domain'};
 6533:                 $uname = $env{'user.name'};
 6534:             }
 6535:             my $uhome=&homeserver($uname,$udom);
 6536:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 6537:                 $result = 'error: no_host';
 6538:             } else {
 6539:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 6540:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 6541: 
 6542:                 my $namevalue='';
 6543:                 foreach my $key (keys(%{$storehash})) {
 6544:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6545:                 }
 6546:                 $namevalue=~s/\&$//;
 6547:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
 6548:                                   "$namespace:$datakey:$namevalue",$uhome);
 6549:             }
 6550:         } else {
 6551:             $result = 'error: data to store was not a hash reference'; 
 6552:         }
 6553:     } else {
 6554:         $result= 'error: invalid requestkey'; 
 6555:     }
 6556:     return $result;
 6557: }
 6558: 
 6559: # ---------------------------------------------------------- Assign Custom Role
 6560: 
 6561: sub assigncustomrole {
 6562:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6563:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6564:                        $end,$start,$deleteflag,$selfenroll,$context);
 6565: }
 6566: 
 6567: # ----------------------------------------------------------------- Revoke Role
 6568: 
 6569: sub revokerole {
 6570:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6571:     my $now=time;
 6572:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6573: }
 6574: 
 6575: # ---------------------------------------------------------- Revoke Custom Role
 6576: 
 6577: sub revokecustomrole {
 6578:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6579:     my $now=time;
 6580:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6581:            $deleteflag,$selfenroll,$context);
 6582: }
 6583: 
 6584: # ------------------------------------------------------------ Disk usage
 6585: sub diskusage {
 6586:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6587:     $directorypath =~ s/\/$//;
 6588:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6589:                        .&escape($getpropath).':'.&escape($uname).':'
 6590:                        .&escape($udom),homeserver($uname,$udom));
 6591:     if ($listing eq 'unknown_cmd') {
 6592:         if ($getpropath) {
 6593:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6594:         }
 6595:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6596:     }
 6597:     return $listing;
 6598: }
 6599: 
 6600: sub is_locked {
 6601:     my ($file_name, $domain, $user) = @_;
 6602:     my @check;
 6603:     my $is_locked;
 6604:     push @check, $file_name;
 6605:     my %locked = &get('file_permissions',\@check,
 6606: 		      $env{'user.domain'},$env{'user.name'});
 6607:     my ($tmp)=keys(%locked);
 6608:     if ($tmp=~/^error:/) { undef(%locked); }
 6609:     
 6610:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6611:         $is_locked = 'false';
 6612:         foreach my $entry (@{$locked{$file_name}}) {
 6613:            if (ref($entry) eq 'ARRAY') { 
 6614:                $is_locked = 'true';
 6615:                last;
 6616:            }
 6617:        }
 6618:     } else {
 6619:         $is_locked = 'false';
 6620:     }
 6621: }
 6622: 
 6623: sub declutter_portfile {
 6624:     my ($file) = @_;
 6625:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6626:     return $file;
 6627: }
 6628: 
 6629: # ------------------------------------------------------------- Mark as Read Only
 6630: 
 6631: sub mark_as_readonly {
 6632:     my ($domain,$user,$files,$what) = @_;
 6633:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6634:     my ($tmp)=keys(%current_permissions);
 6635:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6636:     foreach my $file (@{$files}) {
 6637: 	$file = &declutter_portfile($file);
 6638:         push(@{$current_permissions{$file}},$what);
 6639:     }
 6640:     &put('file_permissions',\%current_permissions,$domain,$user);
 6641:     return;
 6642: }
 6643: 
 6644: # ------------------------------------------------------------Save Selected Files
 6645: 
 6646: sub save_selected_files {
 6647:     my ($user, $path, @files) = @_;
 6648:     my $filename = $user."savedfiles";
 6649:     my @other_files = &files_not_in_path($user, $path);
 6650:     open (OUT, '>'.$tmpdir.$filename);
 6651:     foreach my $file (@files) {
 6652:         print (OUT $env{'form.currentpath'}.$file."\n");
 6653:     }
 6654:     foreach my $file (@other_files) {
 6655:         print (OUT $file."\n");
 6656:     }
 6657:     close (OUT);
 6658:     return 'ok';
 6659: }
 6660: 
 6661: sub clear_selected_files {
 6662:     my ($user) = @_;
 6663:     my $filename = $user."savedfiles";
 6664:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6665:     print (OUT undef);
 6666:     close (OUT);
 6667:     return ("ok");    
 6668: }
 6669: 
 6670: sub files_in_path {
 6671:     my ($user, $path) = @_;
 6672:     my $filename = $user."savedfiles";
 6673:     my %return_files;
 6674:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6675:     while (my $line_in = <IN>) {
 6676:         chomp ($line_in);
 6677:         my @paths_and_file = split (m!/!, $line_in);
 6678:         my $file_part = pop (@paths_and_file);
 6679:         my $path_part = join ('/', @paths_and_file);
 6680:         $path_part.='/';
 6681:         my $path_and_file = $path_part.$file_part;
 6682:         if ($path_part eq $path) {
 6683:             $return_files{$file_part}= 'selected';
 6684:         }
 6685:     }
 6686:     close (IN);
 6687:     return (\%return_files);
 6688: }
 6689: 
 6690: # called in portfolio select mode, to show files selected NOT in current directory
 6691: sub files_not_in_path {
 6692:     my ($user, $path) = @_;
 6693:     my $filename = $user."savedfiles";
 6694:     my @return_files;
 6695:     my $path_part;
 6696:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6697:     while (my $line = <IN>) {
 6698:         #ok, I know it's clunky, but I want it to work
 6699:         my @paths_and_file = split(m|/|, $line);
 6700:         my $file_part = pop(@paths_and_file);
 6701:         chomp($file_part);
 6702:         my $path_part = join('/', @paths_and_file);
 6703:         $path_part .= '/';
 6704:         my $path_and_file = $path_part.$file_part;
 6705:         if ($path_part ne $path) {
 6706:             push(@return_files, ($path_and_file));
 6707:         }
 6708:     }
 6709:     close(OUT);
 6710:     return (@return_files);
 6711: }
 6712: 
 6713: #----------------------------------------------Get portfolio file permissions
 6714: 
 6715: sub get_portfile_permissions {
 6716:     my ($domain,$user) = @_;
 6717:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6718:     my ($tmp)=keys(%current_permissions);
 6719:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6720:     return \%current_permissions;
 6721: }
 6722: 
 6723: #---------------------------------------------Get portfolio file access controls
 6724: 
 6725: sub get_access_controls {
 6726:     my ($current_permissions,$group,$file) = @_;
 6727:     my %access;
 6728:     my $real_file = $file;
 6729:     $file =~ s/\.meta$//;
 6730:     if (defined($file)) {
 6731:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6732:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6733:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6734:             }
 6735:         }
 6736:     } else {
 6737:         foreach my $key (keys(%{$current_permissions})) {
 6738:             if ($key =~ /\0accesscontrol$/) {
 6739:                 if (defined($group)) {
 6740:                     if ($key !~ m-^\Q$group\E/-) {
 6741:                         next;
 6742:                     }
 6743:                 }
 6744:                 my ($fullpath) = split(/\0/,$key);
 6745:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6746:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6747:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6748:                     }
 6749:                 }
 6750:             }
 6751:         }
 6752:     }
 6753:     return %access;
 6754: }
 6755: 
 6756: sub modify_access_controls {
 6757:     my ($file_name,$changes,$domain,$user)=@_;
 6758:     my ($outcome,$deloutcome);
 6759:     my %store_permissions;
 6760:     my %new_values;
 6761:     my %new_control;
 6762:     my %translation;
 6763:     my @deletions = ();
 6764:     my $now = time;
 6765:     if (exists($$changes{'activate'})) {
 6766:         if (ref($$changes{'activate'}) eq 'HASH') {
 6767:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6768:             my $numnew = scalar(@newitems);
 6769:             for (my $i=0; $i<$numnew; $i++) {
 6770:                 my $newkey = $newitems[$i];
 6771:                 my $newid = &Apache::loncommon::get_cgi_id();
 6772:                 if ($newkey =~ /^\d+:/) { 
 6773:                     $newkey =~ s/^(\d+)/$newid/;
 6774:                     $translation{$1} = $newid;
 6775:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6776:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6777:                     $translation{$1} = $newid;
 6778:                 }
 6779:                 $new_values{$file_name."\0".$newkey} = 
 6780:                                           $$changes{'activate'}{$newitems[$i]};
 6781:                 $new_control{$newkey} = $now;
 6782:             }
 6783:         }
 6784:     }
 6785:     my %todelete;
 6786:     my %changed_items;
 6787:     foreach my $action ('delete','update') {
 6788:         if (exists($$changes{$action})) {
 6789:             if (ref($$changes{$action}) eq 'HASH') {
 6790:                 foreach my $key (keys(%{$$changes{$action}})) {
 6791:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6792:                     if ($action eq 'delete') { 
 6793:                         $todelete{$itemnum} = 1;
 6794:                     } else {
 6795:                         $changed_items{$itemnum} = $key;
 6796:                     }
 6797:                 }
 6798:             }
 6799:         }
 6800:     }
 6801:     # get lock on access controls for file.
 6802:     my $lockhash = {
 6803:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6804:                                                        ':'.$env{'user.domain'},
 6805:                    }; 
 6806:     my $tries = 0;
 6807:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6808:    
 6809:     while (($gotlock ne 'ok') && $tries <3) {
 6810:         $tries ++;
 6811:         sleep 1;
 6812:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6813:     }
 6814:     if ($gotlock eq 'ok') {
 6815:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6816:         my ($tmp)=keys(%curr_permissions);
 6817:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6818:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6819:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6820:             if (ref($curr_controls) eq 'HASH') {
 6821:                 foreach my $control_item (keys(%{$curr_controls})) {
 6822:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6823:                     if (defined($todelete{$itemnum})) {
 6824:                         push(@deletions,$file_name."\0".$control_item);
 6825:                     } else {
 6826:                         if (defined($changed_items{$itemnum})) {
 6827:                             $new_control{$changed_items{$itemnum}} = $now;
 6828:                             push(@deletions,$file_name."\0".$control_item);
 6829:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6830:                         } else {
 6831:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6832:                         }
 6833:                     }
 6834:                 }
 6835:             }
 6836:         }
 6837:         my ($group);
 6838:         if (&is_course($domain,$user)) {
 6839:             ($group,my $file) = split(/\//,$file_name,2);
 6840:         }
 6841:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6842:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6843:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6844:         #  remove lock
 6845:         my @del_lock = ($file_name."\0".'locked_access_records');
 6846:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6847:         my $sqlresult =
 6848:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6849:                                     $group);
 6850:     } else {
 6851:         $outcome = "error: could not obtain lockfile\n";  
 6852:     }
 6853:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6854: }
 6855: 
 6856: sub make_public_indefinitely {
 6857:     my ($requrl) = @_;
 6858:     my $now = time;
 6859:     my $action = 'activate';
 6860:     my $aclnum = 0;
 6861:     if (&is_portfolio_url($requrl)) {
 6862:         my (undef,$udom,$unum,$file_name,$group) =
 6863:             &parse_portfolio_url($requrl);
 6864:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6865:         my %access_controls = &get_access_controls($current_perms,
 6866:                                                    $group,$file_name);
 6867:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6868:             my ($num,$scope,$end,$start) = 
 6869:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6870:             if ($scope eq 'public') {
 6871:                 if ($start <= $now && $end == 0) {
 6872:                     $action = 'none';
 6873:                 } else {
 6874:                     $action = 'update';
 6875:                     $aclnum = $num;
 6876:                 }
 6877:                 last;
 6878:             }
 6879:         }
 6880:         if ($action eq 'none') {
 6881:              return 'ok';
 6882:         } else {
 6883:             my %changes;
 6884:             my $newend = 0;
 6885:             my $newstart = $now;
 6886:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6887:             $changes{$action}{$newkey} = {
 6888:                 type => 'public',
 6889:                 time => {
 6890:                     start => $newstart,
 6891:                     end   => $newend,
 6892:                 },
 6893:             };
 6894:             my ($outcome,$deloutcome,$new_values,$translation) =
 6895:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6896:             return $outcome;
 6897:         }
 6898:     } else {
 6899:         return 'invalid';
 6900:     }
 6901: }
 6902: 
 6903: #------------------------------------------------------Get Marked as Read Only
 6904: 
 6905: sub get_marked_as_readonly {
 6906:     my ($domain,$user,$what,$group) = @_;
 6907:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6908:     my @readonly_files;
 6909:     my $cmp1=$what;
 6910:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6911:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6912:         if (defined($group)) {
 6913:             if ($file_name !~ m-^\Q$group\E/-) {
 6914:                 next;
 6915:             }
 6916:         }
 6917:         if (ref($value) eq "ARRAY"){
 6918:             foreach my $stored_what (@{$value}) {
 6919:                 my $cmp2=$stored_what;
 6920:                 if (ref($stored_what) eq 'ARRAY') {
 6921:                     $cmp2=join('',@{$stored_what});
 6922:                 }
 6923:                 if ($cmp1 eq $cmp2) {
 6924:                     push(@readonly_files, $file_name);
 6925:                     last;
 6926:                 } elsif (!defined($what)) {
 6927:                     push(@readonly_files, $file_name);
 6928:                     last;
 6929:                 }
 6930:             }
 6931:         }
 6932:     }
 6933:     return @readonly_files;
 6934: }
 6935: #-----------------------------------------------------------Get Marked as Read Only Hash
 6936: 
 6937: sub get_marked_as_readonly_hash {
 6938:     my ($current_permissions,$group,$what) = @_;
 6939:     my %readonly_files;
 6940:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6941:         if (defined($group)) {
 6942:             if ($file_name !~ m-^\Q$group\E/-) {
 6943:                 next;
 6944:             }
 6945:         }
 6946:         if (ref($value) eq "ARRAY"){
 6947:             foreach my $stored_what (@{$value}) {
 6948:                 if (ref($stored_what) eq 'ARRAY') {
 6949:                     foreach my $lock_descriptor(@{$stored_what}) {
 6950:                         if ($lock_descriptor eq 'graded') {
 6951:                             $readonly_files{$file_name} = 'graded';
 6952:                         } elsif ($lock_descriptor eq 'handback') {
 6953:                             $readonly_files{$file_name} = 'handback';
 6954:                         } else {
 6955:                             if (!exists($readonly_files{$file_name})) {
 6956:                                 $readonly_files{$file_name} = 'locked';
 6957:                             }
 6958:                         }
 6959:                     }
 6960:                 } 
 6961:             }
 6962:         } 
 6963:     }
 6964:     return %readonly_files;
 6965: }
 6966: # ------------------------------------------------------------ Unmark as Read Only
 6967: 
 6968: sub unmark_as_readonly {
 6969:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6970:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6971:     my ($domain,$user,$what,$file_name,$group) = @_;
 6972:     $file_name = &declutter_portfile($file_name);
 6973:     my $symb_crs = $what;
 6974:     if (ref($what)) { $symb_crs=join('',@$what); }
 6975:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6976:     my ($tmp)=keys(%current_permissions);
 6977:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6978:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6979:     foreach my $file (@readonly_files) {
 6980: 	my $clean_file = &declutter_portfile($file);
 6981: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6982: 	my $current_locks = $current_permissions{$file};
 6983:         my @new_locks;
 6984:         my @del_keys;
 6985:         if (ref($current_locks) eq "ARRAY"){
 6986:             foreach my $locker (@{$current_locks}) {
 6987:                 my $compare=$locker;
 6988:                 if (ref($locker) eq 'ARRAY') {
 6989:                     $compare=join('',@{$locker});
 6990:                     if ($compare ne $symb_crs) {
 6991:                         push(@new_locks, $locker);
 6992:                     }
 6993:                 }
 6994:             }
 6995:             if (scalar(@new_locks) > 0) {
 6996:                 $current_permissions{$file} = \@new_locks;
 6997:             } else {
 6998:                 push(@del_keys, $file);
 6999:                 &del('file_permissions',\@del_keys, $domain, $user);
 7000:                 delete($current_permissions{$file});
 7001:             }
 7002:         }
 7003:     }
 7004:     &put('file_permissions',\%current_permissions,$domain,$user);
 7005:     return;
 7006: }
 7007: 
 7008: # ------------------------------------------------------------ Directory lister
 7009: 
 7010: sub dirlist {
 7011:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 7012:     $uri=~s/^\///;
 7013:     $uri=~s/\/$//;
 7014:     my ($udom, $uname);
 7015:     if ($getuserdir) {
 7016:         $udom = $userdomain;
 7017:         $uname = $username;
 7018:     } else {
 7019:         (undef,$udom,$uname)=split(/\//,$uri);
 7020:         if(defined($userdomain)) {
 7021:             $udom = $userdomain;
 7022:         }
 7023:         if(defined($username)) {
 7024:             $uname = $username;
 7025:         }
 7026:     }
 7027:     my ($dirRoot,$listing,@listing_results);
 7028: 
 7029:     $dirRoot = $perlvar{'lonDocRoot'};
 7030:     if (defined($getpropath)) {
 7031:         $dirRoot = &propath($udom,$uname);
 7032:         $dirRoot =~ s/\/$//;
 7033:     } elsif (defined($getuserdir)) {
 7034:         my $subdir=$uname.'__';
 7035:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 7036:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 7037:                    ."/$udom/$subdir/$uname";
 7038:     } elsif (defined($alternateRoot)) {
 7039:         $dirRoot = $alternateRoot;
 7040:     }
 7041: 
 7042:     if($udom) {
 7043:         if($uname) {
 7044:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 7045:                               .$getuserdir.':'.&escape($dirRoot)
 7046:                               .':'.&escape($uname).':'.&escape($udom),
 7047:                               &homeserver($uname,$udom));
 7048:             if ($listing eq 'unknown_cmd') {
 7049:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 7050:                                   &homeserver($uname,$udom));
 7051:             } else {
 7052:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7053:             }
 7054:             if ($listing eq 'unknown_cmd') {
 7055:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 7056: 				  &homeserver($uname,$udom));
 7057:                 @listing_results = split(/:/,$listing);
 7058:             } else {
 7059:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7060:             }
 7061:             return @listing_results;
 7062:         } elsif(!$alternateRoot) {
 7063:             my %allusers;
 7064: 	    my %servers = &get_servers($udom,'library');
 7065:  	    foreach my $tryserver (keys(%servers)) {
 7066:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 7067:                                   &escape($udom),$tryserver);
 7068:                 if ($listing eq 'unknown_cmd') {
 7069: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 7070: 				      $udom, $tryserver);
 7071:                 } else {
 7072:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 7073:                 }
 7074: 		if ($listing eq 'unknown_cmd') {
 7075: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 7076: 				      $udom, $tryserver);
 7077: 		    @listing_results = split(/:/,$listing);
 7078: 		} else {
 7079: 		    @listing_results =
 7080: 			map { &unescape($_); } split(/:/,$listing);
 7081: 		}
 7082: 		if ($listing_results[0] ne 'no_such_dir' && 
 7083: 		    $listing_results[0] ne 'empty'       &&
 7084: 		    $listing_results[0] ne 'con_lost') {
 7085: 		    foreach my $line (@listing_results) {
 7086: 			my ($entry) = split(/&/,$line,2);
 7087: 			$allusers{$entry} = 1;
 7088: 		    }
 7089: 		}
 7090:             }
 7091:             my $alluserstr='';
 7092:             foreach my $user (sort(keys(%allusers))) {
 7093:                 $alluserstr.=$user.'&user:';
 7094:             }
 7095:             $alluserstr=~s/:$//;
 7096:             return split(/:/,$alluserstr);
 7097:         } else {
 7098:             return ('missing user name');
 7099:         }
 7100:     } elsif(!defined($getpropath)) {
 7101:         my @all_domains = sort(&all_domains());
 7102:         foreach my $domain (@all_domains) {
 7103:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 7104:         }
 7105:         return @all_domains;
 7106:     } else {
 7107:         return ('missing domain');
 7108:     }
 7109: }
 7110: 
 7111: # --------------------------------------------- GetFileTimestamp
 7112: # This function utilizes dirlist and returns the date stamp for
 7113: # when it was last modified.  It will also return an error of -1
 7114: # if an error occurs
 7115: 
 7116: sub GetFileTimestamp {
 7117:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 7118:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 7119:     $studentName   = &LONCAPA::clean_username($studentName);
 7120:     my ($fileStat) = 
 7121:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 7122:                                  undef,$getuserdir);
 7123:     my @stats = split('&', $fileStat);
 7124:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7125:         # @stats contains first the filename, then the stat output
 7126:         return $stats[10]; # so this is 10 instead of 9.
 7127:     } else {
 7128:         return -1;
 7129:     }
 7130: }
 7131: 
 7132: sub stat_file {
 7133:     my ($uri) = @_;
 7134:     $uri = &clutter_with_no_wrapper($uri);
 7135: 
 7136:     my ($udom,$uname,$file);
 7137:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7138: 	($udom,$uname,$file) =
 7139: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7140: 	$file = 'userfiles/'.$file;
 7141:     }
 7142:     if ($uri =~ m-^/res/-) {
 7143: 	($udom,$uname) = 
 7144: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7145: 	$file = $uri;
 7146:     }
 7147: 
 7148:     if (!$udom || !$uname || !$file) {
 7149: 	# unable to handle the uri
 7150: 	return ();
 7151:     }
 7152:     my $getpropath;
 7153:     if ($file =~ /^userfiles\//) {
 7154:         $getpropath = 1;
 7155:     }
 7156:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7157:     my @stats = split('&', $result);
 7158:     
 7159:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7160: 	shift(@stats); #filename is first
 7161: 	return @stats;
 7162:     }
 7163:     return ();
 7164: }
 7165: 
 7166: # -------------------------------------------------------- Value of a Condition
 7167: 
 7168: # gets the value of a specific preevaluated condition
 7169: #    stored in the string  $env{user.state.<cid>}
 7170: # or looks up a condition reference in the bighash and if if hasn't
 7171: # already been evaluated recurses into docondval to get the value of
 7172: # the condition, then memoizing it to 
 7173: #   $env{user.state.<cid>.<condition>}
 7174: sub directcondval {
 7175:     my $number=shift;
 7176:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7177: 	&Apache::lonuserstate::evalstate();
 7178:     }
 7179:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7180: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7181:     } elsif ($number =~ /^_/) {
 7182: 	my $sub_condition;
 7183: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7184: 		&GDBM_READER(),0640)) {
 7185: 	    $sub_condition=$bighash{'conditions'.$number};
 7186: 	    untie(%bighash);
 7187: 	}
 7188: 	my $value = &docondval($sub_condition);
 7189: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7190: 	return $value;
 7191:     }
 7192:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7193:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7194:     } else {
 7195:        return 2;
 7196:     }
 7197: }
 7198: 
 7199: # get the collection of conditions for this resource
 7200: sub condval {
 7201:     my $condidx=shift;
 7202:     my $allpathcond='';
 7203:     foreach my $cond (split(/\|/,$condidx)) {
 7204: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7205: 	    $allpathcond.=
 7206: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7207: 	}
 7208:     }
 7209:     $allpathcond=~s/\|$//;
 7210:     return &docondval($allpathcond);
 7211: }
 7212: 
 7213: #evaluates an expression of conditions
 7214: sub docondval {
 7215:     my ($allpathcond) = @_;
 7216:     my $result=0;
 7217:     if ($env{'request.course.id'}
 7218: 	&& defined($allpathcond)) {
 7219: 	my $operand='|';
 7220: 	my @stack;
 7221: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7222: 	    if ($chunk eq '(') {
 7223: 		push @stack,($operand,$result);
 7224: 	    } elsif ($chunk eq ')') {
 7225: 		my $before=pop @stack;
 7226: 		if (pop @stack eq '&') {
 7227: 		    $result=$result>$before?$before:$result;
 7228: 		} else {
 7229: 		    $result=$result>$before?$result:$before;
 7230: 		}
 7231: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7232: 		$operand=$chunk;
 7233: 	    } else {
 7234: 		my $new=directcondval($chunk);
 7235: 		if ($operand eq '&') {
 7236: 		    $result=$result>$new?$new:$result;
 7237: 		} else {
 7238: 		    $result=$result>$new?$result:$new;
 7239: 		}
 7240: 	    }
 7241: 	}
 7242:     }
 7243:     return $result;
 7244: }
 7245: 
 7246: # ---------------------------------------------------- Devalidate courseresdata
 7247: 
 7248: sub devalidatecourseresdata {
 7249:     my ($coursenum,$coursedomain)=@_;
 7250:     my $hashid=$coursenum.':'.$coursedomain;
 7251:     &devalidate_cache_new('courseres',$hashid);
 7252: }
 7253: 
 7254: 
 7255: # --------------------------------------------------- Course Resourcedata Query
 7256: #
 7257: #  Parameters:
 7258: #      $coursenum    - Number of the course.
 7259: #      $coursedomain - Domain at which the course was created.
 7260: #  Returns:
 7261: #     A hash of the course parameters along (I think) with timestamps
 7262: #     and version info.
 7263: 
 7264: sub get_courseresdata {
 7265:     my ($coursenum,$coursedomain)=@_;
 7266:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7267:     my $hashid=$coursenum.':'.$coursedomain;
 7268:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7269:     my %dumpreply;
 7270:     unless (defined($cached)) {
 7271: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7272: 	$result=\%dumpreply;
 7273: 	my ($tmp) = keys(%dumpreply);
 7274: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7275: 	    &do_cache_new('courseres',$hashid,$result,600);
 7276: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7277: 	    return $tmp;
 7278: 	} elsif ($tmp =~ /^(error)/) {
 7279: 	    $result=undef;
 7280: 	    &do_cache_new('courseres',$hashid,$result,600);
 7281: 	}
 7282:     }
 7283:     return $result;
 7284: }
 7285: 
 7286: sub devalidateuserresdata {
 7287:     my ($uname,$udom)=@_;
 7288:     my $hashid="$udom:$uname";
 7289:     &devalidate_cache_new('userres',$hashid);
 7290: }
 7291: 
 7292: sub get_userresdata {
 7293:     my ($uname,$udom)=@_;
 7294:     #most student don\'t have any data set, check if there is some data
 7295:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7296: 
 7297:     my $hashid="$udom:$uname";
 7298:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7299:     if (!defined($cached)) {
 7300: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7301: 	$result=\%resourcedata;
 7302: 	&do_cache_new('userres',$hashid,$result,600);
 7303:     }
 7304:     my ($tmp)=keys(%$result);
 7305:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7306: 	return $result;
 7307:     }
 7308:     #error 2 occurs when the .db doesn't exist
 7309:     if ($tmp!~/error: 2 /) {
 7310: 	&logthis("<font color=\"blue\">WARNING:".
 7311: 		 " Trying to get resource data for ".
 7312: 		 $uname." at ".$udom.": ".
 7313: 		 $tmp."</font>");
 7314:     } elsif ($tmp=~/error: 2 /) {
 7315: 	#&EXT_cache_set($udom,$uname);
 7316: 	&do_cache_new('userres',$hashid,undef,600);
 7317: 	undef($tmp); # not really an error so don't send it back
 7318:     }
 7319:     return $tmp;
 7320: }
 7321: #----------------------------------------------- resdata - return resource data
 7322: #  Purpose:
 7323: #    Return resource data for either users or for a course.
 7324: #  Parameters:
 7325: #     $name      - Course/user name.
 7326: #     $domain    - Name of the domain the user/course is registered on.
 7327: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7328: #     @which     - Array of names of resources desired.
 7329: #  Returns:
 7330: #     The value of the first reasource in @which that is found in the
 7331: #     resource hash.
 7332: #  Exceptional Conditions:
 7333: #     If the $type passed in is not valid (not the string 'course' or 
 7334: #     'user', an undefined  reference is returned.
 7335: #     If none of the resources are found, an undef is returned
 7336: sub resdata {
 7337:     my ($name,$domain,$type,@which)=@_;
 7338:     my $result;
 7339:     if ($type eq 'course') {
 7340: 	$result=&get_courseresdata($name,$domain);
 7341:     } elsif ($type eq 'user') {
 7342: 	$result=&get_userresdata($name,$domain);
 7343:     }
 7344:     if (!ref($result)) { return $result; }    
 7345:     foreach my $item (@which) {
 7346: 	if (defined($result->{$item->[0]})) {
 7347: 	    return [$result->{$item->[0]},$item->[1]];
 7348: 	}
 7349:     }
 7350:     return undef;
 7351: }
 7352: 
 7353: #
 7354: # EXT resource caching routines
 7355: #
 7356: 
 7357: sub clear_EXT_cache_status {
 7358:     &delenv('cache.EXT.');
 7359: }
 7360: 
 7361: sub EXT_cache_status {
 7362:     my ($target_domain,$target_user) = @_;
 7363:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7364:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7365:         # We know already the user has no data
 7366:         return 1;
 7367:     } else {
 7368:         return 0;
 7369:     }
 7370: }
 7371: 
 7372: sub EXT_cache_set {
 7373:     my ($target_domain,$target_user) = @_;
 7374:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7375:     #&appenv({$cachename => time});
 7376: }
 7377: 
 7378: # --------------------------------------------------------- Value of a Variable
 7379: sub EXT {
 7380: 
 7381:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7382:     unless ($varname) { return ''; }
 7383:     #get real user name/domain, courseid and symb
 7384:     my $courseid;
 7385:     my $publicuser;
 7386:     if ($symbparm) {
 7387: 	$symbparm=&get_symb_from_alias($symbparm);
 7388:     }
 7389:     if (!($uname && $udom)) {
 7390:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7391:       if (!$symbparm) {	$symbparm=$cursymb; }
 7392:     } else {
 7393: 	$courseid=$env{'request.course.id'};
 7394:     }
 7395:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7396:     my $rest;
 7397:     if (defined($therest[0])) {
 7398:        $rest=join('.',@therest);
 7399:     } else {
 7400:        $rest='';
 7401:     }
 7402: 
 7403:     my $qualifierrest=$qualifier;
 7404:     if ($rest) { $qualifierrest.='.'.$rest; }
 7405:     my $spacequalifierrest=$space;
 7406:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7407:     if ($realm eq 'user') {
 7408: # --------------------------------------------------------------- user.resource
 7409: 	if ($space eq 'resource') {
 7410: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7411: 		  || defined($Apache::lonhomework::parsing_a_task))
 7412: 		 &&
 7413: 		 ($symbparm eq &symbread()) ) {	
 7414: 		# if we are in the middle of processing the resource the
 7415: 		# get the value we are planning on committing
 7416:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7417:                     return $Apache::lonhomework::results{$qualifierrest};
 7418:                 } else {
 7419:                     return $Apache::lonhomework::history{$qualifierrest};
 7420:                 }
 7421: 	    } else {
 7422: 		my %restored;
 7423: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7424: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7425: 		} else {
 7426: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7427: 		}
 7428: 		return $restored{$qualifierrest};
 7429: 	    }
 7430: # ----------------------------------------------------------------- user.access
 7431:         } elsif ($space eq 'access') {
 7432: 	    # FIXME - not supporting calls for a specific user
 7433:             return &allowed($qualifier,$rest);
 7434: # ------------------------------------------ user.preferences, user.environment
 7435:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7436: 	    if (($uname eq $env{'user.name'}) &&
 7437: 		($udom eq $env{'user.domain'})) {
 7438: 		return $env{join('.',('environment',$qualifierrest))};
 7439: 	    } else {
 7440: 		my %returnhash;
 7441: 		if (!$publicuser) {
 7442: 		    %returnhash=&userenvironment($udom,$uname,
 7443: 						 $qualifierrest);
 7444: 		}
 7445: 		return $returnhash{$qualifierrest};
 7446: 	    }
 7447: # ----------------------------------------------------------------- user.course
 7448:         } elsif ($space eq 'course') {
 7449: 	    # FIXME - not supporting calls for a specific user
 7450:             return $env{join('.',('request.course',$qualifier))};
 7451: # ------------------------------------------------------------------- user.role
 7452:         } elsif ($space eq 'role') {
 7453: 	    # FIXME - not supporting calls for a specific user
 7454:             my ($role,$where)=split(/\./,$env{'request.role'});
 7455:             if ($qualifier eq 'value') {
 7456: 		return $role;
 7457:             } elsif ($qualifier eq 'extent') {
 7458:                 return $where;
 7459:             }
 7460: # ----------------------------------------------------------------- user.domain
 7461:         } elsif ($space eq 'domain') {
 7462:             return $udom;
 7463: # ------------------------------------------------------------------- user.name
 7464:         } elsif ($space eq 'name') {
 7465:             return $uname;
 7466: # ---------------------------------------------------- Any other user namespace
 7467:         } else {
 7468: 	    my %reply;
 7469: 	    if (!$publicuser) {
 7470: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7471: 	    }
 7472: 	    return $reply{$qualifierrest};
 7473:         }
 7474:     } elsif ($realm eq 'query') {
 7475: # ---------------------------------------------- pull stuff out of query string
 7476:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7477: 						[$spacequalifierrest]);
 7478: 	return $env{'form.'.$spacequalifierrest}; 
 7479:    } elsif ($realm eq 'request') {
 7480: # ------------------------------------------------------------- request.browser
 7481:         if ($space eq 'browser') {
 7482: 	    if ($qualifier eq 'textremote') {
 7483: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7484: 		    return 1;
 7485: 		} else {
 7486: 		    return 0;
 7487: 		}
 7488: 	    } else {
 7489: 		return $env{'browser.'.$qualifier};
 7490: 	    }
 7491: # ------------------------------------------------------------ request.filename
 7492:         } else {
 7493:             return $env{'request.'.$spacequalifierrest};
 7494:         }
 7495:     } elsif ($realm eq 'course') {
 7496: # ---------------------------------------------------------- course.description
 7497:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7498:     } elsif ($realm eq 'resource') {
 7499: 
 7500: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7501: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7502: 	}
 7503: 
 7504: 	if ($space eq 'title') {
 7505: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7506: 	    return &gettitle($symbparm);
 7507: 	}
 7508: 	
 7509: 	if ($space eq 'map') {
 7510: 	    my ($map) = &decode_symb($symbparm);
 7511: 	    return &symbread($map);
 7512: 	}
 7513: 	if ($space eq 'filename') {
 7514: 	    if ($symbparm) {
 7515: 		return &clutter((&decode_symb($symbparm))[2]);
 7516: 	    }
 7517: 	    return &hreflocation('',$env{'request.filename'});
 7518: 	}
 7519: 
 7520: 	my ($section, $group, @groups);
 7521: 	my ($courselevelm,$courselevel);
 7522: 	if ($symbparm && defined($courseid) && 
 7523: 	    $courseid eq $env{'request.course.id'}) {
 7524: 
 7525: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7526: 
 7527: # ----------------------------------------------------- Cascading lookup scheme
 7528: 	    my $symbp=$symbparm;
 7529: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7530: 
 7531: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7532: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7533: 
 7534: 	    if (($env{'user.name'} eq $uname) &&
 7535: 		($env{'user.domain'} eq $udom)) {
 7536: 		$section=$env{'request.course.sec'};
 7537:                 @groups = split(/:/,$env{'request.course.groups'});  
 7538:                 @groups=&sort_course_groups($courseid,@groups); 
 7539: 	    } else {
 7540: 		if (! defined($usection)) {
 7541: 		    $section=&getsection($udom,$uname,$courseid);
 7542: 		} else {
 7543: 		    $section = $usection;
 7544: 		}
 7545:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7546: 	    }
 7547: 
 7548: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7549: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7550: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7551: 
 7552: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7553: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7554: 	    $courselevelm=$courseid.'.'.$mapparm;
 7555: 
 7556: # ----------------------------------------------------------- first, check user
 7557: 
 7558: 	    my $userreply=&resdata($uname,$udom,'user',
 7559: 				       ([$courselevelr,'resource'],
 7560: 					[$courselevelm,'map'     ],
 7561: 					[$courselevel, 'course'  ]));
 7562: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7563: 
 7564: # ------------------------------------------------ second, check some of course
 7565:             my $coursereply;
 7566:             if (@groups > 0) {
 7567:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7568:                                        $mapparm,$spacequalifierrest);
 7569:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7570:             }
 7571: 
 7572: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7573: 				  $env{'course.'.$courseid.'.domain'},
 7574: 				  'course',
 7575: 				  ([$seclevelr,   'resource'],
 7576: 				   [$seclevelm,   'map'     ],
 7577: 				   [$seclevel,    'course'  ],
 7578: 				   [$courselevelr,'resource']));
 7579: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7580: 
 7581: # ------------------------------------------------------ third, check map parms
 7582: 	    my %parmhash=();
 7583: 	    my $thisparm='';
 7584: 	    if (tie(%parmhash,'GDBM_File',
 7585: 		    $env{'request.course.fn'}.'_parms.db',
 7586: 		    &GDBM_READER(),0640)) {
 7587: 		$thisparm=$parmhash{$symbparm};
 7588: 		untie(%parmhash);
 7589: 	    }
 7590: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7591: 	}
 7592: # ------------------------------------------ fourth, look in resource metadata
 7593: 
 7594: 	$spacequalifierrest=~s/\./\_/;
 7595: 	my $filename;
 7596: 	if (!$symbparm) { $symbparm=&symbread(); }
 7597: 	if ($symbparm) {
 7598: 	    $filename=(&decode_symb($symbparm))[2];
 7599: 	} else {
 7600: 	    $filename=$env{'request.filename'};
 7601: 	}
 7602: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7603: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7604: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7605: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7606: 
 7607: # ---------------------------------------------- fourth, look in rest of course
 7608: 	if ($symbparm && defined($courseid) && 
 7609: 	    $courseid eq $env{'request.course.id'}) {
 7610: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7611: 				     $env{'course.'.$courseid.'.domain'},
 7612: 				     'course',
 7613: 				     ([$courselevelm,'map'   ],
 7614: 				      [$courselevel, 'course']));
 7615: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7616: 	}
 7617: # ------------------------------------------------------------------ Cascade up
 7618: 	unless ($space eq '0') {
 7619: 	    my @parts=split(/_/,$space);
 7620: 	    my $id=pop(@parts);
 7621: 	    my $part=join('_',@parts);
 7622: 	    if ($part eq '') { $part='0'; }
 7623: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7624: 				 $symbparm,$udom,$uname,$section,1);
 7625: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7626: 	}
 7627: 	if ($recurse) { return undef; }
 7628: 	my $pack_def=&packages_tab_default($filename,$varname);
 7629: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7630: # ---------------------------------------------------- Any other user namespace
 7631:     } elsif ($realm eq 'environment') {
 7632: # ----------------------------------------------------------------- environment
 7633: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7634: 	    return $env{'environment.'.$spacequalifierrest};
 7635: 	} else {
 7636: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7637: 		return '';
 7638: 	    }
 7639: 	    my %returnhash=&userenvironment($udom,$uname,
 7640: 					    $spacequalifierrest);
 7641: 	    return $returnhash{$spacequalifierrest};
 7642: 	}
 7643:     } elsif ($realm eq 'system') {
 7644: # ----------------------------------------------------------------- system.time
 7645: 	if ($space eq 'time') {
 7646: 	    return time;
 7647:         }
 7648:     } elsif ($realm eq 'server') {
 7649: # ----------------------------------------------------------------- system.time
 7650: 	if ($space eq 'name') {
 7651: 	    return $ENV{'SERVER_NAME'};
 7652:         }
 7653:     }
 7654:     return '';
 7655: }
 7656: 
 7657: sub get_reply {
 7658:     my ($reply_value) = @_;
 7659:     if (ref($reply_value) eq 'ARRAY') {
 7660:         if (wantarray) {
 7661: 	    return @$reply_value;
 7662:         }
 7663:         return $reply_value->[0];
 7664:     } else {
 7665:         return $reply_value;
 7666:     }
 7667: }
 7668: 
 7669: sub check_group_parms {
 7670:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7671:     my @groupitems = ();
 7672:     my $resultitem;
 7673:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7674:     foreach my $group (@{$groups}) {
 7675:         foreach my $level (@levels) {
 7676:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7677:              push(@groupitems,[$item,$level->[1]]);
 7678:         }
 7679:     }
 7680:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7681:                             $env{'course.'.$courseid.'.domain'},
 7682:                                      'course',@groupitems);
 7683:     return $coursereply;
 7684: }
 7685: 
 7686: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7687:     my ($courseid,@groups) = @_;
 7688:     @groups = sort(@groups);
 7689:     return @groups;
 7690: }
 7691: 
 7692: sub packages_tab_default {
 7693:     my ($uri,$varname)=@_;
 7694:     my (undef,$part,$name)=split(/\./,$varname);
 7695: 
 7696:     my (@extension,@specifics,$do_default);
 7697:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7698: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7699: 	if ($pack_type eq 'default') {
 7700: 	    $do_default=1;
 7701: 	} elsif ($pack_type eq 'extension') {
 7702: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7703: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7704: 	    # only look at packages defaults for packages that this id is
 7705: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7706: 	}
 7707:     }
 7708:     # first look for a package that matches the requested part id
 7709:     foreach my $package (@specifics) {
 7710: 	my (undef,$pack_type,$pack_part)=@{$package};
 7711: 	next if ($pack_part ne $part);
 7712: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7713: 	    return $packagetab{"$pack_type&$name&default"};
 7714: 	}
 7715:     }
 7716:     # look for any possible matching non extension_ package
 7717:     foreach my $package (@specifics) {
 7718: 	my (undef,$pack_type,$pack_part)=@{$package};
 7719: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7720: 	    return $packagetab{"$pack_type&$name&default"};
 7721: 	}
 7722: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7723: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7724: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7725: 	}
 7726:     }
 7727:     # look for any posible extension_ match
 7728:     foreach my $package (@extension) {
 7729: 	my ($package,$pack_type)=@{$package};
 7730: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7731: 	    return $packagetab{"$pack_type&$name&default"};
 7732: 	}
 7733: 	if (defined($packagetab{$package."&$name&default"})) {
 7734: 	    return $packagetab{$package."&$name&default"};
 7735: 	}
 7736:     }
 7737:     # look for a global default setting
 7738:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7739: 	return $packagetab{"default&$name&default"};
 7740:     }
 7741:     return undef;
 7742: }
 7743: 
 7744: sub add_prefix_and_part {
 7745:     my ($prefix,$part)=@_;
 7746:     my $keyroot;
 7747:     if (defined($prefix) && $prefix !~ /^__/) {
 7748: 	# prefix that has a part already
 7749: 	$keyroot=$prefix;
 7750:     } elsif (defined($prefix)) {
 7751: 	# prefix that is missing a part
 7752: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7753:     } else {
 7754: 	# no prefix at all
 7755: 	if (defined($part)) { $keyroot='_'.$part; }
 7756:     }
 7757:     return $keyroot;
 7758: }
 7759: 
 7760: # ---------------------------------------------------------------- Get metadata
 7761: 
 7762: my %metaentry;
 7763: sub metadata {
 7764:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7765:     $uri=&declutter($uri);
 7766:     # if it is a non metadata possible uri return quickly
 7767:     if (($uri eq '') || 
 7768: 	(($uri =~ m|^/*adm/|) && 
 7769: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7770:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7771: 	return undef;
 7772:     }
 7773:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7774: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7775: 	return undef;
 7776:     }
 7777:     my $filename=$uri;
 7778:     $uri=~s/\.meta$//;
 7779: #
 7780: # Is the metadata already cached?
 7781: # Look at timestamp of caching
 7782: # Everything is cached by the main uri, libraries are never directly cached
 7783: #
 7784:     if (!defined($liburi)) {
 7785: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7786: 	if (defined($cached)) { return $result->{':'.$what}; }
 7787:     }
 7788:     {
 7789: #
 7790: # Is this a recursive call for a library?
 7791: #
 7792: #	if (! exists($metacache{$uri})) {
 7793: #	    $metacache{$uri}={};
 7794: #	}
 7795: 	my $cachetime = 60*60;
 7796:         if ($liburi) {
 7797: 	    $liburi=&declutter($liburi);
 7798:             $filename=$liburi;
 7799:         } else {
 7800: 	    &devalidate_cache_new('meta',$uri);
 7801: 	    undef(%metaentry);
 7802: 	}
 7803:         my %metathesekeys=();
 7804:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7805: 	my $metastring;
 7806: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7807: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7808: 	    $metastring = 
 7809: 		&Apache::lonnet::ssi_body($which,
 7810: 					  ('grade_target' => 'meta'));
 7811: 	    $cachetime = 1; # only want this cached in the child not long term
 7812: 	} elsif ($uri !~ m -^(editupload)/-) {
 7813: 	    my $file=&filelocation('',&clutter($filename));
 7814: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7815: 	    $metastring=&getfile($file);
 7816: 	}
 7817:         my $parser=HTML::LCParser->new(\$metastring);
 7818:         my $token;
 7819:         undef %metathesekeys;
 7820:         while ($token=$parser->get_token) {
 7821: 	    if ($token->[0] eq 'S') {
 7822: 		if (defined($token->[2]->{'package'})) {
 7823: #
 7824: # This is a package - get package info
 7825: #
 7826: 		    my $package=$token->[2]->{'package'};
 7827: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7828: 		    if (defined($token->[2]->{'id'})) { 
 7829: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7830: 		    }
 7831: 		    if ($metaentry{':packages'}) {
 7832: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7833: 		    } else {
 7834: 			$metaentry{':packages'}=$package.$keyroot;
 7835: 		    }
 7836: 		    foreach my $pack_entry (keys(%packagetab)) {
 7837: 			my $part=$keyroot;
 7838: 			$part=~s/^\_//;
 7839: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7840: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7841: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7842: 			    # ignore package.tab specified default values
 7843:                             # here &package_tab_default() will fetch those
 7844: 			    if ($subp eq 'default') { next; }
 7845: 			    my $value=$packagetab{$pack_entry};
 7846: 			    my $unikey;
 7847: 			    if ($pack =~ /_0$/) {
 7848: 				$unikey='parameter_0_'.$name;
 7849: 				$part=0;
 7850: 			    } else {
 7851: 				$unikey='parameter'.$keyroot.'_'.$name;
 7852: 			    }
 7853: 			    if ($subp eq 'display') {
 7854: 				$value.=' [Part: '.$part.']';
 7855: 			    }
 7856: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7857: 			    $metathesekeys{$unikey}=1;
 7858: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7859: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7860: 			    }
 7861: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7862: 				$metaentry{':'.$unikey}=
 7863: 				    $metaentry{':'.$unikey.'.default'};
 7864: 			    }
 7865: 			}
 7866: 		    }
 7867: 		} else {
 7868: #
 7869: # This is not a package - some other kind of start tag
 7870: #
 7871: 		    my $entry=$token->[1];
 7872: 		    my $unikey;
 7873: 		    if ($entry eq 'import') {
 7874: 			$unikey='';
 7875: 		    } else {
 7876: 			$unikey=$entry;
 7877: 		    }
 7878: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7879: 
 7880: 		    if (defined($token->[2]->{'id'})) { 
 7881: 			$unikey.='_'.$token->[2]->{'id'}; 
 7882: 		    }
 7883: 
 7884: 		    if ($entry eq 'import') {
 7885: #
 7886: # Importing a library here
 7887: #
 7888: 			if ($depthcount<20) {
 7889: 			    my $location=$parser->get_text('/import');
 7890: 			    my $dir=$filename;
 7891: 			    $dir=~s|[^/]*$||;
 7892: 			    $location=&filelocation($dir,$location);
 7893: 			    my $metadata = 
 7894: 				&metadata($uri,'keys', $location,$unikey,
 7895: 					  $depthcount+1);
 7896: 			    foreach my $meta (split(',',$metadata)) {
 7897: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7898: 				$metathesekeys{$meta}=1;
 7899: 			    }
 7900: 			}
 7901: 		    } else { 
 7902: 			
 7903: 			if (defined($token->[2]->{'name'})) { 
 7904: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7905: 			}
 7906: 			$metathesekeys{$unikey}=1;
 7907: 			foreach my $param (@{$token->[3]}) {
 7908: 			    $metaentry{':'.$unikey.'.'.$param} =
 7909: 				$token->[2]->{$param};
 7910: 			}
 7911: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7912: 			my $default=$metaentry{':'.$unikey.'.default'};
 7913: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7914: 		 # only ws inside the tag, and not in default, so use default
 7915: 		 # as value
 7916: 			    $metaentry{':'.$unikey}=$default;
 7917: 			} elsif ( $internaltext =~ /\S/ ) {
 7918: 		  # something interesting inside the tag
 7919: 			    $metaentry{':'.$unikey}=$internaltext;
 7920: 			} else {
 7921: 		  # no interesting values, don't set a default
 7922: 			}
 7923: # end of not-a-package not-a-library import
 7924: 		    }
 7925: # end of not-a-package start tag
 7926: 		}
 7927: # the next is the end of "start tag"
 7928: 	    }
 7929: 	}
 7930: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7931: 	$extension = lc($extension);
 7932: 	if ($extension eq 'htm') { $extension='html'; }
 7933: 
 7934: 	foreach my $key (keys(%packagetab)) {
 7935: 	    #no specific packages #how's our extension
 7936: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7937: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7938: 					 \%metathesekeys);
 7939: 	}
 7940: 
 7941: 	if (!exists($metaentry{':packages'})
 7942: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7943: 	    foreach my $key (keys(%packagetab)) {
 7944: 		#no specific packages well let's get default then
 7945: 		if ($key!~/^default&/) { next; }
 7946: 		&metadata_create_package_def($uri,$key,'default',
 7947: 					     \%metathesekeys);
 7948: 	    }
 7949: 	}
 7950: # are there custom rights to evaluate
 7951: 	if ($metaentry{':copyright'} eq 'custom') {
 7952: 
 7953:     #
 7954:     # Importing a rights file here
 7955:     #
 7956: 	    unless ($depthcount) {
 7957: 		my $location=$metaentry{':customdistributionfile'};
 7958: 		my $dir=$filename;
 7959: 		$dir=~s|[^/]*$||;
 7960: 		$location=&filelocation($dir,$location);
 7961: 		my $rights_metadata =
 7962: 		    &metadata($uri,'keys',$location,'_rights',
 7963: 			      $depthcount+1);
 7964: 		foreach my $rights (split(',',$rights_metadata)) {
 7965: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7966: 		    $metathesekeys{$rights}=1;
 7967: 		}
 7968: 	    }
 7969: 	}
 7970: 	# uniqifiy package listing
 7971: 	my %seen;
 7972: 	my @uniq_packages =
 7973: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7974: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7975: 
 7976: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7977: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7978: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7979: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7980: # this is the end of "was not already recently cached
 7981:     }
 7982:     return $metaentry{':'.$what};
 7983: }
 7984: 
 7985: sub metadata_create_package_def {
 7986:     my ($uri,$key,$package,$metathesekeys)=@_;
 7987:     my ($pack,$name,$subp)=split(/\&/,$key);
 7988:     if ($subp eq 'default') { next; }
 7989:     
 7990:     if (defined($metaentry{':packages'})) {
 7991: 	$metaentry{':packages'}.=','.$package;
 7992:     } else {
 7993: 	$metaentry{':packages'}=$package;
 7994:     }
 7995:     my $value=$packagetab{$key};
 7996:     my $unikey;
 7997:     $unikey='parameter_0_'.$name;
 7998:     $metaentry{':'.$unikey.'.part'}=0;
 7999:     $$metathesekeys{$unikey}=1;
 8000:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8001: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 8002:     }
 8003:     if (defined($metaentry{':'.$unikey.'.default'})) {
 8004: 	$metaentry{':'.$unikey}=
 8005: 	    $metaentry{':'.$unikey.'.default'};
 8006:     }
 8007: }
 8008: 
 8009: sub metadata_generate_part0 {
 8010:     my ($metadata,$metacache,$uri) = @_;
 8011:     my %allnames;
 8012:     foreach my $metakey (keys(%$metadata)) {
 8013: 	if ($metakey=~/^parameter\_(.*)/) {
 8014: 	  my $part=$$metacache{':'.$metakey.'.part'};
 8015: 	  my $name=$$metacache{':'.$metakey.'.name'};
 8016: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 8017: 	    $allnames{$name}=$part;
 8018: 	  }
 8019: 	}
 8020:     }
 8021:     foreach my $name (keys(%allnames)) {
 8022:       $$metadata{"parameter_0_$name"}=1;
 8023:       my $key=":parameter_0_$name";
 8024:       $$metacache{"$key.part"}='0';
 8025:       $$metacache{"$key.name"}=$name;
 8026:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 8027: 					   $allnames{$name}.'_'.$name.
 8028: 					   '.type'};
 8029:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 8030: 			     '.display'};
 8031:       my $expr='[Part: '.$allnames{$name}.']';
 8032:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 8033:       $$metacache{"$key.display"}=$olddis;
 8034:     }
 8035: }
 8036: 
 8037: # ------------------------------------------------------ Devalidate title cache
 8038: 
 8039: sub devalidate_title_cache {
 8040:     my ($url)=@_;
 8041:     if (!$env{'request.course.id'}) { return; }
 8042:     my $symb=&symbread($url);
 8043:     if (!$symb) { return; }
 8044:     my $key=$env{'request.course.id'}."\0".$symb;
 8045:     &devalidate_cache_new('title',$key);
 8046: }
 8047: 
 8048: # ------------------------------------------------- Get the title of a course
 8049: 
 8050: sub current_course_title {
 8051:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 8052: }
 8053: # ------------------------------------------------- Get the title of a resource
 8054: 
 8055: sub gettitle {
 8056:     my $urlsymb=shift;
 8057:     my $symb=&symbread($urlsymb);
 8058:     if ($symb) {
 8059: 	my $key=$env{'request.course.id'}."\0".$symb;
 8060: 	my ($result,$cached)=&is_cached_new('title',$key);
 8061: 	if (defined($cached)) { 
 8062: 	    return $result;
 8063: 	}
 8064: 	my ($map,$resid,$url)=&decode_symb($symb);
 8065: 	my $title='';
 8066: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 8067: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 8068: 	} else {
 8069: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8070: 		    &GDBM_READER(),0640)) {
 8071: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 8072: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 8073: 		untie(%bighash);
 8074: 	    }
 8075: 	}
 8076: 	$title=~s/\&colon\;/\:/gs;
 8077: 	if ($title) {
 8078: 	    return &do_cache_new('title',$key,$title,600);
 8079: 	}
 8080: 	$urlsymb=$url;
 8081:     }
 8082:     my $title=&metadata($urlsymb,'title');
 8083:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 8084:     return $title;
 8085: }
 8086: 
 8087: sub get_slot {
 8088:     my ($which,$cnum,$cdom)=@_;
 8089:     if (!$cnum || !$cdom) {
 8090: 	(undef,my $courseid)=&whichuser();
 8091: 	$cdom=$env{'course.'.$courseid.'.domain'};
 8092: 	$cnum=$env{'course.'.$courseid.'.num'};
 8093:     }
 8094:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 8095:     my %slotinfo;
 8096:     if (exists($remembered{$key})) {
 8097: 	$slotinfo{$which} = $remembered{$key};
 8098:     } else {
 8099: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 8100: 	&Apache::lonhomework::showhash(%slotinfo);
 8101: 	my ($tmp)=keys(%slotinfo);
 8102: 	if ($tmp=~/^error:/) { return (); }
 8103: 	$remembered{$key} = $slotinfo{$which};
 8104:     }
 8105:     if (ref($slotinfo{$which}) eq 'HASH') {
 8106: 	return %{$slotinfo{$which}};
 8107:     }
 8108:     return $slotinfo{$which};
 8109: }
 8110: # ------------------------------------------------- Update symbolic store links
 8111: 
 8112: sub symblist {
 8113:     my ($mapname,%newhash)=@_;
 8114:     $mapname=&deversion(&declutter($mapname));
 8115:     my %hash;
 8116:     if (($env{'request.course.fn'}) && (%newhash)) {
 8117:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8118:                       &GDBM_WRCREAT(),0640)) {
 8119: 	    foreach my $url (keys(%newhash)) {
 8120: 		next if ($url eq 'last_known'
 8121: 			 && $env{'form.no_update_last_known'});
 8122: 		$hash{declutter($url)}=&encode_symb($mapname,
 8123: 						    $newhash{$url}->[1],
 8124: 						    $newhash{$url}->[0]);
 8125:             }
 8126:             if (untie(%hash)) {
 8127: 		return 'ok';
 8128:             }
 8129:         }
 8130:     }
 8131:     return 'error';
 8132: }
 8133: 
 8134: # --------------------------------------------------------------- Verify a symb
 8135: 
 8136: sub symbverify {
 8137:     my ($symb,$thisurl)=@_;
 8138:     my $thisfn=$thisurl;
 8139:     $thisfn=&declutter($thisfn);
 8140: # direct jump to resource in page or to a sequence - will construct own symbs
 8141:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8142: # check URL part
 8143:     my ($map,$resid,$url)=&decode_symb($symb);
 8144: 
 8145:     unless ($url eq $thisfn) { return 0; }
 8146: 
 8147:     $symb=&symbclean($symb);
 8148:     $thisurl=&deversion($thisurl);
 8149:     $thisfn=&deversion($thisfn);
 8150: 
 8151:     my %bighash;
 8152:     my $okay=0;
 8153: 
 8154:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8155:                             &GDBM_READER(),0640)) {
 8156:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8157:         unless ($ids) { 
 8158:            $ids=$bighash{'ids_/'.$thisurl};
 8159:         }
 8160:         if ($ids) {
 8161: # ------------------------------------------------------------------- Has ID(s)
 8162: 	    foreach my $id (split(/\,/,$ids)) {
 8163: 	       my ($mapid,$resid)=split(/\./,$id);
 8164:                if (
 8165:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8166:    eq $symb) { 
 8167: 		   if (($env{'request.role.adv'}) ||
 8168: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8169: 		       $okay=1; 
 8170: 		   }
 8171: 	       }
 8172: 	   }
 8173:         }
 8174: 	untie(%bighash);
 8175:     }
 8176:     return $okay;
 8177: }
 8178: 
 8179: # --------------------------------------------------------------- Clean-up symb
 8180: 
 8181: sub symbclean {
 8182:     my $symb=shift;
 8183:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8184: # remove version from map
 8185:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8186: 
 8187: # remove version from URL
 8188:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8189: 
 8190: # remove wrapper
 8191: 
 8192:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8193:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8194:     return $symb;
 8195: }
 8196: 
 8197: # ---------------------------------------------- Split symb to find map and url
 8198: 
 8199: sub encode_symb {
 8200:     my ($map,$resid,$url)=@_;
 8201:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8202: }
 8203: 
 8204: sub decode_symb {
 8205:     my $symb=shift;
 8206:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8207:     my ($map,$resid,$url)=split(/___/,$symb);
 8208:     return (&fixversion($map),$resid,&fixversion($url));
 8209: }
 8210: 
 8211: sub fixversion {
 8212:     my $fn=shift;
 8213:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8214:     my %bighash;
 8215:     my $uri=&clutter($fn);
 8216:     my $key=$env{'request.course.id'}.'_'.$uri;
 8217: # is this cached?
 8218:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8219:     if (defined($cached)) { return $result; }
 8220: # unfortunately not cached, or expired
 8221:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8222: 	    &GDBM_READER(),0640)) {
 8223:  	if ($bighash{'version_'.$uri}) {
 8224:  	    my $version=$bighash{'version_'.$uri};
 8225:  	    unless (($version eq 'mostrecent') || 
 8226: 		    ($version==&getversion($uri))) {
 8227:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8228:  	    }
 8229:  	}
 8230:  	untie %bighash;
 8231:     }
 8232:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8233: }
 8234: 
 8235: sub deversion {
 8236:     my $url=shift;
 8237:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8238:     return $url;
 8239: }
 8240: 
 8241: # ------------------------------------------------------ Return symb list entry
 8242: 
 8243: sub symbread {
 8244:     my ($thisfn,$donotrecurse)=@_;
 8245:     my $cache_str='request.symbread.cached.'.$thisfn;
 8246:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8247: # no filename provided? try from environment
 8248:     unless ($thisfn) {
 8249:         if ($env{'request.symb'}) {
 8250: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8251: 	}
 8252: 	$thisfn=$env{'request.filename'};
 8253:     }
 8254:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8255: # is that filename actually a symb? Verify, clean, and return
 8256:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8257: 	if (&symbverify($thisfn,$1)) {
 8258: 	    return $env{$cache_str}=&symbclean($thisfn);
 8259: 	}
 8260:     }
 8261:     $thisfn=declutter($thisfn);
 8262:     my %hash;
 8263:     my %bighash;
 8264:     my $syval='';
 8265:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8266:         my $targetfn = $thisfn;
 8267:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8268:             $targetfn = 'adm/wrapper/'.$thisfn;
 8269:         }
 8270: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8271: 	    $targetfn=$1;
 8272: 	}
 8273:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8274:                       &GDBM_READER(),0640)) {
 8275: 	    $syval=$hash{$targetfn};
 8276:             untie(%hash);
 8277:         }
 8278: # ---------------------------------------------------------- There was an entry
 8279:         if ($syval) {
 8280: 	    #unless ($syval=~/\_\d+$/) {
 8281: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8282: 		    #&appenv({'request.ambiguous' => $thisfn});
 8283: 		    #return $env{$cache_str}='';
 8284: 		#}    
 8285: 		#$syval.=$1;
 8286: 	    #}
 8287:         } else {
 8288: # ------------------------------------------------------- Was not in symb table
 8289:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8290:                             &GDBM_READER(),0640)) {
 8291: # ---------------------------------------------- Get ID(s) for current resource
 8292:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8293:               unless ($ids) { 
 8294:                  $ids=$bighash{'ids_/'.$thisfn};
 8295:               }
 8296:               unless ($ids) {
 8297: # alias?
 8298: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8299:               }
 8300:               if ($ids) {
 8301: # ------------------------------------------------------------------- Has ID(s)
 8302:                  my @possibilities=split(/\,/,$ids);
 8303:                  if ($#possibilities==0) {
 8304: # ----------------------------------------------- There is only one possibility
 8305: 		     my ($mapid,$resid)=split(/\./,$ids);
 8306: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8307: 						    $resid,$thisfn);
 8308:                  } elsif (!$donotrecurse) {
 8309: # ------------------------------------------ There is more than one possibility
 8310:                      my $realpossible=0;
 8311:                      foreach my $id (@possibilities) {
 8312: 			 my $file=$bighash{'src_'.$id};
 8313:                          if (&allowed('bre',$file)) {
 8314:          		    my ($mapid,$resid)=split(/\./,$id);
 8315:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8316: 				$realpossible++;
 8317:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8318: 						    $resid,$thisfn);
 8319:                             }
 8320: 			 }
 8321:                      }
 8322: 		     if ($realpossible!=1) { $syval=''; }
 8323:                  } else {
 8324:                      $syval='';
 8325:                  }
 8326: 	      }
 8327:               untie(%bighash)
 8328:            }
 8329:         }
 8330:         if ($syval) {
 8331: 	    return $env{$cache_str}=$syval;
 8332:         }
 8333:     }
 8334:     &appenv({'request.ambiguous' => $thisfn});
 8335:     return $env{$cache_str}='';
 8336: }
 8337: 
 8338: # ---------------------------------------------------------- Return random seed
 8339: 
 8340: sub numval {
 8341:     my $txt=shift;
 8342:     $txt=~tr/A-J/0-9/;
 8343:     $txt=~tr/a-j/0-9/;
 8344:     $txt=~tr/K-T/0-9/;
 8345:     $txt=~tr/k-t/0-9/;
 8346:     $txt=~tr/U-Z/0-5/;
 8347:     $txt=~tr/u-z/0-5/;
 8348:     $txt=~s/\D//g;
 8349:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8350:     return int($txt);
 8351: }
 8352: 
 8353: sub numval2 {
 8354:     my $txt=shift;
 8355:     $txt=~tr/A-J/0-9/;
 8356:     $txt=~tr/a-j/0-9/;
 8357:     $txt=~tr/K-T/0-9/;
 8358:     $txt=~tr/k-t/0-9/;
 8359:     $txt=~tr/U-Z/0-5/;
 8360:     $txt=~tr/u-z/0-5/;
 8361:     $txt=~s/\D//g;
 8362:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8363:     my $total;
 8364:     foreach my $val (@txts) { $total+=$val; }
 8365:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8366:     return int($total);
 8367: }
 8368: 
 8369: sub numval3 {
 8370:     use integer;
 8371:     my $txt=shift;
 8372:     $txt=~tr/A-J/0-9/;
 8373:     $txt=~tr/a-j/0-9/;
 8374:     $txt=~tr/K-T/0-9/;
 8375:     $txt=~tr/k-t/0-9/;
 8376:     $txt=~tr/U-Z/0-5/;
 8377:     $txt=~tr/u-z/0-5/;
 8378:     $txt=~s/\D//g;
 8379:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8380:     my $total;
 8381:     foreach my $val (@txts) { $total+=$val; }
 8382:     if ($_64bit) { $total=(($total<<32)>>32); }
 8383:     return $total;
 8384: }
 8385: 
 8386: sub digest {
 8387:     my ($data)=@_;
 8388:     my $digest=&Digest::MD5::md5($data);
 8389:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8390:     my ($e,$f);
 8391:     {
 8392:         use integer;
 8393:         $e=($a+$b);
 8394:         $f=($c+$d);
 8395:         if ($_64bit) {
 8396:             $e=(($e<<32)>>32);
 8397:             $f=(($f<<32)>>32);
 8398:         }
 8399:     }
 8400:     if (wantarray) {
 8401: 	return ($e,$f);
 8402:     } else {
 8403: 	my $g;
 8404: 	{
 8405: 	    use integer;
 8406: 	    $g=($e+$f);
 8407: 	    if ($_64bit) {
 8408: 		$g=(($g<<32)>>32);
 8409: 	    }
 8410: 	}
 8411: 	return $g;
 8412:     }
 8413: }
 8414: 
 8415: sub latest_rnd_algorithm_id {
 8416:     return '64bit5';
 8417: }
 8418: 
 8419: sub get_rand_alg {
 8420:     my ($courseid)=@_;
 8421:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8422:     if ($courseid) {
 8423: 	return $env{"course.$courseid.rndseed"};
 8424:     }
 8425:     return &latest_rnd_algorithm_id();
 8426: }
 8427: 
 8428: sub validCODE {
 8429:     my ($CODE)=@_;
 8430:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8431:     return 0;
 8432: }
 8433: 
 8434: sub getCODE {
 8435:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8436:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8437: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8438: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8439: 	return $Apache::lonhomework::history{'resource.CODE'};
 8440:     }
 8441:     return undef;
 8442: }
 8443: 
 8444: sub rndseed {
 8445:     my ($symb,$courseid,$domain,$username)=@_;
 8446:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8447:     if (!defined($symb)) {
 8448: 	unless ($symb=$wsymb) { return time; }
 8449:     }
 8450:     if (!$courseid) { $courseid=$wcourseid; }
 8451:     if (!$domain) { $domain=$wdomain; }
 8452:     if (!$username) { $username=$wusername }
 8453:     my $which=&get_rand_alg();
 8454: 
 8455:     if (defined(&getCODE())) {
 8456: 	if ($which eq '64bit5') {
 8457: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8458: 	} elsif ($which eq '64bit4') {
 8459: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8460: 	} else {
 8461: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8462: 	}
 8463:     } elsif ($which eq '64bit5') {
 8464: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8465:     } elsif ($which eq '64bit4') {
 8466: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8467:     } elsif ($which eq '64bit3') {
 8468: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8469:     } elsif ($which eq '64bit2') {
 8470: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8471:     } elsif ($which eq '64bit') {
 8472: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8473:     }
 8474:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8475: }
 8476: 
 8477: sub rndseed_32bit {
 8478:     my ($symb,$courseid,$domain,$username)=@_;
 8479:     {
 8480: 	use integer;
 8481: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8482: 	my $symbseed=numval($symb) << 22;
 8483: 	my $namechck=unpack("%32C*",$username) << 17;
 8484: 	my $nameseed=numval($username) << 12;
 8485: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8486: 	my $courseseed=unpack("%32C*",$courseid);
 8487: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8488: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8489: 	#&logthis("rndseed :$num:$symb");
 8490: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8491: 	return $num;
 8492:     }
 8493: }
 8494: 
 8495: sub rndseed_64bit {
 8496:     my ($symb,$courseid,$domain,$username)=@_;
 8497:     {
 8498: 	use integer;
 8499: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8500: 	my $symbseed=numval($symb) << 10;
 8501: 	my $namechck=unpack("%32S*",$username);
 8502: 	
 8503: 	my $nameseed=numval($username) << 21;
 8504: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8505: 	my $courseseed=unpack("%32S*",$courseid);
 8506: 	
 8507: 	my $num1=$symbchck+$symbseed+$namechck;
 8508: 	my $num2=$nameseed+$domainseed+$courseseed;
 8509: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8510: 	#&logthis("rndseed :$num:$symb");
 8511: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8512: 	return "$num1,$num2";
 8513:     }
 8514: }
 8515: 
 8516: sub rndseed_64bit2 {
 8517:     my ($symb,$courseid,$domain,$username)=@_;
 8518:     {
 8519: 	use integer;
 8520: 	# strings need to be an even # of cahracters long, it it is odd the
 8521:         # last characters gets thrown away
 8522: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8523: 	my $symbseed=numval($symb) << 10;
 8524: 	my $namechck=unpack("%32S*",$username.' ');
 8525: 	
 8526: 	my $nameseed=numval($username) << 21;
 8527: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8528: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8529: 	
 8530: 	my $num1=$symbchck+$symbseed+$namechck;
 8531: 	my $num2=$nameseed+$domainseed+$courseseed;
 8532: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8533: 	#&logthis("rndseed :$num:$symb");
 8534: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8535: 	return "$num1,$num2";
 8536:     }
 8537: }
 8538: 
 8539: sub rndseed_64bit3 {
 8540:     my ($symb,$courseid,$domain,$username)=@_;
 8541:     {
 8542: 	use integer;
 8543: 	# strings need to be an even # of cahracters long, it it is odd the
 8544:         # last characters gets thrown away
 8545: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8546: 	my $symbseed=numval2($symb) << 10;
 8547: 	my $namechck=unpack("%32S*",$username.' ');
 8548: 	
 8549: 	my $nameseed=numval2($username) << 21;
 8550: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8551: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8552: 	
 8553: 	my $num1=$symbchck+$symbseed+$namechck;
 8554: 	my $num2=$nameseed+$domainseed+$courseseed;
 8555: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8556: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8557: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8558: 	
 8559: 	return "$num1:$num2";
 8560:     }
 8561: }
 8562: 
 8563: sub rndseed_64bit4 {
 8564:     my ($symb,$courseid,$domain,$username)=@_;
 8565:     {
 8566: 	use integer;
 8567: 	# strings need to be an even # of cahracters long, it it is odd the
 8568:         # last characters gets thrown away
 8569: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8570: 	my $symbseed=numval3($symb) << 10;
 8571: 	my $namechck=unpack("%32S*",$username.' ');
 8572: 	
 8573: 	my $nameseed=numval3($username) << 21;
 8574: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8575: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8576: 	
 8577: 	my $num1=$symbchck+$symbseed+$namechck;
 8578: 	my $num2=$nameseed+$domainseed+$courseseed;
 8579: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8580: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8581: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8582: 	
 8583: 	return "$num1:$num2";
 8584:     }
 8585: }
 8586: 
 8587: sub rndseed_64bit5 {
 8588:     my ($symb,$courseid,$domain,$username)=@_;
 8589:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8590:     return "$num1:$num2";
 8591: }
 8592: 
 8593: sub rndseed_CODE_64bit {
 8594:     my ($symb,$courseid,$domain,$username)=@_;
 8595:     {
 8596: 	use integer;
 8597: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8598: 	my $symbseed=numval2($symb);
 8599: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8600: 	my $CODEseed=numval(&getCODE());
 8601: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8602: 	my $num1=$symbseed+$CODEchck;
 8603: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8604: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8605: 	#&logthis("rndseed :$num1:$num2:$symb");
 8606: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8607: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8608: 	return "$num1:$num2";
 8609:     }
 8610: }
 8611: 
 8612: sub rndseed_CODE_64bit4 {
 8613:     my ($symb,$courseid,$domain,$username)=@_;
 8614:     {
 8615: 	use integer;
 8616: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8617: 	my $symbseed=numval3($symb);
 8618: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8619: 	my $CODEseed=numval3(&getCODE());
 8620: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8621: 	my $num1=$symbseed+$CODEchck;
 8622: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8623: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8624: 	#&logthis("rndseed :$num1:$num2:$symb");
 8625: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8626: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8627: 	return "$num1:$num2";
 8628:     }
 8629: }
 8630: 
 8631: sub rndseed_CODE_64bit5 {
 8632:     my ($symb,$courseid,$domain,$username)=@_;
 8633:     my $code = &getCODE();
 8634:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8635:     return "$num1:$num2";
 8636: }
 8637: 
 8638: sub setup_random_from_rndseed {
 8639:     my ($rndseed)=@_;
 8640:     if ($rndseed =~/([,:])/) {
 8641: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8642: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8643:     } else {
 8644: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8645:     }
 8646: }
 8647: 
 8648: sub latest_receipt_algorithm_id {
 8649:     return 'receipt3';
 8650: }
 8651: 
 8652: sub recunique {
 8653:     my $fucourseid=shift;
 8654:     my $unique;
 8655:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8656: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8657: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8658:     } else {
 8659: 	$unique=$perlvar{'lonReceipt'};
 8660:     }
 8661:     return unpack("%32C*",$unique);
 8662: }
 8663: 
 8664: sub recprefix {
 8665:     my $fucourseid=shift;
 8666:     my $prefix;
 8667:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8668: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8669: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8670:     } else {
 8671: 	$prefix=$perlvar{'lonHostID'};
 8672:     }
 8673:     return unpack("%32C*",$prefix);
 8674: }
 8675: 
 8676: sub ireceipt {
 8677:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8678: 
 8679:     my $return =&recprefix($fucourseid).'-';
 8680: 
 8681:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8682: 	$env{'request.state'} eq 'construct') {
 8683: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8684: 	return $return;
 8685:     }
 8686: 
 8687:     my $cuname=unpack("%32C*",$funame);
 8688:     my $cudom=unpack("%32C*",$fudom);
 8689:     my $cucourseid=unpack("%32C*",$fucourseid);
 8690:     my $cusymb=unpack("%32C*",$fusymb);
 8691:     my $cunique=&recunique($fucourseid);
 8692:     my $cpart=unpack("%32S*",$part);
 8693:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8694: 
 8695: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8696: 			       
 8697: 	$return.= ($cunique%$cuname+
 8698: 		   $cunique%$cudom+
 8699: 		   $cusymb%$cuname+
 8700: 		   $cusymb%$cudom+
 8701: 		   $cucourseid%$cuname+
 8702: 		   $cucourseid%$cudom+
 8703: 		   $cpart%$cuname+
 8704: 		   $cpart%$cudom);
 8705:     } else {
 8706: 	$return.= ($cunique%$cuname+
 8707: 		   $cunique%$cudom+
 8708: 		   $cusymb%$cuname+
 8709: 		   $cusymb%$cudom+
 8710: 		   $cucourseid%$cuname+
 8711: 		   $cucourseid%$cudom);
 8712:     }
 8713:     return $return;
 8714: }
 8715: 
 8716: sub receipt {
 8717:     my ($part)=@_;
 8718:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8719:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8720: }
 8721: 
 8722: sub whichuser {
 8723:     my ($passedsymb)=@_;
 8724:     my ($symb,$courseid,$domain,$name,$publicuser);
 8725:     if (defined($env{'form.grade_symb'})) {
 8726: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8727: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8728: 	if (!$allowed &&
 8729: 	    exists($env{'request.course.sec'}) &&
 8730: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8731: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8732: 			      '/'.$env{'request.course.sec'});
 8733: 	}
 8734: 	if ($allowed) {
 8735: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8736: 	    $courseid=$tmp_courseid;
 8737: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8738: 	    ($name)=&get_env_multiple('form.grade_username');
 8739: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8740: 	}
 8741:     }
 8742:     if (!$passedsymb) {
 8743: 	$symb=&symbread();
 8744:     } else {
 8745: 	$symb=$passedsymb;
 8746:     }
 8747:     $courseid=$env{'request.course.id'};
 8748:     $domain=$env{'user.domain'};
 8749:     $name=$env{'user.name'};
 8750:     if ($name eq 'public' && $domain eq 'public') {
 8751: 	if (!defined($env{'form.username'})) {
 8752: 	    $env{'form.username'}.=time.rand(10000000);
 8753: 	}
 8754: 	$name.=$env{'form.username'};
 8755:     }
 8756:     return ($symb,$courseid,$domain,$name,$publicuser);
 8757: 
 8758: }
 8759: 
 8760: # ------------------------------------------------------------ Serves up a file
 8761: # returns either the contents of the file or 
 8762: # -1 if the file doesn't exist
 8763: #
 8764: # if the target is a file that was uploaded via DOCS, 
 8765: # a check will be made to see if a current copy exists on the local server,
 8766: # if it does this will be served, otherwise a copy will be retrieved from
 8767: # the home server for the course and stored in /home/httpd/html/userfiles on
 8768: # the local server.   
 8769: 
 8770: sub getfile {
 8771:     my ($file) = @_;
 8772:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8773:     &repcopy($file);
 8774:     return &readfile($file);
 8775: }
 8776: 
 8777: sub repcopy_userfile {
 8778:     my ($file)=@_;
 8779:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8780:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8781:     my ($cdom,$cnum,$filename) = 
 8782: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8783:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8784:     if (-e "$file") {
 8785: # we already have a local copy, check it out
 8786: 	my @fileinfo = stat($file);
 8787: 	my $rtncode;
 8788: 	my $info;
 8789: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8790: 	if ($lwpresp ne 'ok') {
 8791: # there is no such file anymore, even though we had a local copy
 8792: 	    if ($rtncode eq '404') {
 8793: 		unlink($file);
 8794: 	    }
 8795: 	    return -1;
 8796: 	}
 8797: 	if ($info < $fileinfo[9]) {
 8798: # nice, the file we have is up-to-date, just say okay
 8799: 	    return 'ok';
 8800: 	} else {
 8801: # the file is outdated, get rid of it
 8802: 	    unlink($file);
 8803: 	}
 8804:     }
 8805: # one way or the other, at this point, we don't have the file
 8806: # construct the correct path for the file
 8807:     my @parts = ($cdom,$cnum); 
 8808:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8809: 	push @parts, split(/\//,$1);
 8810:     }
 8811:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8812:     foreach my $part (@parts) {
 8813: 	$path .= '/'.$part;
 8814: 	if (!-e $path) {
 8815: 	    mkdir($path,0770);
 8816: 	}
 8817:     }
 8818: # now the path exists for sure
 8819: # get a user agent
 8820:     my $ua=new LWP::UserAgent;
 8821:     my $transferfile=$file.'.in.transfer';
 8822: # FIXME: this should flock
 8823:     if (-e $transferfile) { return 'ok'; }
 8824:     my $request;
 8825:     $uri=~s/^\///;
 8826:     my $homeserver = &homeserver($cnum,$cdom);
 8827:     my $protocol = $protocol{$homeserver};
 8828:     $protocol = 'http' if ($protocol ne 'https');
 8829:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8830:     my $response=$ua->request($request,$transferfile);
 8831: # did it work?
 8832:     if ($response->is_error()) {
 8833: 	unlink($transferfile);
 8834: 	&logthis("Userfile repcopy failed for $uri");
 8835: 	return -1;
 8836:     }
 8837: # worked, rename the transfer file
 8838:     rename($transferfile,$file);
 8839:     return 'ok';
 8840: }
 8841: 
 8842: sub tokenwrapper {
 8843:     my $uri=shift;
 8844:     $uri=~s|^https?\://([^/]+)||;
 8845:     $uri=~s|^/||;
 8846:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8847:     my $token=$1;
 8848:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8849:     if ($udom && $uname && $file) {
 8850: 	$file=~s|(\?\.*)*$||;
 8851:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8852:         my $homeserver = &homeserver($uname,$udom);
 8853:         my $protocol = $protocol{$homeserver};
 8854:         $protocol = 'http' if ($protocol ne 'https');
 8855:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8856:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8857:                                '&tokenissued='.$perlvar{'lonHostID'};
 8858:     } else {
 8859:         return '/adm/notfound.html';
 8860:     }
 8861: }
 8862: 
 8863: # call with reqtype HEAD: get last modification time
 8864: # call with reqtype GET: get the file contents
 8865: # Do not call this with reqtype GET for large files! It loads everything into memory
 8866: #
 8867: sub getuploaded {
 8868:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8869:     $uri=~s/^\///;
 8870:     my $homeserver = &homeserver($cnum,$cdom);
 8871:     my $protocol = $protocol{$homeserver};
 8872:     $protocol = 'http' if ($protocol ne 'https');
 8873:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8874:     my $ua=new LWP::UserAgent;
 8875:     my $request=new HTTP::Request($reqtype,$uri);
 8876:     my $response=$ua->request($request);
 8877:     $$rtncode = $response->code;
 8878:     if (! $response->is_success()) {
 8879: 	return 'failed';
 8880:     }      
 8881:     if ($reqtype eq 'HEAD') {
 8882: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8883:     } elsif ($reqtype eq 'GET') {
 8884: 	$$info = $response->content;
 8885:     }
 8886:     return 'ok';
 8887: }
 8888: 
 8889: sub readfile {
 8890:     my $file = shift;
 8891:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8892:     my $fh;
 8893:     open($fh,"<$file");
 8894:     my $a='';
 8895:     while (my $line = <$fh>) { $a .= $line; }
 8896:     return $a;
 8897: }
 8898: 
 8899: sub filelocation {
 8900:     my ($dir,$file) = @_;
 8901:     my $location;
 8902:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8903: 
 8904:     if ($file =~ m-^/adm/-) {
 8905: 	$file=~s-^/adm/wrapper/-/-;
 8906: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8907:     }
 8908: 
 8909:     if ($file=~m:^/~:) { # is a contruction space reference
 8910:         $location = $file;
 8911:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8912:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8913: 	# is a correct contruction space reference
 8914:         $location = $file;
 8915:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8916:         $location = $file;
 8917:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8918:         my ($udom,$uname,$filename)=
 8919:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8920:         my $home=&homeserver($uname,$udom);
 8921:         my $is_me=0;
 8922:         my @ids=&current_machine_ids();
 8923:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8924:         if ($is_me) {
 8925:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8926:         } else {
 8927:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8928:   	      $udom.'/'.$uname.'/'.$filename;
 8929:         }
 8930:     } elsif ($file =~ m-^/adm/-) {
 8931: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8932:     } else {
 8933:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8934:         $file=~s:^/res/:/:;
 8935:         if ( !( $file =~ m:^/:) ) {
 8936:             $location = $dir. '/'.$file;
 8937:         } else {
 8938:             $location = '/home/httpd/html/res'.$file;
 8939:         }
 8940:     }
 8941:     $location=~s://+:/:g; # remove duplicate /
 8942:     while ($location=~m{/\.\./}) {
 8943: 	if ($location =~ m{/[^/]+/\.\./}) {
 8944: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8945: 	} else {
 8946: 	    $location=~ s{/\.\./}{/}g;
 8947: 	}
 8948:     } #remove dir/..
 8949:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8950:     return $location;
 8951: }
 8952: 
 8953: sub hreflocation {
 8954:     my ($dir,$file)=@_;
 8955:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8956: 	$file=filelocation($dir,$file);
 8957:     } elsif ($file=~m-^/adm/-) {
 8958: 	$file=~s-^/adm/wrapper/-/-;
 8959: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8960:     }
 8961:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8962: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8963:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8964: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8965:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8966: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8967: 	    -/uploaded/$1/$2/-x;
 8968:     }
 8969:     if ($file=~ m{^/userfiles/}) {
 8970: 	$file =~ s{^/userfiles/}{/uploaded/};
 8971:     }
 8972:     return $file;
 8973: }
 8974: 
 8975: sub current_machine_domains {
 8976:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8977: }
 8978: 
 8979: sub machine_domains {
 8980:     my ($hostname) = @_;
 8981:     my @domains;
 8982:     my %hostname = &all_hostnames();
 8983:     while( my($id, $name) = each(%hostname)) {
 8984: #	&logthis("-$id-$name-$hostname-");
 8985: 	if ($hostname eq $name) {
 8986: 	    push(@domains,&host_domain($id));
 8987: 	}
 8988:     }
 8989:     return @domains;
 8990: }
 8991: 
 8992: sub current_machine_ids {
 8993:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8994: }
 8995: 
 8996: sub machine_ids {
 8997:     my ($hostname) = @_;
 8998:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8999:     my @ids;
 9000:     my %name_to_host = &all_names();
 9001:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 9002: 	return @{ $name_to_host{$hostname} };
 9003:     }
 9004:     return;
 9005: }
 9006: 
 9007: sub additional_machine_domains {
 9008:     my @domains;
 9009:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 9010:     while( my $line = <$fh>) {
 9011:         $line =~ s/\s//g;
 9012:         push(@domains,$line);
 9013:     }
 9014:     return @domains;
 9015: }
 9016: 
 9017: sub default_login_domain {
 9018:     my $domain = $perlvar{'lonDefDomain'};
 9019:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 9020:     foreach my $posdom (&current_machine_domains(),
 9021:                         &additional_machine_domains()) {
 9022:         if (lc($posdom) eq lc($testdomain)) {
 9023:             $domain=$posdom;
 9024:             last;
 9025:         }
 9026:     }
 9027:     return $domain;
 9028: }
 9029: 
 9030: # ------------------------------------------------------------- Declutters URLs
 9031: 
 9032: sub declutter {
 9033:     my $thisfn=shift;
 9034:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9035:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9036:     $thisfn=~s/^\///;
 9037:     $thisfn=~s|^adm/wrapper/||;
 9038:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 9039:     $thisfn=~s/^res\///;
 9040:     $thisfn=~s/\?.+$//;
 9041:     return $thisfn;
 9042: }
 9043: 
 9044: # ------------------------------------------------------------- Clutter up URLs
 9045: 
 9046: sub clutter {
 9047:     my $thisfn='/'.&declutter(shift);
 9048:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 9049: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 9050:        $thisfn='/res'.$thisfn; 
 9051:     }
 9052:     if ($thisfn !~m|/adm|) {
 9053: 	if ($thisfn =~ m|/ext/|) {
 9054: 	    $thisfn='/adm/wrapper'.$thisfn;
 9055: 	} else {
 9056: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 9057: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 9058: 	    if ($embstyle eq 'ssi'
 9059: 		|| ($embstyle eq 'hdn')
 9060: 		|| ($embstyle eq 'rat')
 9061: 		|| ($embstyle eq 'prv')
 9062: 		|| ($embstyle eq 'ign')) {
 9063: 		#do nothing with these
 9064: 	    } elsif (($embstyle eq 'img') 
 9065: 		|| ($embstyle eq 'emb')
 9066: 		|| ($embstyle eq 'wrp')) {
 9067: 		$thisfn='/adm/wrapper'.$thisfn;
 9068: 	    } elsif ($embstyle eq 'unk'
 9069: 		     && $thisfn!~/\.(sequence|page)$/) {
 9070: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 9071: 	    } else {
 9072: #		&logthis("Got a blank emb style");
 9073: 	    }
 9074: 	}
 9075:     }
 9076:     return $thisfn;
 9077: }
 9078: 
 9079: sub clutter_with_no_wrapper {
 9080:     my $uri = &clutter(shift);
 9081:     if ($uri =~ m-^/adm/-) {
 9082: 	$uri =~ s-^/adm/wrapper/-/-;
 9083: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 9084:     }
 9085:     return $uri;
 9086: }
 9087: 
 9088: sub freeze_escape {
 9089:     my ($value)=@_;
 9090:     if (ref($value)) {
 9091: 	$value=&nfreeze($value);
 9092: 	return '__FROZEN__'.&escape($value);
 9093:     }
 9094:     return &escape($value);
 9095: }
 9096: 
 9097: 
 9098: sub thaw_unescape {
 9099:     my ($value)=@_;
 9100:     if ($value =~ /^__FROZEN__/) {
 9101: 	substr($value,0,10,undef);
 9102: 	$value=&unescape($value);
 9103: 	return &thaw($value);
 9104:     }
 9105:     return &unescape($value);
 9106: }
 9107: 
 9108: sub correct_line_ends {
 9109:     my ($result)=@_;
 9110:     $$result =~s/\r\n/\n/mg;
 9111:     $$result =~s/\r/\n/mg;
 9112: }
 9113: # ================================================================ Main Program
 9114: 
 9115: sub goodbye {
 9116:    &logthis("Starting Shut down");
 9117: #not converted to using infrastruture and probably shouldn't be
 9118:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 9119: #converted
 9120: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 9121:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 9122: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 9123: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 9124: #1.1 only
 9125: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 9126: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 9127: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 9128: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 9129:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 9130:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 9131:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 9132:    &flushcourselogs();
 9133:    &logthis("Shutting down");
 9134: }
 9135: 
 9136: sub get_dns {
 9137:     my ($url,$func,$ignore_cache) = @_;
 9138:     if (!$ignore_cache) {
 9139: 	my ($content,$cached)=
 9140: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9141: 	if ($cached) {
 9142: 	    &$func($content);
 9143: 	    return;
 9144: 	}
 9145:     }
 9146: 
 9147:     my %alldns;
 9148:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9149:     foreach my $dns (<$config>) {
 9150: 	next if ($dns !~ /^\^(\S*)/x);
 9151:         my $line = $1;
 9152:         my ($host,$protocol) = split(/:/,$line);
 9153:         if ($protocol ne 'https') {
 9154:             $protocol = 'http';
 9155:         }
 9156: 	$alldns{$host} = $protocol;
 9157:     }
 9158:     while (%alldns) {
 9159: 	my ($dns) = keys(%alldns);
 9160: 	my $ua=new LWP::UserAgent;
 9161: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9162: 	my $response=$ua->request($request);
 9163:         delete($alldns{$dns});
 9164: 	next if ($response->is_error());
 9165: 	my @content = split("\n",$response->content);
 9166: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9167: 	&$func(\@content);
 9168: 	return;
 9169:     }
 9170:     close($config);
 9171:     my $which = (split('/',$url))[3];
 9172:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9173:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9174:     my @content = <$config>;
 9175:     &$func(\@content);
 9176:     return;
 9177: }
 9178: # ------------------------------------------------------------ Read domain file
 9179: {
 9180:     my $loaded;
 9181:     my %domain;
 9182: 
 9183:     sub parse_domain_tab {
 9184: 	my ($lines) = @_;
 9185: 	foreach my $line (@$lines) {
 9186: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9187: 
 9188: 	    chomp($line);
 9189: 	    my ($name,@elements) = split(/:/,$line,9);
 9190: 	    my %this_domain;
 9191: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9192: 			       'lang_def', 'city', 'longi', 'lati',
 9193: 			       'primary') {
 9194: 		$this_domain{$field} = shift(@elements);
 9195: 	    }
 9196: 	    $domain{$name} = \%this_domain;
 9197: 	}
 9198:     }
 9199: 
 9200:     sub reset_domain_info {
 9201: 	undef($loaded);
 9202: 	undef(%domain);
 9203:     }
 9204: 
 9205:     sub load_domain_tab {
 9206: 	my ($ignore_cache) = @_;
 9207: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9208: 	my $fh;
 9209: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9210: 	    my @lines = <$fh>;
 9211: 	    &parse_domain_tab(\@lines);
 9212: 	}
 9213: 	close($fh);
 9214: 	$loaded = 1;
 9215:     }
 9216: 
 9217:     sub domain {
 9218: 	&load_domain_tab() if (!$loaded);
 9219: 
 9220: 	my ($name,$what) = @_;
 9221: 	return if ( !exists($domain{$name}) );
 9222: 
 9223: 	if (!$what) {
 9224: 	    return $domain{$name}{'description'};
 9225: 	}
 9226: 	return $domain{$name}{$what};
 9227:     }
 9228: 
 9229:     sub domain_info {
 9230:         &load_domain_tab() if (!$loaded);
 9231:         return %domain;
 9232:     }
 9233: 
 9234: }
 9235: 
 9236: 
 9237: # ------------------------------------------------------------- Read hosts file
 9238: {
 9239:     my %hostname;
 9240:     my %hostdom;
 9241:     my %libserv;
 9242:     my $loaded;
 9243:     my %name_to_host;
 9244: 
 9245:     sub parse_hosts_tab {
 9246: 	my ($file) = @_;
 9247: 	foreach my $configline (@$file) {
 9248: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9249: 	    next if ($configline =~ /^\^/);
 9250: 	    chomp($configline);
 9251: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9252: 	    $name=~s/\s//g;
 9253: 	    if ($id && $domain && $role && $name) {
 9254: 		$hostname{$id}=$name;
 9255: 		push(@{$name_to_host{$name}}, $id);
 9256: 		$hostdom{$id}=$domain;
 9257: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9258:                 if (defined($protocol)) {
 9259:                     if ($protocol eq 'https') {
 9260:                         $protocol{$id} = $protocol;
 9261:                     } else {
 9262:                         $protocol{$id} = 'http'; 
 9263:                     }
 9264:                 } else {
 9265:                     $protocol{$id} = 'http';
 9266:                 }
 9267: 	    }
 9268: 	}
 9269:     }
 9270:     
 9271:     sub reset_hosts_info {
 9272: 	&purge_remembered();
 9273: 	&reset_domain_info();
 9274: 	&reset_hosts_ip_info();
 9275: 	undef(%name_to_host);
 9276: 	undef(%hostname);
 9277: 	undef(%hostdom);
 9278: 	undef(%libserv);
 9279: 	undef($loaded);
 9280:     }
 9281: 
 9282:     sub load_hosts_tab {
 9283: 	my ($ignore_cache) = @_;
 9284: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9285: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9286: 	my @config = <$config>;
 9287: 	&parse_hosts_tab(\@config);
 9288: 	close($config);
 9289: 	$loaded=1;
 9290:     }
 9291: 
 9292:     sub hostname {
 9293: 	&load_hosts_tab() if (!$loaded);
 9294: 
 9295: 	my ($lonid) = @_;
 9296: 	return $hostname{$lonid};
 9297:     }
 9298: 
 9299:     sub all_hostnames {
 9300: 	&load_hosts_tab() if (!$loaded);
 9301: 
 9302: 	return %hostname;
 9303:     }
 9304: 
 9305:     sub all_names {
 9306: 	&load_hosts_tab() if (!$loaded);
 9307: 
 9308: 	return %name_to_host;
 9309:     }
 9310: 
 9311:     sub all_host_domain {
 9312:         &load_hosts_tab() if (!$loaded);
 9313:         return %hostdom;
 9314:     }
 9315: 
 9316:     sub is_library {
 9317: 	&load_hosts_tab() if (!$loaded);
 9318: 
 9319: 	return exists($libserv{$_[0]});
 9320:     }
 9321: 
 9322:     sub all_library {
 9323: 	&load_hosts_tab() if (!$loaded);
 9324: 
 9325: 	return %libserv;
 9326:     }
 9327: 
 9328:     sub get_servers {
 9329: 	&load_hosts_tab() if (!$loaded);
 9330: 
 9331: 	my ($domain,$type) = @_;
 9332: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9333: 	                                          : %hostname;
 9334: 	my %result;
 9335: 	if (ref($domain) eq 'ARRAY') {
 9336: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9337: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9338: 		    $result{$host} = $hostname;
 9339: 		}
 9340: 	    }
 9341: 	} else {
 9342: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9343: 		if ($hostdom{$host} eq $domain) {
 9344: 		    $result{$host} = $hostname;
 9345: 		}
 9346: 	    }
 9347: 	}
 9348: 	return %result;
 9349:     }
 9350: 
 9351:     sub host_domain {
 9352: 	&load_hosts_tab() if (!$loaded);
 9353: 
 9354: 	my ($lonid) = @_;
 9355: 	return $hostdom{$lonid};
 9356:     }
 9357: 
 9358:     sub all_domains {
 9359: 	&load_hosts_tab() if (!$loaded);
 9360: 
 9361: 	my %seen;
 9362: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9363: 	return @uniq;
 9364:     }
 9365: }
 9366: 
 9367: { 
 9368:     my %iphost;
 9369:     my %name_to_ip;
 9370:     my %lonid_to_ip;
 9371: 
 9372:     sub get_hosts_from_ip {
 9373: 	my ($ip) = @_;
 9374: 	my %iphosts = &get_iphost();
 9375: 	if (ref($iphosts{$ip})) {
 9376: 	    return @{$iphosts{$ip}};
 9377: 	}
 9378: 	return;
 9379:     }
 9380:     
 9381:     sub reset_hosts_ip_info {
 9382: 	undef(%iphost);
 9383: 	undef(%name_to_ip);
 9384: 	undef(%lonid_to_ip);
 9385:     }
 9386: 
 9387:     sub get_host_ip {
 9388: 	my ($lonid) = @_;
 9389: 	if (exists($lonid_to_ip{$lonid})) {
 9390: 	    return $lonid_to_ip{$lonid};
 9391: 	}
 9392: 	my $name=&hostname($lonid);
 9393:    	my $ip = gethostbyname($name);
 9394: 	return if (!$ip || length($ip) ne 4);
 9395: 	$ip=inet_ntoa($ip);
 9396: 	$name_to_ip{$name}   = $ip;
 9397: 	$lonid_to_ip{$lonid} = $ip;
 9398: 	return $ip;
 9399:     }
 9400:     
 9401:     sub get_iphost {
 9402: 	my ($ignore_cache) = @_;
 9403: 
 9404: 	if (!$ignore_cache) {
 9405: 	    if (%iphost) {
 9406: 		return %iphost;
 9407: 	    }
 9408: 	    my ($ip_info,$cached)=
 9409: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9410: 	    if ($cached) {
 9411: 		%iphost      = %{$ip_info->[0]};
 9412: 		%name_to_ip  = %{$ip_info->[1]};
 9413: 		%lonid_to_ip = %{$ip_info->[2]};
 9414: 		return %iphost;
 9415: 	    }
 9416: 	}
 9417: 
 9418: 	# get yesterday's info for fallback
 9419: 	my %old_name_to_ip;
 9420: 	my ($ip_info,$cached)=
 9421: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9422: 	if ($cached) {
 9423: 	    %old_name_to_ip = %{$ip_info->[1]};
 9424: 	}
 9425: 
 9426: 	my %name_to_host = &all_names();
 9427: 	foreach my $name (keys(%name_to_host)) {
 9428: 	    my $ip;
 9429: 	    if (!exists($name_to_ip{$name})) {
 9430: 		$ip = gethostbyname($name);
 9431: 		if (!$ip || length($ip) ne 4) {
 9432: 		    if (defined($old_name_to_ip{$name})) {
 9433: 			$ip = $old_name_to_ip{$name};
 9434: 			&logthis("Can't find $name defaulting to old $ip");
 9435: 		    } else {
 9436: 			&logthis("Name $name no IP found");
 9437: 			next;
 9438: 		    }
 9439: 		} else {
 9440: 		    $ip=inet_ntoa($ip);
 9441: 		}
 9442: 		$name_to_ip{$name} = $ip;
 9443: 	    } else {
 9444: 		$ip = $name_to_ip{$name};
 9445: 	    }
 9446: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9447: 		$lonid_to_ip{$id} = $ip;
 9448: 	    }
 9449: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9450: 	}
 9451: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9452: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9453: 				      48*60*60);
 9454: 
 9455: 	return %iphost;
 9456:     }
 9457: 
 9458:     #
 9459:     #  Given a DNS returns the loncapa host name for that DNS 
 9460:     # 
 9461:     sub host_from_dns {
 9462:         my ($dns) = @_;
 9463:         my @hosts;
 9464:         my $ip;
 9465: 
 9466:         if (exists($name_to_ip{$dns})) {
 9467:             $ip = $name_to_ip{$dns};
 9468:         }
 9469:         if (!$ip) {
 9470:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9471:             if (length($ip) == 4) { 
 9472: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9473:             }
 9474:         }
 9475:         if ($ip) {
 9476: 	    @hosts = get_hosts_from_ip($ip);
 9477: 	    return $hosts[0];
 9478:         }
 9479:         return undef;
 9480:     }
 9481: 
 9482: }
 9483: 
 9484: BEGIN {
 9485: 
 9486: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9487:     unless ($readit) {
 9488: {
 9489:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9490:     %perlvar = (%perlvar,%{$configvars});
 9491: }
 9492: 
 9493: 
 9494: # ------------------------------------------------------ Read spare server file
 9495: {
 9496:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9497: 
 9498:     while (my $configline=<$config>) {
 9499:        chomp($configline);
 9500:        if ($configline) {
 9501: 	   my ($host,$type) = split(':',$configline,2);
 9502: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9503: 	   push(@{ $spareid{$type} }, $host);
 9504:        }
 9505:     }
 9506:     close($config);
 9507: }
 9508: # ------------------------------------------------------------ Read permissions
 9509: {
 9510:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9511: 
 9512:     while (my $configline=<$config>) {
 9513: 	chomp($configline);
 9514: 	if ($configline) {
 9515: 	    my ($role,$perm)=split(/ /,$configline);
 9516: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9517: 	}
 9518:     }
 9519:     close($config);
 9520: }
 9521: 
 9522: # -------------------------------------------- Read plain texts for permissions
 9523: {
 9524:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9525: 
 9526:     while (my $configline=<$config>) {
 9527: 	chomp($configline);
 9528: 	if ($configline) {
 9529: 	    my ($short,@plain)=split(/:/,$configline);
 9530:             %{$prp{$short}} = ();
 9531: 	    if (@plain > 0) {
 9532:                 $prp{$short}{'std'} = $plain[0];
 9533:                 for (my $i=1; $i<@plain; $i++) {
 9534:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9535:                 }
 9536:             }
 9537: 	}
 9538:     }
 9539:     close($config);
 9540: }
 9541: 
 9542: # ---------------------------------------------------------- Read package table
 9543: {
 9544:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9545: 
 9546:     while (my $configline=<$config>) {
 9547: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9548: 	chomp($configline);
 9549: 	my ($short,$plain)=split(/:/,$configline);
 9550: 	my ($pack,$name)=split(/\&/,$short);
 9551: 	if ($plain ne '') {
 9552: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9553: 	    $packagetab{$short}=$plain; 
 9554: 	}
 9555:     }
 9556:     close($config);
 9557: }
 9558: 
 9559: # ------------- set up temporary directory
 9560: {
 9561:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9562: 
 9563: }
 9564: 
 9565: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9566: 				'compress_threshold'=> 20_000,
 9567:  			        });
 9568: 
 9569: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9570: $dumpcount=0;
 9571: $locknum=0;
 9572: 
 9573: &logtouch();
 9574: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9575: $readit=1;
 9576:     {
 9577: 	use integer;
 9578: 	my $test=(2**32)+1;
 9579: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9580: 	&logthis(" Detected 64bit platform ($_64bit)");
 9581:     }
 9582: }
 9583: }
 9584: 
 9585: 1;
 9586: __END__
 9587: 
 9588: =pod
 9589: 
 9590: =head1 NAME
 9591: 
 9592: Apache::lonnet - Subroutines to ask questions about things in the network.
 9593: 
 9594: =head1 SYNOPSIS
 9595: 
 9596: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9597: 
 9598:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9599: 
 9600: Common parameters:
 9601: 
 9602: =over 4
 9603: 
 9604: =item *
 9605: 
 9606: $uname : an internal username (if $cname expecting a course Id specifically)
 9607: 
 9608: =item *
 9609: 
 9610: $udom : a domain (if $cdom expecting a course's domain specifically)
 9611: 
 9612: =item *
 9613: 
 9614: $symb : a resource instance identifier
 9615: 
 9616: =item *
 9617: 
 9618: $namespace : the name of a .db file that contains the data needed or
 9619: being set.
 9620: 
 9621: =back
 9622: 
 9623: =head1 OVERVIEW
 9624: 
 9625: lonnet provides subroutines which interact with the
 9626: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9627: about classes, users, and resources.
 9628: 
 9629: For many of these objects you can also use this to store data about
 9630: them or modify them in various ways.
 9631: 
 9632: =head2 Symbs
 9633: 
 9634: To identify a specific instance of a resource, LON-CAPA uses symbols
 9635: or "symbs"X<symb>. These identifiers are built from the URL of the
 9636: map, the resource number of the resource in the map, and the URL of
 9637: the resource itself. The latter is somewhat redundant, but might help
 9638: if maps change.
 9639: 
 9640: An example is
 9641: 
 9642:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9643: 
 9644: The respective map entry is
 9645: 
 9646:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9647:   title="Problem 2">
 9648:  </resource>
 9649: 
 9650: Symbs are used by the random number generator, as well as to store and
 9651: restore data specific to a certain instance of for example a problem.
 9652: 
 9653: =head2 Storing And Retrieving Data
 9654: 
 9655: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9656: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9657: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9658: is is the non-critical message twin of cstore. These functions are for
 9659: handlers to store a perl hash to a user's permanent data space in an
 9660: easy manner, and to retrieve it again on another call. It is expected
 9661: that a handler would use this once at the beginning to retrieve data,
 9662: and then again once at the end to send only the new data back.
 9663: 
 9664: The data is stored in the user's data directory on the user's
 9665: homeserver under the ID of the course.
 9666: 
 9667: The hash that is returned by restore will have all of the previous
 9668: value for all of the elements of the hash.
 9669: 
 9670: Example:
 9671: 
 9672:  #creating a hash
 9673:  my %hash;
 9674:  $hash{'foo'}='bar';
 9675: 
 9676:  #storing it
 9677:  &Apache::lonnet::cstore(\%hash);
 9678: 
 9679:  #changing a value
 9680:  $hash{'foo'}='notbar';
 9681: 
 9682:  #adding a new value
 9683:  $hash{'bar'}='foo';
 9684:  &Apache::lonnet::cstore(\%hash);
 9685: 
 9686:  #retrieving the hash
 9687:  my %history=&Apache::lonnet::restore();
 9688: 
 9689:  #print the hash
 9690:  foreach my $key (sort(keys(%history))) {
 9691:    print("\%history{$key} = $history{$key}");
 9692:  }
 9693: 
 9694: Will print out:
 9695: 
 9696:  %history{1:foo} = bar
 9697:  %history{1:keys} = foo:timestamp
 9698:  %history{1:timestamp} = 990455579
 9699:  %history{2:bar} = foo
 9700:  %history{2:foo} = notbar
 9701:  %history{2:keys} = foo:bar:timestamp
 9702:  %history{2:timestamp} = 990455580
 9703:  %history{bar} = foo
 9704:  %history{foo} = notbar
 9705:  %history{timestamp} = 990455580
 9706:  %history{version} = 2
 9707: 
 9708: Note that the special hash entries C<keys>, C<version> and
 9709: C<timestamp> were added to the hash. C<version> will be equal to the
 9710: total number of versions of the data that have been stored. The
 9711: C<timestamp> attribute will be the UNIX time the hash was
 9712: stored. C<keys> is available in every historical section to list which
 9713: keys were added or changed at a specific historical revision of a
 9714: hash.
 9715: 
 9716: B<Warning>: do not store the hash that restore returns directly. This
 9717: will cause a mess since it will restore the historical keys as if the
 9718: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9719: 
 9720: Calling convention:
 9721: 
 9722:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9723:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9724: 
 9725: For more detailed information, see lonnet specific documentation.
 9726: 
 9727: =head1 RETURN MESSAGES
 9728: 
 9729: =over 4
 9730: 
 9731: =item * B<con_lost>: unable to contact remote host
 9732: 
 9733: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9734: when the connection is brought back up
 9735: 
 9736: =item * B<con_failed>: unable to contact remote host and unable to save message
 9737: for later delivery
 9738: 
 9739: =item * B<error:>: an error a occurred, a description of the error follows the :
 9740: 
 9741: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9742: that was requested
 9743: 
 9744: =back
 9745: 
 9746: =head1 PUBLIC SUBROUTINES
 9747: 
 9748: =head2 Session Environment Functions
 9749: 
 9750: =over 4
 9751: 
 9752: =item * 
 9753: X<appenv()>
 9754: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9755: the user envirnoment file, and will be restored for each access this
 9756: user makes during this session, also modifies the %env for the current
 9757: process. Optional rolesarrayref - if defined contains a reference to an array
 9758: of roles which are exempt from the restriction on modifying user.role entries 
 9759: in the user's environment.db and in %env.    
 9760: 
 9761: =item *
 9762: X<delenv()>
 9763: B<delenv($delthis,$regexp)>: removes all items from the session
 9764: environment file that begin with $delthis. If the 
 9765: optional second arg - $regexp - is true, $delthis is treated as a 
 9766: regular expression, otherwise \Q$delthis\E is used. 
 9767: The values are also deleted from the current processes %env.
 9768: 
 9769: =item * get_env_multiple($name) 
 9770: 
 9771: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9772: values may be defined and end up as an array ref.
 9773: 
 9774: returns an array of values
 9775: 
 9776: =back
 9777: 
 9778: =head2 User Information
 9779: 
 9780: =over 4
 9781: 
 9782: =item *
 9783: X<queryauthenticate()>
 9784: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9785: authentication scheme
 9786: 
 9787: =item *
 9788: X<authenticate()>
 9789: B<authenticate($uname,$upass,$udom)>: try to
 9790: authenticate user from domain's lib servers (first use the current
 9791: one). C<$upass> should be the users password.
 9792: 
 9793: =item *
 9794: X<homeserver()>
 9795: B<homeserver($uname,$udom)>: find the server which has
 9796: the user's directory and files (there must be only one), this caches
 9797: the answer, and also caches if there is a borken connection.
 9798: 
 9799: =item *
 9800: X<idget()>
 9801: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9802: (IDs are a unique resource in a domain, there must be only 1 ID per
 9803: username, and only 1 username per ID in a specific domain) (returns
 9804: hash: id=>name,id=>name)
 9805: 
 9806: =item *
 9807: X<idrget()>
 9808: B<idrget($udom,@unames)>: find the IDs behind a list of
 9809: usernames (returns hash: name=>id,name=>id)
 9810: 
 9811: =item *
 9812: X<idput()>
 9813: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9814: 
 9815: =item *
 9816: X<rolesinit()>
 9817: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9818: 
 9819: =item *
 9820: X<getsection()>
 9821: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9822: course $cname, return section name/number or '' for "not in course"
 9823: and '-1' for "no section"
 9824: 
 9825: =item *
 9826: X<userenvironment()>
 9827: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9828: passed in @what from the requested user's environment, returns a hash
 9829: 
 9830: =item * 
 9831: X<userlog_query()>
 9832: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9833: activity.log file. %filters defines filters applied when parsing the
 9834: log file. These can be start or end timestamps, or the type of action
 9835: - log to look for Login or Logout events, check for Checkin or
 9836: Checkout, role for role selection. The response is in the form
 9837: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9838: escaped strings of the action recorded in the activity.log file.
 9839: 
 9840: =back
 9841: 
 9842: =head2 User Roles
 9843: 
 9844: =over 4
 9845: 
 9846: =item *
 9847: 
 9848: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9849:  F: full access
 9850:  U,I,K: authentication modes (cxx only)
 9851:  '': forbidden
 9852:  1: user needs to choose course
 9853:  2: browse allowed
 9854:  A: passphrase authentication needed
 9855: 
 9856: =item *
 9857: 
 9858: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9859: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9860: and course level
 9861: 
 9862: =item *
 9863: 
 9864: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9865: (rolesplain.tab); plain text explanation of a user role term.
 9866: $type is Course (default) or Community.
 9867: If $forcedefault evaluates to true, text returned will be default 
 9868: text for $type. Otherwise, if this is a course, the text returned 
 9869: will be a custom name for the role (if defined in the course's 
 9870: environment).  If no custom name is defined the default is returned.
 9871:    
 9872: =item *
 9873: 
 9874: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9875: All arguments are optional. Returns a hash of a roles, either for
 9876: co-author/assistant author roles for a user's Construction Space
 9877: (default), or if $context is 'userroles', roles for the user himself,
 9878: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9879: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9880: For each key, value is set to colon-separated start and end times for
 9881: the role.  If no username and domain are specified, will default to
 9882: current user/domain. Types, roles, and roledoms are references to arrays
 9883: of role statuses (active, future or previous), roles 
 9884: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9885: to restrict the list of roles reported. If no array ref is 
 9886: provided for types, will default to return only active roles.
 9887: 
 9888: =back
 9889: 
 9890: =head2 User Modification
 9891: 
 9892: =over 4
 9893: 
 9894: =item *
 9895: 
 9896: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9897: user for the level given by URL.  Optional start and end dates (leave empty
 9898: string or zero for "no date")
 9899: 
 9900: =item *
 9901: 
 9902: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9903: change a users, password, possible return values are: ok,
 9904: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9905: refused
 9906: 
 9907: =item *
 9908: 
 9909: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9910: 
 9911: =item *
 9912: 
 9913: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9914:            $forceid,$desiredhome,$email,$inststatus) : 
 9915: modify user
 9916: 
 9917: =item *
 9918: 
 9919: modifystudent
 9920: 
 9921: modify a student's enrollment and identification information.
 9922: The course id is resolved based on the current users environment.  
 9923: This means the envoking user must be a course coordinator or otherwise
 9924: associated with a course.
 9925: 
 9926: This call is essentially a wrapper for lonnet::modifyuser and
 9927: lonnet::modify_student_enrollment
 9928: 
 9929: Inputs: 
 9930: 
 9931: =over 4
 9932: 
 9933: =item B<$udom> Student's loncapa domain
 9934: 
 9935: =item B<$uname> Student's loncapa login name
 9936: 
 9937: =item B<$uid> Student/Employee ID
 9938: 
 9939: =item B<$umode> Student's authentication mode
 9940: 
 9941: =item B<$upass> Student's password
 9942: 
 9943: =item B<$first> Student's first name
 9944: 
 9945: =item B<$middle> Student's middle name
 9946: 
 9947: =item B<$last> Student's last name
 9948: 
 9949: =item B<$gene> Student's generation
 9950: 
 9951: =item B<$usec> Student's section in course
 9952: 
 9953: =item B<$end> Unix time of the roles expiration
 9954: 
 9955: =item B<$start> Unix time of the roles start date
 9956: 
 9957: =item B<$forceid> If defined, allow $uid to be changed
 9958: 
 9959: =item B<$desiredhome> server to use as home server for student
 9960: 
 9961: =item B<$email> Student's permanent e-mail address
 9962: 
 9963: =item B<$type> Type of enrollment (auto or manual)
 9964: 
 9965: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9966: 
 9967: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9968: 
 9969: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9970: 
 9971: =item B<$context> role change context (shown in User Management Logs display in a course)
 9972: 
 9973: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9974: 
 9975: =back
 9976: 
 9977: =item *
 9978: 
 9979: modify_student_enrollment
 9980: 
 9981: Change a students enrollment status in a class.  The environment variable
 9982: 'role.request.course' must be defined for this function to proceed.
 9983: 
 9984: Inputs:
 9985: 
 9986: =over 4
 9987: 
 9988: =item $udom, students domain
 9989: 
 9990: =item $uname, students name
 9991: 
 9992: =item $uid, students user id
 9993: 
 9994: =item $first, students first name
 9995: 
 9996: =item $middle
 9997: 
 9998: =item $last
 9999: 
10000: =item $gene
10001: 
10002: =item $usec
10003: 
10004: =item $end
10005: 
10006: =item $start
10007: 
10008: =item $type
10009: 
10010: =item $locktype
10011: 
10012: =item $cid
10013: 
10014: =item $selfenroll
10015: 
10016: =item $context
10017: 
10018: =back
10019: 
10020: 
10021: =item *
10022: 
10023: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10024: custom role; give a custom role to a user for the level given by URL.  Specify
10025: name and domain of role author, and role name
10026: 
10027: =item *
10028: 
10029: revokerole($udom,$uname,$url,$role) : revoke a role for url
10030: 
10031: =item *
10032: 
10033: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10034: 
10035: =back
10036: 
10037: =head2 Course Infomation
10038: 
10039: =over 4
10040: 
10041: =item *
10042: 
10043: coursedescription($courseid) : returns a hash of information about the
10044: specified course id, including all environment settings for the
10045: course, the description of the course will be in the hash under the
10046: key 'description'
10047: 
10048: =item *
10049: 
10050: resdata($name,$domain,$type,@which) : request for current parameter
10051: setting for a specific $type, where $type is either 'course' or 'user',
10052: @what should be a list of parameters to ask about. This routine caches
10053: answers for 5 minutes.
10054: 
10055: =item *
10056: 
10057: get_courseresdata($courseid, $domain) : dump the entire course resource
10058: data base, returning a hash that is keyed by the resource name and has
10059: values that are the resource value.  I believe that the timestamps and
10060: versions are also returned.
10061: 
10062: 
10063: =back
10064: 
10065: =head2 Course Modification
10066: 
10067: =over 4
10068: 
10069: =item *
10070: 
10071: writecoursepref($courseid,%prefs) : write preferences (environment
10072: database) for a course
10073: 
10074: =item *
10075: 
10076: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10077: 
10078: =item *
10079: 
10080: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
10081: 
10082: =back
10083: 
10084: =head2 Resource Subroutines
10085: 
10086: =over 4
10087: 
10088: =item *
10089: 
10090: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10091: 
10092: =item *
10093: 
10094: repcopy($filename) : subscribes to the requested file, and attempts to
10095: replicate from the owning library server, Might return
10096: 'unavailable', 'not_found', 'forbidden', 'ok', or
10097: 'bad_request', also attempts to grab the metadata for the
10098: resource. Expects the local filesystem pathname
10099: (/home/httpd/html/res/....)
10100: 
10101: =back
10102: 
10103: =head2 Resource Information
10104: 
10105: =over 4
10106: 
10107: =item *
10108: 
10109: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10110: a vairety of different possible values, $varname should be a request
10111: string, and the other parameters can be used to specify who and what
10112: one is asking about.
10113: 
10114: Possible values for $varname are environment.lastname (or other item
10115: from the envirnment hash), user.name (or someother aspect about the
10116: user), resource.0.maxtries (or some other part and parameter of a
10117: resource)
10118: 
10119: =item *
10120: 
10121: directcondval($number) : get current value of a condition; reads from a state
10122: string
10123: 
10124: =item *
10125: 
10126: condval($condidx) : value of condition index based on state
10127: 
10128: =item *
10129: 
10130: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10131: resource's metadata, $what should be either a specific key, or either
10132: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10133: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10134: 
10135: this function automatically caches all requests
10136: 
10137: =item *
10138: 
10139: metadata_query($query,$custom,$customshow) : make a metadata query against the
10140: network of library servers; returns file handle of where SQL and regex results
10141: will be stored for query
10142: 
10143: =item *
10144: 
10145: symbread($filename) : return symbolic list entry (filename argument optional);
10146: returns the data handle
10147: 
10148: =item *
10149: 
10150: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10151: a possible symb for the URL in $thisfn, and if is an encryypted
10152: resource that the user accessed using /enc/ returns a 1 on success, 0
10153: on failure, user must be in a course, as it assumes the existance of
10154: the course initial hash, and uses $env('request.course.id'}
10155: 
10156: 
10157: =item *
10158: 
10159: symbclean($symb) : removes versions numbers from a symb, returns the
10160: cleaned symb
10161: 
10162: =item *
10163: 
10164: is_on_map($uri) : checks if the $uri is somewhere on the current
10165: course map, user must be in a course for it to work.
10166: 
10167: =item *
10168: 
10169: numval($salt) : return random seed value (addend for rndseed)
10170: 
10171: =item *
10172: 
10173: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10174: a random seed, all arguments are optional, if they aren't sent it uses the
10175: environment to derive them. Note: if symb isn't sent and it can't get one
10176: from &symbread it will use the current time as its return value
10177: 
10178: =item *
10179: 
10180: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10181: unfakeable, receipt
10182: 
10183: =item *
10184: 
10185: receipt() : API to ireceipt working off of env values; given out to users
10186: 
10187: =item *
10188: 
10189: countacc($url) : count the number of accesses to a given URL
10190: 
10191: =item *
10192: 
10193: 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
10194: 
10195: =item *
10196: 
10197: 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)
10198: 
10199: =item *
10200: 
10201: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10202: 
10203: =item *
10204: 
10205: devalidate($symb) : devalidate temporary spreadsheet calculations,
10206: forcing spreadsheet to reevaluate the resource scores next time.
10207: 
10208: =back
10209: 
10210: =head2 Storing/Retreiving Data
10211: 
10212: =over 4
10213: 
10214: =item *
10215: 
10216: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10217: for this url; hashref needs to be given and should be a \%hashname; the
10218: remaining args aren't required and if they aren't passed or are '' they will
10219: be derived from the env
10220: 
10221: =item *
10222: 
10223: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10224: uses critical subroutine
10225: 
10226: =item *
10227: 
10228: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10229: all args are optional
10230: 
10231: =item *
10232: 
10233: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10234: dumps the complete (or key matching regexp) namespace into a hash
10235: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10236: normally &store()ed into
10237: 
10238: $range should be either an integer '100' (give me the first 100
10239:                                            matching records)
10240:               or be  two integers sperated by a - with no spaces
10241:                  '30-50' (give me the 30th through the 50th matching
10242:                           records)
10243: 
10244: 
10245: =item *
10246: 
10247: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10248: replaces a &store() version of data with a replacement set of data
10249: for a particular resource in a namespace passed in the $storehash hash 
10250: reference
10251: 
10252: =item *
10253: 
10254: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10255: works very similar to store/cstore, but all data is stored in a
10256: temporary location and can be reset using tmpreset, $storehash should
10257: be a hash reference, returns nothing on success
10258: 
10259: =item *
10260: 
10261: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10262: similar to restore, but all data is stored in a temporary location and
10263: can be reset using tmpreset. Returns a hash of values on success,
10264: error string otherwise.
10265: 
10266: =item *
10267: 
10268: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10269: deltes all keys for $symb form the temporary storage hash.
10270: 
10271: =item *
10272: 
10273: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10274: reference filled in from namesp ($udom and $uname are optional)
10275: 
10276: =item *
10277: 
10278: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10279: namesp ($udom and $uname are optional)
10280: 
10281: =item *
10282: 
10283: dump($namespace,$udom,$uname,$regexp,$range) : 
10284: dumps the complete (or key matching regexp) namespace into a hash
10285: ($udom, $uname, $regexp, $range are optional)
10286: 
10287: $range should be either an integer '100' (give me the first 100
10288:                                            matching records)
10289:               or be  two integers sperated by a - with no spaces
10290:                  '30-50' (give me the 30th through the 50th matching
10291:                           records)
10292: =item *
10293: 
10294: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10295: $store can be a scalar, an array reference, or if the amount to be 
10296: incremented is > 1, a hash reference.
10297: 
10298: ($udom and $uname are optional)
10299: 
10300: =item *
10301: 
10302: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10303: ($udom and $uname are optional)
10304: 
10305: =item *
10306: 
10307: cput($namespace,$storehash,$udom,$uname) : critical put
10308: ($udom and $uname are optional)
10309: 
10310: =item *
10311: 
10312: newput($namespace,$storehash,$udom,$uname) :
10313: 
10314: Attempts to store the items in the $storehash, but only if they don't
10315: currently exist, if this succeeds you can be certain that you have 
10316: successfully created a new key value pair in the $namespace db.
10317: 
10318: 
10319: Args:
10320:  $namespace: name of database to store values to
10321:  $storehash: hashref to store to the db
10322:  $udom: (optional) domain of user containing the db
10323:  $uname: (optional) name of user caontaining the db
10324: 
10325: Returns:
10326:  'ok' -> succeeded in storing all keys of $storehash
10327:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10328:                         least <key> already existed in the db (other
10329:                         requested keys may also already exist)
10330:  'error: <msg>' -> unable to tie the DB or other error occurred
10331:  'con_lost' -> unable to contact request server
10332:  'refused' -> action was not allowed by remote machine
10333: 
10334: 
10335: =item *
10336: 
10337: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10338: reference filled in from namesp (encrypts the return communication)
10339: ($udom and $uname are optional)
10340: 
10341: =item *
10342: 
10343: log($udom,$name,$home,$message) : write to permanent log for user; use
10344: critical subroutine
10345: 
10346: =item *
10347: 
10348: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10349: array reference filled in from namespace found in domain level on either
10350: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10351: 
10352: =item *
10353: 
10354: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10355: domain level either on specified domain server ($uhome) or primary domain 
10356: server ($udom and $uhome are optional)
10357: 
10358: =item * 
10359: 
10360: get_domain_defaults($target_domain) : returns hash with defaults for
10361: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10362: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10363: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10364: Values are retrieved from cache (if current), or from domain's configuration.db
10365: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10366: or lonTabs/domain.tab. 
10367: 
10368: %domdefaults = &get_auth_defaults($target_domain);
10369: 
10370: =back
10371: 
10372: =head2 Network Status Functions
10373: 
10374: =over 4
10375: 
10376: =item *
10377: 
10378: dirlist($uri) : return directory list based on URI
10379: 
10380: =item *
10381: 
10382: spareserver() : find server with least workload from spare.tab
10383: 
10384: 
10385: =item *
10386: 
10387: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10388: if there is no corresponding loncapa host.
10389: 
10390: =back
10391: 
10392: 
10393: =head2 Apache Request
10394: 
10395: =over 4
10396: 
10397: =item *
10398: 
10399: ssi($url,%hash) : server side include, does a complete request cycle on url to
10400: localhost, posts hash
10401: 
10402: =back
10403: 
10404: =head2 Data to String to Data
10405: 
10406: =over 4
10407: 
10408: =item *
10409: 
10410: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10411: and '&' separators, supports elements that are arrayrefs and hashrefs
10412: 
10413: =item *
10414: 
10415: hashref2str($hashref) : convert a hashref into a string complete with
10416: escaping and '=' and '&' separators, supports elements that are
10417: arrayrefs and hashrefs
10418: 
10419: =item *
10420: 
10421: arrayref2str($arrayref) : convert an arrayref into a string complete
10422: with escaping and '&' separators, supports elements that are arrayrefs
10423: and hashrefs
10424: 
10425: =item *
10426: 
10427: str2hash($string) : convert string to hash using unescaping and
10428: splitting on '=' and '&', supports elements that are arrayrefs and
10429: hashrefs
10430: 
10431: =item *
10432: 
10433: str2array($string) : convert string to hash using unescaping and
10434: splitting on '&', supports elements that are arrayrefs and hashrefs
10435: 
10436: =back
10437: 
10438: =head2 Logging Routines
10439: 
10440: =over 4
10441: 
10442: These routines allow one to make log messages in the lonnet.log and
10443: lonnet.perm logfiles.
10444: 
10445: =item *
10446: 
10447: logtouch() : make sure the logfile, lonnet.log, exists
10448: 
10449: =item *
10450: 
10451: logthis() : append message to the normal lonnet.log file, it gets
10452: preiodically rolled over and deleted.
10453: 
10454: =item *
10455: 
10456: logperm() : append a permanent message to lonnet.perm.log, this log
10457: file never gets deleted by any automated portion of the system, only
10458: messages of critical importance should go in here.
10459: 
10460: =back
10461: 
10462: =head2 General File Helper Routines
10463: 
10464: =over 4
10465: 
10466: =item *
10467: 
10468: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10469: (a) files in /uploaded
10470:   (i) If a local copy of the file exists - 
10471:       compares modification date of local copy with last-modified date for 
10472:       definitive version stored on home server for course. If local copy is 
10473:       stale, requests a new version from the home server and stores it. 
10474:       If the original has been removed from the home server, then local copy 
10475:       is unlinked.
10476:   (ii) If local copy does not exist -
10477:       requests the file from the home server and stores it. 
10478:   
10479:   If $caller is 'uploadrep':  
10480:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10481:     for request for files originally uploaded via DOCS. 
10482:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10483:   
10484:   Otherwise:
10485:      This indicates a call from the content generation phase of the request.
10486:      -  returns the entire contents of the file or -1.
10487:      
10488: (b) files in /res
10489:    - returns the entire contents of a file or -1; 
10490:    it properly subscribes to and replicates the file if neccessary.
10491: 
10492: 
10493: =item *
10494: 
10495: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10496:                   reference
10497: 
10498: returns either a stat() list of data about the file or an empty list
10499: if the file doesn't exist or couldn't find out about it (connection
10500: problems or user unknown)
10501: 
10502: =item *
10503: 
10504: filelocation($dir,$file) : returns file system location of a file
10505: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10506: directory that relative $file lookups are to looked in ($dir of /a/dir
10507: and a file of ../bob will become /a/bob)
10508: 
10509: =item *
10510: 
10511: hreflocation($dir,$file) : returns file system location or a URL; same as
10512: filelocation except for hrefs
10513: 
10514: =item *
10515: 
10516: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10517: 
10518: =back
10519: 
10520: =head2 Usererfile file routines (/uploaded*)
10521: 
10522: =over 4
10523: 
10524: =item *
10525: 
10526: userfileupload(): main rotine for putting a file in a user or course's
10527:                   filespace, arguments are,
10528: 
10529:  formname - required - this is the name of the element in $env where the
10530:            filename, and the contents of the file to create/modifed exist
10531:            the filename is in $env{'form.'.$formname.'.filename'} and the
10532:            contents of the file is located in $env{'form.'.$formname}
10533:  coursedoc - if true, store the file in the course of the active role
10534:              of the current user
10535:  subdir - required - subdirectory to put the file in under ../userfiles/
10536:          if undefined, it will be placed in "unknown"
10537: 
10538:  (This routine calls clean_filename() to remove any dangerous
10539:  characters from the filename, and then calls finuserfileupload() to
10540:  complete the transaction)
10541: 
10542:  returns either the url of the uploaded file (/uploaded/....) if successful
10543:  and /adm/notfound.html if unsuccessful
10544: 
10545: =item *
10546: 
10547: clean_filename(): routine for cleaing a filename up for storage in
10548:                  userfile space, argument is:
10549: 
10550:  filename - proposed filename
10551: 
10552: returns: the new clean filename
10553: 
10554: =item *
10555: 
10556: finishuserfileupload(): routine that creaes and sends the file to
10557: userspace, probably shouldn't be called directly
10558: 
10559:   docuname: username or courseid of destination for the file
10560:   docudom: domain of user/course of destination for the file
10561:   formname: same as for userfileupload()
10562:   fname: filename (inculding subdirectories) for the file
10563: 
10564:  returns either the url of the uploaded file (/uploaded/....) if successful
10565:  and /adm/notfound.html if unsuccessful
10566: 
10567: =item *
10568: 
10569: renameuserfile(): renames an existing userfile to a new name
10570: 
10571:   Args:
10572:    docuname: username or courseid of destination for the file
10573:    docudom: domain of user/course of destination for the file
10574:    old: current file name (including any subdirs under userfiles)
10575:    new: desired file name (including any subdirs under userfiles)
10576: 
10577: =item *
10578: 
10579: mkdiruserfile(): creates a directory is a userfiles dir
10580: 
10581:   Args:
10582:    docuname: username or courseid of destination for the file
10583:    docudom: domain of user/course of destination for the file
10584:    dir: dir to create (including any subdirs under userfiles)
10585: 
10586: =item *
10587: 
10588: removeuserfile(): removes a file that exists in userfiles
10589: 
10590:   Args:
10591:    docuname: username or courseid of destination for the file
10592:    docudom: domain of user/course of destination for the file
10593:    fname: filname to delete (including any subdirs under userfiles)
10594: 
10595: =item *
10596: 
10597: removeuploadedurl(): convience function for removeuserfile()
10598: 
10599:   Args:
10600:    url:  a full /uploaded/... url to delete
10601: 
10602: =item * 
10603: 
10604: get_portfile_permissions():
10605:   Args:
10606:     domain: domain of user or course contain the portfolio files
10607:     user: name of user or num of course contain the portfolio files
10608:   Returns:
10609:     hashref of a dump of the proper file_permissions.db
10610:    
10611: 
10612: =item * 
10613: 
10614: get_access_controls():
10615: 
10616: Args:
10617:   current_permissions: the hash ref returned from get_portfile_permissions()
10618:   group: (optional) the group you want the files associated with
10619:   file: (optional) the file you want access info on
10620: 
10621: Returns:
10622:     a hash (keys are file names) of hashes containing
10623:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10624:         values are XML containing access control settings (see below) 
10625: 
10626: Internal notes:
10627: 
10628:  access controls are stored in file_permissions.db as key=value pairs.
10629:     key -> path to file/file_name\0uniqueID:scope_end_start
10630:         where scope -> public,guest,course,group,domains or users.
10631:               end -> UNIX time for end of access (0 -> no end date)
10632:               start -> UNIX time for start of access
10633: 
10634:     value -> XML description of access control
10635:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10636:             <start></start>
10637:             <end></end>
10638: 
10639:             <password></password>  for scope type = guest
10640: 
10641:             <domain></domain>     for scope type = course or group
10642:             <number></number>
10643:             <roles id="">
10644:              <role></role>
10645:              <access></access>
10646:              <section></section>
10647:              <group></group>
10648:             </roles>
10649: 
10650:             <dom></dom>         for scope type = domains
10651: 
10652:             <users>             for scope type = users
10653:              <user>
10654:               <uname></uname>
10655:               <udom></udom>
10656:              </user>
10657:             </users>
10658:            </scope> 
10659:               
10660:  Access data is also aggregated for each file in an additional key=value pair:
10661:  key -> path to file/file_name\0accesscontrol 
10662:  value -> reference to hash
10663:           hash contains key = value pairs
10664:           where key = uniqueID:scope_end_start
10665:                 value = UNIX time record was last updated
10666: 
10667:           Used to improve speed of look-ups of access controls for each file.  
10668:  
10669:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10670: 
10671: modify_access_controls():
10672: 
10673: Modifies access controls for a portfolio file
10674: Args
10675: 1. file name
10676: 2. reference to hash of required changes,
10677: 3. domain
10678: 4. username
10679:   where domain,username are the domain of the portfolio owner 
10680:   (either a user or a course) 
10681: 
10682: Returns:
10683: 1. result of additions or updates ('ok' or 'error', with error message). 
10684: 2. result of deletions ('ok' or 'error', with error message).
10685: 3. reference to hash of any new or updated access controls.
10686: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10687:    key = integer (inbound ID)
10688:    value = uniqueID  
10689: 
10690: =back
10691: 
10692: =head2 HTTP Helper Routines
10693: 
10694: =over 4
10695: 
10696: =item *
10697: 
10698: escape() : unpack non-word characters into CGI-compatible hex codes
10699: 
10700: =item *
10701: 
10702: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10703: 
10704: =back
10705: 
10706: =head1 PRIVATE SUBROUTINES
10707: 
10708: =head2 Underlying communication routines (Shouldn't call)
10709: 
10710: =over 4
10711: 
10712: =item *
10713: 
10714: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10715: 
10716: =item *
10717: 
10718: reply() : uses subreply to send a message to remote machine, logs all failures
10719: 
10720: =item *
10721: 
10722: critical() : passes a critical message to another server; if cannot
10723: get through then place message in connection buffer directory and
10724: returns con_delayed, if incapable of saving message, returns
10725: con_failed
10726: 
10727: =item *
10728: 
10729: reconlonc() : tries to reconnect lonc client processes.
10730: 
10731: =back
10732: 
10733: =head2 Resource Access Logging
10734: 
10735: =over 4
10736: 
10737: =item *
10738: 
10739: flushcourselogs() : flush (save) buffer logs and access logs
10740: 
10741: =item *
10742: 
10743: courselog($what) : save message for course in hash
10744: 
10745: =item *
10746: 
10747: courseacclog($what) : save message for course using &courselog().  Perform
10748: special processing for specific resource types (problems, exams, quizzes, etc).
10749: 
10750: =item *
10751: 
10752: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10753: as a PerlChildExitHandler
10754: 
10755: =back
10756: 
10757: =head2 Other
10758: 
10759: =over 4
10760: 
10761: =item *
10762: 
10763: symblist($mapname,%newhash) : update symbolic storage links
10764: 
10765: =back
10766: 
10767: =cut
10768: 

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