File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1028: download - view: text, annotated - select for diffs
Wed Sep 16 05:59:49 2009 UTC (14 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Modify allow check in createcourse() to accommodate requestcourses case.
  - Need to check course owner's environment.db for reqcrsotherdom.$category
    if course domain is different from course owner's domain.
- If current user is different to course owner, this is a previously queued request - now approved or validated, and user must have ccc priv in course's domain.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1028 2009/09/16 05:59:49 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol);
   80: 
   81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   84:     %courseownerbuf, %coursetypebuf,$locknum);
   85: 
   86: use IO::Socket;
   87: use GDBM_File;
   88: use HTML::LCParser;
   89: use Fcntl qw(:flock);
   90: use Storable qw(thaw nfreeze);
   91: use Time::HiRes qw( gettimeofday tv_interval );
   92: use Cache::Memcached;
   93: use Digest::MD5;
   94: use Math::Random;
   95: use File::MMagic;
   96: use LONCAPA qw(:DEFAULT :match);
   97: use LONCAPA::Configuration;
   98: 
   99: my $readit;
  100: my $max_connection_retries = 10;     # Or some such value.
  101: 
  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  103: 
  104: require Exporter;
  105: 
  106: our @ISA = qw (Exporter);
  107: our @EXPORT = qw(%env);
  108: 
  109: 
  110: # --------------------------------------------------------------------- Logging
  111: {
  112:     my $logid;
  113:     sub instructor_log {
  114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  115:         if (($cnum eq '') || ($cdom eq '')) {
  116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  118:         }
  119: 	$logid++;
  120:         my $now = time();
  121: 	my $id=$now.'00000'.$$.'00000'.$logid;
  122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  123: 				    { $id => {
  124: 					'exe_uname' => $env{'user.name'},
  125: 					'exe_udom'  => $env{'user.domain'},
  126: 					'exe_time'  => $now,
  127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  128: 					'delflag'   => $delflag,
  129: 					'logentry'  => $storehash,
  130: 					'uname'     => $uname,
  131: 					'udom'      => $udom,
  132: 				    }
  133: 				  },$cdom,$cnum);
  134:     }
  135: }
  136: 
  137: sub logtouch {
  138:     my $execdir=$perlvar{'lonDaemons'};
  139:     unless (-e "$execdir/logs/lonnet.log") {	
  140: 	open(my $fh,">>$execdir/logs/lonnet.log");
  141: 	close $fh;
  142:     }
  143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  145: }
  146: 
  147: sub logthis {
  148:     my $message=shift;
  149:     my $execdir=$perlvar{'lonDaemons'};
  150:     my $now=time;
  151:     my $local=localtime($now);
  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  154: 	print $fh $logstring;
  155: 	close($fh);
  156:     }
  157:     return 1;
  158: }
  159: 
  160: sub logperm {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  166: 	print $fh "$now:$message:$local\n";
  167: 	close($fh);
  168:     }
  169:     return 1;
  170: }
  171: 
  172: sub create_connection {
  173:     my ($hostname,$lonid) = @_;
  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  175: 				     Type    => SOCK_STREAM,
  176: 				     Timeout => 10);
  177:     return 0 if (!$client);
  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  179:     my $result = <$client>;
  180:     chomp($result);
  181:     return 1 if ($result eq 'done');
  182:     return 0;
  183: }
  184: 
  185: sub get_server_timezone {
  186:     my ($cnum,$cdom) = @_;
  187:     my $home=&homeserver($cnum,$cdom);
  188:     if ($home ne 'no_host') {
  189:         my $cachetime = 24*3600;
  190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  191:         if (defined($cached)) {
  192:             return $timezone;
  193:         } else {
  194:             my $timezone = &reply('servertimezone',$home);
  195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  196:         }
  197:     }
  198: }
  199: 
  200: sub get_server_loncaparev {
  201:     my ($dom,$lonhost) = @_;
  202:     if (defined($lonhost)) {
  203:         if (!defined(&hostname($lonhost))) {
  204:             undef($lonhost);
  205:         }
  206:     }
  207:     if (!defined($lonhost)) {
  208:         if (defined(&domain($dom,'primary'))) {
  209:             $lonhost=&domain($dom,'primary');
  210:             if ($lonhost eq 'no_host') {
  211:                 undef($lonhost);
  212:             }
  213:         }
  214:     }
  215:     if (defined($lonhost)) {
  216:         my $cachetime = 24*3600;
  217:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  218:         if (defined($cached)) {
  219:             return $loncaparev;
  220:         } else {
  221:             my $loncaparev = &reply('serverloncaparev',$lonhost);
  222:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  223:         }
  224:     }
  225: }
  226: 
  227: # -------------------------------------------------- Non-critical communication
  228: sub subreply {
  229:     my ($cmd,$server)=@_;
  230:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  231:     #
  232:     #  With loncnew process trimming, there's a timing hole between lonc server
  233:     #  process exit and the master server picking up the listen on the AF_UNIX
  234:     #  socket.  In that time interval, a lock file will exist:
  235: 
  236:     my $lockfile=$peerfile.".lock";
  237:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  238: 	sleep(1);
  239:     }
  240:     # At this point, either a loncnew parent is listening or an old lonc
  241:     # or loncnew child is listening so we can connect or everything's dead.
  242:     #
  243:     #   We'll give the connection a few tries before abandoning it.  If
  244:     #   connection is not possible, we'll con_lost back to the client.
  245:     #   
  246:     my $client;
  247:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  248: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  249: 				      Type    => SOCK_STREAM,
  250: 				      Timeout => 10);
  251: 	if ($client) {
  252: 	    last;		# Connected!
  253: 	} else {
  254: 	    &create_connection(&hostname($server),$server);
  255: 	}
  256:         sleep(1);		# Try again later if failed connection.
  257:     }
  258:     my $answer;
  259:     if ($client) {
  260: 	print $client "sethost:$server:$cmd\n";
  261: 	$answer=<$client>;
  262: 	if (!$answer) { $answer="con_lost"; }
  263: 	chomp($answer);
  264:     } else {
  265: 	$answer = 'con_lost';	# Failed connection.
  266:     }
  267:     return $answer;
  268: }
  269: 
  270: sub reply {
  271:     my ($cmd,$server)=@_;
  272:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  273:     my $answer=subreply($cmd,$server);
  274:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  275:        &logthis("<font color=\"blue\">WARNING:".
  276:                 " $cmd to $server returned $answer</font>");
  277:     }
  278:     return $answer;
  279: }
  280: 
  281: # ----------------------------------------------------------- Send USR1 to lonc
  282: 
  283: sub reconlonc {
  284:     my ($lonid) = @_;
  285:     my $hostname = &hostname($lonid);
  286:     if ($lonid) {
  287: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  288: 	if ($hostname && -e $peerfile) {
  289: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  290: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  291: 					     Type    => SOCK_STREAM,
  292: 					     Timeout => 10);
  293: 	    if ($client) {
  294: 		print $client ("reset_retries\n");
  295: 		my $answer=<$client>;
  296: 		#reset just this one.
  297: 	    }
  298: 	}
  299: 	return;
  300:     }
  301: 
  302:     &logthis("Trying to reconnect lonc");
  303:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  304:     if (open(my $fh,"<$loncfile")) {
  305: 	my $loncpid=<$fh>;
  306:         chomp($loncpid);
  307:         if (kill 0 => $loncpid) {
  308: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  309:             kill USR1 => $loncpid;
  310:             sleep 1;
  311:          } else {
  312: 	    &logthis(
  313:                "<font color=\"blue\">WARNING:".
  314:                " lonc at pid $loncpid not responding, giving up</font>");
  315:         }
  316:     } else {
  317: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  318:     }
  319: }
  320: 
  321: # ------------------------------------------------------ Critical communication
  322: 
  323: sub critical {
  324:     my ($cmd,$server)=@_;
  325:     unless (&hostname($server)) {
  326:         &logthis("<font color=\"blue\">WARNING:".
  327:                " Critical message to unknown server ($server)</font>");
  328:         return 'no_such_host';
  329:     }
  330:     my $answer=reply($cmd,$server);
  331:     if ($answer eq 'con_lost') {
  332: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  333: 	my $answer=reply($cmd,$server);
  334:         if ($answer eq 'con_lost') {
  335:             my $now=time;
  336:             my $middlename=$cmd;
  337:             $middlename=substr($middlename,0,16);
  338:             $middlename=~s/\W//g;
  339:             my $dfilename=
  340:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  341:             $dumpcount++;
  342:             {
  343: 		my $dfh;
  344: 		if (open($dfh,">$dfilename")) {
  345: 		    print $dfh "$cmd\n"; 
  346: 		    close($dfh);
  347: 		}
  348:             }
  349:             sleep 2;
  350:             my $wcmd='';
  351:             {
  352: 		my $dfh;
  353: 		if (open($dfh,"<$dfilename")) {
  354: 		    $wcmd=<$dfh>; 
  355: 		    close($dfh);
  356: 		}
  357:             }
  358:             chomp($wcmd);
  359:             if ($wcmd eq $cmd) {
  360: 		&logthis("<font color=\"blue\">WARNING: ".
  361:                          "Connection buffer $dfilename: $cmd</font>");
  362:                 &logperm("D:$server:$cmd");
  363: 	        return 'con_delayed';
  364:             } else {
  365:                 &logthis("<font color=\"red\">CRITICAL:"
  366:                         ." Critical connection failed: $server $cmd</font>");
  367:                 &logperm("F:$server:$cmd");
  368:                 return 'con_failed';
  369:             }
  370:         }
  371:     }
  372:     return $answer;
  373: }
  374: 
  375: # ------------------------------------------- check if return value is an error
  376: 
  377: sub error {
  378:     my ($result) = @_;
  379:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  380: 	if ($2 == 2) { return undef; }
  381: 	return $1;
  382:     }
  383:     return undef;
  384: }
  385: 
  386: sub convert_and_load_session_env {
  387:     my ($lonidsdir,$handle)=@_;
  388:     my @profile;
  389:     {
  390: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  391: 	if (!$opened) {
  392: 	    return 0;
  393: 	}
  394: 	flock($idf,LOCK_SH);
  395: 	@profile=<$idf>;
  396: 	close($idf);
  397:     }
  398:     my %temp_env;
  399:     foreach my $line (@profile) {
  400: 	if ($line !~ m/=/) {
  401: 	    return 0;
  402: 	}
  403: 	chomp($line);
  404: 	my ($envname,$envvalue)=split(/=/,$line,2);
  405: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  406:     }
  407:     unlink("$lonidsdir/$handle.id");
  408:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  409: 	    0640)) {
  410: 	%disk_env = %temp_env;
  411: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  412: 	untie(%disk_env);
  413:     }
  414:     return 1;
  415: }
  416: 
  417: # ------------------------------------------- Transfer profile into environment
  418: my $env_loaded;
  419: sub transfer_profile_to_env {
  420:     my ($lonidsdir,$handle,$force_transfer) = @_;
  421:     if (!$force_transfer && $env_loaded) { return; } 
  422: 
  423:     if (!defined($lonidsdir)) {
  424: 	$lonidsdir = $perlvar{'lonIDsDir'};
  425:     }
  426:     if (!defined($handle)) {
  427:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  428:     }
  429: 
  430:     my $convert;
  431:     {
  432:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  433: 	if (!$opened) {
  434: 	    return;
  435: 	}
  436: 	flock($idf,LOCK_SH);
  437: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  438: 		&GDBM_READER(),0640)) {
  439: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  440: 	    untie(%disk_env);
  441: 	} else {
  442: 	    $convert = 1;
  443: 	}
  444:     }
  445:     if ($convert) {
  446: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  447: 	    &logthis("Failed to load session, or convert session.");
  448: 	}
  449:     }
  450: 
  451:     my %remove;
  452:     while ( my $envname = each(%env) ) {
  453:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  454:             if ($time < time-300) {
  455:                 $remove{$key}++;
  456:             }
  457:         }
  458:     }
  459: 
  460:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  461:     $env_loaded=1;
  462:     foreach my $expired_key (keys(%remove)) {
  463:         &delenv($expired_key);
  464:     }
  465: }
  466: 
  467: # ---------------------------------------------------- Check for valid session 
  468: sub check_for_valid_session {
  469:     my ($r) = @_;
  470:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  471:     my $lonid=$cookies{'lonID'};
  472:     return undef if (!$lonid);
  473: 
  474:     my $handle=&LONCAPA::clean_handle($lonid->value);
  475:     my $lonidsdir=$r->dir_config('lonIDsDir');
  476:     return undef if (!-e "$lonidsdir/$handle.id");
  477: 
  478:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  479:     return undef if (!$opened);
  480: 
  481:     flock($idf,LOCK_SH);
  482:     my %disk_env;
  483:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  484: 	    &GDBM_READER(),0640)) {
  485: 	return undef;	
  486:     }
  487: 
  488:     if (!defined($disk_env{'user.name'})
  489: 	|| !defined($disk_env{'user.domain'})) {
  490: 	return undef;
  491:     }
  492:     return $handle;
  493: }
  494: 
  495: sub timed_flock {
  496:     my ($file,$lock_type) = @_;
  497:     my $failed=0;
  498:     eval {
  499: 	local $SIG{__DIE__}='DEFAULT';
  500: 	local $SIG{ALRM}=sub {
  501: 	    $failed=1;
  502: 	    die("failed lock");
  503: 	};
  504: 	alarm(13);
  505: 	flock($file,$lock_type);
  506: 	alarm(0);
  507:     };
  508:     if ($failed) {
  509: 	return undef;
  510:     } else {
  511: 	return 1;
  512:     }
  513: }
  514: 
  515: # ---------------------------------------------------------- Append Environment
  516: 
  517: sub appenv {
  518:     my ($newenv,$roles) = @_;
  519:     if (ref($newenv) eq 'HASH') {
  520:         foreach my $key (keys(%{$newenv})) {
  521:             my $refused = 0;
  522: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  523:                 $refused = 1;
  524:                 if (ref($roles) eq 'ARRAY') {
  525:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  526:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  527:                         $refused = 0;
  528:                     }
  529:                 }
  530:             }
  531:             if ($refused) {
  532:                 &logthis("<font color=\"blue\">WARNING: ".
  533:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  534:                          .'</font>');
  535: 	        delete($newenv->{$key});
  536:             } else {
  537:                 $env{$key}=$newenv->{$key};
  538:             }
  539:         }
  540:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  541:         if ($opened
  542: 	    && &timed_flock($env_file,LOCK_EX)
  543: 	    &&
  544: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  545: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  546: 	    while (my ($key,$value) = each(%{$newenv})) {
  547: 	        $disk_env{$key} = $value;
  548: 	    }
  549: 	    untie(%disk_env);
  550:         }
  551:     }
  552:     return 'ok';
  553: }
  554: # ----------------------------------------------------- Delete from Environment
  555: 
  556: sub delenv {
  557:     my ($delthis,$regexp) = @_;
  558:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  559:         &logthis("<font color=\"blue\">WARNING: ".
  560:                 "Attempt to delete from environment ".$delthis);
  561:         return 'error';
  562:     }
  563:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  564:     if ($opened
  565: 	&& &timed_flock($env_file,LOCK_EX)
  566: 	&&
  567: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  568: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  569: 	foreach my $key (keys(%disk_env)) {
  570: 	    if ($regexp) {
  571:                 if ($key=~/^$delthis/) {
  572:                     delete($env{$key});
  573:                     delete($disk_env{$key});
  574:                 } 
  575:             } else {
  576:                 if ($key=~/^\Q$delthis\E/) {
  577: 		    delete($env{$key});
  578: 		    delete($disk_env{$key});
  579: 	        }
  580:             }
  581: 	}
  582: 	untie(%disk_env);
  583:     }
  584:     return 'ok';
  585: }
  586: 
  587: sub get_env_multiple {
  588:     my ($name) = @_;
  589:     my @values;
  590:     if (defined($env{$name})) {
  591:         # exists is it an array
  592:         if (ref($env{$name})) {
  593:             @values=@{ $env{$name} };
  594:         } else {
  595:             $values[0]=$env{$name};
  596:         }
  597:     }
  598:     return(@values);
  599: }
  600: 
  601: # ------------------------------------------------------------------- Locking
  602: 
  603: sub set_lock {
  604:     my ($text)=@_;
  605:     $locknum++;
  606:     my $id=$$.'-'.$locknum;
  607:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  608:              'session.lock.'.$id => $text});
  609:     return $id;
  610: }
  611: 
  612: sub get_locks {
  613:     my $num=0;
  614:     my %texts=();
  615:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  616:        if ($lock=~/\w/) {
  617:           $num++;
  618:           $texts{$lock}=$env{'session.lock.'.$lock};
  619:        }
  620:    }
  621:    return ($num,%texts);
  622: }
  623: 
  624: sub remove_lock {
  625:     my ($id)=@_;
  626:     my $newlocks='';
  627:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  628:        if (($lock=~/\w/) && ($lock ne $id)) {
  629:           $newlocks.=','.$lock;
  630:        }
  631:     }
  632:     &appenv({'session.locks' => $newlocks});
  633:     &delenv('session.lock.'.$id);
  634: }
  635: 
  636: sub remove_all_locks {
  637:     my $activelocks=$env{'session.locks'};
  638:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  639:        if ($lock=~/\w/) {
  640:           &remove_lock($lock);
  641:        }
  642:     }
  643: }
  644: 
  645: 
  646: # ------------------------------------------ Find out current server userload
  647: sub userload {
  648:     my $numusers=0;
  649:     {
  650: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  651: 	my $filename;
  652: 	my $curtime=time;
  653: 	while ($filename=readdir(LONIDS)) {
  654: 	    next if ($filename eq '.' || $filename eq '..');
  655: 	    next if ($filename =~ /publicuser_\d+\.id/);
  656: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  657: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  658: 	}
  659: 	closedir(LONIDS);
  660:     }
  661:     my $userloadpercent=0;
  662:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  663:     if ($maxuserload) {
  664: 	$userloadpercent=100*$numusers/$maxuserload;
  665:     }
  666:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  667:     return $userloadpercent;
  668: }
  669: 
  670: # ------------------------------------------ Fight off request when overloaded
  671: 
  672: sub overloaderror {
  673:     my ($r,$checkserver)=@_;
  674:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  675:     my $loadavg;
  676:     if ($checkserver eq $perlvar{'lonHostID'}) {
  677:        open(my $loadfile,'/proc/loadavg');
  678:        $loadavg=<$loadfile>;
  679:        $loadavg =~ s/\s.*//g;
  680:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  681:        close($loadfile);
  682:     } else {
  683:        $loadavg=&reply('load',$checkserver);
  684:     }
  685:     my $overload=$loadavg-100;
  686:     if ($overload>0) {
  687: 	$r->err_headers_out->{'Retry-After'}=$overload;
  688:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  689:         return 413;
  690:     }    
  691:     return '';
  692: }
  693: 
  694: # ------------------------------ Find server with least workload from spare.tab
  695: 
  696: sub spareserver {
  697:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  698:     my $spare_server;
  699:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  700:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  701:                                                      :  $userloadpercent;
  702:     
  703:     foreach my $try_server (@{ $spareid{'primary'} }) {
  704: 	($spare_server, $lowest_load) =
  705: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  706:     }
  707: 
  708:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  709: 
  710:     if (!$found_server) {
  711: 	foreach my $try_server (@{ $spareid{'default'} }) {
  712: 	    ($spare_server, $lowest_load) =
  713: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  714: 	}
  715:     }
  716: 
  717:     if (!$want_server_name) {
  718:         my $protocol = 'http';
  719:         if ($protocol{$spare_server} eq 'https') {
  720:             $protocol = $protocol{$spare_server};
  721:         }
  722:         if (defined($spare_server)) {
  723:             my $hostname = &hostname($spare_server);
  724:             if (defined($hostname)) {  
  725: 	        $spare_server = $protocol.'://'.$hostname;
  726:             }
  727:         }
  728:     }
  729:     return $spare_server;
  730: }
  731: 
  732: sub compare_server_load {
  733:     my ($try_server, $spare_server, $lowest_load) = @_;
  734: 
  735:     my $loadans     = &reply('load',    $try_server);
  736:     my $userloadans = &reply('userload',$try_server);
  737: 
  738:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  739: 	next; #didn't get a number from the server
  740:     }
  741: 
  742:     my $load;
  743:     if ($loadans =~ /\d/) {
  744: 	if ($userloadans =~ /\d/) {
  745: 	    #both are numbers, pick the bigger one
  746: 	    $load = ($loadans > $userloadans) ? $loadans 
  747: 		                              : $userloadans;
  748: 	} else {
  749: 	    $load = $loadans;
  750: 	}
  751:     } else {
  752: 	$load = $userloadans;
  753:     }
  754: 
  755:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  756: 	$spare_server = $try_server;
  757: 	$lowest_load  = $load;
  758:     }
  759:     return ($spare_server,$lowest_load);
  760: }
  761: 
  762: # --------------------------- ask offload servers if user already has a session
  763: sub find_existing_session {
  764:     my ($udom,$uname) = @_;
  765:     foreach my $try_server (@{ $spareid{'primary'} },
  766: 			    @{ $spareid{'default'} }) {
  767: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  768:     }
  769:     return;
  770: }
  771: 
  772: # -------------------------------- ask if server already has a session for user
  773: sub has_user_session {
  774:     my ($lonid,$udom,$uname) = @_;
  775:     my $result = &reply(join(':','userhassession',
  776: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  777:     return 1 if ($result eq 'ok');
  778: 
  779:     return 0;
  780: }
  781: 
  782: # --------------------------------------------- Try to change a user's password
  783: 
  784: sub changepass {
  785:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  786:     $currentpass = &escape($currentpass);
  787:     $newpass     = &escape($newpass);
  788:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  789: 		       $server);
  790:     if (! $answer) {
  791: 	&logthis("No reply on password change request to $server ".
  792: 		 "by $uname in domain $udom.");
  793:     } elsif ($answer =~ "^ok") {
  794:         &logthis("$uname in $udom successfully changed their password ".
  795: 		 "on $server.");
  796:     } elsif ($answer =~ "^pwchange_failure") {
  797: 	&logthis("$uname in $udom was unable to change their password ".
  798: 		 "on $server.  The action was blocked by either lcpasswd ".
  799: 		 "or pwchange");
  800:     } elsif ($answer =~ "^non_authorized") {
  801:         &logthis("$uname in $udom did not get their password correct when ".
  802: 		 "attempting to change it on $server.");
  803:     } elsif ($answer =~ "^auth_mode_error") {
  804:         &logthis("$uname in $udom attempted to change their password despite ".
  805: 		 "not being locally or internally authenticated on $server.");
  806:     } elsif ($answer =~ "^unknown_user") {
  807:         &logthis("$uname in $udom attempted to change their password ".
  808: 		 "on $server but were unable to because $server is not ".
  809: 		 "their home server.");
  810:     } elsif ($answer =~ "^refused") {
  811: 	&logthis("$server refused to change $uname in $udom password because ".
  812: 		 "it was sent an unencrypted request to change the password.");
  813:     }
  814:     return $answer;
  815: }
  816: 
  817: # ----------------------- Try to determine user's current authentication scheme
  818: 
  819: sub queryauthenticate {
  820:     my ($uname,$udom)=@_;
  821:     my $uhome=&homeserver($uname,$udom);
  822:     if (!$uhome) {
  823: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  824: 	return 'no_host';
  825:     }
  826:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  827:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  828: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  829:     }
  830:     return $answer;
  831: }
  832: 
  833: # --------- Try to authenticate user from domain's lib servers (first this one)
  834: 
  835: sub authenticate {
  836:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  837:     $upass=&escape($upass);
  838:     $uname= &LONCAPA::clean_username($uname);
  839:     my $uhome=&homeserver($uname,$udom,1);
  840:     my $newhome;
  841:     if ((!$uhome) || ($uhome eq 'no_host')) {
  842: # Maybe the machine was offline and only re-appeared again recently?
  843:         &reconlonc();
  844: # One more
  845: 	$uhome=&homeserver($uname,$udom,1);
  846:         if (($uhome eq 'no_host') && $checkdefauth) {
  847:             if (defined(&domain($udom,'primary'))) {
  848:                 $newhome=&domain($udom,'primary');
  849:             }
  850:             if ($newhome ne '') {
  851:                 $uhome = $newhome;
  852:             }
  853:         }
  854: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  855: 	    &logthis("User $uname at $udom is unknown in authenticate");
  856: 	    return 'no_host';
  857:         }
  858:     }
  859:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  860:     if ($answer eq 'authorized') {
  861:         if ($newhome) {
  862:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  863:             return 'no_account_on_host'; 
  864:         } else {
  865:             &logthis("User $uname at $udom authorized by $uhome");
  866:             return $uhome;
  867:         }
  868:     }
  869:     if ($answer eq 'non_authorized') {
  870: 	&logthis("User $uname at $udom rejected by $uhome");
  871: 	return 'no_host'; 
  872:     }
  873:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  874:     return 'no_host';
  875: }
  876: 
  877: # ---------------------- Find the homebase for a user from domain's lib servers
  878: 
  879: my %homecache;
  880: sub homeserver {
  881:     my ($uname,$udom,$ignoreBadCache)=@_;
  882:     my $index="$uname:$udom";
  883: 
  884:     if (exists($homecache{$index})) { return $homecache{$index}; }
  885: 
  886:     my %servers = &get_servers($udom,'library');
  887:     foreach my $tryserver (keys(%servers)) {
  888:         next if ($ignoreBadCache ne 'true' && 
  889: 		 exists($badServerCache{$tryserver}));
  890: 
  891: 	my $answer=reply("home:$udom:$uname",$tryserver);
  892: 	if ($answer eq 'found') {
  893: 	    delete($badServerCache{$tryserver}); 
  894: 	    return $homecache{$index}=$tryserver;
  895: 	} elsif ($answer eq 'no_host') {
  896: 	    $badServerCache{$tryserver}=1;
  897: 	}
  898:     }    
  899:     return 'no_host';
  900: }
  901: 
  902: # ------------------------------------- Find the usernames behind a list of IDs
  903: 
  904: sub idget {
  905:     my ($udom,@ids)=@_;
  906:     my %returnhash=();
  907:     
  908:     my %servers = &get_servers($udom,'library');
  909:     foreach my $tryserver (keys(%servers)) {
  910: 	my $idlist=join('&',@ids);
  911: 	$idlist=~tr/A-Z/a-z/; 
  912: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  913: 	my @answer=();
  914: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  915: 	    @answer=split(/\&/,$reply);
  916: 	}                    ;
  917: 	my $i;
  918: 	for ($i=0;$i<=$#ids;$i++) {
  919: 	    if ($answer[$i]) {
  920: 		$returnhash{$ids[$i]}=$answer[$i];
  921: 	    } 
  922: 	}
  923:     } 
  924:     return %returnhash;
  925: }
  926: 
  927: # ------------------------------------- Find the IDs behind a list of usernames
  928: 
  929: sub idrget {
  930:     my ($udom,@unames)=@_;
  931:     my %returnhash=();
  932:     foreach my $uname (@unames) {
  933:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  934:     }
  935:     return %returnhash;
  936: }
  937: 
  938: # ------------------------------- Store away a list of names and associated IDs
  939: 
  940: sub idput {
  941:     my ($udom,%ids)=@_;
  942:     my %servers=();
  943:     foreach my $uname (keys(%ids)) {
  944: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  945:         my $uhom=&homeserver($uname,$udom);
  946:         if ($uhom ne 'no_host') {
  947:             my $id=&escape($ids{$uname});
  948:             $id=~tr/A-Z/a-z/;
  949:             my $esc_unam=&escape($uname);
  950: 	    if ($servers{$uhom}) {
  951: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  952:             } else {
  953:                 $servers{$uhom}=$id.'='.$esc_unam;
  954:             }
  955:         }
  956:     }
  957:     foreach my $server (keys(%servers)) {
  958:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  959:     }
  960: }
  961: 
  962: # ------------------------------dump from db file owned by domainconfig user
  963: sub dump_dom {
  964:     my ($namespace,$udom,$regexp,$range)=@_;
  965:     if (!$udom) {
  966:         $udom=$env{'user.domain'};
  967:     }
  968:     my %returnhash;
  969:     if ($udom) {
  970:         my $uname = &get_domainconfiguser($udom);
  971:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
  972:     }
  973:     return %returnhash;
  974: }
  975: 
  976: # ------------------------------------------ get items from domain db files   
  977: 
  978: sub get_dom {
  979:     my ($namespace,$storearr,$udom,$uhome)=@_;
  980:     my $items='';
  981:     foreach my $item (@$storearr) {
  982:         $items.=&escape($item).'&';
  983:     }
  984:     $items=~s/\&$//;
  985:     if (!$udom) {
  986:         $udom=$env{'user.domain'};
  987:         if (defined(&domain($udom,'primary'))) {
  988:             $uhome=&domain($udom,'primary');
  989:         } else {
  990:             undef($uhome);
  991:         }
  992:     } else {
  993:         if (!$uhome) {
  994:             if (defined(&domain($udom,'primary'))) {
  995:                 $uhome=&domain($udom,'primary');
  996:             }
  997:         }
  998:     }
  999:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1000:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1001:         my %returnhash;
 1002:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1003:             return %returnhash;
 1004:         }
 1005:         my @pairs=split(/\&/,$rep);
 1006:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1007:             return @pairs;
 1008:         }
 1009:         my $i=0;
 1010:         foreach my $item (@$storearr) {
 1011:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1012:             $i++;
 1013:         }
 1014:         return %returnhash;
 1015:     } else {
 1016:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1017:     }
 1018: }
 1019: 
 1020: # -------------------------------------------- put items in domain db files 
 1021: 
 1022: sub put_dom {
 1023:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1024:     if (!$udom) {
 1025:         $udom=$env{'user.domain'};
 1026:         if (defined(&domain($udom,'primary'))) {
 1027:             $uhome=&domain($udom,'primary');
 1028:         } else {
 1029:             undef($uhome);
 1030:         }
 1031:     } else {
 1032:         if (!$uhome) {
 1033:             if (defined(&domain($udom,'primary'))) {
 1034:                 $uhome=&domain($udom,'primary');
 1035:             }
 1036:         }
 1037:     } 
 1038:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1039:         my $items='';
 1040:         foreach my $item (keys(%$storehash)) {
 1041:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1042:         }
 1043:         $items=~s/\&$//;
 1044:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1045:     } else {
 1046:         &logthis("put_dom failed - no homeserver and/or domain");
 1047:     }
 1048: }
 1049: 
 1050: # --------------------- newput for items in db file owned by domainconfig user
 1051: sub newput_dom {
 1052:     my ($namespace,$storehash,$udom) = @_;
 1053:     my $result;
 1054:     if (!$udom) {
 1055:         $udom=$env{'user.domain'};
 1056:     }
 1057:     if ($udom) {
 1058:         my $uname = &get_domainconfiguser($udom);
 1059:         $result = &newput($namespace,$storehash,$udom,$uname);
 1060:     }
 1061:     return $result;
 1062: }
 1063: 
 1064: # --------------------- delete for items in db file owned by domainconfig user
 1065: sub del_dom {
 1066:     my ($namespace,$storearr,$udom)=@_;
 1067:     if (ref($storearr) eq 'ARRAY') {
 1068:         if (!$udom) {
 1069:             $udom=$env{'user.domain'};
 1070:         }
 1071:         if ($udom) {
 1072:             my $uname = &get_domainconfiguser($udom); 
 1073:             return &del($namespace,$storearr,$udom,$uname);
 1074:         }
 1075:     }
 1076: }
 1077: 
 1078: # ----------------------------------construct domainconfig user for a domain 
 1079: sub get_domainconfiguser {
 1080:     my ($udom) = @_;
 1081:     return $udom.'-domainconfig';
 1082: }
 1083: 
 1084: sub retrieve_inst_usertypes {
 1085:     my ($udom) = @_;
 1086:     my (%returnhash,@order);
 1087:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1088:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1089:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1090:         %returnhash = %{$domdefs{'inststatustypes'}};
 1091:         @order = @{$domdefs{'inststatusorder'}};
 1092:     } else {
 1093:         if (defined(&domain($udom,'primary'))) {
 1094:             my $uhome=&domain($udom,'primary');
 1095:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1096:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1097:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1098:                 return (\%returnhash,\@order);
 1099:             }
 1100:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1101:             my @pairs=split(/\&/,$hashitems);
 1102:             foreach my $item (@pairs) {
 1103:                 my ($key,$value)=split(/=/,$item,2);
 1104:                 $key = &unescape($key);
 1105:                 next if ($key =~ /^error: 2 /);
 1106:                 $returnhash{$key}=&thaw_unescape($value);
 1107:             }
 1108:             my @esc_order = split(/\&/,$orderitems);
 1109:             foreach my $item (@esc_order) {
 1110:                 push(@order,&unescape($item));
 1111:             }
 1112:         } else {
 1113:             &logthis("get_dom failed - no primary domain server for $udom");
 1114:         }
 1115:     }
 1116:     return (\%returnhash,\@order);
 1117: }
 1118: 
 1119: sub is_domainimage {
 1120:     my ($url) = @_;
 1121:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1122:         if (&domain($1) ne '') {
 1123:             return '1';
 1124:         }
 1125:     }
 1126:     return;
 1127: }
 1128: 
 1129: sub inst_directory_query {
 1130:     my ($srch) = @_;
 1131:     my $udom = $srch->{'srchdomain'};
 1132:     my %results;
 1133:     my $homeserver = &domain($udom,'primary');
 1134:     my $outcome;
 1135:     if ($homeserver ne '') {
 1136: 	my $queryid=&reply("querysend:instdirsearch:".
 1137: 			   &escape($srch->{'srchby'}).':'.
 1138: 			   &escape($srch->{'srchterm'}).':'.
 1139: 			   &escape($srch->{'srchtype'}),$homeserver);
 1140: 	my $host=&hostname($homeserver);
 1141: 	if ($queryid !~/^\Q$host\E\_/) {
 1142: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1143: 	    return;
 1144: 	}
 1145: 	my $response = &get_query_reply($queryid);
 1146: 	my $maxtries = 5;
 1147: 	my $tries = 1;
 1148: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1149: 	    $response = &get_query_reply($queryid);
 1150: 	    $tries ++;
 1151: 	}
 1152: 
 1153:         if (!&error($response) && $response ne 'refused') {
 1154:             if ($response eq 'unavailable') {
 1155:                 $outcome = $response;
 1156:             } else {
 1157:                 $outcome = 'ok';
 1158:                 my @matches = split(/\n/,$response);
 1159:                 foreach my $match (@matches) {
 1160:                     my ($key,$value) = split(/=/,$match);
 1161:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1162:                 }
 1163:             }
 1164:         }
 1165:     }
 1166:     return ($outcome,%results);
 1167: }
 1168: 
 1169: sub usersearch {
 1170:     my ($srch) = @_;
 1171:     my $dom = $srch->{'srchdomain'};
 1172:     my %results;
 1173:     my %libserv = &all_library();
 1174:     my $query = 'usersearch';
 1175:     foreach my $tryserver (keys(%libserv)) {
 1176:         if (&host_domain($tryserver) eq $dom) {
 1177:             my $host=&hostname($tryserver);
 1178:             my $queryid=
 1179:                 &reply("querysend:".&escape($query).':'.
 1180:                        &escape($srch->{'srchby'}).':'.
 1181:                        &escape($srch->{'srchtype'}).':'.
 1182:                        &escape($srch->{'srchterm'}),$tryserver);
 1183:             if ($queryid !~/^\Q$host\E\_/) {
 1184:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1185:                 next;
 1186:             }
 1187:             my $reply = &get_query_reply($queryid);
 1188:             my $maxtries = 1;
 1189:             my $tries = 1;
 1190:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1191:                 $reply = &get_query_reply($queryid);
 1192:                 $tries ++;
 1193:             }
 1194:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1195:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1196:             } else {
 1197:                 my @matches;
 1198:                 if ($reply =~ /\n/) {
 1199:                     @matches = split(/\n/,$reply);
 1200:                 } else {
 1201:                     @matches = split(/\&/,$reply);
 1202:                 }
 1203:                 foreach my $match (@matches) {
 1204:                     my ($uname,$udom,%userhash);
 1205:                     foreach my $entry (split(/:/,$match)) {
 1206:                         my ($key,$value) =
 1207:                             map {&unescape($_);} split(/=/,$entry);
 1208:                         $userhash{$key} = $value;
 1209:                         if ($key eq 'username') {
 1210:                             $uname = $value;
 1211:                         } elsif ($key eq 'domain') {
 1212:                             $udom = $value;
 1213:                         }
 1214:                     }
 1215:                     $results{$uname.':'.$udom} = \%userhash;
 1216:                 }
 1217:             }
 1218:         }
 1219:     }
 1220:     return %results;
 1221: }
 1222: 
 1223: sub get_instuser {
 1224:     my ($udom,$uname,$id) = @_;
 1225:     my $homeserver = &domain($udom,'primary');
 1226:     my ($outcome,%results);
 1227:     if ($homeserver ne '') {
 1228:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1229:                            &escape($id).':'.&escape($udom),$homeserver);
 1230:         my $host=&hostname($homeserver);
 1231:         if ($queryid !~/^\Q$host\E\_/) {
 1232:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1233:             return;
 1234:         }
 1235:         my $response = &get_query_reply($queryid);
 1236:         my $maxtries = 5;
 1237:         my $tries = 1;
 1238:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1239:             $response = &get_query_reply($queryid);
 1240:             $tries ++;
 1241:         }
 1242:         if (!&error($response) && $response ne 'refused') {
 1243:             if ($response eq 'unavailable') {
 1244:                 $outcome = $response;
 1245:             } else {
 1246:                 $outcome = 'ok';
 1247:                 my @matches = split(/\n/,$response);
 1248:                 foreach my $match (@matches) {
 1249:                     my ($key,$value) = split(/=/,$match);
 1250:                     $results{&unescape($key)} = &thaw_unescape($value);
 1251:                 }
 1252:             }
 1253:         }
 1254:     }
 1255:     my %userinfo;
 1256:     if (ref($results{$uname}) eq 'HASH') {
 1257:         %userinfo = %{$results{$uname}};
 1258:     } 
 1259:     return ($outcome,%userinfo);
 1260: }
 1261: 
 1262: sub inst_rulecheck {
 1263:     my ($udom,$uname,$id,$item,$rules) = @_;
 1264:     my %returnhash;
 1265:     if ($udom ne '') {
 1266:         if (ref($rules) eq 'ARRAY') {
 1267:             @{$rules} = map {&escape($_);} (@{$rules});
 1268:             my $rulestr = join(':',@{$rules});
 1269:             my $homeserver=&domain($udom,'primary');
 1270:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1271:                 my $response;
 1272:                 if ($item eq 'username') {                
 1273:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1274:                                               ':'.&escape($uname).':'.$rulestr,
 1275:                                               $homeserver));
 1276:                 } elsif ($item eq 'id') {
 1277:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1278:                                               ':'.&escape($id).':'.$rulestr,
 1279:                                               $homeserver));
 1280:                 } elsif ($item eq 'selfcreate') {
 1281:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1282:                                                &escape($udom).':'.&escape($uname).
 1283:                                               ':'.$rulestr,$homeserver));
 1284:                 }
 1285:                 if ($response ne 'refused') {
 1286:                     my @pairs=split(/\&/,$response);
 1287:                     foreach my $item (@pairs) {
 1288:                         my ($key,$value)=split(/=/,$item,2);
 1289:                         $key = &unescape($key);
 1290:                         next if ($key =~ /^error: 2 /);
 1291:                         $returnhash{$key}=&thaw_unescape($value);
 1292:                     }
 1293:                 }
 1294:             }
 1295:         }
 1296:     }
 1297:     return %returnhash;
 1298: }
 1299: 
 1300: sub inst_userrules {
 1301:     my ($udom,$check) = @_;
 1302:     my (%ruleshash,@ruleorder);
 1303:     if ($udom ne '') {
 1304:         my $homeserver=&domain($udom,'primary');
 1305:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1306:             my $response;
 1307:             if ($check eq 'id') {
 1308:                 $response=&reply('instidrules:'.&escape($udom),
 1309:                                  $homeserver);
 1310:             } elsif ($check eq 'email') {
 1311:                 $response=&reply('instemailrules:'.&escape($udom),
 1312:                                  $homeserver);
 1313:             } else {
 1314:                 $response=&reply('instuserrules:'.&escape($udom),
 1315:                                  $homeserver);
 1316:             }
 1317:             if (($response ne 'refused') && ($response ne 'error') && 
 1318:                 ($response ne 'unknown_cmd') && 
 1319:                 ($response ne 'no_such_host')) {
 1320:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1321:                 my @pairs=split(/\&/,$hashitems);
 1322:                 foreach my $item (@pairs) {
 1323:                     my ($key,$value)=split(/=/,$item,2);
 1324:                     $key = &unescape($key);
 1325:                     next if ($key =~ /^error: 2 /);
 1326:                     $ruleshash{$key}=&thaw_unescape($value);
 1327:                 }
 1328:                 my @esc_order = split(/\&/,$orderitems);
 1329:                 foreach my $item (@esc_order) {
 1330:                     push(@ruleorder,&unescape($item));
 1331:                 }
 1332:             }
 1333:         }
 1334:     }
 1335:     return (\%ruleshash,\@ruleorder);
 1336: }
 1337: 
 1338: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1339: 
 1340: sub get_domain_defaults {
 1341:     my ($domain) = @_;
 1342:     my $cachetime = 60*60*24;
 1343:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1344:     if (defined($cached)) {
 1345:         if (ref($result) eq 'HASH') {
 1346:             return %{$result};
 1347:         }
 1348:     }
 1349:     my %domdefaults;
 1350:     my %domconfig =
 1351:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1352:                                   'requestcourses','inststatus'],$domain);
 1353:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1354:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1355:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1356:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1357:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1358:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1359:     } else {
 1360:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1361:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1362:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1363:     }
 1364:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1365:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1366:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1367:         } else {
 1368:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1369:         } 
 1370:         my @usertools = ('aboutme','blog','portfolio');
 1371:         foreach my $item (@usertools) {
 1372:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1373:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1374:             }
 1375:         }
 1376:     }
 1377:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1378:         foreach my $item ('official','unofficial','community') {
 1379:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1380:         }
 1381:     }
 1382:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1383:         foreach my $item ('inststatustypes','inststatusorder') {
 1384:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1385:         }
 1386:     }
 1387:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1388:                                   $cachetime);
 1389:     return %domdefaults;
 1390: }
 1391: 
 1392: # --------------------------------------------------- Assign a key to a student
 1393: 
 1394: sub assign_access_key {
 1395: #
 1396: # a valid key looks like uname:udom#comments
 1397: # comments are being appended
 1398: #
 1399:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1400:     $kdom=
 1401:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1402:     $knum=
 1403:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1404:     $cdom=
 1405:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1406:     $cnum=
 1407:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1408:     $udom=$env{'user.name'} unless (defined($udom));
 1409:     $uname=$env{'user.domain'} unless (defined($uname));
 1410:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1411:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1412:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1413:                                                   # assigned to this person
 1414:                                                   # - this should not happen,
 1415:                                                   # unless something went wrong
 1416:                                                   # the first time around
 1417: # ready to assign
 1418:         $logentry=$1.'; '.$logentry;
 1419:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1420:                                                  $kdom,$knum) eq 'ok') {
 1421: # key now belongs to user
 1422: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1423:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1424:                 &appenv({'environment.'.$envkey => $ckey});
 1425:                 return 'ok';
 1426:             } else {
 1427:                 return 
 1428:   'error: Count not permanently assign key, will need to be re-entered later.';
 1429: 	    }
 1430:         } else {
 1431:             return 'error: Could not assign key, try again later.';
 1432:         }
 1433:     } elsif (!$existing{$ckey}) {
 1434: # the key does not exist
 1435: 	return 'error: The key does not exist';
 1436:     } else {
 1437: # the key is somebody else's
 1438: 	return 'error: The key is already in use';
 1439:     }
 1440: }
 1441: 
 1442: # ------------------------------------------ put an additional comment on a key
 1443: 
 1444: sub comment_access_key {
 1445: #
 1446: # a valid key looks like uname:udom#comments
 1447: # comments are being appended
 1448: #
 1449:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1450:     $cdom=
 1451:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1452:     $cnum=
 1453:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1454:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1455:     if ($existing{$ckey}) {
 1456:         $existing{$ckey}.='; '.$logentry;
 1457: # ready to assign
 1458:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1459:                                                  $cdom,$cnum) eq 'ok') {
 1460: 	    return 'ok';
 1461:         } else {
 1462: 	    return 'error: Count not store comment.';
 1463:         }
 1464:     } else {
 1465: # the key does not exist
 1466: 	return 'error: The key does not exist';
 1467:     }
 1468: }
 1469: 
 1470: # ------------------------------------------------------ Generate a set of keys
 1471: 
 1472: sub generate_access_keys {
 1473:     my ($number,$cdom,$cnum,$logentry)=@_;
 1474:     $cdom=
 1475:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1476:     $cnum=
 1477:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1478:     unless (&allowed('mky',$cdom)) { return 0; }
 1479:     unless (($cdom) && ($cnum)) { return 0; }
 1480:     if ($number>10000) { return 0; }
 1481:     sleep(2); # make sure don't get same seed twice
 1482:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1483:     my $total=0;
 1484:     for (my $i=1;$i<=$number;$i++) {
 1485:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1486:                   sprintf("%lx",int(100000*rand)).'-'.
 1487:                   sprintf("%lx",int(100000*rand));
 1488:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1489:        $newkey=~s/0/h/g; # and also 0 and O
 1490:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1491:        if ($existing{$newkey}) {
 1492:            $i--;
 1493:        } else {
 1494: 	  if (&put('accesskeys',
 1495:               { $newkey => '# generated '.localtime().
 1496:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1497:                            '; '.$logentry },
 1498: 		   $cdom,$cnum) eq 'ok') {
 1499:               $total++;
 1500: 	  }
 1501:        }
 1502:     }
 1503:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1504:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1505:     return $total;
 1506: }
 1507: 
 1508: # ------------------------------------------------------- Validate an accesskey
 1509: 
 1510: sub validate_access_key {
 1511:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1512:     $cdom=
 1513:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1514:     $cnum=
 1515:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1516:     $udom=$env{'user.domain'} unless (defined($udom));
 1517:     $uname=$env{'user.name'} unless (defined($uname));
 1518:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1519:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1520: }
 1521: 
 1522: # ------------------------------------- Find the section of student in a course
 1523: sub devalidate_getsection_cache {
 1524:     my ($udom,$unam,$courseid)=@_;
 1525:     my $hashid="$udom:$unam:$courseid";
 1526:     &devalidate_cache_new('getsection',$hashid);
 1527: }
 1528: 
 1529: sub courseid_to_courseurl {
 1530:     my ($courseid) = @_;
 1531:     #already url style courseid
 1532:     return $courseid if ($courseid =~ m{^/});
 1533: 
 1534:     if (exists($env{'course.'.$courseid.'.num'})) {
 1535: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1536: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1537: 	return "/$cdom/$cnum";
 1538:     }
 1539: 
 1540:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1541:     if (exists($courseinfo{'num'})) {
 1542: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1543:     }
 1544: 
 1545:     return undef;
 1546: }
 1547: 
 1548: sub getsection {
 1549:     my ($udom,$unam,$courseid)=@_;
 1550:     my $cachetime=1800;
 1551: 
 1552:     my $hashid="$udom:$unam:$courseid";
 1553:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1554:     if (defined($cached)) { return $result; }
 1555: 
 1556:     my %Pending; 
 1557:     my %Expired;
 1558:     #
 1559:     # Each role can either have not started yet (pending), be active, 
 1560:     #    or have expired.
 1561:     #
 1562:     # If there is an active role, we are done.
 1563:     #
 1564:     # If there is more than one role which has not started yet, 
 1565:     #     choose the one which will start sooner
 1566:     # If there is one role which has not started yet, return it.
 1567:     #
 1568:     # If there is more than one expired role, choose the one which ended last.
 1569:     # If there is a role which has expired, return it.
 1570:     #
 1571:     $courseid = &courseid_to_courseurl($courseid);
 1572:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1573:     foreach my $key (keys(%roleshash)) {
 1574:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1575:         my $section=$1;
 1576:         if ($key eq $courseid.'_st') { $section=''; }
 1577:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1578:         my $now=time;
 1579:         if (defined($end) && $end && ($now > $end)) {
 1580:             $Expired{$end}=$section;
 1581:             next;
 1582:         }
 1583:         if (defined($start) && $start && ($now < $start)) {
 1584:             $Pending{$start}=$section;
 1585:             next;
 1586:         }
 1587:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1588:     }
 1589:     #
 1590:     # Presumedly there will be few matching roles from the above
 1591:     # loop and the sorting time will be negligible.
 1592:     if (scalar(keys(%Pending))) {
 1593:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1594:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1595:     } 
 1596:     if (scalar(keys(%Expired))) {
 1597:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1598:         my $time = pop(@sorted);
 1599:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1600:     }
 1601:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1602: }
 1603: 
 1604: sub save_cache {
 1605:     &purge_remembered();
 1606:     #&Apache::loncommon::validate_page();
 1607:     undef(%env);
 1608:     undef($env_loaded);
 1609: }
 1610: 
 1611: my $to_remember=-1;
 1612: my %remembered;
 1613: my %accessed;
 1614: my $kicks=0;
 1615: my $hits=0;
 1616: sub make_key {
 1617:     my ($name,$id) = @_;
 1618:     if (length($id) > 65 
 1619: 	&& length(&escape($id)) > 200) {
 1620: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1621:     }
 1622:     return &escape($name.':'.$id);
 1623: }
 1624: 
 1625: sub devalidate_cache_new {
 1626:     my ($name,$id,$debug) = @_;
 1627:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1628:     $id=&make_key($name,$id);
 1629:     $memcache->delete($id);
 1630:     delete($remembered{$id});
 1631:     delete($accessed{$id});
 1632: }
 1633: 
 1634: sub is_cached_new {
 1635:     my ($name,$id,$debug) = @_;
 1636:     $id=&make_key($name,$id);
 1637:     if (exists($remembered{$id})) {
 1638: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1639: 	$accessed{$id}=[&gettimeofday()];
 1640: 	$hits++;
 1641: 	return ($remembered{$id},1);
 1642:     }
 1643:     my $value = $memcache->get($id);
 1644:     if (!(defined($value))) {
 1645: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1646: 	return (undef,undef);
 1647:     }
 1648:     if ($value eq '__undef__') {
 1649: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1650: 	$value=undef;
 1651:     }
 1652:     &make_room($id,$value,$debug);
 1653:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1654:     return ($value,1);
 1655: }
 1656: 
 1657: sub do_cache_new {
 1658:     my ($name,$id,$value,$time,$debug) = @_;
 1659:     $id=&make_key($name,$id);
 1660:     my $setvalue=$value;
 1661:     if (!defined($setvalue)) {
 1662: 	$setvalue='__undef__';
 1663:     }
 1664:     if (!defined($time) ) {
 1665: 	$time=600;
 1666:     }
 1667:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1668:     my $result = $memcache->set($id,$setvalue,$time);
 1669:     if (! $result) {
 1670: 	&logthis("caching of id -> $id  failed");
 1671: 	$memcache->disconnect_all();
 1672:     }
 1673:     # need to make a copy of $value
 1674:     &make_room($id,$value,$debug);
 1675:     return $value;
 1676: }
 1677: 
 1678: sub make_room {
 1679:     my ($id,$value,$debug)=@_;
 1680: 
 1681:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1682:                                     : $value;
 1683:     if ($to_remember<0) { return; }
 1684:     $accessed{$id}=[&gettimeofday()];
 1685:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1686:     my $to_kick;
 1687:     my $max_time=0;
 1688:     foreach my $other (keys(%accessed)) {
 1689: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1690: 	    $to_kick=$other;
 1691: 	    $max_time=&tv_interval($accessed{$other});
 1692: 	}
 1693:     }
 1694:     delete($remembered{$to_kick});
 1695:     delete($accessed{$to_kick});
 1696:     $kicks++;
 1697:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1698:     return;
 1699: }
 1700: 
 1701: sub purge_remembered {
 1702:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1703:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1704:     undef(%remembered);
 1705:     undef(%accessed);
 1706: }
 1707: # ------------------------------------- Read an entry from a user's environment
 1708: 
 1709: sub userenvironment {
 1710:     my ($udom,$unam,@what)=@_;
 1711:     my $items;
 1712:     foreach my $item (@what) {
 1713:         $items.=&escape($item).'&';
 1714:     }
 1715:     $items=~s/\&$//;
 1716:     my %returnhash=();
 1717:     my $uhome = &homeserver($unam,$udom);
 1718:     unless ($uhome eq 'no_host') {
 1719:         my @answer=split(/\&/, 
 1720:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 1721:         my $i;
 1722:         for ($i=0;$i<=$#what;$i++) {
 1723: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 1724:         }
 1725:     }
 1726:     return %returnhash;
 1727: }
 1728: 
 1729: # ---------------------------------------------------------- Get a studentphoto
 1730: sub studentphoto {
 1731:     my ($udom,$unam,$ext) = @_;
 1732:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1733:     if (defined($env{'request.course.id'})) {
 1734:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1735:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1736:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1737:             } else {
 1738:                 my ($result,$perm_reqd)=
 1739: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1740:                 if ($result eq 'ok') {
 1741:                     if (!($perm_reqd eq 'yes')) {
 1742:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1743:                     }
 1744:                 }
 1745:             }
 1746:         }
 1747:     } else {
 1748:         my ($result,$perm_reqd) = 
 1749: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1750:         if ($result eq 'ok') {
 1751:             if (!($perm_reqd eq 'yes')) {
 1752:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1753:             }
 1754:         }
 1755:     }
 1756:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1757: }
 1758: 
 1759: sub retrievestudentphoto {
 1760:     my ($udom,$unam,$ext,$type) = @_;
 1761:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1762:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1763:     if ($ret eq 'ok') {
 1764:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1765:         if ($type eq 'thumbnail') {
 1766:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1767:         }
 1768:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1769:         return $tokenurl;
 1770:     } else {
 1771:         if ($type eq 'thumbnail') {
 1772:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1773:         } else { 
 1774:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1775:         }
 1776:     }
 1777: }
 1778: 
 1779: # -------------------------------------------------------------------- New chat
 1780: 
 1781: sub chatsend {
 1782:     my ($newentry,$anon,$group)=@_;
 1783:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1784:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1785:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1786:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1787: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1788: 		   &escape($newentry)).':'.$group,$chome);
 1789: }
 1790: 
 1791: # ------------------------------------------ Find current version of a resource
 1792: 
 1793: sub getversion {
 1794:     my $fname=&clutter(shift);
 1795:     unless ($fname=~/^\/res\//) { return -1; }
 1796:     return &currentversion(&filelocation('',$fname));
 1797: }
 1798: 
 1799: sub currentversion {
 1800:     my $fname=shift;
 1801:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1802:     if (defined($cached)) { return $result; }
 1803:     my $author=$fname;
 1804:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1805:     my ($udom,$uname)=split(/\//,$author);
 1806:     my $home=homeserver($uname,$udom);
 1807:     if ($home eq 'no_host') { 
 1808:         return -1; 
 1809:     }
 1810:     my $answer=reply("currentversion:$fname",$home);
 1811:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1812: 	return -1;
 1813:     }
 1814:     return &do_cache_new('resversion',$fname,$answer,600);
 1815: }
 1816: 
 1817: # ----------------------------- Subscribe to a resource, return URL if possible
 1818: 
 1819: sub subscribe {
 1820:     my $fname=shift;
 1821:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1822:     $fname=~s/[\n\r]//g;
 1823:     my $author=$fname;
 1824:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1825:     my ($udom,$uname)=split(/\//,$author);
 1826:     my $home=homeserver($uname,$udom);
 1827:     if ($home eq 'no_host') {
 1828:         return 'not_found';
 1829:     }
 1830:     my $answer=reply("sub:$fname",$home);
 1831:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1832: 	$answer.=' by '.$home;
 1833:     }
 1834:     return $answer;
 1835: }
 1836:     
 1837: # -------------------------------------------------------------- Replicate file
 1838: 
 1839: sub repcopy {
 1840:     my $filename=shift;
 1841:     $filename=~s/\/+/\//g;
 1842:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1843:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1844:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1845: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1846: 	return &repcopy_userfile($filename);
 1847:     }
 1848:     $filename=~s/[\n\r]//g;
 1849:     my $transname="$filename.in.transfer";
 1850: # FIXME: this should flock
 1851:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1852:     my $remoteurl=subscribe($filename);
 1853:     if ($remoteurl =~ /^con_lost by/) {
 1854: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1855:            return 'unavailable';
 1856:     } elsif ($remoteurl eq 'not_found') {
 1857: 	   #&logthis("Subscribe returned not_found: $filename");
 1858: 	   return 'not_found';
 1859:     } elsif ($remoteurl =~ /^rejected by/) {
 1860: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1861:            return 'forbidden';
 1862:     } elsif ($remoteurl eq 'directory') {
 1863:            return 'ok';
 1864:     } else {
 1865:         my $author=$filename;
 1866:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1867:         my ($udom,$uname)=split(/\//,$author);
 1868:         my $home=homeserver($uname,$udom);
 1869:         unless ($home eq $perlvar{'lonHostID'}) {
 1870:            my @parts=split(/\//,$filename);
 1871:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1872:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1873:                &logthis("Malconfiguration for replication: $filename");
 1874: 	       return 'bad_request';
 1875:            }
 1876:            my $count;
 1877:            for ($count=5;$count<$#parts;$count++) {
 1878:                $path.="/$parts[$count]";
 1879:                if ((-e $path)!=1) {
 1880: 		   mkdir($path,0777);
 1881:                }
 1882:            }
 1883:            my $ua=new LWP::UserAgent;
 1884:            my $request=new HTTP::Request('GET',"$remoteurl");
 1885:            my $response=$ua->request($request,$transname);
 1886:            if ($response->is_error()) {
 1887: 	       unlink($transname);
 1888:                my $message=$response->status_line;
 1889:                &logthis("<font color=\"blue\">WARNING:"
 1890:                        ." LWP get: $message: $filename</font>");
 1891:                return 'unavailable';
 1892:            } else {
 1893: 	       if ($remoteurl!~/\.meta$/) {
 1894:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1895:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1896:                   if ($mresponse->is_error()) {
 1897: 		      unlink($filename.'.meta');
 1898:                       &logthis(
 1899:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1900:                   }
 1901: 	       }
 1902:                rename($transname,$filename);
 1903:                return 'ok';
 1904:            }
 1905:        }
 1906:     }
 1907: }
 1908: 
 1909: # ------------------------------------------------ Get server side include body
 1910: sub ssi_body {
 1911:     my ($filelink,%form)=@_;
 1912:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1913:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1914:     }
 1915:     my $output='';
 1916:     my $response;
 1917:     if ($filelink=~/^https?\:/) {
 1918:        ($output,$response)=&externalssi($filelink);
 1919:     } else {
 1920:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 1921:        $filelink .= 'inhibitmenu=yes';
 1922:        ($output,$response)=&ssi($filelink,%form);
 1923:     }
 1924:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1925:     $output=~s/^.*?\<body[^\>]*\>//si;
 1926:     $output=~s/\<\/body\s*\>.*?$//si;
 1927:     if (wantarray) {
 1928:         return ($output, $response);
 1929:     } else {
 1930:         return $output;
 1931:     }
 1932: }
 1933: 
 1934: # --------------------------------------------------------- Server Side Include
 1935: 
 1936: sub absolute_url {
 1937:     my ($host_name) = @_;
 1938:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1939:     if ($host_name eq '') {
 1940: 	$host_name = $ENV{'SERVER_NAME'};
 1941:     }
 1942:     return $protocol.$host_name;
 1943: }
 1944: 
 1945: #
 1946: #   Server side include.
 1947: # Parameters:
 1948: #  fn     Possibly encrypted resource name/id.
 1949: #  form   Hash that describes how the rendering should be done
 1950: #         and other things.
 1951: # Returns:
 1952: #   Scalar context: The content of the response.
 1953: #   Array context:  2 element list of the content and the full response object.
 1954: #     
 1955: sub ssi {
 1956: 
 1957:     my ($fn,%form)=@_;
 1958:     my $ua=new LWP::UserAgent;
 1959:     my $request;
 1960: 
 1961:     $form{'no_update_last_known'}=1;
 1962:     &Apache::lonenc::check_encrypt(\$fn);
 1963:     if (%form) {
 1964:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1965:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1966:     } else {
 1967:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1968:     }
 1969: 
 1970:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1971:     my $response=$ua->request($request);
 1972: 
 1973:     if (wantarray) {
 1974: 	return ($response->content, $response);
 1975:     } else {
 1976: 	return $response->content;
 1977:     }
 1978: }
 1979: 
 1980: sub externalssi {
 1981:     my ($url)=@_;
 1982:     my $ua=new LWP::UserAgent;
 1983:     my $request=new HTTP::Request('GET',$url);
 1984:     my $response=$ua->request($request);
 1985:     if (wantarray) {
 1986:         return ($response->content, $response);
 1987:     } else {
 1988:         return $response->content;
 1989:     }
 1990: }
 1991: 
 1992: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1993: 
 1994: sub allowuploaded {
 1995:     my ($srcurl,$url)=@_;
 1996:     $url=&clutter(&declutter($url));
 1997:     my $dir=$url;
 1998:     $dir=~s/\/[^\/]+$//;
 1999:     my %httpref=();
 2000:     my $httpurl=&hreflocation('',$url);
 2001:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2002:     &Apache::lonnet::appenv(\%httpref);
 2003: }
 2004: 
 2005: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2006: # input: action, courseID, current domain, intended
 2007: #        path to file, source of file, instruction to parse file for objects,
 2008: #        ref to hash for embedded objects,
 2009: #        ref to hash for codebase of java objects.
 2010: #
 2011: # output: url to file (if action was uploaddoc), 
 2012: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2013: #
 2014: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2015: # course.
 2016: #
 2017: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2018: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2019: #          course's home server.
 2020: #
 2021: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2022: #          be copied from $source (current location) to 
 2023: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2024: #         and will then be copied to
 2025: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2026: #         course's home server.
 2027: #
 2028: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2029: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2030: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2031: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2032: #         in course's home server.
 2033: #
 2034: 
 2035: sub process_coursefile {
 2036:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 2037:     my $fetchresult;
 2038:     my $home=&homeserver($docuname,$docudom);
 2039:     if ($action eq 'propagate') {
 2040:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2041: 			     $home);
 2042:     } else {
 2043:         my $fpath = '';
 2044:         my $fname = $file;
 2045:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2046:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2047:         my $filepath = &build_filepath($fpath);
 2048:         if ($action eq 'copy') {
 2049:             if ($source eq '') {
 2050:                 $fetchresult = 'no source file';
 2051:                 return $fetchresult;
 2052:             } else {
 2053:                 my $destination = $filepath.'/'.$fname;
 2054:                 rename($source,$destination);
 2055:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2056:                                  $home);
 2057:             }
 2058:         } elsif ($action eq 'uploaddoc') {
 2059:             open(my $fh,'>'.$filepath.'/'.$fname);
 2060:             print $fh $env{'form.'.$source};
 2061:             close($fh);
 2062:             if ($parser eq 'parse') {
 2063:                 my $mm = new File::MMagic;
 2064:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
 2065:                 if ($mime_type eq 'text/html') {
 2066:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2067:                     unless ($parse_result eq 'ok') {
 2068:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2069:                     }
 2070:                 }
 2071:             }
 2072:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2073:                                  $home);
 2074:             if ($fetchresult eq 'ok') {
 2075:                 return '/uploaded/'.$fpath.'/'.$fname;
 2076:             } else {
 2077:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2078:                         ' to host '.$home.': '.$fetchresult);
 2079:                 return '/adm/notfound.html';
 2080:             }
 2081:         }
 2082:     }
 2083:     unless ( $fetchresult eq 'ok') {
 2084:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2085:              ' to host '.$home.': '.$fetchresult);
 2086:     }
 2087:     return $fetchresult;
 2088: }
 2089: 
 2090: sub build_filepath {
 2091:     my ($fpath) = @_;
 2092:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2093:     unless ($fpath eq '') {
 2094:         my @parts=split('/',$fpath);
 2095:         foreach my $part (@parts) {
 2096:             $filepath.= '/'.$part;
 2097:             if ((-e $filepath)!=1) {
 2098:                 mkdir($filepath,0777);
 2099:             }
 2100:         }
 2101:     }
 2102:     return $filepath;
 2103: }
 2104: 
 2105: sub store_edited_file {
 2106:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2107:     my $file = $primary_url;
 2108:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2109:     my $fpath = '';
 2110:     my $fname = $file;
 2111:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2112:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2113:     my $filepath = &build_filepath($fpath);
 2114:     open(my $fh,'>'.$filepath.'/'.$fname);
 2115:     print $fh $content;
 2116:     close($fh);
 2117:     my $home=&homeserver($docuname,$docudom);
 2118:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2119: 			  $home);
 2120:     if ($$fetchresult eq 'ok') {
 2121:         return '/uploaded/'.$fpath.'/'.$fname;
 2122:     } else {
 2123:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2124: 		 ' to host '.$home.': '.$$fetchresult);
 2125:         return '/adm/notfound.html';
 2126:     }
 2127: }
 2128: 
 2129: sub clean_filename {
 2130:     my ($fname,$args)=@_;
 2131: # Replace Windows backslashes by forward slashes
 2132:     $fname=~s/\\/\//g;
 2133:     if (!$args->{'keep_path'}) {
 2134:         # Get rid of everything but the actual filename
 2135: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2136:     }
 2137: # Replace spaces by underscores
 2138:     $fname=~s/\s+/\_/g;
 2139: # Replace all other weird characters by nothing
 2140:     $fname=~s{[^/\w\.\-]}{}g;
 2141: # Replace all .\d. sequences with _\d. so they no longer look like version
 2142: # numbers
 2143:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2144:     return $fname;
 2145: }
 2146: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2147: sub resizeImage {
 2148: 	my($img_url) = @_;	
 2149: 	my $ima = Image::Magick->new;                       
 2150:         $ima->Read($img_url);
 2151: 	if($ima->Get('width') > 400)
 2152: 	{
 2153: 		my $factor = $ima->Get('width')/400;
 2154:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2155: 	}
 2156: 	if($ima->Get('height') > 500)
 2157:         {
 2158:         	my $factor = $ima->Get('height')/500;
 2159:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2160:         } 
 2161: 		
 2162: 	$ima->Write($img_url);
 2163: }
 2164: 
 2165: #Wrapper function for userphotoupload
 2166: sub userphotoupload
 2167: {
 2168: 	my($formname,$subdir) = @_;
 2169: 	$upload_photo_form = 1;
 2170: 	return &userfileupload($formname,undef,$subdir);
 2171: }
 2172: 
 2173: # --------------- Take an uploaded file and put it into the userfiles directory
 2174: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2175: #                    the desired filenam is in $env{"form.$formname.filename"}
 2176: #        $coursedoc - if true up to the current course
 2177: #                     if false
 2178: #        $subdir - directory in userfile to store the file into
 2179: #        $parser - instruction to parse file for objects ($parser = parse)    
 2180: #        $allfiles - reference to hash for embedded objects
 2181: #        $codebase - reference to hash for codebase of java objects
 2182: #        $desuname - username for permanent storage of uploaded file
 2183: #        $dsetudom - domain for permanaent storage of uploaded file
 2184: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2185: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2186: # 
 2187: # output: url of file in userspace, or error: <message> 
 2188: #             or /adm/notfound.html if failure to upload occurse
 2189: 
 2190: 
 2191: sub userfileupload {
 2192:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2193:         $destudom,$thumbwidth,$thumbheight)=@_;
 2194:     if (!defined($subdir)) { $subdir='unknown'; }
 2195:     my $fname=$env{'form.'.$formname.'.filename'};
 2196:     $fname=&clean_filename($fname);
 2197: # See if there is anything left
 2198:     unless ($fname) { return 'error: no uploaded file'; }
 2199:     chop($env{'form.'.$formname});
 2200:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2201:         my $now = time;
 2202:         my $filepath = 'tmp/helprequests/'.$now;
 2203:         my @parts=split(/\//,$filepath);
 2204:         my $fullpath = $perlvar{'lonDaemons'};
 2205:         for (my $i=0;$i<@parts;$i++) {
 2206:             $fullpath .= '/'.$parts[$i];
 2207:             if ((-e $fullpath)!=1) {
 2208:                 mkdir($fullpath,0777);
 2209:             }
 2210:         }
 2211:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2212:         print $fh $env{'form.'.$formname};
 2213:         close($fh);
 2214:         return $fullpath.'/'.$fname;
 2215:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2216:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2217:                        '_'.$env{'user.domain'}.'/pending';
 2218:         my @parts=split(/\//,$filepath);
 2219:         my $fullpath = $perlvar{'lonDaemons'};
 2220:         for (my $i=0;$i<@parts;$i++) {
 2221:             $fullpath .= '/'.$parts[$i];
 2222:             if ((-e $fullpath)!=1) {
 2223:                 mkdir($fullpath,0777);
 2224:             }
 2225:         }
 2226:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2227:         print $fh $env{'form.'.$formname};
 2228:         close($fh);
 2229:         return $fullpath.'/'.$fname;
 2230:     }
 2231:     if ($subdir eq 'scantron') {
 2232:         $fname = 'scantron_orig_'.$fname;
 2233:     } else {   
 2234: # Create the directory if not present
 2235:         $fname="$subdir/$fname";
 2236:     }
 2237:     if ($coursedoc) {
 2238: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2239: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2240:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2241:             return &finishuserfileupload($docuname,$docudom,
 2242: 					 $formname,$fname,$parser,$allfiles,
 2243: 					 $codebase,$thumbwidth,$thumbheight);
 2244:         } else {
 2245:             $fname=$env{'form.folder'}.'/'.$fname;
 2246:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2247: 				       $fname,$formname,$parser,
 2248: 				       $allfiles,$codebase);
 2249:         }
 2250:     } elsif (defined($destuname)) {
 2251:         my $docuname=$destuname;
 2252:         my $docudom=$destudom;
 2253: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2254: 				     $parser,$allfiles,$codebase,
 2255:                                      $thumbwidth,$thumbheight);
 2256:         
 2257:     } else {
 2258:         my $docuname=$env{'user.name'};
 2259:         my $docudom=$env{'user.domain'};
 2260:         if (exists($env{'form.group'})) {
 2261:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2262:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2263:         }
 2264: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2265: 				     $parser,$allfiles,$codebase,
 2266:                                      $thumbwidth,$thumbheight);
 2267:     }
 2268: }
 2269: 
 2270: sub finishuserfileupload {
 2271:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2272:         $thumbwidth,$thumbheight) = @_;
 2273:     my $path=$docudom.'/'.$docuname.'/';
 2274:     my $filepath=$perlvar{'lonDocRoot'};
 2275:   
 2276:     my ($fnamepath,$file,$fetchthumb);
 2277:     $file=$fname;
 2278:     if ($fname=~m|/|) {
 2279:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2280: 	$path.=$fnamepath.'/';
 2281:     }
 2282:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2283:     my $count;
 2284:     for ($count=4;$count<=$#parts;$count++) {
 2285:         $filepath.="/$parts[$count]";
 2286:         if ((-e $filepath)!=1) {
 2287: 	    mkdir($filepath,0777);
 2288:         }
 2289:     }
 2290: 
 2291: # Save the file
 2292:     {
 2293: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2294: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2295: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2296: 	    return '/adm/notfound.html';
 2297: 	}
 2298: 	if (!print FH ($env{'form.'.$formname})) {
 2299: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2300: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2301: 	    return '/adm/notfound.html';
 2302: 	}
 2303: 	close(FH);
 2304: 	if($upload_photo_form==1)
 2305: 	{
 2306: 		resizeImage($filepath.'/'.$file);		
 2307: 		$upload_photo_form = 0;
 2308: 	}
 2309:     }
 2310:     if ($parser eq 'parse') {
 2311:         my $mm = new File::MMagic;
 2312:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2313:         if ($mime_type eq 'text/html') {
 2314:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2315:                                                        $allfiles,$codebase);
 2316:             unless ($parse_result eq 'ok') {
 2317:                 &logthis('Failed to parse '.$filepath.$file.
 2318: 	   	         ' for embedded media: '.$parse_result); 
 2319:             }
 2320:         }
 2321:     }
 2322:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2323:         my $input = $filepath.'/'.$file;
 2324:         my $output = $filepath.'/'.'tn-'.$file;
 2325:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2326:         system("convert -sample $thumbsize $input $output");
 2327:         if (-e $filepath.'/'.'tn-'.$file) {
 2328:             $fetchthumb  = 1; 
 2329:         }
 2330:     }
 2331:  
 2332: # Notify homeserver to grep it
 2333: #
 2334:     my $docuhome=&homeserver($docuname,$docudom);	
 2335:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2336:     if ($fetchresult eq 'ok') {
 2337:         if ($fetchthumb) {
 2338:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2339:             if ($thumbresult ne 'ok') {
 2340:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2341:                          $docuhome.': '.$thumbresult);
 2342:             }
 2343:         }
 2344: #
 2345: # Return the URL to it
 2346:         return '/uploaded/'.$path.$file;
 2347:     } else {
 2348:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2349: 		 ': '.$fetchresult);
 2350:         return '/adm/notfound.html';
 2351:     }
 2352: }
 2353: 
 2354: sub extract_embedded_items {
 2355:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2356:     my @state = ();
 2357:     my %javafiles = (
 2358:                       codebase => '',
 2359:                       code => '',
 2360:                       archive => ''
 2361:                     );
 2362:     my %mediafiles = (
 2363:                       src => '',
 2364:                       movie => '',
 2365:                      );
 2366:     my $p;
 2367:     if ($content) {
 2368:         $p = HTML::LCParser->new($content);
 2369:     } else {
 2370:         $p = HTML::LCParser->new($fullpath);
 2371:     }
 2372:     while (my $t=$p->get_token()) {
 2373: 	if ($t->[0] eq 'S') {
 2374: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2375: 	    push(@state, $tagname);
 2376:             if (lc($tagname) eq 'allow') {
 2377:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2378:             }
 2379: 	    if (lc($tagname) eq 'img') {
 2380: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2381: 	    }
 2382: 	    if (lc($tagname) eq 'a') {
 2383: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2384: 	    }
 2385:             if (lc($tagname) eq 'script') {
 2386:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2387:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2388:                 } else {
 2389:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2390:                 }
 2391:             }
 2392:             if (lc($tagname) eq 'link') {
 2393:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2394:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2395:                 }
 2396:             }
 2397: 	    if (lc($tagname) eq 'object' ||
 2398: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2399: 		foreach my $item (keys(%javafiles)) {
 2400: 		    $javafiles{$item} = '';
 2401: 		}
 2402: 	    }
 2403: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2404: 		my $name = lc($attr->{'name'});
 2405: 		foreach my $item (keys(%javafiles)) {
 2406: 		    if ($name eq $item) {
 2407: 			$javafiles{$item} = $attr->{'value'};
 2408: 			last;
 2409: 		    }
 2410: 		}
 2411: 		foreach my $item (keys(%mediafiles)) {
 2412: 		    if ($name eq $item) {
 2413: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2414: 			last;
 2415: 		    }
 2416: 		}
 2417: 	    }
 2418: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2419: 		foreach my $item (keys(%javafiles)) {
 2420: 		    if ($attr->{$item}) {
 2421: 			$javafiles{$item} = $attr->{$item};
 2422: 			last;
 2423: 		    }
 2424: 		}
 2425: 		foreach my $item (keys(%mediafiles)) {
 2426: 		    if ($attr->{$item}) {
 2427: 			&add_filetype($allfiles,$attr->{$item},$item);
 2428: 			last;
 2429: 		    }
 2430: 		}
 2431: 	    }
 2432: 	} elsif ($t->[0] eq 'E') {
 2433: 	    my ($tagname) = ($t->[1]);
 2434: 	    if ($javafiles{'codebase'} ne '') {
 2435: 		$javafiles{'codebase'} .= '/';
 2436: 	    }  
 2437: 	    if (lc($tagname) eq 'applet' ||
 2438: 		lc($tagname) eq 'object' ||
 2439: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2440: 		) {
 2441: 		foreach my $item (keys(%javafiles)) {
 2442: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2443: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2444: 			&add_filetype($allfiles,$file,$item);
 2445: 		    }
 2446: 		}
 2447: 	    } 
 2448: 	    pop @state;
 2449: 	}
 2450:     }
 2451:     return 'ok';
 2452: }
 2453: 
 2454: sub add_filetype {
 2455:     my ($allfiles,$file,$type)=@_;
 2456:     if (exists($allfiles->{$file})) {
 2457: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2458: 	    push(@{$allfiles->{$file}}, &escape($type));
 2459: 	}
 2460:     } else {
 2461: 	@{$allfiles->{$file}} = (&escape($type));
 2462:     }
 2463: }
 2464: 
 2465: sub removeuploadedurl {
 2466:     my ($url)=@_;	
 2467:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2468:     return &removeuserfile($uname,$udom,$fname);
 2469: }
 2470: 
 2471: sub removeuserfile {
 2472:     my ($docuname,$docudom,$fname)=@_;
 2473:     my $home=&homeserver($docuname,$docudom);    
 2474:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2475:     if ($result eq 'ok') {	
 2476:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2477:             my $metafile = $fname.'.meta';
 2478:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2479: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2480:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2481:             my $sqlresult = 
 2482:                 &update_portfolio_table($docuname,$docudom,$file,
 2483:                                         'portfolio_metadata',$group,
 2484:                                         'delete');
 2485:         }
 2486:     }
 2487:     return $result;
 2488: }
 2489: 
 2490: sub mkdiruserfile {
 2491:     my ($docuname,$docudom,$dir)=@_;
 2492:     my $home=&homeserver($docuname,$docudom);
 2493:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2494: }
 2495: 
 2496: sub renameuserfile {
 2497:     my ($docuname,$docudom,$old,$new)=@_;
 2498:     my $home=&homeserver($docuname,$docudom);
 2499:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2500:                         &escape("$old").':'.&escape("$new"),$home);
 2501:     if ($result eq 'ok') {
 2502:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2503:             my $oldmeta = $old.'.meta';
 2504:             my $newmeta = $new.'.meta';
 2505:             my $metaresult = 
 2506:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2507: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2508:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2509:             my $sqlresult = 
 2510:                 &update_portfolio_table($docuname,$docudom,$file,
 2511:                                         'portfolio_metadata',$group,
 2512:                                         'delete');
 2513:         }
 2514:     }
 2515:     return $result;
 2516: }
 2517: 
 2518: # ------------------------------------------------------------------------- Log
 2519: 
 2520: sub log {
 2521:     my ($dom,$nam,$hom,$what)=@_;
 2522:     return critical("log:$dom:$nam:$what",$hom);
 2523: }
 2524: 
 2525: # ------------------------------------------------------------------ Course Log
 2526: #
 2527: # This routine flushes several buffers of non-mission-critical nature
 2528: #
 2529: 
 2530: sub flushcourselogs {
 2531:     &logthis('Flushing log buffers');
 2532: #
 2533: # course logs
 2534: # This is a log of all transactions in a course, which can be used
 2535: # for data mining purposes
 2536: #
 2537: # It also collects the courseid database, which lists last transaction
 2538: # times and course titles for all courseids
 2539: #
 2540:     my %courseidbuffer=();
 2541:     foreach my $crsid (keys(%courselogs)) {
 2542:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2543: 		          &escape($courselogs{$crsid}),
 2544: 		          $coursehombuf{$crsid}) eq 'ok') {
 2545: 	    delete $courselogs{$crsid};
 2546:         } else {
 2547:             &logthis('Failed to flush log buffer for '.$crsid);
 2548:             if (length($courselogs{$crsid})>40000) {
 2549:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2550:                         " exceeded maximum size, deleting.</font>");
 2551:                delete $courselogs{$crsid};
 2552:             }
 2553:         }
 2554:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2555:             'description' => $coursedescrbuf{$crsid},
 2556:             'inst_code'    => $courseinstcodebuf{$crsid},
 2557:             'type'        => $coursetypebuf{$crsid},
 2558:             'owner'       => $courseownerbuf{$crsid},
 2559:         };
 2560:     }
 2561: #
 2562: # Write course id database (reverse lookup) to homeserver of courses 
 2563: # Is used in pickcourse
 2564: #
 2565:     foreach my $crs_home (keys(%courseidbuffer)) {
 2566:         my $response = &courseidput(&host_domain($crs_home),
 2567:                                     $courseidbuffer{$crs_home},
 2568:                                     $crs_home,'timeonly');
 2569:     }
 2570: #
 2571: # File accesses
 2572: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2573: #
 2574:     foreach my $entry (keys(%accesshash)) {
 2575:         if ($entry =~ /___count$/) {
 2576:             my ($dom,$name);
 2577:             ($dom,$name,undef)=
 2578: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2579:             if (! defined($dom) || $dom eq '' || 
 2580:                 ! defined($name) || $name eq '') {
 2581:                 my $cid = $env{'request.course.id'};
 2582:                 $dom  = $env{'request.'.$cid.'.domain'};
 2583:                 $name = $env{'request.'.$cid.'.num'};
 2584:             }
 2585:             my $value = $accesshash{$entry};
 2586:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2587:             my %temphash=($url => $value);
 2588:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2589:             if ($result eq 'ok') {
 2590:                 delete $accesshash{$entry};
 2591:             } elsif ($result eq 'unknown_cmd') {
 2592:                 # Target server has old code running on it.
 2593:                 my %temphash=($entry => $value);
 2594:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2595:                     delete $accesshash{$entry};
 2596:                 }
 2597:             }
 2598:         } else {
 2599:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2600:             my %temphash=($entry => $accesshash{$entry});
 2601:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2602:                 delete $accesshash{$entry};
 2603:             }
 2604:         }
 2605:     }
 2606: #
 2607: # Roles
 2608: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2609: #
 2610:     foreach my $entry (keys(%userrolehash)) {
 2611:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2612: 	    split(/\:/,$entry);
 2613:         if (&Apache::lonnet::put('nohist_userroles',
 2614:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2615:                 $rudom,$runame) eq 'ok') {
 2616: 	    delete $userrolehash{$entry};
 2617:         }
 2618:     }
 2619: #
 2620: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2621: #
 2622:     my %domrolebuffer = ();
 2623:     foreach my $entry (keys(%domainrolehash)) {
 2624:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2625:         if ($domrolebuffer{$rudom}) {
 2626:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2627:                       '='.&escape($domainrolehash{$entry});
 2628:         } else {
 2629:             $domrolebuffer{$rudom}.=&escape($entry).
 2630:                       '='.&escape($domainrolehash{$entry});
 2631:         }
 2632:         delete $domainrolehash{$entry};
 2633:     }
 2634:     foreach my $dom (keys(%domrolebuffer)) {
 2635: 	my %servers = &get_servers($dom,'library');
 2636: 	foreach my $tryserver (keys(%servers)) {
 2637: 	    unless (&reply('domroleput:'.$dom.':'.
 2638: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2639: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2640: 	    }
 2641:         }
 2642:     }
 2643:     $dumpcount++;
 2644: }
 2645: 
 2646: sub courselog {
 2647:     my $what=shift;
 2648:     $what=time.':'.$what;
 2649:     unless ($env{'request.course.id'}) { return ''; }
 2650:     $coursedombuf{$env{'request.course.id'}}=
 2651:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2652:     $coursenumbuf{$env{'request.course.id'}}=
 2653:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2654:     $coursehombuf{$env{'request.course.id'}}=
 2655:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2656:     $coursedescrbuf{$env{'request.course.id'}}=
 2657:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2658:     $courseinstcodebuf{$env{'request.course.id'}}=
 2659:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2660:     $courseownerbuf{$env{'request.course.id'}}=
 2661:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2662:     $coursetypebuf{$env{'request.course.id'}}=
 2663:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2664:     if (defined $courselogs{$env{'request.course.id'}}) {
 2665: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2666:     } else {
 2667: 	$courselogs{$env{'request.course.id'}}.=$what;
 2668:     }
 2669:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2670: 	&flushcourselogs();
 2671:     }
 2672: }
 2673: 
 2674: sub courseacclog {
 2675:     my $fnsymb=shift;
 2676:     unless ($env{'request.course.id'}) { return ''; }
 2677:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2678:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2679:         $what.=':POST';
 2680:         # FIXME: Probably ought to escape things....
 2681: 	foreach my $key (keys(%env)) {
 2682:             if ($key=~/^form\.(.*)/) {
 2683:                 my $formitem = $1;
 2684:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2685:                     $what.=':'.$formitem.'='.$env{$key};
 2686:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2687:                     $what.=':'.$formitem.'='.$env{$key};
 2688:                 }
 2689:             }
 2690:         }
 2691:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2692:         # FIXME: We should not be depending on a form parameter that someone
 2693:         # editing lonsearchcat.pm might change in the future.
 2694:         if ($env{'form.phase'} eq 'course_search') {
 2695:             $what.= ':POST';
 2696:             # FIXME: Probably ought to escape things....
 2697:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2698:                                  'crsdiscuss') {
 2699:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2700:             }
 2701:         }
 2702:     }
 2703:     &courselog($what);
 2704: }
 2705: 
 2706: sub countacc {
 2707:     my $url=&declutter(shift);
 2708:     return if (! defined($url) || $url eq '');
 2709:     unless ($env{'request.course.id'}) { return ''; }
 2710:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2711:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2712:     $accesshash{$key}++;
 2713: }
 2714: 
 2715: sub linklog {
 2716:     my ($from,$to)=@_;
 2717:     $from=&declutter($from);
 2718:     $to=&declutter($to);
 2719:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2720:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2721: }
 2722:   
 2723: sub userrolelog {
 2724:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2725:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2726:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2727:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2728:         ($trole=~/^ta/)) {
 2729:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2730:        $userrolehash
 2731:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2732:                     =$tend.':'.$tstart;
 2733:     }
 2734:     if (($env{'request.role'} =~ /dc\./) &&
 2735: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2736: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2737: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2738:        $userrolehash
 2739:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2740:                     =$tend.':'.$tstart;
 2741:     }
 2742:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2743:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2744:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2745:         ($trole=~/^sc/)) {
 2746:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2747:        $domainrolehash
 2748:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2749:                     = $tend.':'.$tstart;
 2750:     }
 2751: }
 2752: 
 2753: sub courserolelog {
 2754:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2755:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2756:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2757:         ($trole eq 'ta') || ($trole eq 'st') ||
 2758:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2759:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2760:             my $cdom = $1;
 2761:             my $cnum = $2;
 2762:             my $sec = $3;
 2763:             my $namespace = 'rolelog';
 2764:             my %storehash = (
 2765:                                role    => $trole,
 2766:                                start   => $tstart,
 2767:                                end     => $tend,
 2768:                                selfenroll => $selfenroll,
 2769:                                context    => $context,
 2770:                             );
 2771:             if ($trole eq 'gr') {
 2772:                 $namespace = 'groupslog';
 2773:                 $storehash{'group'} = $sec;
 2774:             } else {
 2775:                 $storehash{'section'} = $sec;
 2776:             }
 2777:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2778:             if (($trole ne 'st') || ($sec ne '')) {
 2779:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2780:             }
 2781:         }
 2782:     }
 2783:     return;
 2784: }
 2785: 
 2786: sub get_course_adv_roles {
 2787:     my ($cid,$codes) = @_;
 2788:     $cid=$env{'request.course.id'} unless (defined($cid));
 2789:     my %coursehash=&coursedescription($cid);
 2790:     my $crstype = &Apache::loncommon::course_type($cid);
 2791:     my %nothide=();
 2792:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2793:         if ($user !~ /:/) {
 2794: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2795:         } else {
 2796:             $nothide{$user}=1;
 2797:         }
 2798:     }
 2799:     my %returnhash=();
 2800:     my %dumphash=
 2801:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2802:     my $now=time;
 2803:     my %privileged;
 2804:     foreach my $entry (keys(%dumphash)) {
 2805: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2806:         if (($tstart) && ($tstart<0)) { next; }
 2807:         if (($tend) && ($tend<$now)) { next; }
 2808:         if (($tstart) && ($now<$tstart)) { next; }
 2809:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2810: 	if ($username eq '' || $domain eq '') { next; }
 2811:         unless (ref($privileged{$domain}) eq 'HASH') {
 2812:             my %dompersonnel =
 2813:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2814:             $privileged{$domain} = {};
 2815:             foreach my $server (keys(%dompersonnel)) {
 2816:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2817:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2818:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2819:                         $privileged{$udom}{$uname} = 1;
 2820:                     }
 2821:                 }
 2822:             }
 2823:         }
 2824:         if ((exists($privileged{$domain}{$username})) && 
 2825:             (!$nothide{$username.':'.$domain})) { next; }
 2826: 	if ($role eq 'cr') { next; }
 2827:         if ($codes) {
 2828:             if ($section) { $role .= ':'.$section; }
 2829:             if ($returnhash{$role}) {
 2830:                 $returnhash{$role}.=','.$username.':'.$domain;
 2831:             } else {
 2832:                 $returnhash{$role}=$username.':'.$domain;
 2833:             }
 2834:         } else {
 2835:             my $key=&plaintext($role,$crstype);
 2836:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2837:             if ($returnhash{$key}) {
 2838: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2839:             } else {
 2840:                 $returnhash{$key}=$username.':'.$domain;
 2841:             }
 2842:         }
 2843:     }
 2844:     return %returnhash;
 2845: }
 2846: 
 2847: sub get_my_roles {
 2848:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2849:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2850:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2851:     my (%dumphash,%nothide);
 2852:     if ($context eq 'userroles') { 
 2853:         %dumphash = &dump('roles',$udom,$uname);
 2854:     } else {
 2855:         %dumphash=
 2856:             &dump('nohist_userroles',$udom,$uname);
 2857:         if ($hidepriv) {
 2858:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2859:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2860:                 if ($user !~ /:/) {
 2861:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2862:                 } else {
 2863:                     $nothide{$user} = 1;
 2864:                 }
 2865:             }
 2866:         }
 2867:     }
 2868:     my %returnhash=();
 2869:     my $now=time;
 2870:     my %privileged;
 2871:     foreach my $entry (keys(%dumphash)) {
 2872:         my ($role,$tend,$tstart);
 2873:         if ($context eq 'userroles') {
 2874: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2875:         } else {
 2876:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2877:         }
 2878:         if (($tstart) && ($tstart<0)) { next; }
 2879:         my $status = 'active';
 2880:         if (($tend) && ($tend<=$now)) {
 2881:             $status = 'previous';
 2882:         } 
 2883:         if (($tstart) && ($now<$tstart)) {
 2884:             $status = 'future';
 2885:         }
 2886:         if (ref($types) eq 'ARRAY') {
 2887:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2888:                 next;
 2889:             } 
 2890:         } else {
 2891:             if ($status ne 'active') {
 2892:                 next;
 2893:             }
 2894:         }
 2895:         my ($rolecode,$username,$domain,$section,$area);
 2896:         if ($context eq 'userroles') {
 2897:             ($area,$rolecode) = split(/_/,$entry);
 2898:             (undef,$domain,$username,$section) = split(/\//,$area);
 2899:         } else {
 2900:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2901:         }
 2902:         if (ref($roledoms) eq 'ARRAY') {
 2903:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2904:                 next;
 2905:             }
 2906:         }
 2907:         if (ref($roles) eq 'ARRAY') {
 2908:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2909:                 if ($role =~ /^cr\//) {
 2910:                     if (!grep(/^cr$/,@{$roles})) {
 2911:                         next;
 2912:                     }
 2913:                 } else {
 2914:                     next;
 2915:                 }
 2916:             }
 2917:         }
 2918:         if ($hidepriv) {
 2919:             if ($context eq 'userroles') {
 2920:                 if ((&privileged($username,$domain)) &&
 2921:                     (!$nothide{$username.':'.$domain})) {
 2922:                     next;
 2923:                 }
 2924:             } else {
 2925:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2926:                     my %dompersonnel =
 2927:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2928:                     $privileged{$domain} = {};
 2929:                     if (keys(%dompersonnel)) {
 2930:                         foreach my $server (keys(%dompersonnel)) {
 2931:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2932:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2933:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2934:                                     $privileged{$udom}{$uname} = $trole;
 2935:                                 }
 2936:                             }
 2937:                         }
 2938:                     }
 2939:                 }
 2940:                 if (exists($privileged{$domain}{$username})) {
 2941:                     if (!$nothide{$username.':'.$domain}) {
 2942:                         next;
 2943:                     }
 2944:                 }
 2945:             }
 2946:         }
 2947:         if ($withsec) {
 2948:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2949:                 $tstart.':'.$tend;
 2950:         } else {
 2951:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2952:         }
 2953:     }
 2954:     return %returnhash;
 2955: }
 2956: 
 2957: # ----------------------------------------------------- Frontpage Announcements
 2958: #
 2959: #
 2960: 
 2961: sub postannounce {
 2962:     my ($server,$text)=@_;
 2963:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2964:     unless ($text=~/\w/) { $text=''; }
 2965:     return &reply('setannounce:'.&escape($text),$server);
 2966: }
 2967: 
 2968: sub getannounce {
 2969: 
 2970:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2971: 	my $announcement='';
 2972: 	while (my $line = <$fh>) { $announcement .= $line; }
 2973: 	close($fh);
 2974: 	if ($announcement=~/\w/) { 
 2975: 	    return 
 2976:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2977:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2978: 	} else {
 2979: 	    return '';
 2980: 	}
 2981:     } else {
 2982: 	return '';
 2983:     }
 2984: }
 2985: 
 2986: # ---------------------------------------------------------- Course ID routines
 2987: # Deal with domain's nohist_courseid.db files
 2988: #
 2989: 
 2990: sub courseidput {
 2991:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2992:     my $outcome;
 2993:     if ($caller eq 'timeonly') {
 2994:         my $cids = '';
 2995:         foreach my $item (keys(%$storehash)) {
 2996:             $cids.=&escape($item).'&';
 2997:         }
 2998:         $cids=~s/\&$//;
 2999:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3000:                           $coursehome);       
 3001:     } else {
 3002:         my $items = '';
 3003:         foreach my $item (keys(%$storehash)) {
 3004:             $items.= &escape($item).'='.
 3005:                      &freeze_escape($$storehash{$item}).'&';
 3006:         }
 3007:         $items=~s/\&$//;
 3008:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3009:                           $coursehome);
 3010:     }
 3011:     if ($outcome eq 'unknown_cmd') {
 3012:         my $what;
 3013:         foreach my $cid (keys(%$storehash)) {
 3014:             $what .= &escape($cid).'=';
 3015:             foreach my $item ('description','inst_code','owner','type') {
 3016:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3017:             }
 3018:             $what =~ s/\:$/&/;
 3019:         }
 3020:         $what =~ s/\&$//;  
 3021:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3022:     } else {
 3023:         return $outcome;
 3024:     }
 3025: }
 3026: 
 3027: sub courseiddump {
 3028:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3029:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3030:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
 3031:     my $as_hash = 1;
 3032:     my %returnhash;
 3033:     if (!$domfilter) { $domfilter=''; }
 3034:     my %libserv = &all_library();
 3035:     foreach my $tryserver (keys(%libserv)) {
 3036:         if ( (  $hostidflag == 1 
 3037: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3038: 	     || (!defined($hostidflag)) ) {
 3039: 
 3040: 	    if (($domfilter eq '') ||
 3041: 		(&host_domain($tryserver) eq $domfilter)) {
 3042:                 my $rep = 
 3043:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3044:                          $sincefilter.':'.&escape($descfilter).':'.
 3045:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3046:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3047:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3048:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3049:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3050:                          &escape($cc_clone).':'.$cloneonly,$tryserver);
 3051:                 my @pairs=split(/\&/,$rep);
 3052:                 foreach my $item (@pairs) {
 3053:                     my ($key,$value)=split(/\=/,$item,2);
 3054:                     $key = &unescape($key);
 3055:                     next if ($key =~ /^error: 2 /);
 3056:                     my $result = &thaw_unescape($value);
 3057:                     if (ref($result) eq 'HASH') {
 3058:                         $returnhash{$key}=$result;
 3059:                     } else {
 3060:                         my @responses = split(/:/,$value);
 3061:                         my @items = ('description','inst_code','owner','type');
 3062:                         for (my $i=0; $i<@responses; $i++) {
 3063:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3064:                         }
 3065:                     }
 3066:                 }
 3067:             }
 3068:         }
 3069:     }
 3070:     return %returnhash;
 3071: }
 3072: 
 3073: # ---------------------------------------------------------- DC e-mail
 3074: 
 3075: sub dcmailput {
 3076:     my ($domain,$msgid,$message,$server)=@_;
 3077:     my $status = &Apache::lonnet::critical(
 3078:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3079:        &escape($message),$server);
 3080:     return $status;
 3081: }
 3082: 
 3083: sub dcmaildump {
 3084:     my ($dom,$startdate,$enddate,$senders) = @_;
 3085:     my %returnhash=();
 3086: 
 3087:     if (defined(&domain($dom,'primary'))) {
 3088:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3089:                                                          &escape($enddate).':';
 3090: 	my @esc_senders=map { &escape($_)} @$senders;
 3091: 	$cmd.=&escape(join('&',@esc_senders));
 3092: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3093:             my ($key,$value) = split(/\=/,$line,2);
 3094:             if (($key) && ($value)) {
 3095:                 $returnhash{&unescape($key)} = &unescape($value);
 3096:             }
 3097:         }
 3098:     }
 3099:     return %returnhash;
 3100: }
 3101: # ---------------------------------------------------------- Domain roles
 3102: 
 3103: sub get_domain_roles {
 3104:     my ($dom,$roles,$startdate,$enddate)=@_;
 3105:     if ((!defined($startdate)) || ($startdate eq '')) {
 3106:         $startdate = '.';
 3107:     }
 3108:     if ((!defined($enddate)) || ($enddate eq '')) {
 3109:         $enddate = '.';
 3110:     }
 3111:     my $rolelist;
 3112:     if (ref($roles) eq 'ARRAY') {
 3113:         $rolelist = join(':',@{$roles});
 3114:     }
 3115:     my %personnel = ();
 3116: 
 3117:     my %servers = &get_servers($dom,'library');
 3118:     foreach my $tryserver (keys(%servers)) {
 3119: 	%{$personnel{$tryserver}}=();
 3120: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3121: 					    &escape($startdate).':'.
 3122: 					    &escape($enddate).':'.
 3123: 					    &escape($rolelist), $tryserver))) {
 3124: 	    my ($key,$value) = split(/\=/,$line,2);
 3125: 	    if (($key) && ($value)) {
 3126: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3127: 	    }
 3128: 	}
 3129:     }
 3130:     return %personnel;
 3131: }
 3132: 
 3133: # ----------------------------------------------------------- Check out an item
 3134: 
 3135: sub get_first_access {
 3136:     my ($type,$argsymb)=@_;
 3137:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3138:     if ($argsymb) { $symb=$argsymb; }
 3139:     my ($map,$id,$res)=&decode_symb($symb);
 3140:     if ($type eq 'course') {
 3141: 	$res='course';
 3142:     } elsif ($type eq 'map') {
 3143: 	$res=&symbread($map);
 3144:     } else {
 3145: 	$res=$symb;
 3146:     }
 3147:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3148:     return $times{"$courseid\0$res"};
 3149: }
 3150: 
 3151: sub set_first_access {
 3152:     my ($type)=@_;
 3153:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3154:     my ($map,$id,$res)=&decode_symb($symb);
 3155:     if ($type eq 'course') {
 3156: 	$res='course';
 3157:     } elsif ($type eq 'map') {
 3158: 	$res=&symbread($map);
 3159:     } else {
 3160: 	$res=$symb;
 3161:     }
 3162:     my $firstaccess=&get_first_access($type,$symb);
 3163:     if (!$firstaccess) {
 3164: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3165:     }
 3166:     return 'already_set';
 3167: }
 3168: 
 3169: sub checkout {
 3170:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3171:     my $now=time;
 3172:     my $lonhost=$perlvar{'lonHostID'};
 3173:     my $infostr=&escape(
 3174:                  'CHECKOUTTOKEN&'.
 3175:                  $tuname.'&'.
 3176:                  $tudom.'&'.
 3177:                  $tcrsid.'&'.
 3178:                  $symb.'&'.
 3179: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3180:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3181:     if ($token=~/^error\:/) { 
 3182:         &logthis("<font color=\"blue\">WARNING: ".
 3183:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3184:                  "</font>");
 3185:         return ''; 
 3186:     }
 3187: 
 3188:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3189:     $token=~tr/a-z/A-Z/;
 3190: 
 3191:     my %infohash=('resource.0.outtoken' => $token,
 3192:                   'resource.0.checkouttime' => $now,
 3193:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3194: 
 3195:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3196:        return '';
 3197:     } else {
 3198:         &logthis("<font color=\"blue\">WARNING: ".
 3199:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3200:                  "</font>");
 3201:     }    
 3202: 
 3203:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3204:                          &escape('Checkout '.$infostr.' - '.
 3205:                                                  $token)) ne 'ok') {
 3206: 	return '';
 3207:     } else {
 3208:         &logthis("<font color=\"blue\">WARNING: ".
 3209:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3210:                  "</font>");
 3211:     }
 3212:     return $token;
 3213: }
 3214: 
 3215: # ------------------------------------------------------------ Check in an item
 3216: 
 3217: sub checkin {
 3218:     my $token=shift;
 3219:     my $now=time;
 3220:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3221:     $lonhost=~tr/A-Z/a-z/;
 3222:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3223:     $dtoken=~s/\W/\_/g;
 3224:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3225:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3226: 
 3227:     unless (($tuname) && ($tudom)) {
 3228:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3229:         return '';
 3230:     }
 3231:     
 3232:     unless (&allowed('mgr',$tcrsid)) {
 3233:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3234:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3235:         return '';
 3236:     }
 3237: 
 3238:     my %infohash=('resource.0.intoken' => $token,
 3239:                   'resource.0.checkintime' => $now,
 3240:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3241: 
 3242:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3243:        return '';
 3244:     }    
 3245: 
 3246:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3247:                          &escape('Checkin - '.$token)) ne 'ok') {
 3248: 	return '';
 3249:     }
 3250: 
 3251:     return ($symb,$tuname,$tudom,$tcrsid);    
 3252: }
 3253: 
 3254: # --------------------------------------------- Set Expire Date for Spreadsheet
 3255: 
 3256: sub expirespread {
 3257:     my ($uname,$udom,$stype,$usymb)=@_;
 3258:     my $cid=$env{'request.course.id'}; 
 3259:     if ($cid) {
 3260:        my $now=time;
 3261:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3262:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3263:                             $env{'course.'.$cid.'.num'}.
 3264: 	        	    ':nohist_expirationdates:'.
 3265:                             &escape($key).'='.$now,
 3266:                             $env{'course.'.$cid.'.home'})
 3267:     }
 3268:     return 'ok';
 3269: }
 3270: 
 3271: # ----------------------------------------------------- Devalidate Spreadsheets
 3272: 
 3273: sub devalidate {
 3274:     my ($symb,$uname,$udom)=@_;
 3275:     my $cid=$env{'request.course.id'}; 
 3276:     if ($cid) {
 3277:         # delete the stored spreadsheets for
 3278:         # - the student level sheet of this user in course's homespace
 3279:         # - the assessment level sheet for this resource 
 3280:         #   for this user in user's homespace
 3281: 	# - current conditional state info
 3282: 	my $key=$uname.':'.$udom.':';
 3283:         my $status=
 3284: 	    &del('nohist_calculatedsheets',
 3285: 		 [$key.'studentcalc:'],
 3286: 		 $env{'course.'.$cid.'.domain'},
 3287: 		 $env{'course.'.$cid.'.num'})
 3288: 		.' '.
 3289: 	    &del('nohist_calculatedsheets_'.$cid,
 3290: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3291:         unless ($status eq 'ok ok') {
 3292:            &logthis('Could not devalidate spreadsheet '.
 3293:                     $uname.' at '.$udom.' for '.
 3294: 		    $symb.': '.$status);
 3295:         }
 3296: 	&delenv('user.state.'.$cid);
 3297:     }
 3298: }
 3299: 
 3300: sub get_scalar {
 3301:     my ($string,$end) = @_;
 3302:     my $value;
 3303:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3304: 	$value = $1;
 3305:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3306: 	$value = $1;
 3307:     }
 3308:     return &unescape($value);
 3309: }
 3310: 
 3311: sub array2str {
 3312:   my (@array) = @_;
 3313:   my $result=&arrayref2str(\@array);
 3314:   $result=~s/^__ARRAY_REF__//;
 3315:   $result=~s/__END_ARRAY_REF__$//;
 3316:   return $result;
 3317: }
 3318: 
 3319: sub arrayref2str {
 3320:   my ($arrayref) = @_;
 3321:   my $result='__ARRAY_REF__';
 3322:   foreach my $elem (@$arrayref) {
 3323:     if(ref($elem) eq 'ARRAY') {
 3324:       $result.=&arrayref2str($elem).'&';
 3325:     } elsif(ref($elem) eq 'HASH') {
 3326:       $result.=&hashref2str($elem).'&';
 3327:     } elsif(ref($elem)) {
 3328:       #print("Got a ref of ".(ref($elem))." skipping.");
 3329:     } else {
 3330:       $result.=&escape($elem).'&';
 3331:     }
 3332:   }
 3333:   $result=~s/\&$//;
 3334:   $result .= '__END_ARRAY_REF__';
 3335:   return $result;
 3336: }
 3337: 
 3338: sub hash2str {
 3339:   my (%hash) = @_;
 3340:   my $result=&hashref2str(\%hash);
 3341:   $result=~s/^__HASH_REF__//;
 3342:   $result=~s/__END_HASH_REF__$//;
 3343:   return $result;
 3344: }
 3345: 
 3346: sub hashref2str {
 3347:   my ($hashref)=@_;
 3348:   my $result='__HASH_REF__';
 3349:   foreach my $key (sort(keys(%$hashref))) {
 3350:     if (ref($key) eq 'ARRAY') {
 3351:       $result.=&arrayref2str($key).'=';
 3352:     } elsif (ref($key) eq 'HASH') {
 3353:       $result.=&hashref2str($key).'=';
 3354:     } elsif (ref($key)) {
 3355:       $result.='=';
 3356:       #print("Got a ref of ".(ref($key))." skipping.");
 3357:     } else {
 3358: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3359:     }
 3360: 
 3361:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3362:       $result.=&arrayref2str($hashref->{$key}).'&';
 3363:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3364:       $result.=&hashref2str($hashref->{$key}).'&';
 3365:     } elsif(ref($hashref->{$key})) {
 3366:        $result.='&';
 3367:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3368:     } else {
 3369:       $result.=&escape($hashref->{$key}).'&';
 3370:     }
 3371:   }
 3372:   $result=~s/\&$//;
 3373:   $result .= '__END_HASH_REF__';
 3374:   return $result;
 3375: }
 3376: 
 3377: sub str2hash {
 3378:     my ($string)=@_;
 3379:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3380:     return %$hash;
 3381: }
 3382: 
 3383: sub str2hashref {
 3384:   my ($string) = @_;
 3385: 
 3386:   my %hash;
 3387: 
 3388:   if($string !~ /^__HASH_REF__/) {
 3389:       if (! ($string eq '' || !defined($string))) {
 3390: 	  $hash{'error'}='Not hash reference';
 3391:       }
 3392:       return (\%hash, $string);
 3393:   }
 3394: 
 3395:   $string =~ s/^__HASH_REF__//;
 3396: 
 3397:   while($string !~ /^__END_HASH_REF__/) {
 3398:       #key
 3399:       my $key='';
 3400:       if($string =~ /^__HASH_REF__/) {
 3401:           ($key, $string)=&str2hashref($string);
 3402:           if(defined($key->{'error'})) {
 3403:               $hash{'error'}='Bad data';
 3404:               return (\%hash, $string);
 3405:           }
 3406:       } elsif($string =~ /^__ARRAY_REF__/) {
 3407:           ($key, $string)=&str2arrayref($string);
 3408:           if($key->[0] eq 'Array reference error') {
 3409:               $hash{'error'}='Bad data';
 3410:               return (\%hash, $string);
 3411:           }
 3412:       } else {
 3413:           $string =~ s/^(.*?)=//;
 3414: 	  $key=&unescape($1);
 3415:       }
 3416:       $string =~ s/^=//;
 3417: 
 3418:       #value
 3419:       my $value='';
 3420:       if($string =~ /^__HASH_REF__/) {
 3421:           ($value, $string)=&str2hashref($string);
 3422:           if(defined($value->{'error'})) {
 3423:               $hash{'error'}='Bad data';
 3424:               return (\%hash, $string);
 3425:           }
 3426:       } elsif($string =~ /^__ARRAY_REF__/) {
 3427:           ($value, $string)=&str2arrayref($string);
 3428:           if($value->[0] eq 'Array reference error') {
 3429:               $hash{'error'}='Bad data';
 3430:               return (\%hash, $string);
 3431:           }
 3432:       } else {
 3433: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3434:       }
 3435:       $string =~ s/^&//;
 3436: 
 3437:       $hash{$key}=$value;
 3438:   }
 3439: 
 3440:   $string =~ s/^__END_HASH_REF__//;
 3441: 
 3442:   return (\%hash, $string);
 3443: }
 3444: 
 3445: sub str2array {
 3446:     my ($string)=@_;
 3447:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3448:     return @$array;
 3449: }
 3450: 
 3451: sub str2arrayref {
 3452:   my ($string) = @_;
 3453:   my @array;
 3454: 
 3455:   if($string !~ /^__ARRAY_REF__/) {
 3456:       if (! ($string eq '' || !defined($string))) {
 3457: 	  $array[0]='Array reference error';
 3458:       }
 3459:       return (\@array, $string);
 3460:   }
 3461: 
 3462:   $string =~ s/^__ARRAY_REF__//;
 3463: 
 3464:   while($string !~ /^__END_ARRAY_REF__/) {
 3465:       my $value='';
 3466:       if($string =~ /^__HASH_REF__/) {
 3467:           ($value, $string)=&str2hashref($string);
 3468:           if(defined($value->{'error'})) {
 3469:               $array[0] ='Array reference error';
 3470:               return (\@array, $string);
 3471:           }
 3472:       } elsif($string =~ /^__ARRAY_REF__/) {
 3473:           ($value, $string)=&str2arrayref($string);
 3474:           if($value->[0] eq 'Array reference error') {
 3475:               $array[0] ='Array reference error';
 3476:               return (\@array, $string);
 3477:           }
 3478:       } else {
 3479: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3480:       }
 3481:       $string =~ s/^&//;
 3482: 
 3483:       push(@array, $value);
 3484:   }
 3485: 
 3486:   $string =~ s/^__END_ARRAY_REF__//;
 3487: 
 3488:   return (\@array, $string);
 3489: }
 3490: 
 3491: # -------------------------------------------------------------------Temp Store
 3492: 
 3493: sub tmpreset {
 3494:   my ($symb,$namespace,$domain,$stuname) = @_;
 3495:   if (!$symb) {
 3496:     $symb=&symbread();
 3497:     if (!$symb) { $symb= $env{'request.url'}; }
 3498:   }
 3499:   $symb=escape($symb);
 3500: 
 3501:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3502:   $namespace=~s/\//\_/g;
 3503:   $namespace=~s/\W//g;
 3504: 
 3505:   if (!$domain) { $domain=$env{'user.domain'}; }
 3506:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3507:   if ($domain eq 'public' && $stuname eq 'public') {
 3508:       $stuname=$ENV{'REMOTE_ADDR'};
 3509:   }
 3510:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3511:   my %hash;
 3512:   if (tie(%hash,'GDBM_File',
 3513: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3514: 	  &GDBM_WRCREAT(),0640)) {
 3515:     foreach my $key (keys(%hash)) {
 3516:       if ($key=~ /:$symb/) {
 3517: 	delete($hash{$key});
 3518:       }
 3519:     }
 3520:   }
 3521: }
 3522: 
 3523: sub tmpstore {
 3524:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3525: 
 3526:   if (!$symb) {
 3527:     $symb=&symbread();
 3528:     if (!$symb) { $symb= $env{'request.url'}; }
 3529:   }
 3530:   $symb=escape($symb);
 3531: 
 3532:   if (!$namespace) {
 3533:     # I don't think we would ever want to store this for a course.
 3534:     # it seems this will only be used if we don't have a course.
 3535:     #$namespace=$env{'request.course.id'};
 3536:     #if (!$namespace) {
 3537:       $namespace=$env{'request.state'};
 3538:     #}
 3539:   }
 3540:   $namespace=~s/\//\_/g;
 3541:   $namespace=~s/\W//g;
 3542:   if (!$domain) { $domain=$env{'user.domain'}; }
 3543:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3544:   if ($domain eq 'public' && $stuname eq 'public') {
 3545:       $stuname=$ENV{'REMOTE_ADDR'};
 3546:   }
 3547:   my $now=time;
 3548:   my %hash;
 3549:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3550:   if (tie(%hash,'GDBM_File',
 3551: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3552: 	  &GDBM_WRCREAT(),0640)) {
 3553:     $hash{"version:$symb"}++;
 3554:     my $version=$hash{"version:$symb"};
 3555:     my $allkeys=''; 
 3556:     foreach my $key (keys(%$storehash)) {
 3557:       $allkeys.=$key.':';
 3558:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3559:     }
 3560:     $hash{"$version:$symb:timestamp"}=$now;
 3561:     $allkeys.='timestamp';
 3562:     $hash{"$version:keys:$symb"}=$allkeys;
 3563:     if (untie(%hash)) {
 3564:       return 'ok';
 3565:     } else {
 3566:       return "error:$!";
 3567:     }
 3568:   } else {
 3569:     return "error:$!";
 3570:   }
 3571: }
 3572: 
 3573: # -----------------------------------------------------------------Temp Restore
 3574: 
 3575: sub tmprestore {
 3576:   my ($symb,$namespace,$domain,$stuname) = @_;
 3577: 
 3578:   if (!$symb) {
 3579:     $symb=&symbread();
 3580:     if (!$symb) { $symb= $env{'request.url'}; }
 3581:   }
 3582:   $symb=escape($symb);
 3583: 
 3584:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3585: 
 3586:   if (!$domain) { $domain=$env{'user.domain'}; }
 3587:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3588:   if ($domain eq 'public' && $stuname eq 'public') {
 3589:       $stuname=$ENV{'REMOTE_ADDR'};
 3590:   }
 3591:   my %returnhash;
 3592:   $namespace=~s/\//\_/g;
 3593:   $namespace=~s/\W//g;
 3594:   my %hash;
 3595:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3596:   if (tie(%hash,'GDBM_File',
 3597: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3598: 	  &GDBM_READER(),0640)) {
 3599:     my $version=$hash{"version:$symb"};
 3600:     $returnhash{'version'}=$version;
 3601:     my $scope;
 3602:     for ($scope=1;$scope<=$version;$scope++) {
 3603:       my $vkeys=$hash{"$scope:keys:$symb"};
 3604:       my @keys=split(/:/,$vkeys);
 3605:       my $key;
 3606:       $returnhash{"$scope:keys"}=$vkeys;
 3607:       foreach $key (@keys) {
 3608: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3609: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3610:       }
 3611:     }
 3612:     if (!(untie(%hash))) {
 3613:       return "error:$!";
 3614:     }
 3615:   } else {
 3616:     return "error:$!";
 3617:   }
 3618:   return %returnhash;
 3619: }
 3620: 
 3621: # ----------------------------------------------------------------------- Store
 3622: 
 3623: sub store {
 3624:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3625:     my $home='';
 3626: 
 3627:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3628: 
 3629:     $symb=&symbclean($symb);
 3630:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3631: 
 3632:     if (!$domain) { $domain=$env{'user.domain'}; }
 3633:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3634: 
 3635:     &devalidate($symb,$stuname,$domain);
 3636: 
 3637:     $symb=escape($symb);
 3638:     if (!$namespace) { 
 3639:        unless ($namespace=$env{'request.course.id'}) { 
 3640:           return ''; 
 3641:        } 
 3642:     }
 3643:     if (!$home) { $home=$env{'user.home'}; }
 3644: 
 3645:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3646:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3647: 
 3648:     my $namevalue='';
 3649:     foreach my $key (keys(%$storehash)) {
 3650:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3651:     }
 3652:     $namevalue=~s/\&$//;
 3653:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3654:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3655: }
 3656: 
 3657: # -------------------------------------------------------------- Critical Store
 3658: 
 3659: sub cstore {
 3660:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3661:     my $home='';
 3662: 
 3663:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3664: 
 3665:     $symb=&symbclean($symb);
 3666:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3667: 
 3668:     if (!$domain) { $domain=$env{'user.domain'}; }
 3669:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3670: 
 3671:     &devalidate($symb,$stuname,$domain);
 3672: 
 3673:     $symb=escape($symb);
 3674:     if (!$namespace) { 
 3675:        unless ($namespace=$env{'request.course.id'}) { 
 3676:           return ''; 
 3677:        } 
 3678:     }
 3679:     if (!$home) { $home=$env{'user.home'}; }
 3680: 
 3681:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3682:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3683: 
 3684:     my $namevalue='';
 3685:     foreach my $key (keys(%$storehash)) {
 3686:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3687:     }
 3688:     $namevalue=~s/\&$//;
 3689:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3690:     return critical
 3691:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3692: }
 3693: 
 3694: # --------------------------------------------------------------------- Restore
 3695: 
 3696: sub restore {
 3697:     my ($symb,$namespace,$domain,$stuname) = @_;
 3698:     my $home='';
 3699: 
 3700:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3701: 
 3702:     if (!$symb) {
 3703:       unless ($symb=escape(&symbread())) { return ''; }
 3704:     } else {
 3705:       $symb=&escape(&symbclean($symb));
 3706:     }
 3707:     if (!$namespace) { 
 3708:        unless ($namespace=$env{'request.course.id'}) { 
 3709:           return ''; 
 3710:        } 
 3711:     }
 3712:     if (!$domain) { $domain=$env{'user.domain'}; }
 3713:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3714:     if (!$home) { $home=$env{'user.home'}; }
 3715:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3716: 
 3717:     my %returnhash=();
 3718:     foreach my $line (split(/\&/,$answer)) {
 3719: 	my ($name,$value)=split(/\=/,$line);
 3720:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3721:     }
 3722:     my $version;
 3723:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3724:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3725:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3726:        }
 3727:     }
 3728:     return %returnhash;
 3729: }
 3730: 
 3731: # ---------------------------------------------------------- Course Description
 3732: 
 3733: sub coursedescription {
 3734:     my ($courseid,$args)=@_;
 3735:     $courseid=~s/^\///;
 3736:     $courseid=~s/\_/\//g;
 3737:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3738:     my $chome=&homeserver($cnum,$cdomain);
 3739:     my $normalid=$cdomain.'_'.$cnum;
 3740:     # need to always cache even if we get errors otherwise we keep 
 3741:     # trying and trying and trying to get the course description.
 3742:     my %envhash=();
 3743:     my %returnhash=();
 3744:     
 3745:     my $expiretime=600;
 3746:     if ($env{'request.course.id'} eq $normalid) {
 3747: 	$expiretime=120;
 3748:     }
 3749: 
 3750:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3751:     if (!$args->{'freshen_cache'}
 3752: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3753: 	foreach my $key (keys(%env)) {
 3754: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3755: 	    my ($setting) = $1;
 3756: 	    $returnhash{$setting} = $env{$key};
 3757: 	}
 3758: 	return %returnhash;
 3759:     }
 3760: 
 3761:     # get the data agin
 3762:     if (!$args->{'one_time'}) {
 3763: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3764:     }
 3765: 
 3766:     if ($chome ne 'no_host') {
 3767:        %returnhash=&dump('environment',$cdomain,$cnum);
 3768:        if (!exists($returnhash{'con_lost'})) {
 3769:            $returnhash{'home'}= $chome;
 3770: 	   $returnhash{'domain'} = $cdomain;
 3771: 	   $returnhash{'num'} = $cnum;
 3772:            if (!defined($returnhash{'type'})) {
 3773:                $returnhash{'type'} = 'Course';
 3774:            }
 3775:            while (my ($name,$value) = each %returnhash) {
 3776:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3777:            }
 3778:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3779:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3780: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3781:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3782:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3783:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3784:        }
 3785:     }
 3786:     if (!$args->{'one_time'}) {
 3787: 	&appenv(\%envhash);
 3788:     }
 3789:     return %returnhash;
 3790: }
 3791: 
 3792: # -------------------------------------------------See if a user is privileged
 3793: 
 3794: sub privileged {
 3795:     my ($username,$domain)=@_;
 3796:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3797: 			&homeserver($username,$domain));
 3798:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3799:     my $now=time;
 3800:     if ($rolesdump ne '') {
 3801:         foreach my $entry (split(/&/,$rolesdump)) {
 3802: 	    if ($entry!~/^rolesdef_/) {
 3803: 		my ($area,$role)=split(/=/,$entry);
 3804: 		$area=~s/\_\w\w$//;
 3805: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3806: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3807: 		    my $active=1;
 3808: 		    if ($tend) {
 3809: 			if ($tend<$now) { $active=0; }
 3810: 		    }
 3811: 		    if ($tstart) {
 3812: 			if ($tstart>$now) { $active=0; }
 3813: 		    }
 3814: 		    if ($active) { return 1; }
 3815: 		}
 3816: 	    }
 3817: 	}
 3818:     }
 3819:     return 0;
 3820: }
 3821: 
 3822: # -------------------------------------------------------- Get user privileges
 3823: 
 3824: sub rolesinit {
 3825:     my ($domain,$username,$authhost)=@_;
 3826:     my %userroles;
 3827:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3828:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3829:     my %allroles=();
 3830:     my %allgroups=();   
 3831:     my $now=time;
 3832:     %userroles = ('user.login.time' => $now);
 3833:     my $group_privs;
 3834: 
 3835:     if ($rolesdump ne '') {
 3836:         foreach my $entry (split(/&/,$rolesdump)) {
 3837: 	  if ($entry!~/^rolesdef_/) {
 3838:             my ($area,$role)=split(/=/,$entry);
 3839: 	    $area=~s/\_\w\w$//;
 3840:             my ($trole,$tend,$tstart,$group_privs);
 3841: 	    if ($role=~/^cr/) { 
 3842: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3843: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3844: 		    ($tend,$tstart)=split('_',$trest);
 3845: 		} else {
 3846: 		    $trole=$role;
 3847: 		}
 3848:             } elsif ($role =~ m|^gr/|) {
 3849:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3850:                 ($trole,$group_privs) = split(/\//,$trole);
 3851:                 $group_privs = &unescape($group_privs);
 3852: 	    } else {
 3853: 		($trole,$tend,$tstart)=split(/_/,$role);
 3854: 	    }
 3855: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3856: 					 $username);
 3857: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3858:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3859:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3860:             if (($area ne '') && ($trole ne '')) {
 3861: 		my $spec=$trole.'.'.$area;
 3862: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3863: 		if ($trole =~ /^cr\//) {
 3864:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3865:                 } elsif ($trole eq 'gr') {
 3866:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3867: 		} else {
 3868:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3869: 		}
 3870:             }
 3871:           }
 3872:         }
 3873:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3874:         $userroles{'user.adv'}    = $adv;
 3875: 	$userroles{'user.author'} = $author;
 3876:         $env{'user.adv'}=$adv;
 3877:     }
 3878:     return \%userroles;  
 3879: }
 3880: 
 3881: sub set_arearole {
 3882:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3883: # log the associated role with the area
 3884:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3885:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3886: }
 3887: 
 3888: sub custom_roleprivs {
 3889:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3890:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3891:     my $homsvr=homeserver($rauthor,$rdomain);
 3892:     if (&hostname($homsvr) ne '') {
 3893:         my ($rdummy,$roledef)=
 3894:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3895:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3896:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3897:             if (defined($syspriv)) {
 3898:                 $$allroles{'cm./'}.=':'.$syspriv;
 3899:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3900:             }
 3901:             if ($tdomain ne '') {
 3902:                 if (defined($dompriv)) {
 3903:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3904:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3905:                 }
 3906:                 if (($trest ne '') && (defined($coursepriv))) {
 3907:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3908:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3909:                 }
 3910:             }
 3911:         }
 3912:     }
 3913: }
 3914: 
 3915: sub group_roleprivs {
 3916:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3917:     my $access = 1;
 3918:     my $now = time;
 3919:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3920:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3921:     if ($access) {
 3922:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3923:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3924:     }
 3925: }
 3926: 
 3927: sub standard_roleprivs {
 3928:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3929:     if (defined($pr{$trole.':s'})) {
 3930:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3931:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3932:     }
 3933:     if ($tdomain ne '') {
 3934:         if (defined($pr{$trole.':d'})) {
 3935:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3936:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3937:         }
 3938:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3939:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3940:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3941:         }
 3942:     }
 3943: }
 3944: 
 3945: sub set_userprivs {
 3946:     my ($userroles,$allroles,$allgroups) = @_; 
 3947:     my $author=0;
 3948:     my $adv=0;
 3949:     my %grouproles = ();
 3950:     if (keys(%{$allgroups}) > 0) {
 3951:         foreach my $role (keys(%{$allroles})) {
 3952:             my ($trole,$area,$sec,$extendedarea);
 3953:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3954:                 $trole = $1;
 3955:                 $area = $2;
 3956:                 $sec = $3;
 3957:                 $extendedarea = $area.$sec;
 3958:                 if (exists($$allgroups{$area})) {
 3959:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3960:                         my $spec = $trole.'.'.$extendedarea;
 3961:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3962:                                                 $$allgroups{$area}{$group};
 3963:                     }
 3964:                 }
 3965:             }
 3966:         }
 3967:     }
 3968:     foreach my $group (keys(%grouproles)) {
 3969:         $$allroles{$group} = $grouproles{$group};
 3970:     }
 3971:     foreach my $role (keys(%{$allroles})) {
 3972:         my %thesepriv;
 3973:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3974:         foreach my $item (split(/:/,$$allroles{$role})) {
 3975:             if ($item ne '') {
 3976:                 my ($privilege,$restrictions)=split(/&/,$item);
 3977:                 if ($restrictions eq '') {
 3978:                     $thesepriv{$privilege}='F';
 3979:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3980:                     $thesepriv{$privilege}.=$restrictions;
 3981:                 }
 3982:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3983:             }
 3984:         }
 3985:         my $thesestr='';
 3986:         foreach my $priv (keys(%thesepriv)) {
 3987: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3988: 	}
 3989:         $userroles->{'user.priv.'.$role} = $thesestr;
 3990:     }
 3991:     return ($author,$adv);
 3992: }
 3993: 
 3994: sub role_status {
 3995:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 3996:     my @pwhere = ();
 3997:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 3998:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 3999:         unless (!defined($$role) || $$role eq '') {
 4000:             $$where=join('.',@pwhere);
 4001:             $$trolecode=$$role.'.'.$$where;
 4002:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4003:             $$tstatus='is';
 4004:             if ($$tstart && $$tstart>$then) {
 4005:                 $$tstatus='future';
 4006:                 if ($$tstart && $$tstart>$refresh) {
 4007:                     if ($$tstart<$now) {
 4008:                         if (($$where ne '') && ($$role ne '')) {
 4009:                             my (%allroles,%allgroups,$group_privs);
 4010:                             my %userroles = (
 4011:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4012:                             );
 4013:                             my $spec=$$role.'.'.$$where;
 4014:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4015:                             if ($$role eq 'gr') {
 4016:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4017:                                                     $env{'user.name'})=@_;
 4018:                                 my ($trole) = split('_',$role,1);
 4019:                                 (undef,my $group_privs) = split(/\//,$trole);
 4020:                                 $group_privs = &unescape($group_privs);
 4021:                             }
 4022:                             if ($$role =~ /^cr\//) {
 4023:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4024:                             } elsif ($$role eq 'gr') {
 4025:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4026:                                                     $env{'user.name'});
 4027:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 4028:                                 (undef,my $group_privs) = split(/\//,$trole);
 4029:                                 $group_privs = &unescape($group_privs);
 4030:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4031:                             } else {
 4032:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4033:                             }
 4034:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4035:                             &appenv(\%userroles,[$$role,'cm']);
 4036:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4037:                             $$tstatus = 'is';
 4038:                         }
 4039:                     }
 4040:                 }
 4041:             }
 4042:             if ($$tend) {
 4043:                 if ($$tend<$then) {
 4044:                     $$tstatus='expired';
 4045:                 } elsif ($$tend<$now) {
 4046:                     $$tstatus='will_not';
 4047:                 }
 4048:             }
 4049:         }
 4050:     }
 4051: }
 4052: 
 4053: sub check_adhoc_privs {
 4054:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 4055:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4056:     if ($env{$cckey}) {
 4057:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4058:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4059:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4060:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4061:         }
 4062:     } else {
 4063:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4064:     }
 4065: }
 4066: 
 4067: sub set_adhoc_privileges {
 4068: # role can be cc or ca
 4069:     my ($dcdom,$pickedcourse,$role) = @_;
 4070:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4071:     my $spec = $role.'.'.$area;
 4072:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4073:                                   $env{'user.name'});
 4074:     my %ccrole = ();
 4075:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4076:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4077:     &appenv(\%userroles,[$role,'cm']);
 4078:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4079:     &appenv( {'request.role'        => $spec,
 4080:               'request.role.domain' => $dcdom,
 4081:               'request.course.sec'  => ''
 4082:              }
 4083:            );
 4084:     my $tadv=0;
 4085:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4086:     &appenv({'request.role.adv'    => $tadv});
 4087: }
 4088: 
 4089: # --------------------------------------------------------------- get interface
 4090: 
 4091: sub get {
 4092:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4093:    my $items='';
 4094:    foreach my $item (@$storearr) {
 4095:        $items.=&escape($item).'&';
 4096:    }
 4097:    $items=~s/\&$//;
 4098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4099:    if (!$uname) { $uname=$env{'user.name'}; }
 4100:    my $uhome=&homeserver($uname,$udomain);
 4101: 
 4102:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4103:    my @pairs=split(/\&/,$rep);
 4104:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4105:      return @pairs;
 4106:    }
 4107:    my %returnhash=();
 4108:    my $i=0;
 4109:    foreach my $item (@$storearr) {
 4110:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4111:       $i++;
 4112:    }
 4113:    return %returnhash;
 4114: }
 4115: 
 4116: # --------------------------------------------------------------- del interface
 4117: 
 4118: sub del {
 4119:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4120:    my $items='';
 4121:    foreach my $item (@$storearr) {
 4122:        $items.=&escape($item).'&';
 4123:    }
 4124: 
 4125:    $items=~s/\&$//;
 4126:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4127:    if (!$uname) { $uname=$env{'user.name'}; }
 4128:    my $uhome=&homeserver($uname,$udomain);
 4129:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4130: }
 4131: 
 4132: # -------------------------------------------------------------- dump interface
 4133: 
 4134: sub dump {
 4135:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4136:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4137:     if (!$uname) { $uname=$env{'user.name'}; }
 4138:     my $uhome=&homeserver($uname,$udomain);
 4139:     if ($regexp) {
 4140: 	$regexp=&escape($regexp);
 4141:     } else {
 4142: 	$regexp='.';
 4143:     }
 4144:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4145:     my @pairs=split(/\&/,$rep);
 4146:     my %returnhash=();
 4147:     foreach my $item (@pairs) {
 4148: 	my ($key,$value)=split(/=/,$item,2);
 4149: 	$key = &unescape($key);
 4150: 	next if ($key =~ /^error: 2 /);
 4151: 	$returnhash{$key}=&thaw_unescape($value);
 4152:     }
 4153:     return %returnhash;
 4154: }
 4155: 
 4156: # --------------------------------------------------------- dumpstore interface
 4157: 
 4158: sub dumpstore {
 4159:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4160:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4161:    if (!$uname) { $uname=$env{'user.name'}; }
 4162:    my $uhome=&homeserver($uname,$udomain);
 4163:    if ($regexp) {
 4164:        $regexp=&escape($regexp);
 4165:    } else {
 4166:        $regexp='.';
 4167:    }
 4168:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4169:    my @pairs=split(/\&/,$rep);
 4170:    my %returnhash=();
 4171:    foreach my $item (@pairs) {
 4172:        my ($key,$value)=split(/=/,$item,2);
 4173:        next if ($key =~ /^error: 2 /);
 4174:        $returnhash{$key}=&thaw_unescape($value);
 4175:    }
 4176:    return %returnhash;
 4177: }
 4178: 
 4179: # -------------------------------------------------------------- keys interface
 4180: 
 4181: sub getkeys {
 4182:    my ($namespace,$udomain,$uname)=@_;
 4183:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4184:    if (!$uname) { $uname=$env{'user.name'}; }
 4185:    my $uhome=&homeserver($uname,$udomain);
 4186:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4187:    my @keyarray=();
 4188:    foreach my $key (split(/\&/,$rep)) {
 4189:       next if ($key =~ /^error: 2 /);
 4190:       push(@keyarray,&unescape($key));
 4191:    }
 4192:    return @keyarray;
 4193: }
 4194: 
 4195: # --------------------------------------------------------------- currentdump
 4196: sub currentdump {
 4197:    my ($courseid,$sdom,$sname)=@_;
 4198:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4199:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4200:    $sname    = $env{'user.name'}         if (! defined($sname));
 4201:    my $uhome = &homeserver($sname,$sdom);
 4202:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4203:    return if ($rep =~ /^(error:|no_such_host)/);
 4204:    #
 4205:    my %returnhash=();
 4206:    #
 4207:    if ($rep eq "unknown_cmd") { 
 4208:        # an old lond will not know currentdump
 4209:        # Do a dump and make it look like a currentdump
 4210:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4211:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4212:        my %hash = @tmp;
 4213:        @tmp=();
 4214:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4215:    } else {
 4216:        my @pairs=split(/\&/,$rep);
 4217:        foreach my $pair (@pairs) {
 4218:            my ($key,$value)=split(/=/,$pair,2);
 4219:            my ($symb,$param) = split(/:/,$key);
 4220:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4221:                                                         &thaw_unescape($value);
 4222:        }
 4223:    }
 4224:    return %returnhash;
 4225: }
 4226: 
 4227: sub convert_dump_to_currentdump{
 4228:     my %hash = %{shift()};
 4229:     my %returnhash;
 4230:     # Code ripped from lond, essentially.  The only difference
 4231:     # here is the unescaping done by lonnet::dump().  Conceivably
 4232:     # we might run in to problems with parameter names =~ /^v\./
 4233:     while (my ($key,$value) = each(%hash)) {
 4234:         my ($v,$symb,$param) = split(/:/,$key);
 4235: 	$symb  = &unescape($symb);
 4236: 	$param = &unescape($param);
 4237:         next if ($v eq 'version' || $symb eq 'keys');
 4238:         next if (exists($returnhash{$symb}) &&
 4239:                  exists($returnhash{$symb}->{$param}) &&
 4240:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4241:         $returnhash{$symb}->{$param}=$value;
 4242:         $returnhash{$symb}->{'v.'.$param}=$v;
 4243:     }
 4244:     #
 4245:     # Remove all of the keys in the hashes which keep track of
 4246:     # the version of the parameter.
 4247:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4248:         # use a foreach because we are going to delete from the hash.
 4249:         foreach my $key (keys(%$param_hash)) {
 4250:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4251:         }
 4252:     }
 4253:     return \%returnhash;
 4254: }
 4255: 
 4256: # ------------------------------------------------------ critical inc interface
 4257: 
 4258: sub cinc {
 4259:     return &inc(@_,'critical');
 4260: }
 4261: 
 4262: # --------------------------------------------------------------- inc interface
 4263: 
 4264: sub inc {
 4265:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4266:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4267:     if (!$uname) { $uname=$env{'user.name'}; }
 4268:     my $uhome=&homeserver($uname,$udomain);
 4269:     my $items='';
 4270:     if (! ref($store)) {
 4271:         # got a single value, so use that instead
 4272:         $items = &escape($store).'=&';
 4273:     } elsif (ref($store) eq 'SCALAR') {
 4274:         $items = &escape($$store).'=&';        
 4275:     } elsif (ref($store) eq 'ARRAY') {
 4276:         $items = join('=&',map {&escape($_);} @{$store});
 4277:     } elsif (ref($store) eq 'HASH') {
 4278:         while (my($key,$value) = each(%{$store})) {
 4279:             $items.= &escape($key).'='.&escape($value).'&';
 4280:         }
 4281:     }
 4282:     $items=~s/\&$//;
 4283:     if ($critical) {
 4284: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4285:     } else {
 4286: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4287:     }
 4288: }
 4289: 
 4290: # --------------------------------------------------------------- put interface
 4291: 
 4292: sub put {
 4293:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4294:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4295:    if (!$uname) { $uname=$env{'user.name'}; }
 4296:    my $uhome=&homeserver($uname,$udomain);
 4297:    my $items='';
 4298:    foreach my $item (keys(%$storehash)) {
 4299:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4300:    }
 4301:    $items=~s/\&$//;
 4302:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4303: }
 4304: 
 4305: # ------------------------------------------------------------ newput interface
 4306: 
 4307: sub newput {
 4308:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4309:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4310:    if (!$uname) { $uname=$env{'user.name'}; }
 4311:    my $uhome=&homeserver($uname,$udomain);
 4312:    my $items='';
 4313:    foreach my $key (keys(%$storehash)) {
 4314:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4315:    }
 4316:    $items=~s/\&$//;
 4317:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4318: }
 4319: 
 4320: # ---------------------------------------------------------  putstore interface
 4321: 
 4322: sub putstore {
 4323:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4324:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4325:    if (!$uname) { $uname=$env{'user.name'}; }
 4326:    my $uhome=&homeserver($uname,$udomain);
 4327:    my $items='';
 4328:    foreach my $key (keys(%$storehash)) {
 4329:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4330:    }
 4331:    $items=~s/\&$//;
 4332:    my $esc_symb=&escape($symb);
 4333:    my $esc_v=&escape($version);
 4334:    my $reply =
 4335:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4336: 	      $uhome);
 4337:    if ($reply eq 'unknown_cmd') {
 4338:        # gfall back to way things use to be done
 4339:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4340: 			    $uname);
 4341:    }
 4342:    return $reply;
 4343: }
 4344: 
 4345: sub old_putstore {
 4346:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4347:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4348:     if (!$uname) { $uname=$env{'user.name'}; }
 4349:     my $uhome=&homeserver($uname,$udomain);
 4350:     my %newstorehash;
 4351:     foreach my $item (keys(%$storehash)) {
 4352: 	my $key = $version.':'.&escape($symb).':'.$item;
 4353: 	$newstorehash{$key} = $storehash->{$item};
 4354:     }
 4355:     my $items='';
 4356:     my %allitems = ();
 4357:     foreach my $item (keys(%newstorehash)) {
 4358: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4359: 	    my $key = $1.':keys:'.$2;
 4360: 	    $allitems{$key} .= $3.':';
 4361: 	}
 4362: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4363:     }
 4364:     foreach my $item (keys(%allitems)) {
 4365: 	$allitems{$item} =~ s/\:$//;
 4366: 	$items.= $item.'='.$allitems{$item}.'&';
 4367:     }
 4368:     $items=~s/\&$//;
 4369:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4370: }
 4371: 
 4372: # ------------------------------------------------------ critical put interface
 4373: 
 4374: sub cput {
 4375:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4376:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4377:    if (!$uname) { $uname=$env{'user.name'}; }
 4378:    my $uhome=&homeserver($uname,$udomain);
 4379:    my $items='';
 4380:    foreach my $item (keys(%$storehash)) {
 4381:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4382:    }
 4383:    $items=~s/\&$//;
 4384:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4385: }
 4386: 
 4387: # -------------------------------------------------------------- eget interface
 4388: 
 4389: sub eget {
 4390:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4391:    my $items='';
 4392:    foreach my $item (@$storearr) {
 4393:        $items.=&escape($item).'&';
 4394:    }
 4395:    $items=~s/\&$//;
 4396:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4397:    if (!$uname) { $uname=$env{'user.name'}; }
 4398:    my $uhome=&homeserver($uname,$udomain);
 4399:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4400:    my @pairs=split(/\&/,$rep);
 4401:    my %returnhash=();
 4402:    my $i=0;
 4403:    foreach my $item (@$storearr) {
 4404:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4405:       $i++;
 4406:    }
 4407:    return %returnhash;
 4408: }
 4409: 
 4410: # ------------------------------------------------------------ tmpput interface
 4411: sub tmpput {
 4412:     my ($storehash,$server,$context)=@_;
 4413:     my $items='';
 4414:     foreach my $item (keys(%$storehash)) {
 4415: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4416:     }
 4417:     $items=~s/\&$//;
 4418:     if (defined($context)) {
 4419:         $items .= ':'.&escape($context);
 4420:     }
 4421:     return &reply("tmpput:$items",$server);
 4422: }
 4423: 
 4424: # ------------------------------------------------------------ tmpget interface
 4425: sub tmpget {
 4426:     my ($token,$server)=@_;
 4427:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4428:     my $rep=&reply("tmpget:$token",$server);
 4429:     my %returnhash;
 4430:     foreach my $item (split(/\&/,$rep)) {
 4431: 	my ($key,$value)=split(/=/,$item);
 4432:         next if ($key =~ /^error: 2 /);
 4433: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4434:     }
 4435:     return %returnhash;
 4436: }
 4437: 
 4438: # ------------------------------------------------------------ tmpget interface
 4439: sub tmpdel {
 4440:     my ($token,$server)=@_;
 4441:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4442:     return &reply("tmpdel:$token",$server);
 4443: }
 4444: 
 4445: # -------------------------------------------------- portfolio access checking
 4446: 
 4447: sub portfolio_access {
 4448:     my ($requrl) = @_;
 4449:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4450:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4451:     if ($result) {
 4452:         my %setters;
 4453:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4454:             my ($startblock,$endblock) =
 4455:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4456:             if ($startblock && $endblock) {
 4457:                 return 'B';
 4458:             }
 4459:         } else {
 4460:             my ($startblock,$endblock) =
 4461:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4462:             if ($startblock && $endblock) {
 4463:                 return 'B';
 4464:             }
 4465:         }
 4466:     }
 4467:     if ($result eq 'ok') {
 4468:        return 'F';
 4469:     } elsif ($result =~ /^[^:]+:guest_/) {
 4470:        return 'A';
 4471:     }
 4472:     return '';
 4473: }
 4474: 
 4475: sub get_portfolio_access {
 4476:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4477: 
 4478:     if (!ref($access_hash)) {
 4479: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4480: 	my %access_controls = &get_access_controls($current_perms,$group,
 4481: 						   $file_name);
 4482: 	$access_hash = $access_controls{$file_name};
 4483:     }
 4484: 
 4485:     my ($public,$guest,@domains,@users,@courses,@groups);
 4486:     my $now = time;
 4487:     if (ref($access_hash) eq 'HASH') {
 4488:         foreach my $key (keys(%{$access_hash})) {
 4489:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4490:             if ($start > $now) {
 4491:                 next;
 4492:             }
 4493:             if ($end && $end<$now) {
 4494:                 next;
 4495:             }
 4496:             if ($scope eq 'public') {
 4497:                 $public = $key;
 4498:                 last;
 4499:             } elsif ($scope eq 'guest') {
 4500:                 $guest = $key;
 4501:             } elsif ($scope eq 'domains') {
 4502:                 push(@domains,$key);
 4503:             } elsif ($scope eq 'users') {
 4504:                 push(@users,$key);
 4505:             } elsif ($scope eq 'course') {
 4506:                 push(@courses,$key);
 4507:             } elsif ($scope eq 'group') {
 4508:                 push(@groups,$key);
 4509:             }
 4510:         }
 4511:         if ($public) {
 4512:             return 'ok';
 4513:         }
 4514:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4515:             if ($guest) {
 4516:                 return $guest;
 4517:             }
 4518:         } else {
 4519:             if (@domains > 0) {
 4520:                 foreach my $domkey (@domains) {
 4521:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4522:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4523:                             return 'ok';
 4524:                         }
 4525:                     }
 4526:                 }
 4527:             }
 4528:             if (@users > 0) {
 4529:                 foreach my $userkey (@users) {
 4530:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4531:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4532:                             if (ref($item) eq 'HASH') {
 4533:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4534:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4535:                                     return 'ok';
 4536:                                 }
 4537:                             }
 4538:                         }
 4539:                     } 
 4540:                 }
 4541:             }
 4542:             my %roleshash;
 4543:             my @courses_and_groups = @courses;
 4544:             push(@courses_and_groups,@groups); 
 4545:             if (@courses_and_groups > 0) {
 4546:                 my (%allgroups,%allroles); 
 4547:                 my ($start,$end,$role,$sec,$group);
 4548:                 foreach my $envkey (%env) {
 4549:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4550:                         my $cid = $2.'_'.$3; 
 4551:                         if ($1 eq 'gr') {
 4552:                             $group = $4;
 4553:                             $allgroups{$cid}{$group} = $env{$envkey};
 4554:                         } else {
 4555:                             if ($4 eq '') {
 4556:                                 $sec = 'none';
 4557:                             } else {
 4558:                                 $sec = $4;
 4559:                             }
 4560:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4561:                         }
 4562:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4563:                         my $cid = $2.'_'.$3;
 4564:                         if ($4 eq '') {
 4565:                             $sec = 'none';
 4566:                         } else {
 4567:                             $sec = $4;
 4568:                         }
 4569:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4570:                     }
 4571:                 }
 4572:                 if (keys(%allroles) == 0) {
 4573:                     return;
 4574:                 }
 4575:                 foreach my $key (@courses_and_groups) {
 4576:                     my %content = %{$$access_hash{$key}};
 4577:                     my $cnum = $content{'number'};
 4578:                     my $cdom = $content{'domain'};
 4579:                     my $cid = $cdom.'_'.$cnum;
 4580:                     if (!exists($allroles{$cid})) {
 4581:                         next;
 4582:                     }    
 4583:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4584:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4585:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4586:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4587:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4588:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4589:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4590:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4591:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4592:                                         if (grep/^all$/,@sections) {
 4593:                                             return 'ok';
 4594:                                         } else {
 4595:                                             if (grep/^$sec$/,@sections) {
 4596:                                                 return 'ok';
 4597:                                             }
 4598:                                         }
 4599:                                     }
 4600:                                 }
 4601:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4602:                                     if (grep/^none$/,@groups) {
 4603:                                         return 'ok';
 4604:                                     }
 4605:                                 } else {
 4606:                                     if (grep/^all$/,@groups) {
 4607:                                         return 'ok';
 4608:                                     } 
 4609:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4610:                                         if (grep/^$group$/,@groups) {
 4611:                                             return 'ok';
 4612:                                         }
 4613:                                     }
 4614:                                 } 
 4615:                             }
 4616:                         }
 4617:                     }
 4618:                 }
 4619:             }
 4620:             if ($guest) {
 4621:                 return $guest;
 4622:             }
 4623:         }
 4624:     }
 4625:     return;
 4626: }
 4627: 
 4628: sub course_group_datechecker {
 4629:     my ($dates,$now,$status) = @_;
 4630:     my ($start,$end) = split(/\./,$dates);
 4631:     if (!$start && !$end) {
 4632:         return 'ok';
 4633:     }
 4634:     if (grep/^active$/,@{$status}) {
 4635:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4636:             return 'ok';
 4637:         }
 4638:     }
 4639:     if (grep/^previous$/,@{$status}) {
 4640:         if ($end > $now ) {
 4641:             return 'ok';
 4642:         }
 4643:     }
 4644:     if (grep/^future$/,@{$status}) {
 4645:         if ($start > $now) {
 4646:             return 'ok';
 4647:         }
 4648:     }
 4649:     return; 
 4650: }
 4651: 
 4652: sub parse_portfolio_url {
 4653:     my ($url) = @_;
 4654: 
 4655:     my ($type,$udom,$unum,$group,$file_name);
 4656:     
 4657:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4658: 	$type = 1;
 4659:         $udom = $1;
 4660:         $unum = $2;
 4661:         $file_name = $3;
 4662:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4663: 	$type = 2;
 4664:         $udom = $1;
 4665:         $unum = $2;
 4666:         $group = $3;
 4667:         $file_name = $3.'/'.$4;
 4668:     }
 4669:     if (wantarray) {
 4670: 	return ($type,$udom,$unum,$file_name,$group);
 4671:     }
 4672:     return $type;
 4673: }
 4674: 
 4675: sub is_portfolio_url {
 4676:     my ($url) = @_;
 4677:     return scalar(&parse_portfolio_url($url));
 4678: }
 4679: 
 4680: sub is_portfolio_file {
 4681:     my ($file) = @_;
 4682:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4683:         return 1;
 4684:     }
 4685:     return;
 4686: }
 4687: 
 4688: sub usertools_access {
 4689:     my ($uname,$udom,$tool,$action,$context) = @_;
 4690:     my ($access,%tools);
 4691:     if ($context eq '') {
 4692:         $context = 'tools';
 4693:     }
 4694:     if ($context eq 'requestcourses') {
 4695:         %tools = (
 4696:                       official   => 1,
 4697:                       unofficial => 1,
 4698:                       community  => 1,
 4699:                  );
 4700:     } else {
 4701:         %tools = (
 4702:                       aboutme   => 1,
 4703:                       blog      => 1,
 4704:                       portfolio => 1,
 4705:                  );
 4706:     }
 4707:     return if (!defined($tools{$tool}));
 4708: 
 4709:     if ((!defined($udom)) || (!defined($uname))) {
 4710:         $udom = $env{'user.domain'};
 4711:         $uname = $env{'user.name'};
 4712:     }
 4713: 
 4714:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4715:         if ($action ne 'reload') {
 4716:             if ($context eq 'requestcourses') {
 4717:                 return $env{'environment.canrequest.'.$tool};
 4718:             } else {
 4719:                 return $env{'environment.availabletools.'.$tool};
 4720:             }
 4721:         }
 4722:     }
 4723: 
 4724:     my ($toolstatus,$inststatus);
 4725: 
 4726:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4727:          ($action ne 'reload')) {
 4728:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4729:         $inststatus = $env{'environment.inststatus'};
 4730:     } else {
 4731:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 4732:         $toolstatus = $userenv{$context.'.'.$tool};
 4733:         $inststatus = $userenv{'inststatus'};
 4734:     }
 4735: 
 4736:     if ($toolstatus ne '') {
 4737:         if ($toolstatus) {
 4738:             $access = 1;
 4739:         } else {
 4740:             $access = 0;
 4741:         }
 4742:         return $access;
 4743:     }
 4744: 
 4745:     my $is_adv = &is_advanced_user($udom,$uname);
 4746:     my %domdef = &get_domain_defaults($udom);
 4747:     if (ref($domdef{$tool}) eq 'HASH') {
 4748:         if ($is_adv) {
 4749:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4750:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4751:                     $access = 1;
 4752:                 } else {
 4753:                     $access = 0;
 4754:                 }
 4755:                 return $access;
 4756:             }
 4757:         }
 4758:         if ($inststatus ne '') {
 4759:             my ($hasaccess,$hasnoaccess);
 4760:             foreach my $affiliation (split(/:/,$inststatus)) {
 4761:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4762:                     if ($domdef{$tool}{$affiliation}) {
 4763:                         $hasaccess = 1;
 4764:                     } else {
 4765:                         $hasnoaccess = 1;
 4766:                     }
 4767:                 }
 4768:             }
 4769:             if ($hasaccess || $hasnoaccess) {
 4770:                 if ($hasaccess) {
 4771:                     $access = 1;
 4772:                 } elsif ($hasnoaccess) {
 4773:                     $access = 0; 
 4774:                 }
 4775:                 return $access;
 4776:             }
 4777:         } else {
 4778:             if ($domdef{$tool}{'default'} ne '') {
 4779:                 if ($domdef{$tool}{'default'}) {
 4780:                     $access = 1;
 4781:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4782:                     $access = 0;
 4783:                 }
 4784:                 return $access;
 4785:             }
 4786:         }
 4787:     } else {
 4788:         if ($context eq 'tools') {
 4789:             $access = 1;
 4790:         } else {
 4791:             $access = 0;
 4792:         }
 4793:         return $access;
 4794:     }
 4795: }
 4796: 
 4797: sub is_advanced_user {
 4798:     my ($udom,$uname) = @_;
 4799:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4800:     my %allroles;
 4801:     my $is_adv;
 4802:     foreach my $role (keys(%roleshash)) {
 4803:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4804:         my $area = '/'.$tdomain.'/'.$trest;
 4805:         if ($sec ne '') {
 4806:             $area .= '/'.$sec;
 4807:         }
 4808:         if (($area ne '') && ($trole ne '')) {
 4809:             my $spec=$trole.'.'.$area;
 4810:             if ($trole =~ /^cr\//) {
 4811:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4812:             } elsif ($trole ne 'gr') {
 4813:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4814:             }
 4815:         }
 4816:     }
 4817:     foreach my $role (keys(%allroles)) {
 4818:         last if ($is_adv);
 4819:         foreach my $item (split(/:/,$allroles{$role})) {
 4820:             if ($item ne '') {
 4821:                 my ($privilege,$restrictions)=split(/&/,$item);
 4822:                 if ($privilege eq 'adv') {
 4823:                     $is_adv = 1;
 4824:                     last;
 4825:                 }
 4826:             }
 4827:         }
 4828:     }
 4829:     return $is_adv;
 4830: }
 4831: 
 4832: # ---------------------------------------------- Custom access rule evaluation
 4833: 
 4834: sub customaccess {
 4835:     my ($priv,$uri)=@_;
 4836:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4837:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4838:     $udom = &LONCAPA::clean_domain($udom);
 4839:     $ucrs = &LONCAPA::clean_username($ucrs);
 4840:     my $access=0;
 4841:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4842: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4843: 	if ($type eq 'user') {
 4844: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4845: 		my ($tdom,$tuname)=split(m{/},$scope);
 4846: 		if ($tdom) {
 4847: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4848: 		}
 4849: 		if ($tuname) {
 4850: 		    if ($tuname ne $env{'user.name'}) { next; }
 4851: 		}
 4852: 		$access=($effect eq 'allow');
 4853: 		last;
 4854: 	    }
 4855: 	} else {
 4856: 	    if ($role) {
 4857: 		if ($role ne $urole) { next; }
 4858: 	    }
 4859: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4860: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4861: 		if ($tdom) {
 4862: 		    if ($tdom ne $udom) { next; }
 4863: 		}
 4864: 		if ($tcrs) {
 4865: 		    if ($tcrs ne $ucrs) { next; }
 4866: 		}
 4867: 		if ($tsec) {
 4868: 		    if ($tsec ne $usec) { next; }
 4869: 		}
 4870: 		$access=($effect eq 'allow');
 4871: 		last;
 4872: 	    }
 4873: 	    if ($realm eq '' && $role eq '') {
 4874: 		$access=($effect eq 'allow');
 4875: 	    }
 4876: 	}
 4877:     }
 4878:     return $access;
 4879: }
 4880: 
 4881: # ------------------------------------------------- Check for a user privilege
 4882: 
 4883: sub allowed {
 4884:     my ($priv,$uri,$symb,$role)=@_;
 4885:     my $ver_orguri=$uri;
 4886:     $uri=&deversion($uri);
 4887:     my $orguri=$uri;
 4888:     $uri=&declutter($uri);
 4889: 
 4890:     if ($priv eq 'evb') {
 4891: # Evade communication block restrictions for specified role in a course
 4892:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4893:             return $1;
 4894:         } else {
 4895:             return;
 4896:         }
 4897:     }
 4898: 
 4899:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4900: # Free bre access to adm and meta resources
 4901:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4902: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4903: 	&& ($priv eq 'bre')) {
 4904: 	return 'F';
 4905:     }
 4906: 
 4907: # Free bre access to user's own portfolio contents
 4908:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4909:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4910: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4911:         my %setters;
 4912:         my ($startblock,$endblock) = 
 4913:             &Apache::loncommon::blockcheck(\%setters,'port');
 4914:         if ($startblock && $endblock) {
 4915:             return 'B';
 4916:         } else {
 4917:             return 'F';
 4918:         }
 4919:     }
 4920: 
 4921: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4922:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4923:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4924:         if (exists($env{'request.course.id'})) {
 4925:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4926:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4927:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4928:                 my $courseprivid=$env{'request.course.id'};
 4929:                 $courseprivid=~s/\_/\//;
 4930:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4931:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4932:                     return $1; 
 4933:                 } else {
 4934:                     if ($env{'request.course.sec'}) {
 4935:                         $courseprivid.='/'.$env{'request.course.sec'};
 4936:                     }
 4937:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4938:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4939:                         return $2;
 4940:                     }
 4941:                 }
 4942:             }
 4943:         }
 4944:     }
 4945: 
 4946: # Free bre to public access
 4947: 
 4948:     if ($priv eq 'bre') {
 4949:         my $copyright=&metadata($uri,'copyright');
 4950: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4951:            return 'F'; 
 4952:         }
 4953:         if ($copyright eq 'priv') {
 4954:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4955: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4956: 		return '';
 4957:             }
 4958:         }
 4959:         if ($copyright eq 'domain') {
 4960:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4961: 	    unless (($env{'user.domain'} eq $1) ||
 4962:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4963: 		return '';
 4964:             }
 4965:         }
 4966:         if ($env{'request.role'}=~ /li\.\//) {
 4967:             # Library role, so allow browsing of resources in this domain.
 4968:             return 'F';
 4969:         }
 4970:         if ($copyright eq 'custom') {
 4971: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4972:         }
 4973:     }
 4974:     # Domain coordinator is trying to create a course
 4975:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4976:         # uri is the requested domain in this case.
 4977:         # comparison to 'request.role.domain' shows if the user has selected
 4978:         # a role of dc for the domain in question.
 4979:         return 'F' if ($uri eq $env{'request.role.domain'});
 4980:     }
 4981: 
 4982:     my $thisallowed='';
 4983:     my $statecond=0;
 4984:     my $courseprivid='';
 4985: 
 4986: # Course
 4987: 
 4988:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4989:        $thisallowed.=$1;
 4990:     }
 4991: 
 4992: # Domain
 4993: 
 4994:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4995:        =~/\Q$priv\E\&([^\:]*)/) {
 4996:        $thisallowed.=$1;
 4997:     }
 4998: 
 4999: # Course: uri itself is a course
 5000:     my $courseuri=$uri;
 5001:     $courseuri=~s/\_(\d)/\/$1/;
 5002:     $courseuri=~s/^([^\/])/\/$1/;
 5003: 
 5004:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5005:        =~/\Q$priv\E\&([^\:]*)/) {
 5006:        $thisallowed.=$1;
 5007:     }
 5008: 
 5009: # URI is an uploaded document for this course, default permissions don't matter
 5010: # not allowing 'edit' access (editupload) to uploaded course docs
 5011:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5012: 	$thisallowed='';
 5013:         my ($match)=&is_on_map($uri);
 5014:         if ($match) {
 5015:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5016:                   =~/\Q$priv\E\&([^\:]*)/) {
 5017:                 $thisallowed.=$1;
 5018:             }
 5019:         } else {
 5020:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5021:             if ($refuri) {
 5022:                 if ($refuri =~ m|^/adm/|) {
 5023:                     $thisallowed='F';
 5024:                 } else {
 5025:                     $refuri=&declutter($refuri);
 5026:                     my ($match) = &is_on_map($refuri);
 5027:                     if ($match) {
 5028:                         $thisallowed='F';
 5029:                     }
 5030:                 }
 5031:             }
 5032:         }
 5033:     }
 5034: 
 5035:     if ($priv eq 'bre'
 5036: 	&& $thisallowed ne 'F' 
 5037: 	&& $thisallowed ne '2'
 5038: 	&& &is_portfolio_url($uri)) {
 5039: 	$thisallowed = &portfolio_access($uri);
 5040:     }
 5041:     
 5042: # Full access at system, domain or course-wide level? Exit.
 5043:     if ($thisallowed=~/F/) {
 5044: 	return 'F';
 5045:     }
 5046: 
 5047: # If this is generating or modifying users, exit with special codes
 5048: 
 5049:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5050: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5051: 	    my ($audom,$auname)=split('/',$uri);
 5052: # no author name given, so this just checks on the general right to make a co-author in this domain
 5053: 	    unless ($auname) { return $thisallowed; }
 5054: # an author name is given, so we are about to actually make a co-author for a certain account
 5055: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5056: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5057: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5058: 	}
 5059: 	return $thisallowed;
 5060:     }
 5061: #
 5062: # Gathered so far: system, domain and course wide privileges
 5063: #
 5064: # Course: See if uri or referer is an individual resource that is part of 
 5065: # the course
 5066: 
 5067:     if ($env{'request.course.id'}) {
 5068: 
 5069:        $courseprivid=$env{'request.course.id'};
 5070:        if ($env{'request.course.sec'}) {
 5071:           $courseprivid.='/'.$env{'request.course.sec'};
 5072:        }
 5073:        $courseprivid=~s/\_/\//;
 5074:        my $checkreferer=1;
 5075:        my ($match,$cond)=&is_on_map($uri);
 5076:        if ($match) {
 5077:            $statecond=$cond;
 5078:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5079:                =~/\Q$priv\E\&([^\:]*)/) {
 5080:                $thisallowed.=$1;
 5081:                $checkreferer=0;
 5082:            }
 5083:        }
 5084:        
 5085:        if ($checkreferer) {
 5086: 	  my $refuri=$env{'httpref.'.$orguri};
 5087:             unless ($refuri) {
 5088:                 foreach my $key (keys(%env)) {
 5089: 		    if ($key=~/^httpref\..*\*/) {
 5090: 			my $pattern=$key;
 5091:                         $pattern=~s/^httpref\.\/res\///;
 5092:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5093:                         $pattern=~s/\//\\\//g;
 5094:                         if ($orguri=~/$pattern/) {
 5095: 			    $refuri=$env{$key};
 5096:                         }
 5097:                     }
 5098:                 }
 5099:             }
 5100: 
 5101:          if ($refuri) { 
 5102: 	  $refuri=&declutter($refuri);
 5103:           my ($match,$cond)=&is_on_map($refuri);
 5104:             if ($match) {
 5105:               my $refstatecond=$cond;
 5106:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5107:                   =~/\Q$priv\E\&([^\:]*)/) {
 5108:                   $thisallowed.=$1;
 5109:                   $uri=$refuri;
 5110:                   $statecond=$refstatecond;
 5111:               }
 5112:           }
 5113:         }
 5114:        }
 5115:    }
 5116: 
 5117: #
 5118: # Gathered now: all privileges that could apply, and condition number
 5119: # 
 5120: #
 5121: # Full or no access?
 5122: #
 5123: 
 5124:     if ($thisallowed=~/F/) {
 5125: 	return 'F';
 5126:     }
 5127: 
 5128:     unless ($thisallowed) {
 5129:         return '';
 5130:     }
 5131: 
 5132: # Restrictions exist, deal with them
 5133: #
 5134: #   C:according to course preferences
 5135: #   R:according to resource settings
 5136: #   L:unless locked
 5137: #   X:according to user session state
 5138: #
 5139: 
 5140: # Possibly locked functionality, check all courses
 5141: # Locks might take effect only after 10 minutes cache expiration for other
 5142: # courses, and 2 minutes for current course
 5143: 
 5144:     my $envkey;
 5145:     if ($thisallowed=~/L/) {
 5146:         foreach $envkey (keys(%env)) {
 5147:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5148:                my $courseid=$2;
 5149:                my $roleid=$1.'.'.$2;
 5150:                $courseid=~s/^\///;
 5151:                my $expiretime=600;
 5152:                if ($env{'request.role'} eq $roleid) {
 5153: 		  $expiretime=120;
 5154:                }
 5155: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5156:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5157:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5158: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5159:                }
 5160:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5161:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5162: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5163:                        &log($env{'user.domain'},$env{'user.name'},
 5164:                             $env{'user.home'},
 5165:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5166:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5167:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5168: 		       return '';
 5169:                    }
 5170:                }
 5171:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5172:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5173: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5174:                        &log($env{'user.domain'},$env{'user.name'},
 5175:                             $env{'user.home'},
 5176:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5177:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5178:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5179: 		       return '';
 5180:                    }
 5181:                }
 5182: 	   }
 5183:        }
 5184:     }
 5185:    
 5186: #
 5187: # Rest of the restrictions depend on selected course
 5188: #
 5189: 
 5190:     unless ($env{'request.course.id'}) {
 5191: 	if ($thisallowed eq 'A') {
 5192: 	    return 'A';
 5193:         } elsif ($thisallowed eq 'B') {
 5194:             return 'B';
 5195: 	} else {
 5196: 	    return '1';
 5197: 	}
 5198:     }
 5199: 
 5200: #
 5201: # Now user is definitely in a course
 5202: #
 5203: 
 5204: 
 5205: # Course preferences
 5206: 
 5207:    if ($thisallowed=~/C/) {
 5208:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5209:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5210:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5211: 	   =~/\Q$rolecode\E/) {
 5212: 	   if ($priv ne 'pch') { 
 5213: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5214: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5215: 			$env{'request.course.id'});
 5216: 	   }
 5217:            return '';
 5218:        }
 5219: 
 5220:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5221: 	   =~/\Q$unamedom\E/) {
 5222: 	   if ($priv ne 'pch') { 
 5223: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5224: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5225: 			$env{'request.course.id'});
 5226: 	   }
 5227:            return '';
 5228:        }
 5229:    }
 5230: 
 5231: # Resource preferences
 5232: 
 5233:    if ($thisallowed=~/R/) {
 5234:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5235:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5236: 	   if ($priv ne 'pch') { 
 5237: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5238: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5239: 	   }
 5240: 	   return '';
 5241:        }
 5242:    }
 5243: 
 5244: # Restricted by state or randomout?
 5245: 
 5246:    if ($thisallowed=~/X/) {
 5247:       if ($env{'acc.randomout'}) {
 5248: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5249:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5250:             return ''; 
 5251:          }
 5252:       }
 5253:       if (&condval($statecond)) {
 5254: 	 return '2';
 5255:       } else {
 5256:          return '';
 5257:       }
 5258:    }
 5259: 
 5260:     if ($thisallowed eq 'A') {
 5261: 	return 'A';
 5262:     } elsif ($thisallowed eq 'B') {
 5263:         return 'B';
 5264:     }
 5265:    return 'F';
 5266: }
 5267: 
 5268: sub split_uri_for_cond {
 5269:     my $uri=&deversion(&declutter(shift));
 5270:     my @uriparts=split(/\//,$uri);
 5271:     my $filename=pop(@uriparts);
 5272:     my $pathname=join('/',@uriparts);
 5273:     return ($pathname,$filename);
 5274: }
 5275: # --------------------------------------------------- Is a resource on the map?
 5276: 
 5277: sub is_on_map {
 5278:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5279:     #Trying to find the conditional for the file
 5280:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5281: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5282:     if ($match) {
 5283: 	return (1,$1);
 5284:     } else {
 5285: 	return (0,0);
 5286:     }
 5287: }
 5288: 
 5289: # --------------------------------------------------------- Get symb from alias
 5290: 
 5291: sub get_symb_from_alias {
 5292:     my $symb=shift;
 5293:     my ($map,$resid,$url)=&decode_symb($symb);
 5294: # Already is a symb
 5295:     if ($url) { return $symb; }
 5296: # Must be an alias
 5297:     my $aliassymb='';
 5298:     my %bighash;
 5299:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5300:                             &GDBM_READER(),0640)) {
 5301:         my $rid=$bighash{'mapalias_'.$symb};
 5302: 	if ($rid) {
 5303: 	    my ($mapid,$resid)=split(/\./,$rid);
 5304: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5305: 				    $resid,$bighash{'src_'.$rid});
 5306: 	}
 5307:         untie %bighash;
 5308:     }
 5309:     return $aliassymb;
 5310: }
 5311: 
 5312: # ----------------------------------------------------------------- Define Role
 5313: 
 5314: sub definerole {
 5315:   if (allowed('mcr','/')) {
 5316:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5317:     foreach my $role (split(':',$sysrole)) {
 5318: 	my ($crole,$cqual)=split(/\&/,$role);
 5319:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5320:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5321: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5322:                return "refused:s:$crole&$cqual"; 
 5323:             }
 5324:         }
 5325:     }
 5326:     foreach my $role (split(':',$domrole)) {
 5327: 	my ($crole,$cqual)=split(/\&/,$role);
 5328:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5329:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5330: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5331:                return "refused:d:$crole&$cqual"; 
 5332:             }
 5333:         }
 5334:     }
 5335:     foreach my $role (split(':',$courole)) {
 5336: 	my ($crole,$cqual)=split(/\&/,$role);
 5337:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5338:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5339: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5340:                return "refused:c:$crole&$cqual"; 
 5341:             }
 5342:         }
 5343:     }
 5344:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5345:                 "$env{'user.domain'}:$env{'user.name'}:".
 5346: 	        "rolesdef_$rolename=".
 5347:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5348:     return reply($command,$env{'user.home'});
 5349:   } else {
 5350:     return 'refused';
 5351:   }
 5352: }
 5353: 
 5354: # ---------------- Make a metadata query against the network of library servers
 5355: 
 5356: sub metadata_query {
 5357:     my ($query,$custom,$customshow,$server_array)=@_;
 5358:     my %rhash;
 5359:     my %libserv = &all_library();
 5360:     my @server_list = (defined($server_array) ? @$server_array
 5361:                                               : keys(%libserv) );
 5362:     for my $server (@server_list) {
 5363: 	unless ($custom or $customshow) {
 5364: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5365: 	    $rhash{$server}=$reply;
 5366: 	}
 5367: 	else {
 5368: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5369: 			     &escape($custom).':'.&escape($customshow),
 5370: 			     $server);
 5371: 	    $rhash{$server}=$reply;
 5372: 	}
 5373:     }
 5374:     return \%rhash;
 5375: }
 5376: 
 5377: # ----------------------------------------- Send log queries and wait for reply
 5378: 
 5379: sub log_query {
 5380:     my ($uname,$udom,$query,%filters)=@_;
 5381:     my $uhome=&homeserver($uname,$udom);
 5382:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5383:     my $uhost=&hostname($uhome);
 5384:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5385:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5386:                        $uhome);
 5387:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5388:     return get_query_reply($queryid);
 5389: }
 5390: 
 5391: # -------------------------- Update MySQL table for portfolio file
 5392: 
 5393: sub update_portfolio_table {
 5394:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5395:     if ($group ne '') {
 5396:         $file_name =~s /^\Q$group\E//;
 5397:     }
 5398:     my $homeserver = &homeserver($uname,$udom);
 5399:     my $queryid=
 5400:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5401:                ':'.&escape($file_name).':'.$action,$homeserver);
 5402:     my $reply = &get_query_reply($queryid);
 5403:     return $reply;
 5404: }
 5405: 
 5406: # -------------------------- Update MySQL allusers table
 5407: 
 5408: sub update_allusers_table {
 5409:     my ($uname,$udom,$names) = @_;
 5410:     my $homeserver = &homeserver($uname,$udom);
 5411:     my $queryid=
 5412:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5413:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5414:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5415:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5416:                'generation='.&escape($names->{'generation'}).'%%'.
 5417:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5418:                'id='.&escape($names->{'id'}),$homeserver);
 5419:     my $reply = &get_query_reply($queryid);
 5420:     return $reply;
 5421: }
 5422: 
 5423: # ------- Request retrieval of institutional classlists for course(s)
 5424: 
 5425: sub fetch_enrollment_query {
 5426:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5427:     my $homeserver;
 5428:     my $maxtries = 1;
 5429:     if ($context eq 'automated') {
 5430:         $homeserver = $perlvar{'lonHostID'};
 5431:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5432:     } else {
 5433:         $homeserver = &homeserver($cnum,$dom);
 5434:     }
 5435:     my $host=&hostname($homeserver);
 5436:     my $cmd = '';
 5437:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5438:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5439:     }
 5440:     $cmd =~ s/%%$//;
 5441:     $cmd = &escape($cmd);
 5442:     my $query = 'fetchenrollment';
 5443:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5444:     unless ($queryid=~/^\Q$host\E\_/) { 
 5445:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5446:         return 'error: '.$queryid;
 5447:     }
 5448:     my $reply = &get_query_reply($queryid);
 5449:     my $tries = 1;
 5450:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5451:         $reply = &get_query_reply($queryid);
 5452:         $tries ++;
 5453:     }
 5454:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5455:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5456:     } else {
 5457:         my @responses = split(/:/,$reply);
 5458:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5459:             foreach my $line (@responses) {
 5460:                 my ($key,$value) = split(/=/,$line,2);
 5461:                 $$replyref{$key} = $value;
 5462:             }
 5463:         } else {
 5464:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5465:             foreach my $line (@responses) {
 5466:                 my ($key,$value) = split(/=/,$line);
 5467:                 $$replyref{$key} = $value;
 5468:                 if ($value > 0) {
 5469:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5470:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5471:                         my $destname = $pathname.'/'.$filename;
 5472:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5473:                         if ($xml_classlist =~ /^error/) {
 5474:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5475:                         } else {
 5476:                             if ( open(FILE,">$destname") ) {
 5477:                                 print FILE &unescape($xml_classlist);
 5478:                                 close(FILE);
 5479:                             } else {
 5480:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5481:                             }
 5482:                         }
 5483:                     }
 5484:                 }
 5485:             }
 5486:         }
 5487:         return 'ok';
 5488:     }
 5489:     return 'error';
 5490: }
 5491: 
 5492: sub get_query_reply {
 5493:     my $queryid=shift;
 5494:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5495:     my $reply='';
 5496:     for (1..100) {
 5497: 	sleep 2;
 5498:         if (-e $replyfile.'.end') {
 5499: 	    if (open(my $fh,$replyfile)) {
 5500: 		$reply = join('',<$fh>);
 5501: 		close($fh);
 5502: 	   } else { return 'error: reply_file_error'; }
 5503:            return &unescape($reply);
 5504: 	}
 5505:     }
 5506:     return 'timeout:'.$queryid;
 5507: }
 5508: 
 5509: sub courselog_query {
 5510: #
 5511: # possible filters:
 5512: # url: url or symb
 5513: # username
 5514: # domain
 5515: # action: view, submit, grade
 5516: # start: timestamp
 5517: # end: timestamp
 5518: #
 5519:     my (%filters)=@_;
 5520:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5521:     if ($filters{'url'}) {
 5522: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5523:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5524:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5525:     }
 5526:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5527:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5528:     return &log_query($cname,$cdom,'courselog',%filters);
 5529: }
 5530: 
 5531: sub userlog_query {
 5532: #
 5533: # possible filters:
 5534: # action: log check role
 5535: # start: timestamp
 5536: # end: timestamp
 5537: #
 5538:     my ($uname,$udom,%filters)=@_;
 5539:     return &log_query($uname,$udom,'userlog',%filters);
 5540: }
 5541: 
 5542: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5543: 
 5544: sub auto_run {
 5545:     my ($cnum,$cdom) = @_;
 5546:     my $response = 0;
 5547:     my $settings;
 5548:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5549:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5550:         $settings = $domconfig{'autoenroll'};
 5551:         if ($settings->{'run'} eq '1') {
 5552:             $response = 1;
 5553:         }
 5554:     } else {
 5555:         my $homeserver;
 5556:         if (&is_course($cdom,$cnum)) {
 5557:             $homeserver = &homeserver($cnum,$cdom);
 5558:         } else {
 5559:             $homeserver = &domain($cdom,'primary');
 5560:         }
 5561:         if ($homeserver ne 'no_host') {
 5562:             $response = &reply('autorun:'.$cdom,$homeserver);
 5563:         }
 5564:     }
 5565:     return $response;
 5566: }
 5567: 
 5568: sub auto_get_sections {
 5569:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5570:     my $homeserver;
 5571:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5572:         $homeserver = &homeserver($cnum,$cdom);
 5573:     }
 5574:     if (!defined($homeserver)) { 
 5575:         if ($cdom =~ /^$match_domain$/) {
 5576:             $homeserver = &domain($cdom,'primary');
 5577:         }
 5578:     }
 5579:     my @secs;
 5580:     if (defined($homeserver)) {
 5581:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5582:         unless ($response eq 'refused') {
 5583:             @secs = split(/:/,$response);
 5584:         }
 5585:     }
 5586:     return @secs;
 5587: }
 5588: 
 5589: sub auto_new_course {
 5590:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5591:     my $homeserver = &homeserver($cnum,$cdom);
 5592:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5593:     return $response;
 5594: }
 5595: 
 5596: sub auto_validate_courseID {
 5597:     my ($cnum,$cdom,$inst_course_id) = @_;
 5598:     my $homeserver = &homeserver($cnum,$cdom);
 5599:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5600:     return $response;
 5601: }
 5602: 
 5603: sub auto_validate_instcode {
 5604:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5605:     my ($homeserver,$response);
 5606:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5607:         $homeserver = &homeserver($cnum,$cdom);
 5608:     }
 5609:     if (!defined($homeserver)) {
 5610:         if ($cdom =~ /^$match_domain$/) {
 5611:             $homeserver = &domain($cdom,'primary');
 5612:         }
 5613:     }
 5614:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5615:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5616:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 5617:     return ($outcome,$description);
 5618: }
 5619: 
 5620: sub auto_create_password {
 5621:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5622:     my ($homeserver,$response);
 5623:     my $create_passwd = 0;
 5624:     my $authchk = '';
 5625:     if ($udom =~ /^$match_domain$/) {
 5626:         $homeserver = &domain($udom,'primary');
 5627:     }
 5628:     if ($homeserver eq '') {
 5629:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5630:             $homeserver = &homeserver($cnum,$cdom);
 5631:         }
 5632:     }
 5633:     if ($homeserver eq '') {
 5634:         $authchk = 'nodomain';
 5635:     } else {
 5636:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5637:         if ($response eq 'refused') {
 5638:             $authchk = 'refused';
 5639:         } else {
 5640:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5641:         }
 5642:     }
 5643:     return ($authparam,$create_passwd,$authchk);
 5644: }
 5645: 
 5646: sub auto_photo_permission {
 5647:     my ($cnum,$cdom,$students) = @_;
 5648:     my $homeserver = &homeserver($cnum,$cdom);
 5649:     my ($outcome,$perm_reqd,$conditions) = 
 5650: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5651:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5652: 	return (undef,undef);
 5653:     }
 5654:     return ($outcome,$perm_reqd,$conditions);
 5655: }
 5656: 
 5657: sub auto_checkphotos {
 5658:     my ($uname,$udom,$pid) = @_;
 5659:     my $homeserver = &homeserver($uname,$udom);
 5660:     my ($result,$resulttype);
 5661:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5662: 				   &escape($uname).':'.&escape($pid),
 5663: 				   $homeserver));
 5664:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5665: 	return (undef,undef);
 5666:     }
 5667:     if ($outcome) {
 5668:         ($result,$resulttype) = split(/:/,$outcome);
 5669:     } 
 5670:     return ($result,$resulttype);
 5671: }
 5672: 
 5673: sub auto_photochoice {
 5674:     my ($cnum,$cdom) = @_;
 5675:     my $homeserver = &homeserver($cnum,$cdom);
 5676:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5677: 						       &escape($cdom),
 5678: 						       $homeserver)));
 5679:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5680: 	return (undef,undef);
 5681:     }
 5682:     return ($update,$comment);
 5683: }
 5684: 
 5685: sub auto_photoupdate {
 5686:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5687:     my $homeserver = &homeserver($cnum,$dom);
 5688:     my $host=&hostname($homeserver);
 5689:     my $cmd = '';
 5690:     my $maxtries = 1;
 5691:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5692:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5693:     }
 5694:     $cmd =~ s/%%$//;
 5695:     $cmd = &escape($cmd);
 5696:     my $query = 'institutionalphotos';
 5697:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5698:     unless ($queryid=~/^\Q$host\E\_/) {
 5699:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5700:         return 'error: '.$queryid;
 5701:     }
 5702:     my $reply = &get_query_reply($queryid);
 5703:     my $tries = 1;
 5704:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5705:         $reply = &get_query_reply($queryid);
 5706:         $tries ++;
 5707:     }
 5708:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5709:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5710:     } else {
 5711:         my @responses = split(/:/,$reply);
 5712:         my $outcome = shift(@responses); 
 5713:         foreach my $item (@responses) {
 5714:             my ($key,$value) = split(/=/,$item);
 5715:             $$photo{$key} = $value;
 5716:         }
 5717:         return $outcome;
 5718:     }
 5719:     return 'error';
 5720: }
 5721: 
 5722: sub auto_instcode_format {
 5723:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5724: 	$cat_order) = @_;
 5725:     my $courses = '';
 5726:     my @homeservers;
 5727:     if ($caller eq 'global') {
 5728: 	my %servers = &get_servers($codedom,'library');
 5729: 	foreach my $tryserver (keys(%servers)) {
 5730: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5731: 		push(@homeservers,$tryserver);
 5732: 	    }
 5733:         }
 5734:     } elsif ($caller eq 'requests') {
 5735:         if ($codedom =~ /^$match_domain$/) {
 5736:             my $chome = &domain($codedom,'primary');
 5737:             unless ($chome eq 'no_host') {
 5738:                 push(@homeservers,$chome);
 5739:             }
 5740:         }
 5741:     } else {
 5742:         push(@homeservers,&homeserver($caller,$codedom));
 5743:     }
 5744:     foreach my $code (keys(%{$instcodes})) {
 5745:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5746:     }
 5747:     chop($courses);
 5748:     my $ok_response = 0;
 5749:     my $response;
 5750:     while (@homeservers > 0 && $ok_response == 0) {
 5751:         my $server = shift(@homeservers); 
 5752:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5753:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5754:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5755: 		split(/:/,$response);
 5756:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5757:             push(@{$codetitles},&str2array($codetitles_str));
 5758:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5759:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5760:             $ok_response = 1;
 5761:         }
 5762:     }
 5763:     if ($ok_response) {
 5764:         return 'ok';
 5765:     } else {
 5766:         return $response;
 5767:     }
 5768: }
 5769: 
 5770: sub auto_instcode_defaults {
 5771:     my ($domain,$returnhash,$code_order) = @_;
 5772:     my @homeservers;
 5773: 
 5774:     my %servers = &get_servers($domain,'library');
 5775:     foreach my $tryserver (keys(%servers)) {
 5776: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5777: 	    push(@homeservers,$tryserver);
 5778: 	}
 5779:     }
 5780: 
 5781:     my $response;
 5782:     foreach my $server (@homeservers) {
 5783:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5784:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5785: 	
 5786: 	foreach my $pair (split(/\&/,$response)) {
 5787: 	    my ($name,$value)=split(/\=/,$pair);
 5788: 	    if ($name eq 'code_order') {
 5789: 		@{$code_order} = split(/\&/,&unescape($value));
 5790: 	    } else {
 5791: 		$returnhash->{&unescape($name)}=&unescape($value);
 5792: 	    }
 5793: 	}
 5794: 	return 'ok';
 5795:     }
 5796: 
 5797:     return $response;
 5798: }
 5799: 
 5800: sub auto_possible_instcodes {
 5801:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 5802:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 5803:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 5804:         return;
 5805:     }
 5806:     my (@homeservers,$uhome);
 5807:     if (defined(&domain($domain,'primary'))) {
 5808:         $uhome=&domain($domain,'primary');
 5809:         push(@homeservers,&domain($domain,'primary'));
 5810:     } else {
 5811:         my %servers = &get_servers($domain,'library');
 5812:         foreach my $tryserver (keys(%servers)) {
 5813:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5814:                 push(@homeservers,$tryserver);
 5815:             }
 5816:         }
 5817:     }
 5818:     my $response;
 5819:     foreach my $server (@homeservers) {
 5820:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 5821:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5822:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 5823:             split(':',$response);
 5824:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 5825:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 5826:         foreach my $item (split('&',$cat_title)) {   
 5827:             my ($name,$value)=split('=',$item);
 5828:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 5829:         }
 5830:         foreach my $item (split('&',$cat_order)) {
 5831:             my ($name,$value)=split('=',$item);
 5832:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 5833:         }
 5834:         return 'ok';
 5835:     }
 5836:     return $response;
 5837: }
 5838: 
 5839: sub auto_courserequest_checks {
 5840:     my ($dom) = @_;
 5841:     my ($homeserver,%validations);
 5842:     if ($dom =~ /^$match_domain$/) {
 5843:         $homeserver = &domain($dom,'primary');
 5844:     }
 5845:     unless ($homeserver eq 'no_host') {
 5846:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 5847:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 5848:             my @items = split(/&/,$response);
 5849:             foreach my $item (@items) {
 5850:                 my ($key,$value) = split('=',$item);
 5851:                 $validations{&unescape($key)} = &thaw_unescape($value);
 5852:             }
 5853:         }
 5854:     }
 5855:     return %validations; 
 5856: }
 5857: 
 5858: sub auto_courserequest_validation {
 5859:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 5860:     my ($homeserver,$response);
 5861:     if ($dom =~ /^$match_domain$/) {
 5862:         $homeserver = &domain($dom,'primary');
 5863:     }
 5864:     unless ($homeserver eq 'no_host') {  
 5865:           
 5866:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 5867:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 5868:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 5869:                                     $homeserver));
 5870:     }
 5871:     return $response;
 5872: }
 5873: 
 5874: sub auto_validate_class_sec {
 5875:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5876:     my $homeserver = &homeserver($cnum,$cdom);
 5877:     my $ownerlist;
 5878:     if (ref($owners) eq 'ARRAY') {
 5879:         $ownerlist = join(',',@{$owners});
 5880:     } else {
 5881:         $ownerlist = $owners;
 5882:     }
 5883:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5884:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5885:     return $response;
 5886: }
 5887: 
 5888: # ------------------------------------------------------- Course Group routines
 5889: 
 5890: sub get_coursegroups {
 5891:     my ($cdom,$cnum,$group,$namespace) = @_;
 5892:     return(&dump($namespace,$cdom,$cnum,$group));
 5893: }
 5894: 
 5895: sub modify_coursegroup {
 5896:     my ($cdom,$cnum,$groupsettings) = @_;
 5897:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5898: }
 5899: 
 5900: sub toggle_coursegroup_status {
 5901:     my ($cdom,$cnum,$group,$action) = @_;
 5902:     my ($from_namespace,$to_namespace);
 5903:     if ($action eq 'delete') {
 5904:         $from_namespace = 'coursegroups';
 5905:         $to_namespace = 'deleted_groups';
 5906:     } else {
 5907:         $from_namespace = 'deleted_groups';
 5908:         $to_namespace = 'coursegroups';
 5909:     }
 5910:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5911:     if (my $tmp = &error(%curr_group)) {
 5912:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5913:         return ('read error',$tmp);
 5914:     } else {
 5915:         my %savedsettings = %curr_group; 
 5916:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5917:         my $deloutcome;
 5918:         if ($result eq 'ok') {
 5919:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5920:         } else {
 5921:             return ('write error',$result);
 5922:         }
 5923:         if ($deloutcome eq 'ok') {
 5924:             return 'ok';
 5925:         } else {
 5926:             return ('delete error',$deloutcome);
 5927:         }
 5928:     }
 5929: }
 5930: 
 5931: sub modify_group_roles {
 5932:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5933:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5934:     my $role = 'gr/'.&escape($userprivs);
 5935:     my ($uname,$udom) = split(/:/,$user);
 5936:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5937:     if ($result eq 'ok') {
 5938:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5939:     }
 5940:     return $result;
 5941: }
 5942: 
 5943: sub modify_coursegroup_membership {
 5944:     my ($cdom,$cnum,$membership) = @_;
 5945:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5946:     return $result;
 5947: }
 5948: 
 5949: sub get_active_groups {
 5950:     my ($udom,$uname,$cdom,$cnum) = @_;
 5951:     my $now = time;
 5952:     my %groups = ();
 5953:     foreach my $key (keys(%env)) {
 5954:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5955:             my ($start,$end) = split(/\./,$env{$key});
 5956:             if (($end!=0) && ($end<$now)) { next; }
 5957:             if (($start!=0) && ($start>$now)) { next; }
 5958:             if ($1 eq $cdom && $2 eq $cnum) {
 5959:                 $groups{$3} = $env{$key} ;
 5960:             }
 5961:         }
 5962:     }
 5963:     return %groups;
 5964: }
 5965: 
 5966: sub get_group_membership {
 5967:     my ($cdom,$cnum,$group) = @_;
 5968:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5969: }
 5970: 
 5971: sub get_users_groups {
 5972:     my ($udom,$uname,$courseid) = @_;
 5973:     my @usersgroups;
 5974:     my $cachetime=1800;
 5975: 
 5976:     my $hashid="$udom:$uname:$courseid";
 5977:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5978:     if (defined($cached)) {
 5979:         @usersgroups = split(/:/,$grouplist);
 5980:     } else {  
 5981:         $grouplist = '';
 5982:         my $courseurl = &courseid_to_courseurl($courseid);
 5983:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5984:         my $access_end = $env{'course.'.$courseid.
 5985:                               '.default_enrollment_end_date'};
 5986:         my $now = time;
 5987:         foreach my $key (keys(%roleshash)) {
 5988:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5989:                 my $group = $1;
 5990:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5991:                     my $start = $2;
 5992:                     my $end = $1;
 5993:                     if ($start == -1) { next; } # deleted from group
 5994:                     if (($start!=0) && ($start>$now)) { next; }
 5995:                     if (($end!=0) && ($end<$now)) {
 5996:                         if ($access_end && $access_end < $now) {
 5997:                             if ($access_end - $end < 86400) {
 5998:                                 push(@usersgroups,$group);
 5999:                             }
 6000:                         }
 6001:                         next;
 6002:                     }
 6003:                     push(@usersgroups,$group);
 6004:                 }
 6005:             }
 6006:         }
 6007:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6008:         $grouplist = join(':',@usersgroups);
 6009:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6010:     }
 6011:     return @usersgroups;
 6012: }
 6013: 
 6014: sub devalidate_getgroups_cache {
 6015:     my ($udom,$uname,$cdom,$cnum)=@_;
 6016:     my $courseid = $cdom.'_'.$cnum;
 6017: 
 6018:     my $hashid="$udom:$uname:$courseid";
 6019:     &devalidate_cache_new('getgroups',$hashid);
 6020: }
 6021: 
 6022: # ------------------------------------------------------------------ Plain Text
 6023: 
 6024: sub plaintext {
 6025:     my ($short,$type,$cid,$forcedefault) = @_;
 6026:     if ($short =~ /^cr/) {
 6027: 	return (split('/',$short))[-1];
 6028:     }
 6029:     if (!defined($cid)) {
 6030:         $cid = $env{'request.course.id'};
 6031:     }
 6032:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 6033:         unless ($forcedefault) {
 6034:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6035:             &Apache::lonlocal::mt_escape(\$roletext);
 6036:             return &Apache::lonlocal::mt($roletext);
 6037:         }
 6038:     }
 6039:     my %rolenames = (
 6040:                       Course    => 'std',
 6041:                       Community => 'alt1',
 6042:                     );
 6043:     if (defined($type) && 
 6044:          defined($rolenames{$type}) && 
 6045:          defined($prp{$short}{$rolenames{$type}})) {
 6046:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6047:     } else {
 6048:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 6049:     }
 6050: }
 6051: 
 6052: # ----------------------------------------------------------------- Assign Role
 6053: 
 6054: sub assignrole {
 6055:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6056:         $context)=@_;
 6057:     my $mrole;
 6058:     if ($role =~ /^cr\//) {
 6059:         my $cwosec=$url;
 6060:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6061: 	unless (&allowed('ccr',$cwosec)) {
 6062:            my $refused = 1;
 6063:            if ($context eq 'requestcourses') {
 6064:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 6065:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 6066:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 6067:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6068:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6069:                            if ($crsenv{'internal.courseowner'} eq
 6070:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 6071:                                $refused = '';
 6072:                            }
 6073:                        }
 6074:                    }
 6075:                }
 6076:            }
 6077:            if ($refused) {
 6078:                &logthis('Refused custom assignrole: '.
 6079:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 6080:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 6081:                return 'refused';
 6082:            }
 6083:         }
 6084:         $mrole='cr';
 6085:     } elsif ($role =~ /^gr\//) {
 6086:         my $cwogrp=$url;
 6087:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 6088:         unless (&allowed('mdg',$cwogrp)) {
 6089:             &logthis('Refused group assignrole: '.
 6090:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6091:                     $env{'user.name'}.' at '.$env{'user.domain'});
 6092:             return 'refused';
 6093:         }
 6094:         $mrole='gr';
 6095:     } else {
 6096:         my $cwosec=$url;
 6097:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6098:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 6099:             my $refused;
 6100:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 6101:                 if (!(&allowed('c'.$role,$url))) {
 6102:                     $refused = 1;
 6103:                 }
 6104:             } else {
 6105:                 $refused = 1;
 6106:             }
 6107:             if ($refused) {
 6108:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6109:                     $refused = '';
 6110:                 } elsif ($context eq 'requestcourses') {
 6111:                     my @possroles = ('st','ta','ep','in','cc');
 6112:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 6113:                         my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6114:                         my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6115:                         if ($crsenv{'internal.courseowner'} eq 
 6116:                              $env{'user.name'}.':'.$env{'user.domain'}) {
 6117:                             $refused = '';
 6118:                         }
 6119:                     }
 6120:                 }
 6121:                 if ($refused) {
 6122:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6123:                              ' '.$role.' '.$end.' '.$start.' by '.
 6124: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6125:                     return 'refused';
 6126:                 }
 6127:             }
 6128:         }
 6129:         $mrole=$role;
 6130:     }
 6131:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6132:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6133:     if ($end) { $command.='_'.$end; }
 6134:     if ($start) {
 6135: 	if ($end) { 
 6136:            $command.='_'.$start; 
 6137:         } else {
 6138:            $command.='_0_'.$start;
 6139:         }
 6140:     }
 6141:     my $origstart = $start;
 6142:     my $origend = $end;
 6143:     my $delflag;
 6144: # actually delete
 6145:     if ($deleteflag) {
 6146: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6147: # modify command to delete the role
 6148:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6149:                 "$udom:$uname:$url".'_'."$mrole";
 6150: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6151: # set start and finish to negative values for userrolelog
 6152:            $start=-1;
 6153:            $end=-1;
 6154:            $delflag = 1;
 6155:         }
 6156:     }
 6157: # send command
 6158:     my $answer=&reply($command,&homeserver($uname,$udom));
 6159: # log new user role if status is ok
 6160:     if ($answer eq 'ok') {
 6161: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6162: # for course roles, perform group memberships changes triggered by role change.
 6163:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6164:         unless ($role =~ /^gr/) {
 6165:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6166:                                              $origstart,$selfenroll,$context);
 6167:         }
 6168:     }
 6169:     return $answer;
 6170: }
 6171: 
 6172: # -------------------------------------------------- Modify user authentication
 6173: # Overrides without validation
 6174: 
 6175: sub modifyuserauth {
 6176:     my ($udom,$uname,$umode,$upass)=@_;
 6177:     my $uhome=&homeserver($uname,$udom);
 6178:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6179:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6180:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6181:              ' in domain '.$env{'request.role.domain'});  
 6182:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6183: 		     &escape($upass),$uhome);
 6184:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6185:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6186:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6187:     &log($udom,,$uname,$uhome,
 6188:         'Authentication changed by '.$env{'user.domain'}.', '.
 6189:                                      $env{'user.name'}.', '.$umode.
 6190:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6191:     unless ($reply eq 'ok') {
 6192:         &logthis('Authentication mode error: '.$reply);
 6193: 	return 'error: '.$reply;
 6194:     }   
 6195:     return 'ok';
 6196: }
 6197: 
 6198: # --------------------------------------------------------------- Modify a user
 6199: 
 6200: sub modifyuser {
 6201:     my ($udom,    $uname, $uid,
 6202:         $umode,   $upass, $first,
 6203:         $middle,  $last,  $gene,
 6204:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6205:     $udom= &LONCAPA::clean_domain($udom);
 6206:     $uname=&LONCAPA::clean_username($uname);
 6207:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6208:              $umode.', '.$first.', '.$middle.', '.
 6209: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6210:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6211:                                      ' desiredhome not specified'). 
 6212:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6213:              ' in domain '.$env{'request.role.domain'});
 6214:     my $uhome=&homeserver($uname,$udom,'true');
 6215: # ----------------------------------------------------------------- Create User
 6216:     if (($uhome eq 'no_host') && 
 6217: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6218:         my $unhome='';
 6219:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6220:             $unhome = $desiredhome;
 6221: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6222: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6223:         } else { # load balancing routine for determining $unhome
 6224:             my $loadm=10000000;
 6225: 	    my %servers = &get_servers($udom,'library');
 6226: 	    foreach my $tryserver (keys(%servers)) {
 6227: 		my $answer=reply('load',$tryserver);
 6228: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6229: 		    $loadm=$answer;
 6230: 		    $unhome=$tryserver;
 6231: 		}
 6232: 	    }
 6233:         }
 6234:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6235: 	    return 'error: unable to find a home server for '.$uname.
 6236:                    ' in domain '.$udom;
 6237:         }
 6238:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6239:                          &escape($upass),$unhome);
 6240: 	unless ($reply eq 'ok') {
 6241:             return 'error: '.$reply;
 6242:         }   
 6243:         $uhome=&homeserver($uname,$udom,'true');
 6244:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6245: 	    return 'error: unable verify users home machine.';
 6246:         }
 6247:     }   # End of creation of new user
 6248: # ---------------------------------------------------------------------- Add ID
 6249:     if ($uid) {
 6250:        $uid=~tr/A-Z/a-z/;
 6251:        my %uidhash=&idrget($udom,$uname);
 6252:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6253:          && (!$forceid)) {
 6254: 	  unless ($uid eq $uidhash{$uname}) {
 6255: 	      return 'error: user id "'.$uid.'" does not match '.
 6256:                   'current user id "'.$uidhash{$uname}.'".';
 6257:           }
 6258:        } else {
 6259: 	  &idput($udom,($uname => $uid));
 6260:        }
 6261:     }
 6262: # -------------------------------------------------------------- Add names, etc
 6263:     my @tmp=&get('environment',
 6264: 		   ['firstname','middlename','lastname','generation','id',
 6265:                     'permanentemail','inststatus'],
 6266: 		   $udom,$uname);
 6267:     my %names;
 6268:     if ($tmp[0] =~ m/^error:.*/) { 
 6269:         %names=(); 
 6270:     } else {
 6271:         %names = @tmp;
 6272:     }
 6273: #
 6274: # Make sure to not trash student environment if instructor does not bother
 6275: # to supply name and email information
 6276: #
 6277:     if ($first)  { $names{'firstname'}  = $first; }
 6278:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6279:     if ($last)   { $names{'lastname'}   = $last; }
 6280:     if (defined($gene))   { $names{'generation'} = $gene; }
 6281:     if ($email) {
 6282:        $email=~s/[^\w\@\.\-\,]//gs;
 6283:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6284:     }
 6285:     if ($uid) { $names{'id'}  = $uid; }
 6286:     if (defined($inststatus)) {
 6287:         $names{'inststatus'} = '';
 6288:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6289:         if (ref($usertypes) eq 'HASH') {
 6290:             my @okstatuses; 
 6291:             foreach my $item (split(/:/,$inststatus)) {
 6292:                 if (defined($usertypes->{$item})) {
 6293:                     push(@okstatuses,$item);  
 6294:                 }
 6295:             }
 6296:             if (@okstatuses) {
 6297:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6298:             }
 6299:         }
 6300:     }
 6301:     my $reply = &put('environment', \%names, $udom,$uname);
 6302:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6303:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6304:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6305:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6306:                  $umode.', '.$first.', '.$middle.', '.
 6307: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6308:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6309:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6310:     } else {
 6311:         $logmsg .= ' during self creation';
 6312:     }
 6313:     &logthis($logmsg);
 6314:     return 'ok';
 6315: }
 6316: 
 6317: # -------------------------------------------------------------- Modify student
 6318: 
 6319: sub modifystudent {
 6320:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6321:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6322:         $selfenroll,$context,$inststatus)=@_;
 6323:     if (!$cid) {
 6324: 	unless ($cid=$env{'request.course.id'}) {
 6325: 	    return 'not_in_class';
 6326: 	}
 6327:     }
 6328: # --------------------------------------------------------------- Make the user
 6329:     my $reply=&modifyuser
 6330: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6331:          $desiredhome,$email,$inststatus);
 6332:     unless ($reply eq 'ok') { return $reply; }
 6333:     # This will cause &modify_student_enrollment to get the uid from the
 6334:     # students environment
 6335:     $uid = undef if (!$forceid);
 6336:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6337: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6338:     return $reply;
 6339: }
 6340: 
 6341: sub modify_student_enrollment {
 6342:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6343:     my ($cdom,$cnum,$chome);
 6344:     if (!$cid) {
 6345: 	unless ($cid=$env{'request.course.id'}) {
 6346: 	    return 'not_in_class';
 6347: 	}
 6348: 	$cdom=$env{'course.'.$cid.'.domain'};
 6349: 	$cnum=$env{'course.'.$cid.'.num'};
 6350:     } else {
 6351: 	($cdom,$cnum)=split(/_/,$cid);
 6352:     }
 6353:     $chome=$env{'course.'.$cid.'.home'};
 6354:     if (!$chome) {
 6355: 	$chome=&homeserver($cnum,$cdom);
 6356:     }
 6357:     if (!$chome) { return 'unknown_course'; }
 6358:     # Make sure the user exists
 6359:     my $uhome=&homeserver($uname,$udom);
 6360:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6361: 	return 'error: no such user';
 6362:     }
 6363:     # Get student data if we were not given enough information
 6364:     if (!defined($first)  || $first  eq '' || 
 6365:         !defined($last)   || $last   eq '' || 
 6366:         !defined($uid)    || $uid    eq '' || 
 6367:         !defined($middle) || $middle eq '' || 
 6368:         !defined($gene)   || $gene   eq '') {
 6369:         # They did not supply us with enough data to enroll the student, so
 6370:         # we need to pick up more information.
 6371:         my %tmp = &get('environment',
 6372:                        ['firstname','middlename','lastname', 'generation','id']
 6373:                        ,$udom,$uname);
 6374: 
 6375:         #foreach my $key (keys(%tmp)) {
 6376:         #    &logthis("key $key = ".$tmp{$key});
 6377:         #}
 6378:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6379:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6380:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6381:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6382:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6383:     }
 6384:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6385:     my $reply=cput('classlist',
 6386: 		   {"$uname:$udom" => 
 6387: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6388: 		   $cdom,$cnum);
 6389:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6390: 	return 'error: '.$reply;
 6391:     } else {
 6392: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6393:     }
 6394:     # Add student role to user
 6395:     my $uurl='/'.$cid;
 6396:     $uurl=~s/\_/\//g;
 6397:     if ($usec) {
 6398: 	$uurl.='/'.$usec;
 6399:     }
 6400:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6401: }
 6402: 
 6403: sub format_name {
 6404:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6405:     my $name;
 6406:     if ($first ne 'lastname') {
 6407: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6408:     } else {
 6409: 	if ($lastname=~/\S/) {
 6410: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6411: 	    $name=~s/\s+,/,/;
 6412: 	} else {
 6413: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6414: 	}
 6415:     }
 6416:     $name=~s/^\s+//;
 6417:     $name=~s/\s+$//;
 6418:     $name=~s/\s+/ /g;
 6419:     return $name;
 6420: }
 6421: 
 6422: # ------------------------------------------------- Write to course preferences
 6423: 
 6424: sub writecoursepref {
 6425:     my ($courseid,%prefs)=@_;
 6426:     $courseid=~s/^\///;
 6427:     $courseid=~s/\_/\//g;
 6428:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6429:     my $chome=homeserver($cnum,$cdomain);
 6430:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6431: 	return 'error: no such course';
 6432:     }
 6433:     my $cstring='';
 6434:     foreach my $pref (keys(%prefs)) {
 6435: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6436:     }
 6437:     $cstring=~s/\&$//;
 6438:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6439: }
 6440: 
 6441: # ---------------------------------------------------------- Make/modify course
 6442: 
 6443: sub createcourse {
 6444:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6445:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 6446:     $url=&declutter($url);
 6447:     my $cid='';
 6448:     if ($context eq 'requestcourses') {
 6449:         my $can_create = 0;
 6450:         my ($ownername,$ownerdom) = split(':',$course_owner);
 6451:         if ($udom eq $ownerdom) {
 6452:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 6453:                                   $context)) {
 6454:                 $can_create = 1;
 6455:             }
 6456:         } else {
 6457:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 6458:                                            $category);
 6459:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 6460:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 6461:                 if (@curr > 0) {
 6462:                     my @options = qw(approval validate autolimit);
 6463:                     my $optregex = join('|',@options);
 6464:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 6465:                         $can_create = 1;
 6466:                     }
 6467:                 }
 6468:             }
 6469:         }
 6470:         if ($can_create) {
 6471:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 6472:                 unless (&allowed('ccc',$udom)) {
 6473:                     return 'refused'; 
 6474:                 }
 6475:             }
 6476:         } else {
 6477:             return 'refused';
 6478:         }
 6479:     } elsif (!&allowed('ccc',$udom)) {
 6480:         return 'refused';
 6481:     }
 6482: # --------------------------------------------------------------- Get Unique ID
 6483:     my $uname;
 6484:     if ($cnum =~ /^$match_courseid$/) {
 6485:         my $chome=&homeserver($cnum,$udom,'true');
 6486:         if (($chome eq '') || ($chome eq 'no_host')) {
 6487:             $uname = $cnum;
 6488:         } else {
 6489:             $uname = &generate_coursenum($udom);
 6490:         }
 6491:     } else {
 6492:         $uname = &generate_coursenum($udom);
 6493:     }
 6494:     return $uname if ($uname =~ /^error/);
 6495: # -------------------------------------------------- Check supplied server name
 6496:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6497:     if (! &is_library($course_server)) {
 6498:         return 'error:bad server name '.$course_server;
 6499:     }
 6500: # ------------------------------------------------------------- Make the course
 6501:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6502:                       $course_server);
 6503:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6504:     my $uhome=&homeserver($uname,$udom,'true');
 6505:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6506: 	return 'error: no such course';
 6507:     }
 6508: # ----------------------------------------------------------------- Course made
 6509: # log existence
 6510:     my $newcourse = {
 6511:                     $udom.'_'.$uname => {
 6512:                                      description => $description,
 6513:                                      inst_code   => $inst_code,
 6514:                                      owner       => $course_owner,
 6515:                                      type        => $crstype,
 6516:                                                 },
 6517:                     };
 6518:     &courseidput($udom,$newcourse,$uhome,'notime');
 6519: # set toplevel url
 6520:     my $topurl=$url;
 6521:     unless ($nonstandard) {
 6522: # ------------------------------------------ For standard courses, make top url
 6523:         my $mapurl=&clutter($url);
 6524:         if ($mapurl eq '/res/') { $mapurl=''; }
 6525:         $env{'form.initmap'}=(<<ENDINITMAP);
 6526: <map>
 6527: <resource id="1" type="start"></resource>
 6528: <resource id="2" src="$mapurl"></resource>
 6529: <resource id="3" type="finish"></resource>
 6530: <link index="1" from="1" to="2"></link>
 6531: <link index="2" from="2" to="3"></link>
 6532: </map>
 6533: ENDINITMAP
 6534:         $topurl=&declutter(
 6535:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6536:                           );
 6537:     }
 6538: # ----------------------------------------------------------- Write preferences
 6539:     &writecoursepref($udom.'_'.$uname,
 6540:                      ('description' => $description,
 6541:                       'url'         => $topurl));
 6542:     return '/'.$udom.'/'.$uname;
 6543: }
 6544: 
 6545: # ------------------------------------------------------------------- Create ID
 6546: sub generate_coursenum {
 6547:     my ($udom) = @_;
 6548:     my $domdesc = &domain($udom);
 6549:     return 'error: invalid domain' if ($domdesc eq '');
 6550:     my $uname=int(1+rand(9)).
 6551:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6552:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6553:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6554: # ----------------------------------------------- Make sure that does not exist
 6555:     my $uhome=&homeserver($uname,$udom,'true');
 6556:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6557:         $uname=int(1+rand(9)).
 6558:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6559:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6560:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6561:         $uhome=&homeserver($uname,$udom,'true');
 6562:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6563:             return 'error: unable to generate unique course-ID';
 6564:         }
 6565:     }
 6566:     return $uname;
 6567: }
 6568: 
 6569: sub is_course {
 6570:     my ($cdom,$cnum) = @_;
 6571:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6572: 				undef,'.');
 6573:     if (exists($courses{$cdom.'_'.$cnum})) {
 6574:         return 1;
 6575:     }
 6576:     return 0;
 6577: }
 6578: 
 6579: sub store_userdata {
 6580:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 6581:     my $result;
 6582:     if ($datakey ne '') {
 6583:         if (ref($storehash) eq 'HASH') {
 6584:             if ($udom eq '' || $uname eq '') {
 6585:                 $udom = $env{'user.domain'};
 6586:                 $uname = $env{'user.name'};
 6587:             }
 6588:             my $uhome=&homeserver($uname,$udom);
 6589:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 6590:                 $result = 'error: no_host';
 6591:             } else {
 6592:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 6593:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 6594: 
 6595:                 my $namevalue='';
 6596:                 foreach my $key (keys(%{$storehash})) {
 6597:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6598:                 }
 6599:                 $namevalue=~s/\&$//;
 6600:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
 6601:                                   "$namespace:$datakey:$namevalue",$uhome);
 6602:             }
 6603:         } else {
 6604:             $result = 'error: data to store was not a hash reference'; 
 6605:         }
 6606:     } else {
 6607:         $result= 'error: invalid requestkey'; 
 6608:     }
 6609:     return $result;
 6610: }
 6611: 
 6612: # ---------------------------------------------------------- Assign Custom Role
 6613: 
 6614: sub assigncustomrole {
 6615:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6616:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6617:                        $end,$start,$deleteflag,$selfenroll,$context);
 6618: }
 6619: 
 6620: # ----------------------------------------------------------------- Revoke Role
 6621: 
 6622: sub revokerole {
 6623:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6624:     my $now=time;
 6625:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6626: }
 6627: 
 6628: # ---------------------------------------------------------- Revoke Custom Role
 6629: 
 6630: sub revokecustomrole {
 6631:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6632:     my $now=time;
 6633:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6634:            $deleteflag,$selfenroll,$context);
 6635: }
 6636: 
 6637: # ------------------------------------------------------------ Disk usage
 6638: sub diskusage {
 6639:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6640:     $directorypath =~ s/\/$//;
 6641:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6642:                        .&escape($getpropath).':'.&escape($uname).':'
 6643:                        .&escape($udom),homeserver($uname,$udom));
 6644:     if ($listing eq 'unknown_cmd') {
 6645:         if ($getpropath) {
 6646:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6647:         }
 6648:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6649:     }
 6650:     return $listing;
 6651: }
 6652: 
 6653: sub is_locked {
 6654:     my ($file_name, $domain, $user) = @_;
 6655:     my @check;
 6656:     my $is_locked;
 6657:     push @check, $file_name;
 6658:     my %locked = &get('file_permissions',\@check,
 6659: 		      $env{'user.domain'},$env{'user.name'});
 6660:     my ($tmp)=keys(%locked);
 6661:     if ($tmp=~/^error:/) { undef(%locked); }
 6662:     
 6663:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6664:         $is_locked = 'false';
 6665:         foreach my $entry (@{$locked{$file_name}}) {
 6666:            if (ref($entry) eq 'ARRAY') { 
 6667:                $is_locked = 'true';
 6668:                last;
 6669:            }
 6670:        }
 6671:     } else {
 6672:         $is_locked = 'false';
 6673:     }
 6674: }
 6675: 
 6676: sub declutter_portfile {
 6677:     my ($file) = @_;
 6678:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6679:     return $file;
 6680: }
 6681: 
 6682: # ------------------------------------------------------------- Mark as Read Only
 6683: 
 6684: sub mark_as_readonly {
 6685:     my ($domain,$user,$files,$what) = @_;
 6686:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6687:     my ($tmp)=keys(%current_permissions);
 6688:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6689:     foreach my $file (@{$files}) {
 6690: 	$file = &declutter_portfile($file);
 6691:         push(@{$current_permissions{$file}},$what);
 6692:     }
 6693:     &put('file_permissions',\%current_permissions,$domain,$user);
 6694:     return;
 6695: }
 6696: 
 6697: # ------------------------------------------------------------Save Selected Files
 6698: 
 6699: sub save_selected_files {
 6700:     my ($user, $path, @files) = @_;
 6701:     my $filename = $user."savedfiles";
 6702:     my @other_files = &files_not_in_path($user, $path);
 6703:     open (OUT, '>'.$tmpdir.$filename);
 6704:     foreach my $file (@files) {
 6705:         print (OUT $env{'form.currentpath'}.$file."\n");
 6706:     }
 6707:     foreach my $file (@other_files) {
 6708:         print (OUT $file."\n");
 6709:     }
 6710:     close (OUT);
 6711:     return 'ok';
 6712: }
 6713: 
 6714: sub clear_selected_files {
 6715:     my ($user) = @_;
 6716:     my $filename = $user."savedfiles";
 6717:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6718:     print (OUT undef);
 6719:     close (OUT);
 6720:     return ("ok");    
 6721: }
 6722: 
 6723: sub files_in_path {
 6724:     my ($user, $path) = @_;
 6725:     my $filename = $user."savedfiles";
 6726:     my %return_files;
 6727:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6728:     while (my $line_in = <IN>) {
 6729:         chomp ($line_in);
 6730:         my @paths_and_file = split (m!/!, $line_in);
 6731:         my $file_part = pop (@paths_and_file);
 6732:         my $path_part = join ('/', @paths_and_file);
 6733:         $path_part.='/';
 6734:         my $path_and_file = $path_part.$file_part;
 6735:         if ($path_part eq $path) {
 6736:             $return_files{$file_part}= 'selected';
 6737:         }
 6738:     }
 6739:     close (IN);
 6740:     return (\%return_files);
 6741: }
 6742: 
 6743: # called in portfolio select mode, to show files selected NOT in current directory
 6744: sub files_not_in_path {
 6745:     my ($user, $path) = @_;
 6746:     my $filename = $user."savedfiles";
 6747:     my @return_files;
 6748:     my $path_part;
 6749:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6750:     while (my $line = <IN>) {
 6751:         #ok, I know it's clunky, but I want it to work
 6752:         my @paths_and_file = split(m|/|, $line);
 6753:         my $file_part = pop(@paths_and_file);
 6754:         chomp($file_part);
 6755:         my $path_part = join('/', @paths_and_file);
 6756:         $path_part .= '/';
 6757:         my $path_and_file = $path_part.$file_part;
 6758:         if ($path_part ne $path) {
 6759:             push(@return_files, ($path_and_file));
 6760:         }
 6761:     }
 6762:     close(OUT);
 6763:     return (@return_files);
 6764: }
 6765: 
 6766: #----------------------------------------------Get portfolio file permissions
 6767: 
 6768: sub get_portfile_permissions {
 6769:     my ($domain,$user) = @_;
 6770:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6771:     my ($tmp)=keys(%current_permissions);
 6772:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6773:     return \%current_permissions;
 6774: }
 6775: 
 6776: #---------------------------------------------Get portfolio file access controls
 6777: 
 6778: sub get_access_controls {
 6779:     my ($current_permissions,$group,$file) = @_;
 6780:     my %access;
 6781:     my $real_file = $file;
 6782:     $file =~ s/\.meta$//;
 6783:     if (defined($file)) {
 6784:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6785:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6786:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6787:             }
 6788:         }
 6789:     } else {
 6790:         foreach my $key (keys(%{$current_permissions})) {
 6791:             if ($key =~ /\0accesscontrol$/) {
 6792:                 if (defined($group)) {
 6793:                     if ($key !~ m-^\Q$group\E/-) {
 6794:                         next;
 6795:                     }
 6796:                 }
 6797:                 my ($fullpath) = split(/\0/,$key);
 6798:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6799:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6800:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6801:                     }
 6802:                 }
 6803:             }
 6804:         }
 6805:     }
 6806:     return %access;
 6807: }
 6808: 
 6809: sub modify_access_controls {
 6810:     my ($file_name,$changes,$domain,$user)=@_;
 6811:     my ($outcome,$deloutcome);
 6812:     my %store_permissions;
 6813:     my %new_values;
 6814:     my %new_control;
 6815:     my %translation;
 6816:     my @deletions = ();
 6817:     my $now = time;
 6818:     if (exists($$changes{'activate'})) {
 6819:         if (ref($$changes{'activate'}) eq 'HASH') {
 6820:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6821:             my $numnew = scalar(@newitems);
 6822:             for (my $i=0; $i<$numnew; $i++) {
 6823:                 my $newkey = $newitems[$i];
 6824:                 my $newid = &Apache::loncommon::get_cgi_id();
 6825:                 if ($newkey =~ /^\d+:/) { 
 6826:                     $newkey =~ s/^(\d+)/$newid/;
 6827:                     $translation{$1} = $newid;
 6828:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6829:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6830:                     $translation{$1} = $newid;
 6831:                 }
 6832:                 $new_values{$file_name."\0".$newkey} = 
 6833:                                           $$changes{'activate'}{$newitems[$i]};
 6834:                 $new_control{$newkey} = $now;
 6835:             }
 6836:         }
 6837:     }
 6838:     my %todelete;
 6839:     my %changed_items;
 6840:     foreach my $action ('delete','update') {
 6841:         if (exists($$changes{$action})) {
 6842:             if (ref($$changes{$action}) eq 'HASH') {
 6843:                 foreach my $key (keys(%{$$changes{$action}})) {
 6844:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6845:                     if ($action eq 'delete') { 
 6846:                         $todelete{$itemnum} = 1;
 6847:                     } else {
 6848:                         $changed_items{$itemnum} = $key;
 6849:                     }
 6850:                 }
 6851:             }
 6852:         }
 6853:     }
 6854:     # get lock on access controls for file.
 6855:     my $lockhash = {
 6856:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6857:                                                        ':'.$env{'user.domain'},
 6858:                    }; 
 6859:     my $tries = 0;
 6860:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6861:    
 6862:     while (($gotlock ne 'ok') && $tries <3) {
 6863:         $tries ++;
 6864:         sleep 1;
 6865:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6866:     }
 6867:     if ($gotlock eq 'ok') {
 6868:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6869:         my ($tmp)=keys(%curr_permissions);
 6870:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6871:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6872:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6873:             if (ref($curr_controls) eq 'HASH') {
 6874:                 foreach my $control_item (keys(%{$curr_controls})) {
 6875:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6876:                     if (defined($todelete{$itemnum})) {
 6877:                         push(@deletions,$file_name."\0".$control_item);
 6878:                     } else {
 6879:                         if (defined($changed_items{$itemnum})) {
 6880:                             $new_control{$changed_items{$itemnum}} = $now;
 6881:                             push(@deletions,$file_name."\0".$control_item);
 6882:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6883:                         } else {
 6884:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6885:                         }
 6886:                     }
 6887:                 }
 6888:             }
 6889:         }
 6890:         my ($group);
 6891:         if (&is_course($domain,$user)) {
 6892:             ($group,my $file) = split(/\//,$file_name,2);
 6893:         }
 6894:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6895:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6896:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6897:         #  remove lock
 6898:         my @del_lock = ($file_name."\0".'locked_access_records');
 6899:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6900:         my $sqlresult =
 6901:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6902:                                     $group);
 6903:     } else {
 6904:         $outcome = "error: could not obtain lockfile\n";  
 6905:     }
 6906:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6907: }
 6908: 
 6909: sub make_public_indefinitely {
 6910:     my ($requrl) = @_;
 6911:     my $now = time;
 6912:     my $action = 'activate';
 6913:     my $aclnum = 0;
 6914:     if (&is_portfolio_url($requrl)) {
 6915:         my (undef,$udom,$unum,$file_name,$group) =
 6916:             &parse_portfolio_url($requrl);
 6917:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6918:         my %access_controls = &get_access_controls($current_perms,
 6919:                                                    $group,$file_name);
 6920:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6921:             my ($num,$scope,$end,$start) = 
 6922:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6923:             if ($scope eq 'public') {
 6924:                 if ($start <= $now && $end == 0) {
 6925:                     $action = 'none';
 6926:                 } else {
 6927:                     $action = 'update';
 6928:                     $aclnum = $num;
 6929:                 }
 6930:                 last;
 6931:             }
 6932:         }
 6933:         if ($action eq 'none') {
 6934:              return 'ok';
 6935:         } else {
 6936:             my %changes;
 6937:             my $newend = 0;
 6938:             my $newstart = $now;
 6939:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6940:             $changes{$action}{$newkey} = {
 6941:                 type => 'public',
 6942:                 time => {
 6943:                     start => $newstart,
 6944:                     end   => $newend,
 6945:                 },
 6946:             };
 6947:             my ($outcome,$deloutcome,$new_values,$translation) =
 6948:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6949:             return $outcome;
 6950:         }
 6951:     } else {
 6952:         return 'invalid';
 6953:     }
 6954: }
 6955: 
 6956: #------------------------------------------------------Get Marked as Read Only
 6957: 
 6958: sub get_marked_as_readonly {
 6959:     my ($domain,$user,$what,$group) = @_;
 6960:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6961:     my @readonly_files;
 6962:     my $cmp1=$what;
 6963:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6964:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6965:         if (defined($group)) {
 6966:             if ($file_name !~ m-^\Q$group\E/-) {
 6967:                 next;
 6968:             }
 6969:         }
 6970:         if (ref($value) eq "ARRAY"){
 6971:             foreach my $stored_what (@{$value}) {
 6972:                 my $cmp2=$stored_what;
 6973:                 if (ref($stored_what) eq 'ARRAY') {
 6974:                     $cmp2=join('',@{$stored_what});
 6975:                 }
 6976:                 if ($cmp1 eq $cmp2) {
 6977:                     push(@readonly_files, $file_name);
 6978:                     last;
 6979:                 } elsif (!defined($what)) {
 6980:                     push(@readonly_files, $file_name);
 6981:                     last;
 6982:                 }
 6983:             }
 6984:         }
 6985:     }
 6986:     return @readonly_files;
 6987: }
 6988: #-----------------------------------------------------------Get Marked as Read Only Hash
 6989: 
 6990: sub get_marked_as_readonly_hash {
 6991:     my ($current_permissions,$group,$what) = @_;
 6992:     my %readonly_files;
 6993:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6994:         if (defined($group)) {
 6995:             if ($file_name !~ m-^\Q$group\E/-) {
 6996:                 next;
 6997:             }
 6998:         }
 6999:         if (ref($value) eq "ARRAY"){
 7000:             foreach my $stored_what (@{$value}) {
 7001:                 if (ref($stored_what) eq 'ARRAY') {
 7002:                     foreach my $lock_descriptor(@{$stored_what}) {
 7003:                         if ($lock_descriptor eq 'graded') {
 7004:                             $readonly_files{$file_name} = 'graded';
 7005:                         } elsif ($lock_descriptor eq 'handback') {
 7006:                             $readonly_files{$file_name} = 'handback';
 7007:                         } else {
 7008:                             if (!exists($readonly_files{$file_name})) {
 7009:                                 $readonly_files{$file_name} = 'locked';
 7010:                             }
 7011:                         }
 7012:                     }
 7013:                 } 
 7014:             }
 7015:         } 
 7016:     }
 7017:     return %readonly_files;
 7018: }
 7019: # ------------------------------------------------------------ Unmark as Read Only
 7020: 
 7021: sub unmark_as_readonly {
 7022:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 7023:     # for portfolio submissions, $what contains [$symb,$crsid] 
 7024:     my ($domain,$user,$what,$file_name,$group) = @_;
 7025:     $file_name = &declutter_portfile($file_name);
 7026:     my $symb_crs = $what;
 7027:     if (ref($what)) { $symb_crs=join('',@$what); }
 7028:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 7029:     my ($tmp)=keys(%current_permissions);
 7030:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7031:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 7032:     foreach my $file (@readonly_files) {
 7033: 	my $clean_file = &declutter_portfile($file);
 7034: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 7035: 	my $current_locks = $current_permissions{$file};
 7036:         my @new_locks;
 7037:         my @del_keys;
 7038:         if (ref($current_locks) eq "ARRAY"){
 7039:             foreach my $locker (@{$current_locks}) {
 7040:                 my $compare=$locker;
 7041:                 if (ref($locker) eq 'ARRAY') {
 7042:                     $compare=join('',@{$locker});
 7043:                     if ($compare ne $symb_crs) {
 7044:                         push(@new_locks, $locker);
 7045:                     }
 7046:                 }
 7047:             }
 7048:             if (scalar(@new_locks) > 0) {
 7049:                 $current_permissions{$file} = \@new_locks;
 7050:             } else {
 7051:                 push(@del_keys, $file);
 7052:                 &del('file_permissions',\@del_keys, $domain, $user);
 7053:                 delete($current_permissions{$file});
 7054:             }
 7055:         }
 7056:     }
 7057:     &put('file_permissions',\%current_permissions,$domain,$user);
 7058:     return;
 7059: }
 7060: 
 7061: # ------------------------------------------------------------ Directory lister
 7062: 
 7063: sub dirlist {
 7064:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 7065:     $uri=~s/^\///;
 7066:     $uri=~s/\/$//;
 7067:     my ($udom, $uname);
 7068:     if ($getuserdir) {
 7069:         $udom = $userdomain;
 7070:         $uname = $username;
 7071:     } else {
 7072:         (undef,$udom,$uname)=split(/\//,$uri);
 7073:         if(defined($userdomain)) {
 7074:             $udom = $userdomain;
 7075:         }
 7076:         if(defined($username)) {
 7077:             $uname = $username;
 7078:         }
 7079:     }
 7080:     my ($dirRoot,$listing,@listing_results);
 7081: 
 7082:     $dirRoot = $perlvar{'lonDocRoot'};
 7083:     if (defined($getpropath)) {
 7084:         $dirRoot = &propath($udom,$uname);
 7085:         $dirRoot =~ s/\/$//;
 7086:     } elsif (defined($getuserdir)) {
 7087:         my $subdir=$uname.'__';
 7088:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 7089:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 7090:                    ."/$udom/$subdir/$uname";
 7091:     } elsif (defined($alternateRoot)) {
 7092:         $dirRoot = $alternateRoot;
 7093:     }
 7094: 
 7095:     if($udom) {
 7096:         if($uname) {
 7097:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 7098:                               .$getuserdir.':'.&escape($dirRoot)
 7099:                               .':'.&escape($uname).':'.&escape($udom),
 7100:                               &homeserver($uname,$udom));
 7101:             if ($listing eq 'unknown_cmd') {
 7102:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 7103:                                   &homeserver($uname,$udom));
 7104:             } else {
 7105:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7106:             }
 7107:             if ($listing eq 'unknown_cmd') {
 7108:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 7109: 				  &homeserver($uname,$udom));
 7110:                 @listing_results = split(/:/,$listing);
 7111:             } else {
 7112:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7113:             }
 7114:             return @listing_results;
 7115:         } elsif(!$alternateRoot) {
 7116:             my %allusers;
 7117: 	    my %servers = &get_servers($udom,'library');
 7118:  	    foreach my $tryserver (keys(%servers)) {
 7119:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 7120:                                   &escape($udom),$tryserver);
 7121:                 if ($listing eq 'unknown_cmd') {
 7122: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 7123: 				      $udom, $tryserver);
 7124:                 } else {
 7125:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 7126:                 }
 7127: 		if ($listing eq 'unknown_cmd') {
 7128: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 7129: 				      $udom, $tryserver);
 7130: 		    @listing_results = split(/:/,$listing);
 7131: 		} else {
 7132: 		    @listing_results =
 7133: 			map { &unescape($_); } split(/:/,$listing);
 7134: 		}
 7135: 		if ($listing_results[0] ne 'no_such_dir' && 
 7136: 		    $listing_results[0] ne 'empty'       &&
 7137: 		    $listing_results[0] ne 'con_lost') {
 7138: 		    foreach my $line (@listing_results) {
 7139: 			my ($entry) = split(/&/,$line,2);
 7140: 			$allusers{$entry} = 1;
 7141: 		    }
 7142: 		}
 7143:             }
 7144:             my $alluserstr='';
 7145:             foreach my $user (sort(keys(%allusers))) {
 7146:                 $alluserstr.=$user.'&user:';
 7147:             }
 7148:             $alluserstr=~s/:$//;
 7149:             return split(/:/,$alluserstr);
 7150:         } else {
 7151:             return ('missing user name');
 7152:         }
 7153:     } elsif(!defined($getpropath)) {
 7154:         my @all_domains = sort(&all_domains());
 7155:         foreach my $domain (@all_domains) {
 7156:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 7157:         }
 7158:         return @all_domains;
 7159:     } else {
 7160:         return ('missing domain');
 7161:     }
 7162: }
 7163: 
 7164: # --------------------------------------------- GetFileTimestamp
 7165: # This function utilizes dirlist and returns the date stamp for
 7166: # when it was last modified.  It will also return an error of -1
 7167: # if an error occurs
 7168: 
 7169: sub GetFileTimestamp {
 7170:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 7171:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 7172:     $studentName   = &LONCAPA::clean_username($studentName);
 7173:     my ($fileStat) = 
 7174:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 7175:                                  undef,$getuserdir);
 7176:     my @stats = split('&', $fileStat);
 7177:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7178:         # @stats contains first the filename, then the stat output
 7179:         return $stats[10]; # so this is 10 instead of 9.
 7180:     } else {
 7181:         return -1;
 7182:     }
 7183: }
 7184: 
 7185: sub stat_file {
 7186:     my ($uri) = @_;
 7187:     $uri = &clutter_with_no_wrapper($uri);
 7188: 
 7189:     my ($udom,$uname,$file);
 7190:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7191: 	($udom,$uname,$file) =
 7192: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7193: 	$file = 'userfiles/'.$file;
 7194:     }
 7195:     if ($uri =~ m-^/res/-) {
 7196: 	($udom,$uname) = 
 7197: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7198: 	$file = $uri;
 7199:     }
 7200: 
 7201:     if (!$udom || !$uname || !$file) {
 7202: 	# unable to handle the uri
 7203: 	return ();
 7204:     }
 7205:     my $getpropath;
 7206:     if ($file =~ /^userfiles\//) {
 7207:         $getpropath = 1;
 7208:     }
 7209:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7210:     my @stats = split('&', $result);
 7211:     
 7212:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7213: 	shift(@stats); #filename is first
 7214: 	return @stats;
 7215:     }
 7216:     return ();
 7217: }
 7218: 
 7219: # -------------------------------------------------------- Value of a Condition
 7220: 
 7221: # gets the value of a specific preevaluated condition
 7222: #    stored in the string  $env{user.state.<cid>}
 7223: # or looks up a condition reference in the bighash and if if hasn't
 7224: # already been evaluated recurses into docondval to get the value of
 7225: # the condition, then memoizing it to 
 7226: #   $env{user.state.<cid>.<condition>}
 7227: sub directcondval {
 7228:     my $number=shift;
 7229:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7230: 	&Apache::lonuserstate::evalstate();
 7231:     }
 7232:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7233: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7234:     } elsif ($number =~ /^_/) {
 7235: 	my $sub_condition;
 7236: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7237: 		&GDBM_READER(),0640)) {
 7238: 	    $sub_condition=$bighash{'conditions'.$number};
 7239: 	    untie(%bighash);
 7240: 	}
 7241: 	my $value = &docondval($sub_condition);
 7242: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7243: 	return $value;
 7244:     }
 7245:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7246:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7247:     } else {
 7248:        return 2;
 7249:     }
 7250: }
 7251: 
 7252: # get the collection of conditions for this resource
 7253: sub condval {
 7254:     my $condidx=shift;
 7255:     my $allpathcond='';
 7256:     foreach my $cond (split(/\|/,$condidx)) {
 7257: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7258: 	    $allpathcond.=
 7259: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7260: 	}
 7261:     }
 7262:     $allpathcond=~s/\|$//;
 7263:     return &docondval($allpathcond);
 7264: }
 7265: 
 7266: #evaluates an expression of conditions
 7267: sub docondval {
 7268:     my ($allpathcond) = @_;
 7269:     my $result=0;
 7270:     if ($env{'request.course.id'}
 7271: 	&& defined($allpathcond)) {
 7272: 	my $operand='|';
 7273: 	my @stack;
 7274: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7275: 	    if ($chunk eq '(') {
 7276: 		push @stack,($operand,$result);
 7277: 	    } elsif ($chunk eq ')') {
 7278: 		my $before=pop @stack;
 7279: 		if (pop @stack eq '&') {
 7280: 		    $result=$result>$before?$before:$result;
 7281: 		} else {
 7282: 		    $result=$result>$before?$result:$before;
 7283: 		}
 7284: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7285: 		$operand=$chunk;
 7286: 	    } else {
 7287: 		my $new=directcondval($chunk);
 7288: 		if ($operand eq '&') {
 7289: 		    $result=$result>$new?$new:$result;
 7290: 		} else {
 7291: 		    $result=$result>$new?$result:$new;
 7292: 		}
 7293: 	    }
 7294: 	}
 7295:     }
 7296:     return $result;
 7297: }
 7298: 
 7299: # ---------------------------------------------------- Devalidate courseresdata
 7300: 
 7301: sub devalidatecourseresdata {
 7302:     my ($coursenum,$coursedomain)=@_;
 7303:     my $hashid=$coursenum.':'.$coursedomain;
 7304:     &devalidate_cache_new('courseres',$hashid);
 7305: }
 7306: 
 7307: 
 7308: # --------------------------------------------------- Course Resourcedata Query
 7309: #
 7310: #  Parameters:
 7311: #      $coursenum    - Number of the course.
 7312: #      $coursedomain - Domain at which the course was created.
 7313: #  Returns:
 7314: #     A hash of the course parameters along (I think) with timestamps
 7315: #     and version info.
 7316: 
 7317: sub get_courseresdata {
 7318:     my ($coursenum,$coursedomain)=@_;
 7319:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7320:     my $hashid=$coursenum.':'.$coursedomain;
 7321:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7322:     my %dumpreply;
 7323:     unless (defined($cached)) {
 7324: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7325: 	$result=\%dumpreply;
 7326: 	my ($tmp) = keys(%dumpreply);
 7327: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7328: 	    &do_cache_new('courseres',$hashid,$result,600);
 7329: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7330: 	    return $tmp;
 7331: 	} elsif ($tmp =~ /^(error)/) {
 7332: 	    $result=undef;
 7333: 	    &do_cache_new('courseres',$hashid,$result,600);
 7334: 	}
 7335:     }
 7336:     return $result;
 7337: }
 7338: 
 7339: sub devalidateuserresdata {
 7340:     my ($uname,$udom)=@_;
 7341:     my $hashid="$udom:$uname";
 7342:     &devalidate_cache_new('userres',$hashid);
 7343: }
 7344: 
 7345: sub get_userresdata {
 7346:     my ($uname,$udom)=@_;
 7347:     #most student don\'t have any data set, check if there is some data
 7348:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7349: 
 7350:     my $hashid="$udom:$uname";
 7351:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7352:     if (!defined($cached)) {
 7353: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7354: 	$result=\%resourcedata;
 7355: 	&do_cache_new('userres',$hashid,$result,600);
 7356:     }
 7357:     my ($tmp)=keys(%$result);
 7358:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7359: 	return $result;
 7360:     }
 7361:     #error 2 occurs when the .db doesn't exist
 7362:     if ($tmp!~/error: 2 /) {
 7363: 	&logthis("<font color=\"blue\">WARNING:".
 7364: 		 " Trying to get resource data for ".
 7365: 		 $uname." at ".$udom.": ".
 7366: 		 $tmp."</font>");
 7367:     } elsif ($tmp=~/error: 2 /) {
 7368: 	#&EXT_cache_set($udom,$uname);
 7369: 	&do_cache_new('userres',$hashid,undef,600);
 7370: 	undef($tmp); # not really an error so don't send it back
 7371:     }
 7372:     return $tmp;
 7373: }
 7374: #----------------------------------------------- resdata - return resource data
 7375: #  Purpose:
 7376: #    Return resource data for either users or for a course.
 7377: #  Parameters:
 7378: #     $name      - Course/user name.
 7379: #     $domain    - Name of the domain the user/course is registered on.
 7380: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7381: #     @which     - Array of names of resources desired.
 7382: #  Returns:
 7383: #     The value of the first reasource in @which that is found in the
 7384: #     resource hash.
 7385: #  Exceptional Conditions:
 7386: #     If the $type passed in is not valid (not the string 'course' or 
 7387: #     'user', an undefined  reference is returned.
 7388: #     If none of the resources are found, an undef is returned
 7389: sub resdata {
 7390:     my ($name,$domain,$type,@which)=@_;
 7391:     my $result;
 7392:     if ($type eq 'course') {
 7393: 	$result=&get_courseresdata($name,$domain);
 7394:     } elsif ($type eq 'user') {
 7395: 	$result=&get_userresdata($name,$domain);
 7396:     }
 7397:     if (!ref($result)) { return $result; }    
 7398:     foreach my $item (@which) {
 7399: 	if (defined($result->{$item->[0]})) {
 7400: 	    return [$result->{$item->[0]},$item->[1]];
 7401: 	}
 7402:     }
 7403:     return undef;
 7404: }
 7405: 
 7406: #
 7407: # EXT resource caching routines
 7408: #
 7409: 
 7410: sub clear_EXT_cache_status {
 7411:     &delenv('cache.EXT.');
 7412: }
 7413: 
 7414: sub EXT_cache_status {
 7415:     my ($target_domain,$target_user) = @_;
 7416:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7417:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7418:         # We know already the user has no data
 7419:         return 1;
 7420:     } else {
 7421:         return 0;
 7422:     }
 7423: }
 7424: 
 7425: sub EXT_cache_set {
 7426:     my ($target_domain,$target_user) = @_;
 7427:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7428:     #&appenv({$cachename => time});
 7429: }
 7430: 
 7431: # --------------------------------------------------------- Value of a Variable
 7432: sub EXT {
 7433: 
 7434:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7435:     unless ($varname) { return ''; }
 7436:     #get real user name/domain, courseid and symb
 7437:     my $courseid;
 7438:     my $publicuser;
 7439:     if ($symbparm) {
 7440: 	$symbparm=&get_symb_from_alias($symbparm);
 7441:     }
 7442:     if (!($uname && $udom)) {
 7443:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7444:       if (!$symbparm) {	$symbparm=$cursymb; }
 7445:     } else {
 7446: 	$courseid=$env{'request.course.id'};
 7447:     }
 7448:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7449:     my $rest;
 7450:     if (defined($therest[0])) {
 7451:        $rest=join('.',@therest);
 7452:     } else {
 7453:        $rest='';
 7454:     }
 7455: 
 7456:     my $qualifierrest=$qualifier;
 7457:     if ($rest) { $qualifierrest.='.'.$rest; }
 7458:     my $spacequalifierrest=$space;
 7459:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7460:     if ($realm eq 'user') {
 7461: # --------------------------------------------------------------- user.resource
 7462: 	if ($space eq 'resource') {
 7463: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7464: 		  || defined($Apache::lonhomework::parsing_a_task))
 7465: 		 &&
 7466: 		 ($symbparm eq &symbread()) ) {	
 7467: 		# if we are in the middle of processing the resource the
 7468: 		# get the value we are planning on committing
 7469:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7470:                     return $Apache::lonhomework::results{$qualifierrest};
 7471:                 } else {
 7472:                     return $Apache::lonhomework::history{$qualifierrest};
 7473:                 }
 7474: 	    } else {
 7475: 		my %restored;
 7476: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7477: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7478: 		} else {
 7479: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7480: 		}
 7481: 		return $restored{$qualifierrest};
 7482: 	    }
 7483: # ----------------------------------------------------------------- user.access
 7484:         } elsif ($space eq 'access') {
 7485: 	    # FIXME - not supporting calls for a specific user
 7486:             return &allowed($qualifier,$rest);
 7487: # ------------------------------------------ user.preferences, user.environment
 7488:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7489: 	    if (($uname eq $env{'user.name'}) &&
 7490: 		($udom eq $env{'user.domain'})) {
 7491: 		return $env{join('.',('environment',$qualifierrest))};
 7492: 	    } else {
 7493: 		my %returnhash;
 7494: 		if (!$publicuser) {
 7495: 		    %returnhash=&userenvironment($udom,$uname,
 7496: 						 $qualifierrest);
 7497: 		}
 7498: 		return $returnhash{$qualifierrest};
 7499: 	    }
 7500: # ----------------------------------------------------------------- user.course
 7501:         } elsif ($space eq 'course') {
 7502: 	    # FIXME - not supporting calls for a specific user
 7503:             return $env{join('.',('request.course',$qualifier))};
 7504: # ------------------------------------------------------------------- user.role
 7505:         } elsif ($space eq 'role') {
 7506: 	    # FIXME - not supporting calls for a specific user
 7507:             my ($role,$where)=split(/\./,$env{'request.role'});
 7508:             if ($qualifier eq 'value') {
 7509: 		return $role;
 7510:             } elsif ($qualifier eq 'extent') {
 7511:                 return $where;
 7512:             }
 7513: # ----------------------------------------------------------------- user.domain
 7514:         } elsif ($space eq 'domain') {
 7515:             return $udom;
 7516: # ------------------------------------------------------------------- user.name
 7517:         } elsif ($space eq 'name') {
 7518:             return $uname;
 7519: # ---------------------------------------------------- Any other user namespace
 7520:         } else {
 7521: 	    my %reply;
 7522: 	    if (!$publicuser) {
 7523: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7524: 	    }
 7525: 	    return $reply{$qualifierrest};
 7526:         }
 7527:     } elsif ($realm eq 'query') {
 7528: # ---------------------------------------------- pull stuff out of query string
 7529:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7530: 						[$spacequalifierrest]);
 7531: 	return $env{'form.'.$spacequalifierrest}; 
 7532:    } elsif ($realm eq 'request') {
 7533: # ------------------------------------------------------------- request.browser
 7534:         if ($space eq 'browser') {
 7535: 	    if ($qualifier eq 'textremote') {
 7536: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7537: 		    return 1;
 7538: 		} else {
 7539: 		    return 0;
 7540: 		}
 7541: 	    } else {
 7542: 		return $env{'browser.'.$qualifier};
 7543: 	    }
 7544: # ------------------------------------------------------------ request.filename
 7545:         } else {
 7546:             return $env{'request.'.$spacequalifierrest};
 7547:         }
 7548:     } elsif ($realm eq 'course') {
 7549: # ---------------------------------------------------------- course.description
 7550:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7551:     } elsif ($realm eq 'resource') {
 7552: 
 7553: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7554: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7555: 	}
 7556: 
 7557: 	if ($space eq 'title') {
 7558: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7559: 	    return &gettitle($symbparm);
 7560: 	}
 7561: 	
 7562: 	if ($space eq 'map') {
 7563: 	    my ($map) = &decode_symb($symbparm);
 7564: 	    return &symbread($map);
 7565: 	}
 7566: 	if ($space eq 'filename') {
 7567: 	    if ($symbparm) {
 7568: 		return &clutter((&decode_symb($symbparm))[2]);
 7569: 	    }
 7570: 	    return &hreflocation('',$env{'request.filename'});
 7571: 	}
 7572: 
 7573: 	my ($section, $group, @groups);
 7574: 	my ($courselevelm,$courselevel);
 7575: 	if ($symbparm && defined($courseid) && 
 7576: 	    $courseid eq $env{'request.course.id'}) {
 7577: 
 7578: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7579: 
 7580: # ----------------------------------------------------- Cascading lookup scheme
 7581: 	    my $symbp=$symbparm;
 7582: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7583: 
 7584: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7585: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7586: 
 7587: 	    if (($env{'user.name'} eq $uname) &&
 7588: 		($env{'user.domain'} eq $udom)) {
 7589: 		$section=$env{'request.course.sec'};
 7590:                 @groups = split(/:/,$env{'request.course.groups'});  
 7591:                 @groups=&sort_course_groups($courseid,@groups); 
 7592: 	    } else {
 7593: 		if (! defined($usection)) {
 7594: 		    $section=&getsection($udom,$uname,$courseid);
 7595: 		} else {
 7596: 		    $section = $usection;
 7597: 		}
 7598:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7599: 	    }
 7600: 
 7601: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7602: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7603: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7604: 
 7605: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7606: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7607: 	    $courselevelm=$courseid.'.'.$mapparm;
 7608: 
 7609: # ----------------------------------------------------------- first, check user
 7610: 
 7611: 	    my $userreply=&resdata($uname,$udom,'user',
 7612: 				       ([$courselevelr,'resource'],
 7613: 					[$courselevelm,'map'     ],
 7614: 					[$courselevel, 'course'  ]));
 7615: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7616: 
 7617: # ------------------------------------------------ second, check some of course
 7618:             my $coursereply;
 7619:             if (@groups > 0) {
 7620:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7621:                                        $mapparm,$spacequalifierrest);
 7622:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7623:             }
 7624: 
 7625: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7626: 				  $env{'course.'.$courseid.'.domain'},
 7627: 				  'course',
 7628: 				  ([$seclevelr,   'resource'],
 7629: 				   [$seclevelm,   'map'     ],
 7630: 				   [$seclevel,    'course'  ],
 7631: 				   [$courselevelr,'resource']));
 7632: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7633: 
 7634: # ------------------------------------------------------ third, check map parms
 7635: 	    my %parmhash=();
 7636: 	    my $thisparm='';
 7637: 	    if (tie(%parmhash,'GDBM_File',
 7638: 		    $env{'request.course.fn'}.'_parms.db',
 7639: 		    &GDBM_READER(),0640)) {
 7640: 		$thisparm=$parmhash{$symbparm};
 7641: 		untie(%parmhash);
 7642: 	    }
 7643: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7644: 	}
 7645: # ------------------------------------------ fourth, look in resource metadata
 7646: 
 7647: 	$spacequalifierrest=~s/\./\_/;
 7648: 	my $filename;
 7649: 	if (!$symbparm) { $symbparm=&symbread(); }
 7650: 	if ($symbparm) {
 7651: 	    $filename=(&decode_symb($symbparm))[2];
 7652: 	} else {
 7653: 	    $filename=$env{'request.filename'};
 7654: 	}
 7655: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7656: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7657: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7658: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7659: 
 7660: # ---------------------------------------------- fourth, look in rest of course
 7661: 	if ($symbparm && defined($courseid) && 
 7662: 	    $courseid eq $env{'request.course.id'}) {
 7663: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7664: 				     $env{'course.'.$courseid.'.domain'},
 7665: 				     'course',
 7666: 				     ([$courselevelm,'map'   ],
 7667: 				      [$courselevel, 'course']));
 7668: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7669: 	}
 7670: # ------------------------------------------------------------------ Cascade up
 7671: 	unless ($space eq '0') {
 7672: 	    my @parts=split(/_/,$space);
 7673: 	    my $id=pop(@parts);
 7674: 	    my $part=join('_',@parts);
 7675: 	    if ($part eq '') { $part='0'; }
 7676: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7677: 				 $symbparm,$udom,$uname,$section,1);
 7678: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7679: 	}
 7680: 	if ($recurse) { return undef; }
 7681: 	my $pack_def=&packages_tab_default($filename,$varname);
 7682: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7683: # ---------------------------------------------------- Any other user namespace
 7684:     } elsif ($realm eq 'environment') {
 7685: # ----------------------------------------------------------------- environment
 7686: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7687: 	    return $env{'environment.'.$spacequalifierrest};
 7688: 	} else {
 7689: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7690: 		return '';
 7691: 	    }
 7692: 	    my %returnhash=&userenvironment($udom,$uname,
 7693: 					    $spacequalifierrest);
 7694: 	    return $returnhash{$spacequalifierrest};
 7695: 	}
 7696:     } elsif ($realm eq 'system') {
 7697: # ----------------------------------------------------------------- system.time
 7698: 	if ($space eq 'time') {
 7699: 	    return time;
 7700:         }
 7701:     } elsif ($realm eq 'server') {
 7702: # ----------------------------------------------------------------- system.time
 7703: 	if ($space eq 'name') {
 7704: 	    return $ENV{'SERVER_NAME'};
 7705:         }
 7706:     }
 7707:     return '';
 7708: }
 7709: 
 7710: sub get_reply {
 7711:     my ($reply_value) = @_;
 7712:     if (ref($reply_value) eq 'ARRAY') {
 7713:         if (wantarray) {
 7714: 	    return @$reply_value;
 7715:         }
 7716:         return $reply_value->[0];
 7717:     } else {
 7718:         return $reply_value;
 7719:     }
 7720: }
 7721: 
 7722: sub check_group_parms {
 7723:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7724:     my @groupitems = ();
 7725:     my $resultitem;
 7726:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7727:     foreach my $group (@{$groups}) {
 7728:         foreach my $level (@levels) {
 7729:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7730:              push(@groupitems,[$item,$level->[1]]);
 7731:         }
 7732:     }
 7733:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7734:                             $env{'course.'.$courseid.'.domain'},
 7735:                                      'course',@groupitems);
 7736:     return $coursereply;
 7737: }
 7738: 
 7739: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7740:     my ($courseid,@groups) = @_;
 7741:     @groups = sort(@groups);
 7742:     return @groups;
 7743: }
 7744: 
 7745: sub packages_tab_default {
 7746:     my ($uri,$varname)=@_;
 7747:     my (undef,$part,$name)=split(/\./,$varname);
 7748: 
 7749:     my (@extension,@specifics,$do_default);
 7750:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7751: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7752: 	if ($pack_type eq 'default') {
 7753: 	    $do_default=1;
 7754: 	} elsif ($pack_type eq 'extension') {
 7755: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7756: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7757: 	    # only look at packages defaults for packages that this id is
 7758: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7759: 	}
 7760:     }
 7761:     # first look for a package that matches the requested part id
 7762:     foreach my $package (@specifics) {
 7763: 	my (undef,$pack_type,$pack_part)=@{$package};
 7764: 	next if ($pack_part ne $part);
 7765: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7766: 	    return $packagetab{"$pack_type&$name&default"};
 7767: 	}
 7768:     }
 7769:     # look for any possible matching non extension_ package
 7770:     foreach my $package (@specifics) {
 7771: 	my (undef,$pack_type,$pack_part)=@{$package};
 7772: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7773: 	    return $packagetab{"$pack_type&$name&default"};
 7774: 	}
 7775: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7776: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7777: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7778: 	}
 7779:     }
 7780:     # look for any posible extension_ match
 7781:     foreach my $package (@extension) {
 7782: 	my ($package,$pack_type)=@{$package};
 7783: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7784: 	    return $packagetab{"$pack_type&$name&default"};
 7785: 	}
 7786: 	if (defined($packagetab{$package."&$name&default"})) {
 7787: 	    return $packagetab{$package."&$name&default"};
 7788: 	}
 7789:     }
 7790:     # look for a global default setting
 7791:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7792: 	return $packagetab{"default&$name&default"};
 7793:     }
 7794:     return undef;
 7795: }
 7796: 
 7797: sub add_prefix_and_part {
 7798:     my ($prefix,$part)=@_;
 7799:     my $keyroot;
 7800:     if (defined($prefix) && $prefix !~ /^__/) {
 7801: 	# prefix that has a part already
 7802: 	$keyroot=$prefix;
 7803:     } elsif (defined($prefix)) {
 7804: 	# prefix that is missing a part
 7805: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7806:     } else {
 7807: 	# no prefix at all
 7808: 	if (defined($part)) { $keyroot='_'.$part; }
 7809:     }
 7810:     return $keyroot;
 7811: }
 7812: 
 7813: # ---------------------------------------------------------------- Get metadata
 7814: 
 7815: my %metaentry;
 7816: sub metadata {
 7817:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7818:     $uri=&declutter($uri);
 7819:     # if it is a non metadata possible uri return quickly
 7820:     if (($uri eq '') || 
 7821: 	(($uri =~ m|^/*adm/|) && 
 7822: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7823:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7824: 	return undef;
 7825:     }
 7826:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7827: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7828: 	return undef;
 7829:     }
 7830:     my $filename=$uri;
 7831:     $uri=~s/\.meta$//;
 7832: #
 7833: # Is the metadata already cached?
 7834: # Look at timestamp of caching
 7835: # Everything is cached by the main uri, libraries are never directly cached
 7836: #
 7837:     if (!defined($liburi)) {
 7838: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7839: 	if (defined($cached)) { return $result->{':'.$what}; }
 7840:     }
 7841:     {
 7842: #
 7843: # Is this a recursive call for a library?
 7844: #
 7845: #	if (! exists($metacache{$uri})) {
 7846: #	    $metacache{$uri}={};
 7847: #	}
 7848: 	my $cachetime = 60*60;
 7849:         if ($liburi) {
 7850: 	    $liburi=&declutter($liburi);
 7851:             $filename=$liburi;
 7852:         } else {
 7853: 	    &devalidate_cache_new('meta',$uri);
 7854: 	    undef(%metaentry);
 7855: 	}
 7856:         my %metathesekeys=();
 7857:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7858: 	my $metastring;
 7859: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7860: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7861: 	    $metastring = 
 7862: 		&Apache::lonnet::ssi_body($which,
 7863: 					  ('grade_target' => 'meta'));
 7864: 	    $cachetime = 1; # only want this cached in the child not long term
 7865: 	} elsif ($uri !~ m -^(editupload)/-) {
 7866: 	    my $file=&filelocation('',&clutter($filename));
 7867: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7868: 	    $metastring=&getfile($file);
 7869: 	}
 7870:         my $parser=HTML::LCParser->new(\$metastring);
 7871:         my $token;
 7872:         undef %metathesekeys;
 7873:         while ($token=$parser->get_token) {
 7874: 	    if ($token->[0] eq 'S') {
 7875: 		if (defined($token->[2]->{'package'})) {
 7876: #
 7877: # This is a package - get package info
 7878: #
 7879: 		    my $package=$token->[2]->{'package'};
 7880: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7881: 		    if (defined($token->[2]->{'id'})) { 
 7882: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7883: 		    }
 7884: 		    if ($metaentry{':packages'}) {
 7885: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7886: 		    } else {
 7887: 			$metaentry{':packages'}=$package.$keyroot;
 7888: 		    }
 7889: 		    foreach my $pack_entry (keys(%packagetab)) {
 7890: 			my $part=$keyroot;
 7891: 			$part=~s/^\_//;
 7892: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7893: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7894: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7895: 			    # ignore package.tab specified default values
 7896:                             # here &package_tab_default() will fetch those
 7897: 			    if ($subp eq 'default') { next; }
 7898: 			    my $value=$packagetab{$pack_entry};
 7899: 			    my $unikey;
 7900: 			    if ($pack =~ /_0$/) {
 7901: 				$unikey='parameter_0_'.$name;
 7902: 				$part=0;
 7903: 			    } else {
 7904: 				$unikey='parameter'.$keyroot.'_'.$name;
 7905: 			    }
 7906: 			    if ($subp eq 'display') {
 7907: 				$value.=' [Part: '.$part.']';
 7908: 			    }
 7909: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7910: 			    $metathesekeys{$unikey}=1;
 7911: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7912: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7913: 			    }
 7914: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7915: 				$metaentry{':'.$unikey}=
 7916: 				    $metaentry{':'.$unikey.'.default'};
 7917: 			    }
 7918: 			}
 7919: 		    }
 7920: 		} else {
 7921: #
 7922: # This is not a package - some other kind of start tag
 7923: #
 7924: 		    my $entry=$token->[1];
 7925: 		    my $unikey;
 7926: 		    if ($entry eq 'import') {
 7927: 			$unikey='';
 7928: 		    } else {
 7929: 			$unikey=$entry;
 7930: 		    }
 7931: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7932: 
 7933: 		    if (defined($token->[2]->{'id'})) { 
 7934: 			$unikey.='_'.$token->[2]->{'id'}; 
 7935: 		    }
 7936: 
 7937: 		    if ($entry eq 'import') {
 7938: #
 7939: # Importing a library here
 7940: #
 7941: 			if ($depthcount<20) {
 7942: 			    my $location=$parser->get_text('/import');
 7943: 			    my $dir=$filename;
 7944: 			    $dir=~s|[^/]*$||;
 7945: 			    $location=&filelocation($dir,$location);
 7946: 			    my $metadata = 
 7947: 				&metadata($uri,'keys', $location,$unikey,
 7948: 					  $depthcount+1);
 7949: 			    foreach my $meta (split(',',$metadata)) {
 7950: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7951: 				$metathesekeys{$meta}=1;
 7952: 			    }
 7953: 			}
 7954: 		    } else { 
 7955: 			
 7956: 			if (defined($token->[2]->{'name'})) { 
 7957: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7958: 			}
 7959: 			$metathesekeys{$unikey}=1;
 7960: 			foreach my $param (@{$token->[3]}) {
 7961: 			    $metaentry{':'.$unikey.'.'.$param} =
 7962: 				$token->[2]->{$param};
 7963: 			}
 7964: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7965: 			my $default=$metaentry{':'.$unikey.'.default'};
 7966: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7967: 		 # only ws inside the tag, and not in default, so use default
 7968: 		 # as value
 7969: 			    $metaentry{':'.$unikey}=$default;
 7970: 			} elsif ( $internaltext =~ /\S/ ) {
 7971: 		  # something interesting inside the tag
 7972: 			    $metaentry{':'.$unikey}=$internaltext;
 7973: 			} else {
 7974: 		  # no interesting values, don't set a default
 7975: 			}
 7976: # end of not-a-package not-a-library import
 7977: 		    }
 7978: # end of not-a-package start tag
 7979: 		}
 7980: # the next is the end of "start tag"
 7981: 	    }
 7982: 	}
 7983: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7984: 	$extension = lc($extension);
 7985: 	if ($extension eq 'htm') { $extension='html'; }
 7986: 
 7987: 	foreach my $key (keys(%packagetab)) {
 7988: 	    #no specific packages #how's our extension
 7989: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7990: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7991: 					 \%metathesekeys);
 7992: 	}
 7993: 
 7994: 	if (!exists($metaentry{':packages'})
 7995: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7996: 	    foreach my $key (keys(%packagetab)) {
 7997: 		#no specific packages well let's get default then
 7998: 		if ($key!~/^default&/) { next; }
 7999: 		&metadata_create_package_def($uri,$key,'default',
 8000: 					     \%metathesekeys);
 8001: 	    }
 8002: 	}
 8003: # are there custom rights to evaluate
 8004: 	if ($metaentry{':copyright'} eq 'custom') {
 8005: 
 8006:     #
 8007:     # Importing a rights file here
 8008:     #
 8009: 	    unless ($depthcount) {
 8010: 		my $location=$metaentry{':customdistributionfile'};
 8011: 		my $dir=$filename;
 8012: 		$dir=~s|[^/]*$||;
 8013: 		$location=&filelocation($dir,$location);
 8014: 		my $rights_metadata =
 8015: 		    &metadata($uri,'keys',$location,'_rights',
 8016: 			      $depthcount+1);
 8017: 		foreach my $rights (split(',',$rights_metadata)) {
 8018: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 8019: 		    $metathesekeys{$rights}=1;
 8020: 		}
 8021: 	    }
 8022: 	}
 8023: 	# uniqifiy package listing
 8024: 	my %seen;
 8025: 	my @uniq_packages =
 8026: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 8027: 	$metaentry{':packages'} = join(',',@uniq_packages);
 8028: 
 8029: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 8030: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 8031: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 8032: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 8033: # this is the end of "was not already recently cached
 8034:     }
 8035:     return $metaentry{':'.$what};
 8036: }
 8037: 
 8038: sub metadata_create_package_def {
 8039:     my ($uri,$key,$package,$metathesekeys)=@_;
 8040:     my ($pack,$name,$subp)=split(/\&/,$key);
 8041:     if ($subp eq 'default') { next; }
 8042:     
 8043:     if (defined($metaentry{':packages'})) {
 8044: 	$metaentry{':packages'}.=','.$package;
 8045:     } else {
 8046: 	$metaentry{':packages'}=$package;
 8047:     }
 8048:     my $value=$packagetab{$key};
 8049:     my $unikey;
 8050:     $unikey='parameter_0_'.$name;
 8051:     $metaentry{':'.$unikey.'.part'}=0;
 8052:     $$metathesekeys{$unikey}=1;
 8053:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8054: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 8055:     }
 8056:     if (defined($metaentry{':'.$unikey.'.default'})) {
 8057: 	$metaentry{':'.$unikey}=
 8058: 	    $metaentry{':'.$unikey.'.default'};
 8059:     }
 8060: }
 8061: 
 8062: sub metadata_generate_part0 {
 8063:     my ($metadata,$metacache,$uri) = @_;
 8064:     my %allnames;
 8065:     foreach my $metakey (keys(%$metadata)) {
 8066: 	if ($metakey=~/^parameter\_(.*)/) {
 8067: 	  my $part=$$metacache{':'.$metakey.'.part'};
 8068: 	  my $name=$$metacache{':'.$metakey.'.name'};
 8069: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 8070: 	    $allnames{$name}=$part;
 8071: 	  }
 8072: 	}
 8073:     }
 8074:     foreach my $name (keys(%allnames)) {
 8075:       $$metadata{"parameter_0_$name"}=1;
 8076:       my $key=":parameter_0_$name";
 8077:       $$metacache{"$key.part"}='0';
 8078:       $$metacache{"$key.name"}=$name;
 8079:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 8080: 					   $allnames{$name}.'_'.$name.
 8081: 					   '.type'};
 8082:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 8083: 			     '.display'};
 8084:       my $expr='[Part: '.$allnames{$name}.']';
 8085:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 8086:       $$metacache{"$key.display"}=$olddis;
 8087:     }
 8088: }
 8089: 
 8090: # ------------------------------------------------------ Devalidate title cache
 8091: 
 8092: sub devalidate_title_cache {
 8093:     my ($url)=@_;
 8094:     if (!$env{'request.course.id'}) { return; }
 8095:     my $symb=&symbread($url);
 8096:     if (!$symb) { return; }
 8097:     my $key=$env{'request.course.id'}."\0".$symb;
 8098:     &devalidate_cache_new('title',$key);
 8099: }
 8100: 
 8101: # ------------------------------------------------- Get the title of a course
 8102: 
 8103: sub current_course_title {
 8104:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 8105: }
 8106: # ------------------------------------------------- Get the title of a resource
 8107: 
 8108: sub gettitle {
 8109:     my $urlsymb=shift;
 8110:     my $symb=&symbread($urlsymb);
 8111:     if ($symb) {
 8112: 	my $key=$env{'request.course.id'}."\0".$symb;
 8113: 	my ($result,$cached)=&is_cached_new('title',$key);
 8114: 	if (defined($cached)) { 
 8115: 	    return $result;
 8116: 	}
 8117: 	my ($map,$resid,$url)=&decode_symb($symb);
 8118: 	my $title='';
 8119: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 8120: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 8121: 	} else {
 8122: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8123: 		    &GDBM_READER(),0640)) {
 8124: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 8125: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 8126: 		untie(%bighash);
 8127: 	    }
 8128: 	}
 8129: 	$title=~s/\&colon\;/\:/gs;
 8130: 	if ($title) {
 8131: 	    return &do_cache_new('title',$key,$title,600);
 8132: 	}
 8133: 	$urlsymb=$url;
 8134:     }
 8135:     my $title=&metadata($urlsymb,'title');
 8136:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 8137:     return $title;
 8138: }
 8139: 
 8140: sub get_slot {
 8141:     my ($which,$cnum,$cdom)=@_;
 8142:     if (!$cnum || !$cdom) {
 8143: 	(undef,my $courseid)=&whichuser();
 8144: 	$cdom=$env{'course.'.$courseid.'.domain'};
 8145: 	$cnum=$env{'course.'.$courseid.'.num'};
 8146:     }
 8147:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 8148:     my %slotinfo;
 8149:     if (exists($remembered{$key})) {
 8150: 	$slotinfo{$which} = $remembered{$key};
 8151:     } else {
 8152: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 8153: 	&Apache::lonhomework::showhash(%slotinfo);
 8154: 	my ($tmp)=keys(%slotinfo);
 8155: 	if ($tmp=~/^error:/) { return (); }
 8156: 	$remembered{$key} = $slotinfo{$which};
 8157:     }
 8158:     if (ref($slotinfo{$which}) eq 'HASH') {
 8159: 	return %{$slotinfo{$which}};
 8160:     }
 8161:     return $slotinfo{$which};
 8162: }
 8163: # ------------------------------------------------- Update symbolic store links
 8164: 
 8165: sub symblist {
 8166:     my ($mapname,%newhash)=@_;
 8167:     $mapname=&deversion(&declutter($mapname));
 8168:     my %hash;
 8169:     if (($env{'request.course.fn'}) && (%newhash)) {
 8170:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8171:                       &GDBM_WRCREAT(),0640)) {
 8172: 	    foreach my $url (keys(%newhash)) {
 8173: 		next if ($url eq 'last_known'
 8174: 			 && $env{'form.no_update_last_known'});
 8175: 		$hash{declutter($url)}=&encode_symb($mapname,
 8176: 						    $newhash{$url}->[1],
 8177: 						    $newhash{$url}->[0]);
 8178:             }
 8179:             if (untie(%hash)) {
 8180: 		return 'ok';
 8181:             }
 8182:         }
 8183:     }
 8184:     return 'error';
 8185: }
 8186: 
 8187: # --------------------------------------------------------------- Verify a symb
 8188: 
 8189: sub symbverify {
 8190:     my ($symb,$thisurl)=@_;
 8191:     my $thisfn=$thisurl;
 8192:     $thisfn=&declutter($thisfn);
 8193: # direct jump to resource in page or to a sequence - will construct own symbs
 8194:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8195: # check URL part
 8196:     my ($map,$resid,$url)=&decode_symb($symb);
 8197: 
 8198:     unless ($url eq $thisfn) { return 0; }
 8199: 
 8200:     $symb=&symbclean($symb);
 8201:     $thisurl=&deversion($thisurl);
 8202:     $thisfn=&deversion($thisfn);
 8203: 
 8204:     my %bighash;
 8205:     my $okay=0;
 8206: 
 8207:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8208:                             &GDBM_READER(),0640)) {
 8209:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8210:         unless ($ids) { 
 8211:            $ids=$bighash{'ids_/'.$thisurl};
 8212:         }
 8213:         if ($ids) {
 8214: # ------------------------------------------------------------------- Has ID(s)
 8215: 	    foreach my $id (split(/\,/,$ids)) {
 8216: 	       my ($mapid,$resid)=split(/\./,$id);
 8217:                if (
 8218:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8219:    eq $symb) { 
 8220: 		   if (($env{'request.role.adv'}) ||
 8221: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8222: 		       $okay=1; 
 8223: 		   }
 8224: 	       }
 8225: 	   }
 8226:         }
 8227: 	untie(%bighash);
 8228:     }
 8229:     return $okay;
 8230: }
 8231: 
 8232: # --------------------------------------------------------------- Clean-up symb
 8233: 
 8234: sub symbclean {
 8235:     my $symb=shift;
 8236:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8237: # remove version from map
 8238:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8239: 
 8240: # remove version from URL
 8241:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8242: 
 8243: # remove wrapper
 8244: 
 8245:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8246:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8247:     return $symb;
 8248: }
 8249: 
 8250: # ---------------------------------------------- Split symb to find map and url
 8251: 
 8252: sub encode_symb {
 8253:     my ($map,$resid,$url)=@_;
 8254:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8255: }
 8256: 
 8257: sub decode_symb {
 8258:     my $symb=shift;
 8259:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8260:     my ($map,$resid,$url)=split(/___/,$symb);
 8261:     return (&fixversion($map),$resid,&fixversion($url));
 8262: }
 8263: 
 8264: sub fixversion {
 8265:     my $fn=shift;
 8266:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8267:     my %bighash;
 8268:     my $uri=&clutter($fn);
 8269:     my $key=$env{'request.course.id'}.'_'.$uri;
 8270: # is this cached?
 8271:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8272:     if (defined($cached)) { return $result; }
 8273: # unfortunately not cached, or expired
 8274:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8275: 	    &GDBM_READER(),0640)) {
 8276:  	if ($bighash{'version_'.$uri}) {
 8277:  	    my $version=$bighash{'version_'.$uri};
 8278:  	    unless (($version eq 'mostrecent') || 
 8279: 		    ($version==&getversion($uri))) {
 8280:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8281:  	    }
 8282:  	}
 8283:  	untie %bighash;
 8284:     }
 8285:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8286: }
 8287: 
 8288: sub deversion {
 8289:     my $url=shift;
 8290:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8291:     return $url;
 8292: }
 8293: 
 8294: # ------------------------------------------------------ Return symb list entry
 8295: 
 8296: sub symbread {
 8297:     my ($thisfn,$donotrecurse)=@_;
 8298:     my $cache_str='request.symbread.cached.'.$thisfn;
 8299:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8300: # no filename provided? try from environment
 8301:     unless ($thisfn) {
 8302:         if ($env{'request.symb'}) {
 8303: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8304: 	}
 8305: 	$thisfn=$env{'request.filename'};
 8306:     }
 8307:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8308: # is that filename actually a symb? Verify, clean, and return
 8309:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8310: 	if (&symbverify($thisfn,$1)) {
 8311: 	    return $env{$cache_str}=&symbclean($thisfn);
 8312: 	}
 8313:     }
 8314:     $thisfn=declutter($thisfn);
 8315:     my %hash;
 8316:     my %bighash;
 8317:     my $syval='';
 8318:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8319:         my $targetfn = $thisfn;
 8320:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8321:             $targetfn = 'adm/wrapper/'.$thisfn;
 8322:         }
 8323: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8324: 	    $targetfn=$1;
 8325: 	}
 8326:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8327:                       &GDBM_READER(),0640)) {
 8328: 	    $syval=$hash{$targetfn};
 8329:             untie(%hash);
 8330:         }
 8331: # ---------------------------------------------------------- There was an entry
 8332:         if ($syval) {
 8333: 	    #unless ($syval=~/\_\d+$/) {
 8334: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8335: 		    #&appenv({'request.ambiguous' => $thisfn});
 8336: 		    #return $env{$cache_str}='';
 8337: 		#}    
 8338: 		#$syval.=$1;
 8339: 	    #}
 8340:         } else {
 8341: # ------------------------------------------------------- Was not in symb table
 8342:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8343:                             &GDBM_READER(),0640)) {
 8344: # ---------------------------------------------- Get ID(s) for current resource
 8345:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8346:               unless ($ids) { 
 8347:                  $ids=$bighash{'ids_/'.$thisfn};
 8348:               }
 8349:               unless ($ids) {
 8350: # alias?
 8351: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8352:               }
 8353:               if ($ids) {
 8354: # ------------------------------------------------------------------- Has ID(s)
 8355:                  my @possibilities=split(/\,/,$ids);
 8356:                  if ($#possibilities==0) {
 8357: # ----------------------------------------------- There is only one possibility
 8358: 		     my ($mapid,$resid)=split(/\./,$ids);
 8359: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8360: 						    $resid,$thisfn);
 8361:                  } elsif (!$donotrecurse) {
 8362: # ------------------------------------------ There is more than one possibility
 8363:                      my $realpossible=0;
 8364:                      foreach my $id (@possibilities) {
 8365: 			 my $file=$bighash{'src_'.$id};
 8366:                          if (&allowed('bre',$file)) {
 8367:          		    my ($mapid,$resid)=split(/\./,$id);
 8368:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8369: 				$realpossible++;
 8370:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8371: 						    $resid,$thisfn);
 8372:                             }
 8373: 			 }
 8374:                      }
 8375: 		     if ($realpossible!=1) { $syval=''; }
 8376:                  } else {
 8377:                      $syval='';
 8378:                  }
 8379: 	      }
 8380:               untie(%bighash)
 8381:            }
 8382:         }
 8383:         if ($syval) {
 8384: 	    return $env{$cache_str}=$syval;
 8385:         }
 8386:     }
 8387:     &appenv({'request.ambiguous' => $thisfn});
 8388:     return $env{$cache_str}='';
 8389: }
 8390: 
 8391: # ---------------------------------------------------------- Return random seed
 8392: 
 8393: sub numval {
 8394:     my $txt=shift;
 8395:     $txt=~tr/A-J/0-9/;
 8396:     $txt=~tr/a-j/0-9/;
 8397:     $txt=~tr/K-T/0-9/;
 8398:     $txt=~tr/k-t/0-9/;
 8399:     $txt=~tr/U-Z/0-5/;
 8400:     $txt=~tr/u-z/0-5/;
 8401:     $txt=~s/\D//g;
 8402:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8403:     return int($txt);
 8404: }
 8405: 
 8406: sub numval2 {
 8407:     my $txt=shift;
 8408:     $txt=~tr/A-J/0-9/;
 8409:     $txt=~tr/a-j/0-9/;
 8410:     $txt=~tr/K-T/0-9/;
 8411:     $txt=~tr/k-t/0-9/;
 8412:     $txt=~tr/U-Z/0-5/;
 8413:     $txt=~tr/u-z/0-5/;
 8414:     $txt=~s/\D//g;
 8415:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8416:     my $total;
 8417:     foreach my $val (@txts) { $total+=$val; }
 8418:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8419:     return int($total);
 8420: }
 8421: 
 8422: sub numval3 {
 8423:     use integer;
 8424:     my $txt=shift;
 8425:     $txt=~tr/A-J/0-9/;
 8426:     $txt=~tr/a-j/0-9/;
 8427:     $txt=~tr/K-T/0-9/;
 8428:     $txt=~tr/k-t/0-9/;
 8429:     $txt=~tr/U-Z/0-5/;
 8430:     $txt=~tr/u-z/0-5/;
 8431:     $txt=~s/\D//g;
 8432:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8433:     my $total;
 8434:     foreach my $val (@txts) { $total+=$val; }
 8435:     if ($_64bit) { $total=(($total<<32)>>32); }
 8436:     return $total;
 8437: }
 8438: 
 8439: sub digest {
 8440:     my ($data)=@_;
 8441:     my $digest=&Digest::MD5::md5($data);
 8442:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8443:     my ($e,$f);
 8444:     {
 8445:         use integer;
 8446:         $e=($a+$b);
 8447:         $f=($c+$d);
 8448:         if ($_64bit) {
 8449:             $e=(($e<<32)>>32);
 8450:             $f=(($f<<32)>>32);
 8451:         }
 8452:     }
 8453:     if (wantarray) {
 8454: 	return ($e,$f);
 8455:     } else {
 8456: 	my $g;
 8457: 	{
 8458: 	    use integer;
 8459: 	    $g=($e+$f);
 8460: 	    if ($_64bit) {
 8461: 		$g=(($g<<32)>>32);
 8462: 	    }
 8463: 	}
 8464: 	return $g;
 8465:     }
 8466: }
 8467: 
 8468: sub latest_rnd_algorithm_id {
 8469:     return '64bit5';
 8470: }
 8471: 
 8472: sub get_rand_alg {
 8473:     my ($courseid)=@_;
 8474:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8475:     if ($courseid) {
 8476: 	return $env{"course.$courseid.rndseed"};
 8477:     }
 8478:     return &latest_rnd_algorithm_id();
 8479: }
 8480: 
 8481: sub validCODE {
 8482:     my ($CODE)=@_;
 8483:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8484:     return 0;
 8485: }
 8486: 
 8487: sub getCODE {
 8488:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8489:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8490: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8491: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8492: 	return $Apache::lonhomework::history{'resource.CODE'};
 8493:     }
 8494:     return undef;
 8495: }
 8496: 
 8497: sub rndseed {
 8498:     my ($symb,$courseid,$domain,$username)=@_;
 8499:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8500:     if (!defined($symb)) {
 8501: 	unless ($symb=$wsymb) { return time; }
 8502:     }
 8503:     if (!$courseid) { $courseid=$wcourseid; }
 8504:     if (!$domain) { $domain=$wdomain; }
 8505:     if (!$username) { $username=$wusername }
 8506:     my $which=&get_rand_alg();
 8507: 
 8508:     if (defined(&getCODE())) {
 8509: 	if ($which eq '64bit5') {
 8510: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8511: 	} elsif ($which eq '64bit4') {
 8512: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8513: 	} else {
 8514: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8515: 	}
 8516:     } elsif ($which eq '64bit5') {
 8517: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8518:     } elsif ($which eq '64bit4') {
 8519: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8520:     } elsif ($which eq '64bit3') {
 8521: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8522:     } elsif ($which eq '64bit2') {
 8523: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8524:     } elsif ($which eq '64bit') {
 8525: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8526:     }
 8527:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8528: }
 8529: 
 8530: sub rndseed_32bit {
 8531:     my ($symb,$courseid,$domain,$username)=@_;
 8532:     {
 8533: 	use integer;
 8534: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8535: 	my $symbseed=numval($symb) << 22;
 8536: 	my $namechck=unpack("%32C*",$username) << 17;
 8537: 	my $nameseed=numval($username) << 12;
 8538: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8539: 	my $courseseed=unpack("%32C*",$courseid);
 8540: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8541: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8542: 	#&logthis("rndseed :$num:$symb");
 8543: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8544: 	return $num;
 8545:     }
 8546: }
 8547: 
 8548: sub rndseed_64bit {
 8549:     my ($symb,$courseid,$domain,$username)=@_;
 8550:     {
 8551: 	use integer;
 8552: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8553: 	my $symbseed=numval($symb) << 10;
 8554: 	my $namechck=unpack("%32S*",$username);
 8555: 	
 8556: 	my $nameseed=numval($username) << 21;
 8557: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8558: 	my $courseseed=unpack("%32S*",$courseid);
 8559: 	
 8560: 	my $num1=$symbchck+$symbseed+$namechck;
 8561: 	my $num2=$nameseed+$domainseed+$courseseed;
 8562: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8563: 	#&logthis("rndseed :$num:$symb");
 8564: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8565: 	return "$num1,$num2";
 8566:     }
 8567: }
 8568: 
 8569: sub rndseed_64bit2 {
 8570:     my ($symb,$courseid,$domain,$username)=@_;
 8571:     {
 8572: 	use integer;
 8573: 	# strings need to be an even # of cahracters long, it it is odd the
 8574:         # last characters gets thrown away
 8575: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8576: 	my $symbseed=numval($symb) << 10;
 8577: 	my $namechck=unpack("%32S*",$username.' ');
 8578: 	
 8579: 	my $nameseed=numval($username) << 21;
 8580: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8581: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8582: 	
 8583: 	my $num1=$symbchck+$symbseed+$namechck;
 8584: 	my $num2=$nameseed+$domainseed+$courseseed;
 8585: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8586: 	#&logthis("rndseed :$num:$symb");
 8587: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8588: 	return "$num1,$num2";
 8589:     }
 8590: }
 8591: 
 8592: sub rndseed_64bit3 {
 8593:     my ($symb,$courseid,$domain,$username)=@_;
 8594:     {
 8595: 	use integer;
 8596: 	# strings need to be an even # of cahracters long, it it is odd the
 8597:         # last characters gets thrown away
 8598: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8599: 	my $symbseed=numval2($symb) << 10;
 8600: 	my $namechck=unpack("%32S*",$username.' ');
 8601: 	
 8602: 	my $nameseed=numval2($username) << 21;
 8603: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8604: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8605: 	
 8606: 	my $num1=$symbchck+$symbseed+$namechck;
 8607: 	my $num2=$nameseed+$domainseed+$courseseed;
 8608: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8609: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8610: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8611: 	
 8612: 	return "$num1:$num2";
 8613:     }
 8614: }
 8615: 
 8616: sub rndseed_64bit4 {
 8617:     my ($symb,$courseid,$domain,$username)=@_;
 8618:     {
 8619: 	use integer;
 8620: 	# strings need to be an even # of cahracters long, it it is odd the
 8621:         # last characters gets thrown away
 8622: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8623: 	my $symbseed=numval3($symb) << 10;
 8624: 	my $namechck=unpack("%32S*",$username.' ');
 8625: 	
 8626: 	my $nameseed=numval3($username) << 21;
 8627: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8628: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8629: 	
 8630: 	my $num1=$symbchck+$symbseed+$namechck;
 8631: 	my $num2=$nameseed+$domainseed+$courseseed;
 8632: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8633: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8634: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8635: 	
 8636: 	return "$num1:$num2";
 8637:     }
 8638: }
 8639: 
 8640: sub rndseed_64bit5 {
 8641:     my ($symb,$courseid,$domain,$username)=@_;
 8642:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8643:     return "$num1:$num2";
 8644: }
 8645: 
 8646: sub rndseed_CODE_64bit {
 8647:     my ($symb,$courseid,$domain,$username)=@_;
 8648:     {
 8649: 	use integer;
 8650: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8651: 	my $symbseed=numval2($symb);
 8652: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8653: 	my $CODEseed=numval(&getCODE());
 8654: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8655: 	my $num1=$symbseed+$CODEchck;
 8656: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8657: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8658: 	#&logthis("rndseed :$num1:$num2:$symb");
 8659: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8660: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8661: 	return "$num1:$num2";
 8662:     }
 8663: }
 8664: 
 8665: sub rndseed_CODE_64bit4 {
 8666:     my ($symb,$courseid,$domain,$username)=@_;
 8667:     {
 8668: 	use integer;
 8669: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8670: 	my $symbseed=numval3($symb);
 8671: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8672: 	my $CODEseed=numval3(&getCODE());
 8673: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8674: 	my $num1=$symbseed+$CODEchck;
 8675: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8676: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8677: 	#&logthis("rndseed :$num1:$num2:$symb");
 8678: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8679: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8680: 	return "$num1:$num2";
 8681:     }
 8682: }
 8683: 
 8684: sub rndseed_CODE_64bit5 {
 8685:     my ($symb,$courseid,$domain,$username)=@_;
 8686:     my $code = &getCODE();
 8687:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8688:     return "$num1:$num2";
 8689: }
 8690: 
 8691: sub setup_random_from_rndseed {
 8692:     my ($rndseed)=@_;
 8693:     if ($rndseed =~/([,:])/) {
 8694: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8695: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8696:     } else {
 8697: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8698:     }
 8699: }
 8700: 
 8701: sub latest_receipt_algorithm_id {
 8702:     return 'receipt3';
 8703: }
 8704: 
 8705: sub recunique {
 8706:     my $fucourseid=shift;
 8707:     my $unique;
 8708:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8709: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8710: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8711:     } else {
 8712: 	$unique=$perlvar{'lonReceipt'};
 8713:     }
 8714:     return unpack("%32C*",$unique);
 8715: }
 8716: 
 8717: sub recprefix {
 8718:     my $fucourseid=shift;
 8719:     my $prefix;
 8720:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8721: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8722: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8723:     } else {
 8724: 	$prefix=$perlvar{'lonHostID'};
 8725:     }
 8726:     return unpack("%32C*",$prefix);
 8727: }
 8728: 
 8729: sub ireceipt {
 8730:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8731: 
 8732:     my $return =&recprefix($fucourseid).'-';
 8733: 
 8734:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8735: 	$env{'request.state'} eq 'construct') {
 8736: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8737: 	return $return;
 8738:     }
 8739: 
 8740:     my $cuname=unpack("%32C*",$funame);
 8741:     my $cudom=unpack("%32C*",$fudom);
 8742:     my $cucourseid=unpack("%32C*",$fucourseid);
 8743:     my $cusymb=unpack("%32C*",$fusymb);
 8744:     my $cunique=&recunique($fucourseid);
 8745:     my $cpart=unpack("%32S*",$part);
 8746:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8747: 
 8748: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8749: 			       
 8750: 	$return.= ($cunique%$cuname+
 8751: 		   $cunique%$cudom+
 8752: 		   $cusymb%$cuname+
 8753: 		   $cusymb%$cudom+
 8754: 		   $cucourseid%$cuname+
 8755: 		   $cucourseid%$cudom+
 8756: 		   $cpart%$cuname+
 8757: 		   $cpart%$cudom);
 8758:     } else {
 8759: 	$return.= ($cunique%$cuname+
 8760: 		   $cunique%$cudom+
 8761: 		   $cusymb%$cuname+
 8762: 		   $cusymb%$cudom+
 8763: 		   $cucourseid%$cuname+
 8764: 		   $cucourseid%$cudom);
 8765:     }
 8766:     return $return;
 8767: }
 8768: 
 8769: sub receipt {
 8770:     my ($part)=@_;
 8771:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8772:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8773: }
 8774: 
 8775: sub whichuser {
 8776:     my ($passedsymb)=@_;
 8777:     my ($symb,$courseid,$domain,$name,$publicuser);
 8778:     if (defined($env{'form.grade_symb'})) {
 8779: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8780: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8781: 	if (!$allowed &&
 8782: 	    exists($env{'request.course.sec'}) &&
 8783: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8784: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8785: 			      '/'.$env{'request.course.sec'});
 8786: 	}
 8787: 	if ($allowed) {
 8788: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8789: 	    $courseid=$tmp_courseid;
 8790: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8791: 	    ($name)=&get_env_multiple('form.grade_username');
 8792: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8793: 	}
 8794:     }
 8795:     if (!$passedsymb) {
 8796: 	$symb=&symbread();
 8797:     } else {
 8798: 	$symb=$passedsymb;
 8799:     }
 8800:     $courseid=$env{'request.course.id'};
 8801:     $domain=$env{'user.domain'};
 8802:     $name=$env{'user.name'};
 8803:     if ($name eq 'public' && $domain eq 'public') {
 8804: 	if (!defined($env{'form.username'})) {
 8805: 	    $env{'form.username'}.=time.rand(10000000);
 8806: 	}
 8807: 	$name.=$env{'form.username'};
 8808:     }
 8809:     return ($symb,$courseid,$domain,$name,$publicuser);
 8810: 
 8811: }
 8812: 
 8813: # ------------------------------------------------------------ Serves up a file
 8814: # returns either the contents of the file or 
 8815: # -1 if the file doesn't exist
 8816: #
 8817: # if the target is a file that was uploaded via DOCS, 
 8818: # a check will be made to see if a current copy exists on the local server,
 8819: # if it does this will be served, otherwise a copy will be retrieved from
 8820: # the home server for the course and stored in /home/httpd/html/userfiles on
 8821: # the local server.   
 8822: 
 8823: sub getfile {
 8824:     my ($file) = @_;
 8825:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8826:     &repcopy($file);
 8827:     return &readfile($file);
 8828: }
 8829: 
 8830: sub repcopy_userfile {
 8831:     my ($file)=@_;
 8832:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8833:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8834:     my ($cdom,$cnum,$filename) = 
 8835: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8836:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8837:     if (-e "$file") {
 8838: # we already have a local copy, check it out
 8839: 	my @fileinfo = stat($file);
 8840: 	my $rtncode;
 8841: 	my $info;
 8842: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8843: 	if ($lwpresp ne 'ok') {
 8844: # there is no such file anymore, even though we had a local copy
 8845: 	    if ($rtncode eq '404') {
 8846: 		unlink($file);
 8847: 	    }
 8848: 	    return -1;
 8849: 	}
 8850: 	if ($info < $fileinfo[9]) {
 8851: # nice, the file we have is up-to-date, just say okay
 8852: 	    return 'ok';
 8853: 	} else {
 8854: # the file is outdated, get rid of it
 8855: 	    unlink($file);
 8856: 	}
 8857:     }
 8858: # one way or the other, at this point, we don't have the file
 8859: # construct the correct path for the file
 8860:     my @parts = ($cdom,$cnum); 
 8861:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8862: 	push @parts, split(/\//,$1);
 8863:     }
 8864:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8865:     foreach my $part (@parts) {
 8866: 	$path .= '/'.$part;
 8867: 	if (!-e $path) {
 8868: 	    mkdir($path,0770);
 8869: 	}
 8870:     }
 8871: # now the path exists for sure
 8872: # get a user agent
 8873:     my $ua=new LWP::UserAgent;
 8874:     my $transferfile=$file.'.in.transfer';
 8875: # FIXME: this should flock
 8876:     if (-e $transferfile) { return 'ok'; }
 8877:     my $request;
 8878:     $uri=~s/^\///;
 8879:     my $homeserver = &homeserver($cnum,$cdom);
 8880:     my $protocol = $protocol{$homeserver};
 8881:     $protocol = 'http' if ($protocol ne 'https');
 8882:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8883:     my $response=$ua->request($request,$transferfile);
 8884: # did it work?
 8885:     if ($response->is_error()) {
 8886: 	unlink($transferfile);
 8887: 	&logthis("Userfile repcopy failed for $uri");
 8888: 	return -1;
 8889:     }
 8890: # worked, rename the transfer file
 8891:     rename($transferfile,$file);
 8892:     return 'ok';
 8893: }
 8894: 
 8895: sub tokenwrapper {
 8896:     my $uri=shift;
 8897:     $uri=~s|^https?\://([^/]+)||;
 8898:     $uri=~s|^/||;
 8899:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8900:     my $token=$1;
 8901:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8902:     if ($udom && $uname && $file) {
 8903: 	$file=~s|(\?\.*)*$||;
 8904:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8905:         my $homeserver = &homeserver($uname,$udom);
 8906:         my $protocol = $protocol{$homeserver};
 8907:         $protocol = 'http' if ($protocol ne 'https');
 8908:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8909:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8910:                                '&tokenissued='.$perlvar{'lonHostID'};
 8911:     } else {
 8912:         return '/adm/notfound.html';
 8913:     }
 8914: }
 8915: 
 8916: # call with reqtype HEAD: get last modification time
 8917: # call with reqtype GET: get the file contents
 8918: # Do not call this with reqtype GET for large files! It loads everything into memory
 8919: #
 8920: sub getuploaded {
 8921:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8922:     $uri=~s/^\///;
 8923:     my $homeserver = &homeserver($cnum,$cdom);
 8924:     my $protocol = $protocol{$homeserver};
 8925:     $protocol = 'http' if ($protocol ne 'https');
 8926:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8927:     my $ua=new LWP::UserAgent;
 8928:     my $request=new HTTP::Request($reqtype,$uri);
 8929:     my $response=$ua->request($request);
 8930:     $$rtncode = $response->code;
 8931:     if (! $response->is_success()) {
 8932: 	return 'failed';
 8933:     }      
 8934:     if ($reqtype eq 'HEAD') {
 8935: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8936:     } elsif ($reqtype eq 'GET') {
 8937: 	$$info = $response->content;
 8938:     }
 8939:     return 'ok';
 8940: }
 8941: 
 8942: sub readfile {
 8943:     my $file = shift;
 8944:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8945:     my $fh;
 8946:     open($fh,"<$file");
 8947:     my $a='';
 8948:     while (my $line = <$fh>) { $a .= $line; }
 8949:     return $a;
 8950: }
 8951: 
 8952: sub filelocation {
 8953:     my ($dir,$file) = @_;
 8954:     my $location;
 8955:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8956: 
 8957:     if ($file =~ m-^/adm/-) {
 8958: 	$file=~s-^/adm/wrapper/-/-;
 8959: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8960:     }
 8961: 
 8962:     if ($file=~m:^/~:) { # is a contruction space reference
 8963:         $location = $file;
 8964:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8965:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8966: 	# is a correct contruction space reference
 8967:         $location = $file;
 8968:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8969:         $location = $file;
 8970:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8971:         my ($udom,$uname,$filename)=
 8972:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8973:         my $home=&homeserver($uname,$udom);
 8974:         my $is_me=0;
 8975:         my @ids=&current_machine_ids();
 8976:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8977:         if ($is_me) {
 8978:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8979:         } else {
 8980:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8981:   	      $udom.'/'.$uname.'/'.$filename;
 8982:         }
 8983:     } elsif ($file =~ m-^/adm/-) {
 8984: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8985:     } else {
 8986:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8987:         $file=~s:^/res/:/:;
 8988:         if ( !( $file =~ m:^/:) ) {
 8989:             $location = $dir. '/'.$file;
 8990:         } else {
 8991:             $location = '/home/httpd/html/res'.$file;
 8992:         }
 8993:     }
 8994:     $location=~s://+:/:g; # remove duplicate /
 8995:     while ($location=~m{/\.\./}) {
 8996: 	if ($location =~ m{/[^/]+/\.\./}) {
 8997: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8998: 	} else {
 8999: 	    $location=~ s{/\.\./}{/}g;
 9000: 	}
 9001:     } #remove dir/..
 9002:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 9003:     return $location;
 9004: }
 9005: 
 9006: sub hreflocation {
 9007:     my ($dir,$file)=@_;
 9008:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 9009: 	$file=filelocation($dir,$file);
 9010:     } elsif ($file=~m-^/adm/-) {
 9011: 	$file=~s-^/adm/wrapper/-/-;
 9012: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9013:     }
 9014:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 9015: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 9016:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 9017: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 9018:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 9019: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 9020: 	    -/uploaded/$1/$2/-x;
 9021:     }
 9022:     if ($file=~ m{^/userfiles/}) {
 9023: 	$file =~ s{^/userfiles/}{/uploaded/};
 9024:     }
 9025:     return $file;
 9026: }
 9027: 
 9028: sub current_machine_domains {
 9029:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 9030: }
 9031: 
 9032: sub machine_domains {
 9033:     my ($hostname) = @_;
 9034:     my @domains;
 9035:     my %hostname = &all_hostnames();
 9036:     while( my($id, $name) = each(%hostname)) {
 9037: #	&logthis("-$id-$name-$hostname-");
 9038: 	if ($hostname eq $name) {
 9039: 	    push(@domains,&host_domain($id));
 9040: 	}
 9041:     }
 9042:     return @domains;
 9043: }
 9044: 
 9045: sub current_machine_ids {
 9046:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 9047: }
 9048: 
 9049: sub machine_ids {
 9050:     my ($hostname) = @_;
 9051:     $hostname ||= &hostname($perlvar{'lonHostID'});
 9052:     my @ids;
 9053:     my %name_to_host = &all_names();
 9054:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 9055: 	return @{ $name_to_host{$hostname} };
 9056:     }
 9057:     return;
 9058: }
 9059: 
 9060: sub additional_machine_domains {
 9061:     my @domains;
 9062:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 9063:     while( my $line = <$fh>) {
 9064:         $line =~ s/\s//g;
 9065:         push(@domains,$line);
 9066:     }
 9067:     return @domains;
 9068: }
 9069: 
 9070: sub default_login_domain {
 9071:     my $domain = $perlvar{'lonDefDomain'};
 9072:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 9073:     foreach my $posdom (&current_machine_domains(),
 9074:                         &additional_machine_domains()) {
 9075:         if (lc($posdom) eq lc($testdomain)) {
 9076:             $domain=$posdom;
 9077:             last;
 9078:         }
 9079:     }
 9080:     return $domain;
 9081: }
 9082: 
 9083: # ------------------------------------------------------------- Declutters URLs
 9084: 
 9085: sub declutter {
 9086:     my $thisfn=shift;
 9087:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9088:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9089:     $thisfn=~s/^\///;
 9090:     $thisfn=~s|^adm/wrapper/||;
 9091:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 9092:     $thisfn=~s/^res\///;
 9093:     $thisfn=~s/\?.+$//;
 9094:     return $thisfn;
 9095: }
 9096: 
 9097: # ------------------------------------------------------------- Clutter up URLs
 9098: 
 9099: sub clutter {
 9100:     my $thisfn='/'.&declutter(shift);
 9101:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 9102: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 9103:        $thisfn='/res'.$thisfn; 
 9104:     }
 9105:     if ($thisfn !~m|/adm|) {
 9106: 	if ($thisfn =~ m|/ext/|) {
 9107: 	    $thisfn='/adm/wrapper'.$thisfn;
 9108: 	} else {
 9109: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 9110: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 9111: 	    if ($embstyle eq 'ssi'
 9112: 		|| ($embstyle eq 'hdn')
 9113: 		|| ($embstyle eq 'rat')
 9114: 		|| ($embstyle eq 'prv')
 9115: 		|| ($embstyle eq 'ign')) {
 9116: 		#do nothing with these
 9117: 	    } elsif (($embstyle eq 'img') 
 9118: 		|| ($embstyle eq 'emb')
 9119: 		|| ($embstyle eq 'wrp')) {
 9120: 		$thisfn='/adm/wrapper'.$thisfn;
 9121: 	    } elsif ($embstyle eq 'unk'
 9122: 		     && $thisfn!~/\.(sequence|page)$/) {
 9123: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 9124: 	    } else {
 9125: #		&logthis("Got a blank emb style");
 9126: 	    }
 9127: 	}
 9128:     }
 9129:     return $thisfn;
 9130: }
 9131: 
 9132: sub clutter_with_no_wrapper {
 9133:     my $uri = &clutter(shift);
 9134:     if ($uri =~ m-^/adm/-) {
 9135: 	$uri =~ s-^/adm/wrapper/-/-;
 9136: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 9137:     }
 9138:     return $uri;
 9139: }
 9140: 
 9141: sub freeze_escape {
 9142:     my ($value)=@_;
 9143:     if (ref($value)) {
 9144: 	$value=&nfreeze($value);
 9145: 	return '__FROZEN__'.&escape($value);
 9146:     }
 9147:     return &escape($value);
 9148: }
 9149: 
 9150: 
 9151: sub thaw_unescape {
 9152:     my ($value)=@_;
 9153:     if ($value =~ /^__FROZEN__/) {
 9154: 	substr($value,0,10,undef);
 9155: 	$value=&unescape($value);
 9156: 	return &thaw($value);
 9157:     }
 9158:     return &unescape($value);
 9159: }
 9160: 
 9161: sub correct_line_ends {
 9162:     my ($result)=@_;
 9163:     $$result =~s/\r\n/\n/mg;
 9164:     $$result =~s/\r/\n/mg;
 9165: }
 9166: # ================================================================ Main Program
 9167: 
 9168: sub goodbye {
 9169:    &logthis("Starting Shut down");
 9170: #not converted to using infrastruture and probably shouldn't be
 9171:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 9172: #converted
 9173: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 9174:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 9175: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 9176: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 9177: #1.1 only
 9178: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 9179: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 9180: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 9181: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 9182:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 9183:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 9184:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 9185:    &flushcourselogs();
 9186:    &logthis("Shutting down");
 9187: }
 9188: 
 9189: sub get_dns {
 9190:     my ($url,$func,$ignore_cache) = @_;
 9191:     if (!$ignore_cache) {
 9192: 	my ($content,$cached)=
 9193: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9194: 	if ($cached) {
 9195: 	    &$func($content);
 9196: 	    return;
 9197: 	}
 9198:     }
 9199: 
 9200:     my %alldns;
 9201:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9202:     foreach my $dns (<$config>) {
 9203: 	next if ($dns !~ /^\^(\S*)/x);
 9204:         my $line = $1;
 9205:         my ($host,$protocol) = split(/:/,$line);
 9206:         if ($protocol ne 'https') {
 9207:             $protocol = 'http';
 9208:         }
 9209: 	$alldns{$host} = $protocol;
 9210:     }
 9211:     while (%alldns) {
 9212: 	my ($dns) = keys(%alldns);
 9213: 	my $ua=new LWP::UserAgent;
 9214: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9215: 	my $response=$ua->request($request);
 9216:         delete($alldns{$dns});
 9217: 	next if ($response->is_error());
 9218: 	my @content = split("\n",$response->content);
 9219: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9220: 	&$func(\@content);
 9221: 	return;
 9222:     }
 9223:     close($config);
 9224:     my $which = (split('/',$url))[3];
 9225:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9226:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9227:     my @content = <$config>;
 9228:     &$func(\@content);
 9229:     return;
 9230: }
 9231: # ------------------------------------------------------------ Read domain file
 9232: {
 9233:     my $loaded;
 9234:     my %domain;
 9235: 
 9236:     sub parse_domain_tab {
 9237: 	my ($lines) = @_;
 9238: 	foreach my $line (@$lines) {
 9239: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9240: 
 9241: 	    chomp($line);
 9242: 	    my ($name,@elements) = split(/:/,$line,9);
 9243: 	    my %this_domain;
 9244: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9245: 			       'lang_def', 'city', 'longi', 'lati',
 9246: 			       'primary') {
 9247: 		$this_domain{$field} = shift(@elements);
 9248: 	    }
 9249: 	    $domain{$name} = \%this_domain;
 9250: 	}
 9251:     }
 9252: 
 9253:     sub reset_domain_info {
 9254: 	undef($loaded);
 9255: 	undef(%domain);
 9256:     }
 9257: 
 9258:     sub load_domain_tab {
 9259: 	my ($ignore_cache) = @_;
 9260: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9261: 	my $fh;
 9262: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9263: 	    my @lines = <$fh>;
 9264: 	    &parse_domain_tab(\@lines);
 9265: 	}
 9266: 	close($fh);
 9267: 	$loaded = 1;
 9268:     }
 9269: 
 9270:     sub domain {
 9271: 	&load_domain_tab() if (!$loaded);
 9272: 
 9273: 	my ($name,$what) = @_;
 9274: 	return if ( !exists($domain{$name}) );
 9275: 
 9276: 	if (!$what) {
 9277: 	    return $domain{$name}{'description'};
 9278: 	}
 9279: 	return $domain{$name}{$what};
 9280:     }
 9281: 
 9282:     sub domain_info {
 9283:         &load_domain_tab() if (!$loaded);
 9284:         return %domain;
 9285:     }
 9286: 
 9287: }
 9288: 
 9289: 
 9290: # ------------------------------------------------------------- Read hosts file
 9291: {
 9292:     my %hostname;
 9293:     my %hostdom;
 9294:     my %libserv;
 9295:     my $loaded;
 9296:     my %name_to_host;
 9297: 
 9298:     sub parse_hosts_tab {
 9299: 	my ($file) = @_;
 9300: 	foreach my $configline (@$file) {
 9301: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9302: 	    next if ($configline =~ /^\^/);
 9303: 	    chomp($configline);
 9304: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9305: 	    $name=~s/\s//g;
 9306: 	    if ($id && $domain && $role && $name) {
 9307: 		$hostname{$id}=$name;
 9308: 		push(@{$name_to_host{$name}}, $id);
 9309: 		$hostdom{$id}=$domain;
 9310: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9311:                 if (defined($protocol)) {
 9312:                     if ($protocol eq 'https') {
 9313:                         $protocol{$id} = $protocol;
 9314:                     } else {
 9315:                         $protocol{$id} = 'http'; 
 9316:                     }
 9317:                 } else {
 9318:                     $protocol{$id} = 'http';
 9319:                 }
 9320: 	    }
 9321: 	}
 9322:     }
 9323:     
 9324:     sub reset_hosts_info {
 9325: 	&purge_remembered();
 9326: 	&reset_domain_info();
 9327: 	&reset_hosts_ip_info();
 9328: 	undef(%name_to_host);
 9329: 	undef(%hostname);
 9330: 	undef(%hostdom);
 9331: 	undef(%libserv);
 9332: 	undef($loaded);
 9333:     }
 9334: 
 9335:     sub load_hosts_tab {
 9336: 	my ($ignore_cache) = @_;
 9337: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9338: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9339: 	my @config = <$config>;
 9340: 	&parse_hosts_tab(\@config);
 9341: 	close($config);
 9342: 	$loaded=1;
 9343:     }
 9344: 
 9345:     sub hostname {
 9346: 	&load_hosts_tab() if (!$loaded);
 9347: 
 9348: 	my ($lonid) = @_;
 9349: 	return $hostname{$lonid};
 9350:     }
 9351: 
 9352:     sub all_hostnames {
 9353: 	&load_hosts_tab() if (!$loaded);
 9354: 
 9355: 	return %hostname;
 9356:     }
 9357: 
 9358:     sub all_names {
 9359: 	&load_hosts_tab() if (!$loaded);
 9360: 
 9361: 	return %name_to_host;
 9362:     }
 9363: 
 9364:     sub all_host_domain {
 9365:         &load_hosts_tab() if (!$loaded);
 9366:         return %hostdom;
 9367:     }
 9368: 
 9369:     sub is_library {
 9370: 	&load_hosts_tab() if (!$loaded);
 9371: 
 9372: 	return exists($libserv{$_[0]});
 9373:     }
 9374: 
 9375:     sub all_library {
 9376: 	&load_hosts_tab() if (!$loaded);
 9377: 
 9378: 	return %libserv;
 9379:     }
 9380: 
 9381:     sub get_servers {
 9382: 	&load_hosts_tab() if (!$loaded);
 9383: 
 9384: 	my ($domain,$type) = @_;
 9385: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9386: 	                                          : %hostname;
 9387: 	my %result;
 9388: 	if (ref($domain) eq 'ARRAY') {
 9389: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9390: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9391: 		    $result{$host} = $hostname;
 9392: 		}
 9393: 	    }
 9394: 	} else {
 9395: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9396: 		if ($hostdom{$host} eq $domain) {
 9397: 		    $result{$host} = $hostname;
 9398: 		}
 9399: 	    }
 9400: 	}
 9401: 	return %result;
 9402:     }
 9403: 
 9404:     sub host_domain {
 9405: 	&load_hosts_tab() if (!$loaded);
 9406: 
 9407: 	my ($lonid) = @_;
 9408: 	return $hostdom{$lonid};
 9409:     }
 9410: 
 9411:     sub all_domains {
 9412: 	&load_hosts_tab() if (!$loaded);
 9413: 
 9414: 	my %seen;
 9415: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9416: 	return @uniq;
 9417:     }
 9418: }
 9419: 
 9420: { 
 9421:     my %iphost;
 9422:     my %name_to_ip;
 9423:     my %lonid_to_ip;
 9424: 
 9425:     sub get_hosts_from_ip {
 9426: 	my ($ip) = @_;
 9427: 	my %iphosts = &get_iphost();
 9428: 	if (ref($iphosts{$ip})) {
 9429: 	    return @{$iphosts{$ip}};
 9430: 	}
 9431: 	return;
 9432:     }
 9433:     
 9434:     sub reset_hosts_ip_info {
 9435: 	undef(%iphost);
 9436: 	undef(%name_to_ip);
 9437: 	undef(%lonid_to_ip);
 9438:     }
 9439: 
 9440:     sub get_host_ip {
 9441: 	my ($lonid) = @_;
 9442: 	if (exists($lonid_to_ip{$lonid})) {
 9443: 	    return $lonid_to_ip{$lonid};
 9444: 	}
 9445: 	my $name=&hostname($lonid);
 9446:    	my $ip = gethostbyname($name);
 9447: 	return if (!$ip || length($ip) ne 4);
 9448: 	$ip=inet_ntoa($ip);
 9449: 	$name_to_ip{$name}   = $ip;
 9450: 	$lonid_to_ip{$lonid} = $ip;
 9451: 	return $ip;
 9452:     }
 9453:     
 9454:     sub get_iphost {
 9455: 	my ($ignore_cache) = @_;
 9456: 
 9457: 	if (!$ignore_cache) {
 9458: 	    if (%iphost) {
 9459: 		return %iphost;
 9460: 	    }
 9461: 	    my ($ip_info,$cached)=
 9462: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9463: 	    if ($cached) {
 9464: 		%iphost      = %{$ip_info->[0]};
 9465: 		%name_to_ip  = %{$ip_info->[1]};
 9466: 		%lonid_to_ip = %{$ip_info->[2]};
 9467: 		return %iphost;
 9468: 	    }
 9469: 	}
 9470: 
 9471: 	# get yesterday's info for fallback
 9472: 	my %old_name_to_ip;
 9473: 	my ($ip_info,$cached)=
 9474: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9475: 	if ($cached) {
 9476: 	    %old_name_to_ip = %{$ip_info->[1]};
 9477: 	}
 9478: 
 9479: 	my %name_to_host = &all_names();
 9480: 	foreach my $name (keys(%name_to_host)) {
 9481: 	    my $ip;
 9482: 	    if (!exists($name_to_ip{$name})) {
 9483: 		$ip = gethostbyname($name);
 9484: 		if (!$ip || length($ip) ne 4) {
 9485: 		    if (defined($old_name_to_ip{$name})) {
 9486: 			$ip = $old_name_to_ip{$name};
 9487: 			&logthis("Can't find $name defaulting to old $ip");
 9488: 		    } else {
 9489: 			&logthis("Name $name no IP found");
 9490: 			next;
 9491: 		    }
 9492: 		} else {
 9493: 		    $ip=inet_ntoa($ip);
 9494: 		}
 9495: 		$name_to_ip{$name} = $ip;
 9496: 	    } else {
 9497: 		$ip = $name_to_ip{$name};
 9498: 	    }
 9499: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9500: 		$lonid_to_ip{$id} = $ip;
 9501: 	    }
 9502: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9503: 	}
 9504: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9505: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9506: 				      48*60*60);
 9507: 
 9508: 	return %iphost;
 9509:     }
 9510: 
 9511:     #
 9512:     #  Given a DNS returns the loncapa host name for that DNS 
 9513:     # 
 9514:     sub host_from_dns {
 9515:         my ($dns) = @_;
 9516:         my @hosts;
 9517:         my $ip;
 9518: 
 9519:         if (exists($name_to_ip{$dns})) {
 9520:             $ip = $name_to_ip{$dns};
 9521:         }
 9522:         if (!$ip) {
 9523:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9524:             if (length($ip) == 4) { 
 9525: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9526:             }
 9527:         }
 9528:         if ($ip) {
 9529: 	    @hosts = get_hosts_from_ip($ip);
 9530: 	    return $hosts[0];
 9531:         }
 9532:         return undef;
 9533:     }
 9534: 
 9535: }
 9536: 
 9537: BEGIN {
 9538: 
 9539: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9540:     unless ($readit) {
 9541: {
 9542:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9543:     %perlvar = (%perlvar,%{$configvars});
 9544: }
 9545: 
 9546: 
 9547: # ------------------------------------------------------ Read spare server file
 9548: {
 9549:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9550: 
 9551:     while (my $configline=<$config>) {
 9552:        chomp($configline);
 9553:        if ($configline) {
 9554: 	   my ($host,$type) = split(':',$configline,2);
 9555: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9556: 	   push(@{ $spareid{$type} }, $host);
 9557:        }
 9558:     }
 9559:     close($config);
 9560: }
 9561: # ------------------------------------------------------------ Read permissions
 9562: {
 9563:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9564: 
 9565:     while (my $configline=<$config>) {
 9566: 	chomp($configline);
 9567: 	if ($configline) {
 9568: 	    my ($role,$perm)=split(/ /,$configline);
 9569: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9570: 	}
 9571:     }
 9572:     close($config);
 9573: }
 9574: 
 9575: # -------------------------------------------- Read plain texts for permissions
 9576: {
 9577:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9578: 
 9579:     while (my $configline=<$config>) {
 9580: 	chomp($configline);
 9581: 	if ($configline) {
 9582: 	    my ($short,@plain)=split(/:/,$configline);
 9583:             %{$prp{$short}} = ();
 9584: 	    if (@plain > 0) {
 9585:                 $prp{$short}{'std'} = $plain[0];
 9586:                 for (my $i=1; $i<@plain; $i++) {
 9587:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9588:                 }
 9589:             }
 9590: 	}
 9591:     }
 9592:     close($config);
 9593: }
 9594: 
 9595: # ---------------------------------------------------------- Read package table
 9596: {
 9597:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9598: 
 9599:     while (my $configline=<$config>) {
 9600: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9601: 	chomp($configline);
 9602: 	my ($short,$plain)=split(/:/,$configline);
 9603: 	my ($pack,$name)=split(/\&/,$short);
 9604: 	if ($plain ne '') {
 9605: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9606: 	    $packagetab{$short}=$plain; 
 9607: 	}
 9608:     }
 9609:     close($config);
 9610: }
 9611: 
 9612: # ------------- set up temporary directory
 9613: {
 9614:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9615: 
 9616: }
 9617: 
 9618: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9619: 				'compress_threshold'=> 20_000,
 9620:  			        });
 9621: 
 9622: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9623: $dumpcount=0;
 9624: $locknum=0;
 9625: 
 9626: &logtouch();
 9627: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9628: $readit=1;
 9629:     {
 9630: 	use integer;
 9631: 	my $test=(2**32)+1;
 9632: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9633: 	&logthis(" Detected 64bit platform ($_64bit)");
 9634:     }
 9635: }
 9636: }
 9637: 
 9638: 1;
 9639: __END__
 9640: 
 9641: =pod
 9642: 
 9643: =head1 NAME
 9644: 
 9645: Apache::lonnet - Subroutines to ask questions about things in the network.
 9646: 
 9647: =head1 SYNOPSIS
 9648: 
 9649: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9650: 
 9651:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9652: 
 9653: Common parameters:
 9654: 
 9655: =over 4
 9656: 
 9657: =item *
 9658: 
 9659: $uname : an internal username (if $cname expecting a course Id specifically)
 9660: 
 9661: =item *
 9662: 
 9663: $udom : a domain (if $cdom expecting a course's domain specifically)
 9664: 
 9665: =item *
 9666: 
 9667: $symb : a resource instance identifier
 9668: 
 9669: =item *
 9670: 
 9671: $namespace : the name of a .db file that contains the data needed or
 9672: being set.
 9673: 
 9674: =back
 9675: 
 9676: =head1 OVERVIEW
 9677: 
 9678: lonnet provides subroutines which interact with the
 9679: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9680: about classes, users, and resources.
 9681: 
 9682: For many of these objects you can also use this to store data about
 9683: them or modify them in various ways.
 9684: 
 9685: =head2 Symbs
 9686: 
 9687: To identify a specific instance of a resource, LON-CAPA uses symbols
 9688: or "symbs"X<symb>. These identifiers are built from the URL of the
 9689: map, the resource number of the resource in the map, and the URL of
 9690: the resource itself. The latter is somewhat redundant, but might help
 9691: if maps change.
 9692: 
 9693: An example is
 9694: 
 9695:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9696: 
 9697: The respective map entry is
 9698: 
 9699:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9700:   title="Problem 2">
 9701:  </resource>
 9702: 
 9703: Symbs are used by the random number generator, as well as to store and
 9704: restore data specific to a certain instance of for example a problem.
 9705: 
 9706: =head2 Storing And Retrieving Data
 9707: 
 9708: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9709: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9710: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9711: is is the non-critical message twin of cstore. These functions are for
 9712: handlers to store a perl hash to a user's permanent data space in an
 9713: easy manner, and to retrieve it again on another call. It is expected
 9714: that a handler would use this once at the beginning to retrieve data,
 9715: and then again once at the end to send only the new data back.
 9716: 
 9717: The data is stored in the user's data directory on the user's
 9718: homeserver under the ID of the course.
 9719: 
 9720: The hash that is returned by restore will have all of the previous
 9721: value for all of the elements of the hash.
 9722: 
 9723: Example:
 9724: 
 9725:  #creating a hash
 9726:  my %hash;
 9727:  $hash{'foo'}='bar';
 9728: 
 9729:  #storing it
 9730:  &Apache::lonnet::cstore(\%hash);
 9731: 
 9732:  #changing a value
 9733:  $hash{'foo'}='notbar';
 9734: 
 9735:  #adding a new value
 9736:  $hash{'bar'}='foo';
 9737:  &Apache::lonnet::cstore(\%hash);
 9738: 
 9739:  #retrieving the hash
 9740:  my %history=&Apache::lonnet::restore();
 9741: 
 9742:  #print the hash
 9743:  foreach my $key (sort(keys(%history))) {
 9744:    print("\%history{$key} = $history{$key}");
 9745:  }
 9746: 
 9747: Will print out:
 9748: 
 9749:  %history{1:foo} = bar
 9750:  %history{1:keys} = foo:timestamp
 9751:  %history{1:timestamp} = 990455579
 9752:  %history{2:bar} = foo
 9753:  %history{2:foo} = notbar
 9754:  %history{2:keys} = foo:bar:timestamp
 9755:  %history{2:timestamp} = 990455580
 9756:  %history{bar} = foo
 9757:  %history{foo} = notbar
 9758:  %history{timestamp} = 990455580
 9759:  %history{version} = 2
 9760: 
 9761: Note that the special hash entries C<keys>, C<version> and
 9762: C<timestamp> were added to the hash. C<version> will be equal to the
 9763: total number of versions of the data that have been stored. The
 9764: C<timestamp> attribute will be the UNIX time the hash was
 9765: stored. C<keys> is available in every historical section to list which
 9766: keys were added or changed at a specific historical revision of a
 9767: hash.
 9768: 
 9769: B<Warning>: do not store the hash that restore returns directly. This
 9770: will cause a mess since it will restore the historical keys as if the
 9771: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9772: 
 9773: Calling convention:
 9774: 
 9775:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9776:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9777: 
 9778: For more detailed information, see lonnet specific documentation.
 9779: 
 9780: =head1 RETURN MESSAGES
 9781: 
 9782: =over 4
 9783: 
 9784: =item * B<con_lost>: unable to contact remote host
 9785: 
 9786: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9787: when the connection is brought back up
 9788: 
 9789: =item * B<con_failed>: unable to contact remote host and unable to save message
 9790: for later delivery
 9791: 
 9792: =item * B<error:>: an error a occurred, a description of the error follows the :
 9793: 
 9794: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9795: that was requested
 9796: 
 9797: =back
 9798: 
 9799: =head1 PUBLIC SUBROUTINES
 9800: 
 9801: =head2 Session Environment Functions
 9802: 
 9803: =over 4
 9804: 
 9805: =item * 
 9806: X<appenv()>
 9807: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9808: the user envirnoment file, and will be restored for each access this
 9809: user makes during this session, also modifies the %env for the current
 9810: process. Optional rolesarrayref - if defined contains a reference to an array
 9811: of roles which are exempt from the restriction on modifying user.role entries 
 9812: in the user's environment.db and in %env.    
 9813: 
 9814: =item *
 9815: X<delenv()>
 9816: B<delenv($delthis,$regexp)>: removes all items from the session
 9817: environment file that begin with $delthis. If the 
 9818: optional second arg - $regexp - is true, $delthis is treated as a 
 9819: regular expression, otherwise \Q$delthis\E is used. 
 9820: The values are also deleted from the current processes %env.
 9821: 
 9822: =item * get_env_multiple($name) 
 9823: 
 9824: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9825: values may be defined and end up as an array ref.
 9826: 
 9827: returns an array of values
 9828: 
 9829: =back
 9830: 
 9831: =head2 User Information
 9832: 
 9833: =over 4
 9834: 
 9835: =item *
 9836: X<queryauthenticate()>
 9837: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9838: authentication scheme
 9839: 
 9840: =item *
 9841: X<authenticate()>
 9842: B<authenticate($uname,$upass,$udom)>: try to
 9843: authenticate user from domain's lib servers (first use the current
 9844: one). C<$upass> should be the users password.
 9845: 
 9846: =item *
 9847: X<homeserver()>
 9848: B<homeserver($uname,$udom)>: find the server which has
 9849: the user's directory and files (there must be only one), this caches
 9850: the answer, and also caches if there is a borken connection.
 9851: 
 9852: =item *
 9853: X<idget()>
 9854: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9855: (IDs are a unique resource in a domain, there must be only 1 ID per
 9856: username, and only 1 username per ID in a specific domain) (returns
 9857: hash: id=>name,id=>name)
 9858: 
 9859: =item *
 9860: X<idrget()>
 9861: B<idrget($udom,@unames)>: find the IDs behind a list of
 9862: usernames (returns hash: name=>id,name=>id)
 9863: 
 9864: =item *
 9865: X<idput()>
 9866: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9867: 
 9868: =item *
 9869: X<rolesinit()>
 9870: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9871: 
 9872: =item *
 9873: X<getsection()>
 9874: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9875: course $cname, return section name/number or '' for "not in course"
 9876: and '-1' for "no section"
 9877: 
 9878: =item *
 9879: X<userenvironment()>
 9880: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9881: passed in @what from the requested user's environment, returns a hash
 9882: 
 9883: =item * 
 9884: X<userlog_query()>
 9885: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9886: activity.log file. %filters defines filters applied when parsing the
 9887: log file. These can be start or end timestamps, or the type of action
 9888: - log to look for Login or Logout events, check for Checkin or
 9889: Checkout, role for role selection. The response is in the form
 9890: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9891: escaped strings of the action recorded in the activity.log file.
 9892: 
 9893: =back
 9894: 
 9895: =head2 User Roles
 9896: 
 9897: =over 4
 9898: 
 9899: =item *
 9900: 
 9901: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9902:  F: full access
 9903:  U,I,K: authentication modes (cxx only)
 9904:  '': forbidden
 9905:  1: user needs to choose course
 9906:  2: browse allowed
 9907:  A: passphrase authentication needed
 9908: 
 9909: =item *
 9910: 
 9911: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9912: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9913: and course level
 9914: 
 9915: =item *
 9916: 
 9917: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9918: (rolesplain.tab); plain text explanation of a user role term.
 9919: $type is Course (default) or Community.
 9920: If $forcedefault evaluates to true, text returned will be default 
 9921: text for $type. Otherwise, if this is a course, the text returned 
 9922: will be a custom name for the role (if defined in the course's 
 9923: environment).  If no custom name is defined the default is returned.
 9924:    
 9925: =item *
 9926: 
 9927: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9928: All arguments are optional. Returns a hash of a roles, either for
 9929: co-author/assistant author roles for a user's Construction Space
 9930: (default), or if $context is 'userroles', roles for the user himself,
 9931: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9932: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9933: For each key, value is set to colon-separated start and end times for
 9934: the role.  If no username and domain are specified, will default to
 9935: current user/domain. Types, roles, and roledoms are references to arrays
 9936: of role statuses (active, future or previous), roles 
 9937: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9938: to restrict the list of roles reported. If no array ref is 
 9939: provided for types, will default to return only active roles.
 9940: 
 9941: =back
 9942: 
 9943: =head2 User Modification
 9944: 
 9945: =over 4
 9946: 
 9947: =item *
 9948: 
 9949: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9950: user for the level given by URL.  Optional start and end dates (leave empty
 9951: string or zero for "no date")
 9952: 
 9953: =item *
 9954: 
 9955: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9956: change a users, password, possible return values are: ok,
 9957: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9958: refused
 9959: 
 9960: =item *
 9961: 
 9962: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9963: 
 9964: =item *
 9965: 
 9966: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9967:            $forceid,$desiredhome,$email,$inststatus) : 
 9968: modify user
 9969: 
 9970: =item *
 9971: 
 9972: modifystudent
 9973: 
 9974: modify a student's enrollment and identification information.
 9975: The course id is resolved based on the current users environment.  
 9976: This means the envoking user must be a course coordinator or otherwise
 9977: associated with a course.
 9978: 
 9979: This call is essentially a wrapper for lonnet::modifyuser and
 9980: lonnet::modify_student_enrollment
 9981: 
 9982: Inputs: 
 9983: 
 9984: =over 4
 9985: 
 9986: =item B<$udom> Student's loncapa domain
 9987: 
 9988: =item B<$uname> Student's loncapa login name
 9989: 
 9990: =item B<$uid> Student/Employee ID
 9991: 
 9992: =item B<$umode> Student's authentication mode
 9993: 
 9994: =item B<$upass> Student's password
 9995: 
 9996: =item B<$first> Student's first name
 9997: 
 9998: =item B<$middle> Student's middle name
 9999: 
10000: =item B<$last> Student's last name
10001: 
10002: =item B<$gene> Student's generation
10003: 
10004: =item B<$usec> Student's section in course
10005: 
10006: =item B<$end> Unix time of the roles expiration
10007: 
10008: =item B<$start> Unix time of the roles start date
10009: 
10010: =item B<$forceid> If defined, allow $uid to be changed
10011: 
10012: =item B<$desiredhome> server to use as home server for student
10013: 
10014: =item B<$email> Student's permanent e-mail address
10015: 
10016: =item B<$type> Type of enrollment (auto or manual)
10017: 
10018: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
10019: 
10020: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10021: 
10022: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10023: 
10024: =item B<$context> role change context (shown in User Management Logs display in a course)
10025: 
10026: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
10027: 
10028: =back
10029: 
10030: =item *
10031: 
10032: modify_student_enrollment
10033: 
10034: Change a students enrollment status in a class.  The environment variable
10035: 'role.request.course' must be defined for this function to proceed.
10036: 
10037: Inputs:
10038: 
10039: =over 4
10040: 
10041: =item $udom, students domain
10042: 
10043: =item $uname, students name
10044: 
10045: =item $uid, students user id
10046: 
10047: =item $first, students first name
10048: 
10049: =item $middle
10050: 
10051: =item $last
10052: 
10053: =item $gene
10054: 
10055: =item $usec
10056: 
10057: =item $end
10058: 
10059: =item $start
10060: 
10061: =item $type
10062: 
10063: =item $locktype
10064: 
10065: =item $cid
10066: 
10067: =item $selfenroll
10068: 
10069: =item $context
10070: 
10071: =back
10072: 
10073: 
10074: =item *
10075: 
10076: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10077: custom role; give a custom role to a user for the level given by URL.  Specify
10078: name and domain of role author, and role name
10079: 
10080: =item *
10081: 
10082: revokerole($udom,$uname,$url,$role) : revoke a role for url
10083: 
10084: =item *
10085: 
10086: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10087: 
10088: =back
10089: 
10090: =head2 Course Infomation
10091: 
10092: =over 4
10093: 
10094: =item *
10095: 
10096: coursedescription($courseid) : returns a hash of information about the
10097: specified course id, including all environment settings for the
10098: course, the description of the course will be in the hash under the
10099: key 'description'
10100: 
10101: =item *
10102: 
10103: resdata($name,$domain,$type,@which) : request for current parameter
10104: setting for a specific $type, where $type is either 'course' or 'user',
10105: @what should be a list of parameters to ask about. This routine caches
10106: answers for 5 minutes.
10107: 
10108: =item *
10109: 
10110: get_courseresdata($courseid, $domain) : dump the entire course resource
10111: data base, returning a hash that is keyed by the resource name and has
10112: values that are the resource value.  I believe that the timestamps and
10113: versions are also returned.
10114: 
10115: 
10116: =back
10117: 
10118: =head2 Course Modification
10119: 
10120: =over 4
10121: 
10122: =item *
10123: 
10124: writecoursepref($courseid,%prefs) : write preferences (environment
10125: database) for a course
10126: 
10127: =item *
10128: 
10129: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10130: 
10131: =item *
10132: 
10133: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
10134: 
10135: =back
10136: 
10137: =head2 Resource Subroutines
10138: 
10139: =over 4
10140: 
10141: =item *
10142: 
10143: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10144: 
10145: =item *
10146: 
10147: repcopy($filename) : subscribes to the requested file, and attempts to
10148: replicate from the owning library server, Might return
10149: 'unavailable', 'not_found', 'forbidden', 'ok', or
10150: 'bad_request', also attempts to grab the metadata for the
10151: resource. Expects the local filesystem pathname
10152: (/home/httpd/html/res/....)
10153: 
10154: =back
10155: 
10156: =head2 Resource Information
10157: 
10158: =over 4
10159: 
10160: =item *
10161: 
10162: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10163: a vairety of different possible values, $varname should be a request
10164: string, and the other parameters can be used to specify who and what
10165: one is asking about.
10166: 
10167: Possible values for $varname are environment.lastname (or other item
10168: from the envirnment hash), user.name (or someother aspect about the
10169: user), resource.0.maxtries (or some other part and parameter of a
10170: resource)
10171: 
10172: =item *
10173: 
10174: directcondval($number) : get current value of a condition; reads from a state
10175: string
10176: 
10177: =item *
10178: 
10179: condval($condidx) : value of condition index based on state
10180: 
10181: =item *
10182: 
10183: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10184: resource's metadata, $what should be either a specific key, or either
10185: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10186: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10187: 
10188: this function automatically caches all requests
10189: 
10190: =item *
10191: 
10192: metadata_query($query,$custom,$customshow) : make a metadata query against the
10193: network of library servers; returns file handle of where SQL and regex results
10194: will be stored for query
10195: 
10196: =item *
10197: 
10198: symbread($filename) : return symbolic list entry (filename argument optional);
10199: returns the data handle
10200: 
10201: =item *
10202: 
10203: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10204: a possible symb for the URL in $thisfn, and if is an encryypted
10205: resource that the user accessed using /enc/ returns a 1 on success, 0
10206: on failure, user must be in a course, as it assumes the existance of
10207: the course initial hash, and uses $env('request.course.id'}
10208: 
10209: 
10210: =item *
10211: 
10212: symbclean($symb) : removes versions numbers from a symb, returns the
10213: cleaned symb
10214: 
10215: =item *
10216: 
10217: is_on_map($uri) : checks if the $uri is somewhere on the current
10218: course map, user must be in a course for it to work.
10219: 
10220: =item *
10221: 
10222: numval($salt) : return random seed value (addend for rndseed)
10223: 
10224: =item *
10225: 
10226: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10227: a random seed, all arguments are optional, if they aren't sent it uses the
10228: environment to derive them. Note: if symb isn't sent and it can't get one
10229: from &symbread it will use the current time as its return value
10230: 
10231: =item *
10232: 
10233: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10234: unfakeable, receipt
10235: 
10236: =item *
10237: 
10238: receipt() : API to ireceipt working off of env values; given out to users
10239: 
10240: =item *
10241: 
10242: countacc($url) : count the number of accesses to a given URL
10243: 
10244: =item *
10245: 
10246: 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
10247: 
10248: =item *
10249: 
10250: 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)
10251: 
10252: =item *
10253: 
10254: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10255: 
10256: =item *
10257: 
10258: devalidate($symb) : devalidate temporary spreadsheet calculations,
10259: forcing spreadsheet to reevaluate the resource scores next time.
10260: 
10261: =back
10262: 
10263: =head2 Storing/Retreiving Data
10264: 
10265: =over 4
10266: 
10267: =item *
10268: 
10269: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10270: for this url; hashref needs to be given and should be a \%hashname; the
10271: remaining args aren't required and if they aren't passed or are '' they will
10272: be derived from the env
10273: 
10274: =item *
10275: 
10276: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10277: uses critical subroutine
10278: 
10279: =item *
10280: 
10281: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10282: all args are optional
10283: 
10284: =item *
10285: 
10286: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10287: dumps the complete (or key matching regexp) namespace into a hash
10288: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10289: normally &store()ed into
10290: 
10291: $range should be either an integer '100' (give me the first 100
10292:                                            matching records)
10293:               or be  two integers sperated by a - with no spaces
10294:                  '30-50' (give me the 30th through the 50th matching
10295:                           records)
10296: 
10297: 
10298: =item *
10299: 
10300: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10301: replaces a &store() version of data with a replacement set of data
10302: for a particular resource in a namespace passed in the $storehash hash 
10303: reference
10304: 
10305: =item *
10306: 
10307: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10308: works very similar to store/cstore, but all data is stored in a
10309: temporary location and can be reset using tmpreset, $storehash should
10310: be a hash reference, returns nothing on success
10311: 
10312: =item *
10313: 
10314: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10315: similar to restore, but all data is stored in a temporary location and
10316: can be reset using tmpreset. Returns a hash of values on success,
10317: error string otherwise.
10318: 
10319: =item *
10320: 
10321: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10322: deltes all keys for $symb form the temporary storage hash.
10323: 
10324: =item *
10325: 
10326: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10327: reference filled in from namesp ($udom and $uname are optional)
10328: 
10329: =item *
10330: 
10331: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10332: namesp ($udom and $uname are optional)
10333: 
10334: =item *
10335: 
10336: dump($namespace,$udom,$uname,$regexp,$range) : 
10337: dumps the complete (or key matching regexp) namespace into a hash
10338: ($udom, $uname, $regexp, $range are optional)
10339: 
10340: $range should be either an integer '100' (give me the first 100
10341:                                            matching records)
10342:               or be  two integers sperated by a - with no spaces
10343:                  '30-50' (give me the 30th through the 50th matching
10344:                           records)
10345: =item *
10346: 
10347: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10348: $store can be a scalar, an array reference, or if the amount to be 
10349: incremented is > 1, a hash reference.
10350: 
10351: ($udom and $uname are optional)
10352: 
10353: =item *
10354: 
10355: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10356: ($udom and $uname are optional)
10357: 
10358: =item *
10359: 
10360: cput($namespace,$storehash,$udom,$uname) : critical put
10361: ($udom and $uname are optional)
10362: 
10363: =item *
10364: 
10365: newput($namespace,$storehash,$udom,$uname) :
10366: 
10367: Attempts to store the items in the $storehash, but only if they don't
10368: currently exist, if this succeeds you can be certain that you have 
10369: successfully created a new key value pair in the $namespace db.
10370: 
10371: 
10372: Args:
10373:  $namespace: name of database to store values to
10374:  $storehash: hashref to store to the db
10375:  $udom: (optional) domain of user containing the db
10376:  $uname: (optional) name of user caontaining the db
10377: 
10378: Returns:
10379:  'ok' -> succeeded in storing all keys of $storehash
10380:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10381:                         least <key> already existed in the db (other
10382:                         requested keys may also already exist)
10383:  'error: <msg>' -> unable to tie the DB or other error occurred
10384:  'con_lost' -> unable to contact request server
10385:  'refused' -> action was not allowed by remote machine
10386: 
10387: 
10388: =item *
10389: 
10390: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10391: reference filled in from namesp (encrypts the return communication)
10392: ($udom and $uname are optional)
10393: 
10394: =item *
10395: 
10396: log($udom,$name,$home,$message) : write to permanent log for user; use
10397: critical subroutine
10398: 
10399: =item *
10400: 
10401: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10402: array reference filled in from namespace found in domain level on either
10403: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10404: 
10405: =item *
10406: 
10407: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10408: domain level either on specified domain server ($uhome) or primary domain 
10409: server ($udom and $uhome are optional)
10410: 
10411: =item * 
10412: 
10413: get_domain_defaults($target_domain) : returns hash with defaults for
10414: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10415: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10416: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10417: Values are retrieved from cache (if current), or from domain's configuration.db
10418: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10419: or lonTabs/domain.tab. 
10420: 
10421: %domdefaults = &get_auth_defaults($target_domain);
10422: 
10423: =back
10424: 
10425: =head2 Network Status Functions
10426: 
10427: =over 4
10428: 
10429: =item *
10430: 
10431: dirlist($uri) : return directory list based on URI
10432: 
10433: =item *
10434: 
10435: spareserver() : find server with least workload from spare.tab
10436: 
10437: 
10438: =item *
10439: 
10440: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10441: if there is no corresponding loncapa host.
10442: 
10443: =back
10444: 
10445: 
10446: =head2 Apache Request
10447: 
10448: =over 4
10449: 
10450: =item *
10451: 
10452: ssi($url,%hash) : server side include, does a complete request cycle on url to
10453: localhost, posts hash
10454: 
10455: =back
10456: 
10457: =head2 Data to String to Data
10458: 
10459: =over 4
10460: 
10461: =item *
10462: 
10463: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10464: and '&' separators, supports elements that are arrayrefs and hashrefs
10465: 
10466: =item *
10467: 
10468: hashref2str($hashref) : convert a hashref into a string complete with
10469: escaping and '=' and '&' separators, supports elements that are
10470: arrayrefs and hashrefs
10471: 
10472: =item *
10473: 
10474: arrayref2str($arrayref) : convert an arrayref into a string complete
10475: with escaping and '&' separators, supports elements that are arrayrefs
10476: and hashrefs
10477: 
10478: =item *
10479: 
10480: str2hash($string) : convert string to hash using unescaping and
10481: splitting on '=' and '&', supports elements that are arrayrefs and
10482: hashrefs
10483: 
10484: =item *
10485: 
10486: str2array($string) : convert string to hash using unescaping and
10487: splitting on '&', supports elements that are arrayrefs and hashrefs
10488: 
10489: =back
10490: 
10491: =head2 Logging Routines
10492: 
10493: =over 4
10494: 
10495: These routines allow one to make log messages in the lonnet.log and
10496: lonnet.perm logfiles.
10497: 
10498: =item *
10499: 
10500: logtouch() : make sure the logfile, lonnet.log, exists
10501: 
10502: =item *
10503: 
10504: logthis() : append message to the normal lonnet.log file, it gets
10505: preiodically rolled over and deleted.
10506: 
10507: =item *
10508: 
10509: logperm() : append a permanent message to lonnet.perm.log, this log
10510: file never gets deleted by any automated portion of the system, only
10511: messages of critical importance should go in here.
10512: 
10513: =back
10514: 
10515: =head2 General File Helper Routines
10516: 
10517: =over 4
10518: 
10519: =item *
10520: 
10521: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10522: (a) files in /uploaded
10523:   (i) If a local copy of the file exists - 
10524:       compares modification date of local copy with last-modified date for 
10525:       definitive version stored on home server for course. If local copy is 
10526:       stale, requests a new version from the home server and stores it. 
10527:       If the original has been removed from the home server, then local copy 
10528:       is unlinked.
10529:   (ii) If local copy does not exist -
10530:       requests the file from the home server and stores it. 
10531:   
10532:   If $caller is 'uploadrep':  
10533:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10534:     for request for files originally uploaded via DOCS. 
10535:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10536:   
10537:   Otherwise:
10538:      This indicates a call from the content generation phase of the request.
10539:      -  returns the entire contents of the file or -1.
10540:      
10541: (b) files in /res
10542:    - returns the entire contents of a file or -1; 
10543:    it properly subscribes to and replicates the file if neccessary.
10544: 
10545: 
10546: =item *
10547: 
10548: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10549:                   reference
10550: 
10551: returns either a stat() list of data about the file or an empty list
10552: if the file doesn't exist or couldn't find out about it (connection
10553: problems or user unknown)
10554: 
10555: =item *
10556: 
10557: filelocation($dir,$file) : returns file system location of a file
10558: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10559: directory that relative $file lookups are to looked in ($dir of /a/dir
10560: and a file of ../bob will become /a/bob)
10561: 
10562: =item *
10563: 
10564: hreflocation($dir,$file) : returns file system location or a URL; same as
10565: filelocation except for hrefs
10566: 
10567: =item *
10568: 
10569: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10570: 
10571: =back
10572: 
10573: =head2 Usererfile file routines (/uploaded*)
10574: 
10575: =over 4
10576: 
10577: =item *
10578: 
10579: userfileupload(): main rotine for putting a file in a user or course's
10580:                   filespace, arguments are,
10581: 
10582:  formname - required - this is the name of the element in $env where the
10583:            filename, and the contents of the file to create/modifed exist
10584:            the filename is in $env{'form.'.$formname.'.filename'} and the
10585:            contents of the file is located in $env{'form.'.$formname}
10586:  coursedoc - if true, store the file in the course of the active role
10587:              of the current user
10588:  subdir - required - subdirectory to put the file in under ../userfiles/
10589:          if undefined, it will be placed in "unknown"
10590: 
10591:  (This routine calls clean_filename() to remove any dangerous
10592:  characters from the filename, and then calls finuserfileupload() to
10593:  complete the transaction)
10594: 
10595:  returns either the url of the uploaded file (/uploaded/....) if successful
10596:  and /adm/notfound.html if unsuccessful
10597: 
10598: =item *
10599: 
10600: clean_filename(): routine for cleaing a filename up for storage in
10601:                  userfile space, argument is:
10602: 
10603:  filename - proposed filename
10604: 
10605: returns: the new clean filename
10606: 
10607: =item *
10608: 
10609: finishuserfileupload(): routine that creaes and sends the file to
10610: userspace, probably shouldn't be called directly
10611: 
10612:   docuname: username or courseid of destination for the file
10613:   docudom: domain of user/course of destination for the file
10614:   formname: same as for userfileupload()
10615:   fname: filename (inculding subdirectories) for the file
10616: 
10617:  returns either the url of the uploaded file (/uploaded/....) if successful
10618:  and /adm/notfound.html if unsuccessful
10619: 
10620: =item *
10621: 
10622: renameuserfile(): renames an existing userfile to a new name
10623: 
10624:   Args:
10625:    docuname: username or courseid of destination for the file
10626:    docudom: domain of user/course of destination for the file
10627:    old: current file name (including any subdirs under userfiles)
10628:    new: desired file name (including any subdirs under userfiles)
10629: 
10630: =item *
10631: 
10632: mkdiruserfile(): creates a directory is a userfiles dir
10633: 
10634:   Args:
10635:    docuname: username or courseid of destination for the file
10636:    docudom: domain of user/course of destination for the file
10637:    dir: dir to create (including any subdirs under userfiles)
10638: 
10639: =item *
10640: 
10641: removeuserfile(): removes a file that exists in userfiles
10642: 
10643:   Args:
10644:    docuname: username or courseid of destination for the file
10645:    docudom: domain of user/course of destination for the file
10646:    fname: filname to delete (including any subdirs under userfiles)
10647: 
10648: =item *
10649: 
10650: removeuploadedurl(): convience function for removeuserfile()
10651: 
10652:   Args:
10653:    url:  a full /uploaded/... url to delete
10654: 
10655: =item * 
10656: 
10657: get_portfile_permissions():
10658:   Args:
10659:     domain: domain of user or course contain the portfolio files
10660:     user: name of user or num of course contain the portfolio files
10661:   Returns:
10662:     hashref of a dump of the proper file_permissions.db
10663:    
10664: 
10665: =item * 
10666: 
10667: get_access_controls():
10668: 
10669: Args:
10670:   current_permissions: the hash ref returned from get_portfile_permissions()
10671:   group: (optional) the group you want the files associated with
10672:   file: (optional) the file you want access info on
10673: 
10674: Returns:
10675:     a hash (keys are file names) of hashes containing
10676:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10677:         values are XML containing access control settings (see below) 
10678: 
10679: Internal notes:
10680: 
10681:  access controls are stored in file_permissions.db as key=value pairs.
10682:     key -> path to file/file_name\0uniqueID:scope_end_start
10683:         where scope -> public,guest,course,group,domains or users.
10684:               end -> UNIX time for end of access (0 -> no end date)
10685:               start -> UNIX time for start of access
10686: 
10687:     value -> XML description of access control
10688:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10689:             <start></start>
10690:             <end></end>
10691: 
10692:             <password></password>  for scope type = guest
10693: 
10694:             <domain></domain>     for scope type = course or group
10695:             <number></number>
10696:             <roles id="">
10697:              <role></role>
10698:              <access></access>
10699:              <section></section>
10700:              <group></group>
10701:             </roles>
10702: 
10703:             <dom></dom>         for scope type = domains
10704: 
10705:             <users>             for scope type = users
10706:              <user>
10707:               <uname></uname>
10708:               <udom></udom>
10709:              </user>
10710:             </users>
10711:            </scope> 
10712:               
10713:  Access data is also aggregated for each file in an additional key=value pair:
10714:  key -> path to file/file_name\0accesscontrol 
10715:  value -> reference to hash
10716:           hash contains key = value pairs
10717:           where key = uniqueID:scope_end_start
10718:                 value = UNIX time record was last updated
10719: 
10720:           Used to improve speed of look-ups of access controls for each file.  
10721:  
10722:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10723: 
10724: modify_access_controls():
10725: 
10726: Modifies access controls for a portfolio file
10727: Args
10728: 1. file name
10729: 2. reference to hash of required changes,
10730: 3. domain
10731: 4. username
10732:   where domain,username are the domain of the portfolio owner 
10733:   (either a user or a course) 
10734: 
10735: Returns:
10736: 1. result of additions or updates ('ok' or 'error', with error message). 
10737: 2. result of deletions ('ok' or 'error', with error message).
10738: 3. reference to hash of any new or updated access controls.
10739: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10740:    key = integer (inbound ID)
10741:    value = uniqueID  
10742: 
10743: =back
10744: 
10745: =head2 HTTP Helper Routines
10746: 
10747: =over 4
10748: 
10749: =item *
10750: 
10751: escape() : unpack non-word characters into CGI-compatible hex codes
10752: 
10753: =item *
10754: 
10755: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10756: 
10757: =back
10758: 
10759: =head1 PRIVATE SUBROUTINES
10760: 
10761: =head2 Underlying communication routines (Shouldn't call)
10762: 
10763: =over 4
10764: 
10765: =item *
10766: 
10767: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10768: 
10769: =item *
10770: 
10771: reply() : uses subreply to send a message to remote machine, logs all failures
10772: 
10773: =item *
10774: 
10775: critical() : passes a critical message to another server; if cannot
10776: get through then place message in connection buffer directory and
10777: returns con_delayed, if incapable of saving message, returns
10778: con_failed
10779: 
10780: =item *
10781: 
10782: reconlonc() : tries to reconnect lonc client processes.
10783: 
10784: =back
10785: 
10786: =head2 Resource Access Logging
10787: 
10788: =over 4
10789: 
10790: =item *
10791: 
10792: flushcourselogs() : flush (save) buffer logs and access logs
10793: 
10794: =item *
10795: 
10796: courselog($what) : save message for course in hash
10797: 
10798: =item *
10799: 
10800: courseacclog($what) : save message for course using &courselog().  Perform
10801: special processing for specific resource types (problems, exams, quizzes, etc).
10802: 
10803: =item *
10804: 
10805: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10806: as a PerlChildExitHandler
10807: 
10808: =back
10809: 
10810: =head2 Other
10811: 
10812: =over 4
10813: 
10814: =item *
10815: 
10816: symblist($mapname,%newhash) : update symbolic storage links
10817: 
10818: =back
10819: 
10820: =cut
10821: 

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