File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.988: download - view: text, annotated - select for diffs
Sun Mar 1 01:12:23 2009 UTC (15 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
lonparmset.pm
- Titles used for standard course roles can be defined in course environment.
  - Replacements which match custom roles used in course may not be used.

lonnet.pm
- plaintext() takes additional (fourth) argument
  - $forcedefault to force display of standard titles for role.
- get_course_adv_roles() includes call to loncommon::course_type() to get course type.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.988 2009/03/01 01:12:23 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: use IO::Socket;
   78: 
   79: # use Date::Parse;
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol);
   82: 
   83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   86:     %courseownerbuf, %coursetypebuf,$locknum);
   87: 
   88: use IO::Socket;
   89: use GDBM_File;
   90: use HTML::LCParser;
   91: use Fcntl qw(:flock);
   92: use Storable qw(thaw nfreeze);
   93: use Time::HiRes qw( gettimeofday tv_interval );
   94: use Cache::Memcached;
   95: use Digest::MD5;
   96: use Math::Random;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: 
  100: my $readit;
  101: my $max_connection_retries = 10;     # Or some such value.
  102: 
  103: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  104: 
  105: require Exporter;
  106: 
  107: our @ISA = qw (Exporter);
  108: our @EXPORT = qw(%env);
  109: 
  110: 
  111: # --------------------------------------------------------------------- Logging
  112: {
  113:     my $logid;
  114:     sub instructor_log {
  115: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  116:         if (($cnum eq '') || ($cdom eq '')) {
  117:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  118:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  119:         }
  120: 	$logid++;
  121:         my $now = time();
  122: 	my $id=$now.'00000'.$$.'00000'.$logid;
  123: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  124: 				    { $id => {
  125: 					'exe_uname' => $env{'user.name'},
  126: 					'exe_udom'  => $env{'user.domain'},
  127: 					'exe_time'  => $now,
  128: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  129: 					'delflag'   => $delflag,
  130: 					'logentry'  => $storehash,
  131: 					'uname'     => $uname,
  132: 					'udom'      => $udom,
  133: 				    }
  134: 				  },$cdom,$cnum);
  135:     }
  136: }
  137: 
  138: sub logtouch {
  139:     my $execdir=$perlvar{'lonDaemons'};
  140:     unless (-e "$execdir/logs/lonnet.log") {	
  141: 	open(my $fh,">>$execdir/logs/lonnet.log");
  142: 	close $fh;
  143:     }
  144:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  145:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  146: }
  147: 
  148: sub logthis {
  149:     my $message=shift;
  150:     my $execdir=$perlvar{'lonDaemons'};
  151:     my $now=time;
  152:     my $local=localtime($now);
  153:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  154: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  155: 	print $fh $logstring;
  156: 	close($fh);
  157:     }
  158:     return 1;
  159: }
  160: 
  161: sub logperm {
  162:     my $message=shift;
  163:     my $execdir=$perlvar{'lonDaemons'};
  164:     my $now=time;
  165:     my $local=localtime($now);
  166:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  167: 	print $fh "$now:$message:$local\n";
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub create_connection {
  174:     my ($hostname,$lonid) = @_;
  175:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  176: 				     Type    => SOCK_STREAM,
  177: 				     Timeout => 10);
  178:     return 0 if (!$client);
  179:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  180:     my $result = <$client>;
  181:     chomp($result);
  182:     return 1 if ($result eq 'done');
  183:     return 0;
  184: }
  185: 
  186: sub get_server_timezone {
  187:     my ($cnum,$cdom) = @_;
  188:     my $home=&homeserver($cnum,$cdom);
  189:     if ($home ne 'no_host') {
  190:         my $cachetime = 24*3600;
  191:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  192:         if (defined($cached)) {
  193:             return $timezone;
  194:         } else {
  195:             my $timezone = &reply('servertimezone',$home);
  196:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  197:         }
  198:     }
  199: }
  200: 
  201: # -------------------------------------------------- Non-critical communication
  202: sub subreply {
  203:     my ($cmd,$server)=@_;
  204:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  205:     #
  206:     #  With loncnew process trimming, there's a timing hole between lonc server
  207:     #  process exit and the master server picking up the listen on the AF_UNIX
  208:     #  socket.  In that time interval, a lock file will exist:
  209: 
  210:     my $lockfile=$peerfile.".lock";
  211:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  212: 	sleep(1);
  213:     }
  214:     # At this point, either a loncnew parent is listening or an old lonc
  215:     # or loncnew child is listening so we can connect or everything's dead.
  216:     #
  217:     #   We'll give the connection a few tries before abandoning it.  If
  218:     #   connection is not possible, we'll con_lost back to the client.
  219:     #   
  220:     my $client;
  221:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  222: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  223: 				      Type    => SOCK_STREAM,
  224: 				      Timeout => 10);
  225: 	if ($client) {
  226: 	    last;		# Connected!
  227: 	} else {
  228: 	    &create_connection(&hostname($server),$server);
  229: 	}
  230:         sleep(1);		# Try again later if failed connection.
  231:     }
  232:     my $answer;
  233:     if ($client) {
  234: 	print $client "sethost:$server:$cmd\n";
  235: 	$answer=<$client>;
  236: 	if (!$answer) { $answer="con_lost"; }
  237: 	chomp($answer);
  238:     } else {
  239: 	$answer = 'con_lost';	# Failed connection.
  240:     }
  241:     return $answer;
  242: }
  243: 
  244: sub reply {
  245:     my ($cmd,$server)=@_;
  246:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  247:     my $answer=subreply($cmd,$server);
  248:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  249:        &logthis("<font color=\"blue\">WARNING:".
  250:                 " $cmd to $server returned $answer</font>");
  251:     }
  252:     return $answer;
  253: }
  254: 
  255: # ----------------------------------------------------------- Send USR1 to lonc
  256: 
  257: sub reconlonc {
  258:     my ($lonid) = @_;
  259:     my $hostname = &hostname($lonid);
  260:     if ($lonid) {
  261: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  262: 	if ($hostname && -e $peerfile) {
  263: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  264: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  265: 					     Type    => SOCK_STREAM,
  266: 					     Timeout => 10);
  267: 	    if ($client) {
  268: 		print $client ("reset_retries\n");
  269: 		my $answer=<$client>;
  270: 		#reset just this one.
  271: 	    }
  272: 	}
  273: 	return;
  274:     }
  275: 
  276:     &logthis("Trying to reconnect lonc");
  277:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  278:     if (open(my $fh,"<$loncfile")) {
  279: 	my $loncpid=<$fh>;
  280:         chomp($loncpid);
  281:         if (kill 0 => $loncpid) {
  282: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  283:             kill USR1 => $loncpid;
  284:             sleep 1;
  285:          } else {
  286: 	    &logthis(
  287:                "<font color=\"blue\">WARNING:".
  288:                " lonc at pid $loncpid not responding, giving up</font>");
  289:         }
  290:     } else {
  291: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  292:     }
  293: }
  294: 
  295: # ------------------------------------------------------ Critical communication
  296: 
  297: sub critical {
  298:     my ($cmd,$server)=@_;
  299:     unless (&hostname($server)) {
  300:         &logthis("<font color=\"blue\">WARNING:".
  301:                " Critical message to unknown server ($server)</font>");
  302:         return 'no_such_host';
  303:     }
  304:     my $answer=reply($cmd,$server);
  305:     if ($answer eq 'con_lost') {
  306: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  307: 	my $answer=reply($cmd,$server);
  308:         if ($answer eq 'con_lost') {
  309:             my $now=time;
  310:             my $middlename=$cmd;
  311:             $middlename=substr($middlename,0,16);
  312:             $middlename=~s/\W//g;
  313:             my $dfilename=
  314:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  315:             $dumpcount++;
  316:             {
  317: 		my $dfh;
  318: 		if (open($dfh,">$dfilename")) {
  319: 		    print $dfh "$cmd\n"; 
  320: 		    close($dfh);
  321: 		}
  322:             }
  323:             sleep 2;
  324:             my $wcmd='';
  325:             {
  326: 		my $dfh;
  327: 		if (open($dfh,"<$dfilename")) {
  328: 		    $wcmd=<$dfh>; 
  329: 		    close($dfh);
  330: 		}
  331:             }
  332:             chomp($wcmd);
  333:             if ($wcmd eq $cmd) {
  334: 		&logthis("<font color=\"blue\">WARNING: ".
  335:                          "Connection buffer $dfilename: $cmd</font>");
  336:                 &logperm("D:$server:$cmd");
  337: 	        return 'con_delayed';
  338:             } else {
  339:                 &logthis("<font color=\"red\">CRITICAL:"
  340:                         ." Critical connection failed: $server $cmd</font>");
  341:                 &logperm("F:$server:$cmd");
  342:                 return 'con_failed';
  343:             }
  344:         }
  345:     }
  346:     return $answer;
  347: }
  348: 
  349: # ------------------------------------------- check if return value is an error
  350: 
  351: sub error {
  352:     my ($result) = @_;
  353:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  354: 	if ($2 == 2) { return undef; }
  355: 	return $1;
  356:     }
  357:     return undef;
  358: }
  359: 
  360: sub convert_and_load_session_env {
  361:     my ($lonidsdir,$handle)=@_;
  362:     my @profile;
  363:     {
  364: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  365: 	if (!$opened) {
  366: 	    return 0;
  367: 	}
  368: 	flock($idf,LOCK_SH);
  369: 	@profile=<$idf>;
  370: 	close($idf);
  371:     }
  372:     my %temp_env;
  373:     foreach my $line (@profile) {
  374: 	if ($line !~ m/=/) {
  375: 	    return 0;
  376: 	}
  377: 	chomp($line);
  378: 	my ($envname,$envvalue)=split(/=/,$line,2);
  379: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  380:     }
  381:     unlink("$lonidsdir/$handle.id");
  382:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  383: 	    0640)) {
  384: 	%disk_env = %temp_env;
  385: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  386: 	untie(%disk_env);
  387:     }
  388:     return 1;
  389: }
  390: 
  391: # ------------------------------------------- Transfer profile into environment
  392: my $env_loaded;
  393: sub transfer_profile_to_env {
  394:     my ($lonidsdir,$handle,$force_transfer) = @_;
  395:     if (!$force_transfer && $env_loaded) { return; } 
  396: 
  397:     if (!defined($lonidsdir)) {
  398: 	$lonidsdir = $perlvar{'lonIDsDir'};
  399:     }
  400:     if (!defined($handle)) {
  401:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  402:     }
  403: 
  404:     my $convert;
  405:     {
  406:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  407: 	if (!$opened) {
  408: 	    return;
  409: 	}
  410: 	flock($idf,LOCK_SH);
  411: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  412: 		&GDBM_READER(),0640)) {
  413: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  414: 	    untie(%disk_env);
  415: 	} else {
  416: 	    $convert = 1;
  417: 	}
  418:     }
  419:     if ($convert) {
  420: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  421: 	    &logthis("Failed to load session, or convert session.");
  422: 	}
  423:     }
  424: 
  425:     my %remove;
  426:     while ( my $envname = each(%env) ) {
  427:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  428:             if ($time < time-300) {
  429:                 $remove{$key}++;
  430:             }
  431:         }
  432:     }
  433: 
  434:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  435:     $env_loaded=1;
  436:     foreach my $expired_key (keys(%remove)) {
  437:         &delenv($expired_key);
  438:     }
  439: }
  440: 
  441: # ---------------------------------------------------- Check for valid session 
  442: sub check_for_valid_session {
  443:     my ($r) = @_;
  444:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  445:     my $lonid=$cookies{'lonID'};
  446:     return undef if (!$lonid);
  447: 
  448:     my $handle=&LONCAPA::clean_handle($lonid->value);
  449:     my $lonidsdir=$r->dir_config('lonIDsDir');
  450:     return undef if (!-e "$lonidsdir/$handle.id");
  451: 
  452:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  453:     return undef if (!$opened);
  454: 
  455:     flock($idf,LOCK_SH);
  456:     my %disk_env;
  457:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  458: 	    &GDBM_READER(),0640)) {
  459: 	return undef;	
  460:     }
  461: 
  462:     if (!defined($disk_env{'user.name'})
  463: 	|| !defined($disk_env{'user.domain'})) {
  464: 	return undef;
  465:     }
  466:     return $handle;
  467: }
  468: 
  469: sub timed_flock {
  470:     my ($file,$lock_type) = @_;
  471:     my $failed=0;
  472:     eval {
  473: 	local $SIG{__DIE__}='DEFAULT';
  474: 	local $SIG{ALRM}=sub {
  475: 	    $failed=1;
  476: 	    die("failed lock");
  477: 	};
  478: 	alarm(13);
  479: 	flock($file,$lock_type);
  480: 	alarm(0);
  481:     };
  482:     if ($failed) {
  483: 	return undef;
  484:     } else {
  485: 	return 1;
  486:     }
  487: }
  488: 
  489: # ---------------------------------------------------------- Append Environment
  490: 
  491: sub appenv {
  492:     my ($newenv,$roles) = @_;
  493:     if (ref($newenv) eq 'HASH') {
  494:         foreach my $key (keys(%{$newenv})) {
  495:             my $refused = 0;
  496: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  497:                 $refused = 1;
  498:                 if (ref($roles) eq 'ARRAY') {
  499:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  500:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  501:                         $refused = 0;
  502:                     }
  503:                 }
  504:             }
  505:             if ($refused) {
  506:                 &logthis("<font color=\"blue\">WARNING: ".
  507:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  508:                          .'</font>');
  509: 	        delete($newenv->{$key});
  510:             } else {
  511:                 $env{$key}=$newenv->{$key};
  512:             }
  513:         }
  514:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  515:         if ($opened
  516: 	    && &timed_flock($env_file,LOCK_EX)
  517: 	    &&
  518: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  519: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  520: 	    while (my ($key,$value) = each(%{$newenv})) {
  521: 	        $disk_env{$key} = $value;
  522: 	    }
  523: 	    untie(%disk_env);
  524:         }
  525:     }
  526:     return 'ok';
  527: }
  528: # ----------------------------------------------------- Delete from Environment
  529: 
  530: sub delenv {
  531:     my ($delthis,$regexp) = @_;
  532:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  533:         &logthis("<font color=\"blue\">WARNING: ".
  534:                 "Attempt to delete from environment ".$delthis);
  535:         return 'error';
  536:     }
  537:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  538:     if ($opened
  539: 	&& &timed_flock($env_file,LOCK_EX)
  540: 	&&
  541: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  542: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  543: 	foreach my $key (keys(%disk_env)) {
  544: 	    if ($regexp) {
  545:                 if ($key=~/^$delthis/) {
  546:                     delete($env{$key});
  547:                     delete($disk_env{$key});
  548:                 } 
  549:             } else {
  550:                 if ($key=~/^\Q$delthis\E/) {
  551: 		    delete($env{$key});
  552: 		    delete($disk_env{$key});
  553: 	        }
  554:             }
  555: 	}
  556: 	untie(%disk_env);
  557:     }
  558:     return 'ok';
  559: }
  560: 
  561: sub get_env_multiple {
  562:     my ($name) = @_;
  563:     my @values;
  564:     if (defined($env{$name})) {
  565:         # exists is it an array
  566:         if (ref($env{$name})) {
  567:             @values=@{ $env{$name} };
  568:         } else {
  569:             $values[0]=$env{$name};
  570:         }
  571:     }
  572:     return(@values);
  573: }
  574: 
  575: # ------------------------------------------------------------------- Locking
  576: 
  577: sub set_lock {
  578:     my ($text)=@_;
  579:     $locknum++;
  580:     my $id=$$.'-'.$locknum;
  581:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  582:              'session.lock.'.$id => $text});
  583:     return $id;
  584: }
  585: 
  586: sub get_locks {
  587:     my $num=0;
  588:     my %texts=();
  589:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  590:        if ($lock=~/\w/) {
  591:           $num++;
  592:           $texts{$lock}=$env{'session.lock.'.$lock};
  593:        }
  594:    }
  595:    return ($num,%texts);
  596: }
  597: 
  598: sub remove_lock {
  599:     my ($id)=@_;
  600:     my $newlocks='';
  601:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  602:        if (($lock=~/\w/) && ($lock ne $id)) {
  603:           $newlocks.=','.$lock;
  604:        }
  605:     }
  606:     &appenv({'session.locks' => $newlocks});
  607:     &delenv('session.lock.'.$id);
  608: }
  609: 
  610: sub remove_all_locks {
  611:     my $activelocks=$env{'session.locks'};
  612:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  613:        if ($lock=~/\w/) {
  614:           &remove_lock($lock);
  615:        }
  616:     }
  617: }
  618: 
  619: 
  620: # ------------------------------------------ Find out current server userload
  621: sub userload {
  622:     my $numusers=0;
  623:     {
  624: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  625: 	my $filename;
  626: 	my $curtime=time;
  627: 	while ($filename=readdir(LONIDS)) {
  628: 	    next if ($filename eq '.' || $filename eq '..');
  629: 	    next if ($filename =~ /publicuser_\d+\.id/);
  630: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  631: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  632: 	}
  633: 	closedir(LONIDS);
  634:     }
  635:     my $userloadpercent=0;
  636:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  637:     if ($maxuserload) {
  638: 	$userloadpercent=100*$numusers/$maxuserload;
  639:     }
  640:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  641:     return $userloadpercent;
  642: }
  643: 
  644: # ------------------------------------------ Fight off request when overloaded
  645: 
  646: sub overloaderror {
  647:     my ($r,$checkserver)=@_;
  648:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  649:     my $loadavg;
  650:     if ($checkserver eq $perlvar{'lonHostID'}) {
  651:        open(my $loadfile,'/proc/loadavg');
  652:        $loadavg=<$loadfile>;
  653:        $loadavg =~ s/\s.*//g;
  654:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  655:        close($loadfile);
  656:     } else {
  657:        $loadavg=&reply('load',$checkserver);
  658:     }
  659:     my $overload=$loadavg-100;
  660:     if ($overload>0) {
  661: 	$r->err_headers_out->{'Retry-After'}=$overload;
  662:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  663:         return 413;
  664:     }    
  665:     return '';
  666: }
  667: 
  668: # ------------------------------ Find server with least workload from spare.tab
  669: 
  670: sub spareserver {
  671:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  672:     my $spare_server;
  673:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  674:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  675:                                                      :  $userloadpercent;
  676:     
  677:     foreach my $try_server (@{ $spareid{'primary'} }) {
  678: 	($spare_server, $lowest_load) =
  679: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  680:     }
  681: 
  682:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  683: 
  684:     if (!$found_server) {
  685: 	foreach my $try_server (@{ $spareid{'default'} }) {
  686: 	    ($spare_server, $lowest_load) =
  687: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  688: 	}
  689:     }
  690: 
  691:     if (!$want_server_name) {
  692:         my $protocol = 'http';
  693:         if ($protocol{$spare_server} eq 'https') {
  694:             $protocol = $protocol{$spare_server};
  695:         }
  696: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  697:     }
  698:     return $spare_server;
  699: }
  700: 
  701: sub compare_server_load {
  702:     my ($try_server, $spare_server, $lowest_load) = @_;
  703: 
  704:     my $loadans     = &reply('load',    $try_server);
  705:     my $userloadans = &reply('userload',$try_server);
  706: 
  707:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  708: 	next; #didn't get a number from the server
  709:     }
  710: 
  711:     my $load;
  712:     if ($loadans =~ /\d/) {
  713: 	if ($userloadans =~ /\d/) {
  714: 	    #both are numbers, pick the bigger one
  715: 	    $load = ($loadans > $userloadans) ? $loadans 
  716: 		                              : $userloadans;
  717: 	} else {
  718: 	    $load = $loadans;
  719: 	}
  720:     } else {
  721: 	$load = $userloadans;
  722:     }
  723: 
  724:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  725: 	$spare_server = $try_server;
  726: 	$lowest_load  = $load;
  727:     }
  728:     return ($spare_server,$lowest_load);
  729: }
  730: 
  731: # --------------------------- ask offload servers if user already has a session
  732: sub find_existing_session {
  733:     my ($udom,$uname) = @_;
  734:     foreach my $try_server (@{ $spareid{'primary'} },
  735: 			    @{ $spareid{'default'} }) {
  736: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  737:     }
  738:     return;
  739: }
  740: 
  741: # -------------------------------- ask if server already has a session for user
  742: sub has_user_session {
  743:     my ($lonid,$udom,$uname) = @_;
  744:     my $result = &reply(join(':','userhassession',
  745: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  746:     return 1 if ($result eq 'ok');
  747: 
  748:     return 0;
  749: }
  750: 
  751: # --------------------------------------------- Try to change a user's password
  752: 
  753: sub changepass {
  754:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  755:     $currentpass = &escape($currentpass);
  756:     $newpass     = &escape($newpass);
  757:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  758: 		       $server);
  759:     if (! $answer) {
  760: 	&logthis("No reply on password change request to $server ".
  761: 		 "by $uname in domain $udom.");
  762:     } elsif ($answer =~ "^ok") {
  763:         &logthis("$uname in $udom successfully changed their password ".
  764: 		 "on $server.");
  765:     } elsif ($answer =~ "^pwchange_failure") {
  766: 	&logthis("$uname in $udom was unable to change their password ".
  767: 		 "on $server.  The action was blocked by either lcpasswd ".
  768: 		 "or pwchange");
  769:     } elsif ($answer =~ "^non_authorized") {
  770:         &logthis("$uname in $udom did not get their password correct when ".
  771: 		 "attempting to change it on $server.");
  772:     } elsif ($answer =~ "^auth_mode_error") {
  773:         &logthis("$uname in $udom attempted to change their password despite ".
  774: 		 "not being locally or internally authenticated on $server.");
  775:     } elsif ($answer =~ "^unknown_user") {
  776:         &logthis("$uname in $udom attempted to change their password ".
  777: 		 "on $server but were unable to because $server is not ".
  778: 		 "their home server.");
  779:     } elsif ($answer =~ "^refused") {
  780: 	&logthis("$server refused to change $uname in $udom password because ".
  781: 		 "it was sent an unencrypted request to change the password.");
  782:     }
  783:     return $answer;
  784: }
  785: 
  786: # ----------------------- Try to determine user's current authentication scheme
  787: 
  788: sub queryauthenticate {
  789:     my ($uname,$udom)=@_;
  790:     my $uhome=&homeserver($uname,$udom);
  791:     if (!$uhome) {
  792: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  793: 	return 'no_host';
  794:     }
  795:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  796:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  797: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  798:     }
  799:     return $answer;
  800: }
  801: 
  802: # --------- Try to authenticate user from domain's lib servers (first this one)
  803: 
  804: sub authenticate {
  805:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  806:     $upass=&escape($upass);
  807:     $uname= &LONCAPA::clean_username($uname);
  808:     my $uhome=&homeserver($uname,$udom,1);
  809:     my $newhome;
  810:     if ((!$uhome) || ($uhome eq 'no_host')) {
  811: # Maybe the machine was offline and only re-appeared again recently?
  812:         &reconlonc();
  813: # One more
  814: 	$uhome=&homeserver($uname,$udom,1);
  815:         if (($uhome eq 'no_host') && $checkdefauth) {
  816:             if (defined(&domain($udom,'primary'))) {
  817:                 $newhome=&domain($udom,'primary');
  818:             }
  819:             if ($newhome ne '') {
  820:                 $uhome = $newhome;
  821:             }
  822:         }
  823: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  824: 	    &logthis("User $uname at $udom is unknown in authenticate");
  825: 	    return 'no_host';
  826:         }
  827:     }
  828:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  829:     if ($answer eq 'authorized') {
  830:         if ($newhome) {
  831:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  832:             return 'no_account_on_host'; 
  833:         } else {
  834:             &logthis("User $uname at $udom authorized by $uhome");
  835:             return $uhome;
  836:         }
  837:     }
  838:     if ($answer eq 'non_authorized') {
  839: 	&logthis("User $uname at $udom rejected by $uhome");
  840: 	return 'no_host'; 
  841:     }
  842:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  843:     return 'no_host';
  844: }
  845: 
  846: # ---------------------- Find the homebase for a user from domain's lib servers
  847: 
  848: my %homecache;
  849: sub homeserver {
  850:     my ($uname,$udom,$ignoreBadCache)=@_;
  851:     my $index="$uname:$udom";
  852: 
  853:     if (exists($homecache{$index})) { return $homecache{$index}; }
  854: 
  855:     my %servers = &get_servers($udom,'library');
  856:     foreach my $tryserver (keys(%servers)) {
  857:         next if ($ignoreBadCache ne 'true' && 
  858: 		 exists($badServerCache{$tryserver}));
  859: 
  860: 	my $answer=reply("home:$udom:$uname",$tryserver);
  861: 	if ($answer eq 'found') {
  862: 	    delete($badServerCache{$tryserver}); 
  863: 	    return $homecache{$index}=$tryserver;
  864: 	} elsif ($answer eq 'no_host') {
  865: 	    $badServerCache{$tryserver}=1;
  866: 	}
  867:     }    
  868:     return 'no_host';
  869: }
  870: 
  871: # ------------------------------------- Find the usernames behind a list of IDs
  872: 
  873: sub idget {
  874:     my ($udom,@ids)=@_;
  875:     my %returnhash=();
  876:     
  877:     my %servers = &get_servers($udom,'library');
  878:     foreach my $tryserver (keys(%servers)) {
  879: 	my $idlist=join('&',@ids);
  880: 	$idlist=~tr/A-Z/a-z/; 
  881: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  882: 	my @answer=();
  883: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  884: 	    @answer=split(/\&/,$reply);
  885: 	}                    ;
  886: 	my $i;
  887: 	for ($i=0;$i<=$#ids;$i++) {
  888: 	    if ($answer[$i]) {
  889: 		$returnhash{$ids[$i]}=$answer[$i];
  890: 	    } 
  891: 	}
  892:     } 
  893:     return %returnhash;
  894: }
  895: 
  896: # ------------------------------------- Find the IDs behind a list of usernames
  897: 
  898: sub idrget {
  899:     my ($udom,@unames)=@_;
  900:     my %returnhash=();
  901:     foreach my $uname (@unames) {
  902:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  903:     }
  904:     return %returnhash;
  905: }
  906: 
  907: # ------------------------------- Store away a list of names and associated IDs
  908: 
  909: sub idput {
  910:     my ($udom,%ids)=@_;
  911:     my %servers=();
  912:     foreach my $uname (keys(%ids)) {
  913: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  914:         my $uhom=&homeserver($uname,$udom);
  915:         if ($uhom ne 'no_host') {
  916:             my $id=&escape($ids{$uname});
  917:             $id=~tr/A-Z/a-z/;
  918:             my $esc_unam=&escape($uname);
  919: 	    if ($servers{$uhom}) {
  920: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  921:             } else {
  922:                 $servers{$uhom}=$id.'='.$esc_unam;
  923:             }
  924:         }
  925:     }
  926:     foreach my $server (keys(%servers)) {
  927:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  928:     }
  929: }
  930: 
  931: # ------------------------------------------- get items from domain db files   
  932: 
  933: sub get_dom {
  934:     my ($namespace,$storearr,$udom,$uhome)=@_;
  935:     my $items='';
  936:     foreach my $item (@$storearr) {
  937:         $items.=&escape($item).'&';
  938:     }
  939:     $items=~s/\&$//;
  940:     if (!$udom) {
  941:         $udom=$env{'user.domain'};
  942:         if (defined(&domain($udom,'primary'))) {
  943:             $uhome=&domain($udom,'primary');
  944:         } else {
  945:             undef($uhome);
  946:         }
  947:     } else {
  948:         if (!$uhome) {
  949:             if (defined(&domain($udom,'primary'))) {
  950:                 $uhome=&domain($udom,'primary');
  951:             }
  952:         }
  953:     }
  954:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  955:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  956:         my %returnhash;
  957:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  958:             return %returnhash;
  959:         }
  960:         my @pairs=split(/\&/,$rep);
  961:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  962:             return @pairs;
  963:         }
  964:         my $i=0;
  965:         foreach my $item (@$storearr) {
  966:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  967:             $i++;
  968:         }
  969:         return %returnhash;
  970:     } else {
  971:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  972:     }
  973: }
  974: 
  975: # -------------------------------------------- put items in domain db files 
  976: 
  977: sub put_dom {
  978:     my ($namespace,$storehash,$udom,$uhome)=@_;
  979:     if (!$udom) {
  980:         $udom=$env{'user.domain'};
  981:         if (defined(&domain($udom,'primary'))) {
  982:             $uhome=&domain($udom,'primary');
  983:         } else {
  984:             undef($uhome);
  985:         }
  986:     } else {
  987:         if (!$uhome) {
  988:             if (defined(&domain($udom,'primary'))) {
  989:                 $uhome=&domain($udom,'primary');
  990:             }
  991:         }
  992:     } 
  993:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  994:         my $items='';
  995:         foreach my $item (keys(%$storehash)) {
  996:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  997:         }
  998:         $items=~s/\&$//;
  999:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1000:     } else {
 1001:         &logthis("put_dom failed - no homeserver and/or domain");
 1002:     }
 1003: }
 1004: 
 1005: sub retrieve_inst_usertypes {
 1006:     my ($udom) = @_;
 1007:     my (%returnhash,@order);
 1008:     if (defined(&domain($udom,'primary'))) {
 1009:         my $uhome=&domain($udom,'primary');
 1010:         my $rep=&reply("inst_usertypes:$udom",$uhome);
 1011:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1012:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1013:             return (\%returnhash,\@order);
 1014:         }
 1015:         my ($hashitems,$orderitems) = split(/:/,$rep); 
 1016:         my @pairs=split(/\&/,$hashitems);
 1017:         foreach my $item (@pairs) {
 1018:             my ($key,$value)=split(/=/,$item,2);
 1019:             $key = &unescape($key);
 1020:             next if ($key =~ /^error: 2 /);
 1021:             $returnhash{$key}=&thaw_unescape($value);
 1022:         }
 1023:         my @esc_order = split(/\&/,$orderitems);
 1024:         foreach my $item (@esc_order) {
 1025:             push(@order,&unescape($item));
 1026:         }
 1027:     } else {
 1028:         &logthis("get_dom failed - no primary domain server for $udom");
 1029:     }
 1030:     return (\%returnhash,\@order);
 1031: }
 1032: 
 1033: sub is_domainimage {
 1034:     my ($url) = @_;
 1035:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1036:         if (&domain($1) ne '') {
 1037:             return '1';
 1038:         }
 1039:     }
 1040:     return;
 1041: }
 1042: 
 1043: sub inst_directory_query {
 1044:     my ($srch) = @_;
 1045:     my $udom = $srch->{'srchdomain'};
 1046:     my %results;
 1047:     my $homeserver = &domain($udom,'primary');
 1048:     my $outcome;
 1049:     if ($homeserver ne '') {
 1050: 	my $queryid=&reply("querysend:instdirsearch:".
 1051: 			   &escape($srch->{'srchby'}).':'.
 1052: 			   &escape($srch->{'srchterm'}).':'.
 1053: 			   &escape($srch->{'srchtype'}),$homeserver);
 1054: 	my $host=&hostname($homeserver);
 1055: 	if ($queryid !~/^\Q$host\E\_/) {
 1056: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1057: 	    return;
 1058: 	}
 1059: 	my $response = &get_query_reply($queryid);
 1060: 	my $maxtries = 5;
 1061: 	my $tries = 1;
 1062: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1063: 	    $response = &get_query_reply($queryid);
 1064: 	    $tries ++;
 1065: 	}
 1066: 
 1067:         if (!&error($response) && $response ne 'refused') {
 1068:             if ($response eq 'unavailable') {
 1069:                 $outcome = $response;
 1070:             } else {
 1071:                 $outcome = 'ok';
 1072:                 my @matches = split(/\n/,$response);
 1073:                 foreach my $match (@matches) {
 1074:                     my ($key,$value) = split(/=/,$match);
 1075:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1076:                 }
 1077:             }
 1078:         }
 1079:     }
 1080:     return ($outcome,%results);
 1081: }
 1082: 
 1083: sub usersearch {
 1084:     my ($srch) = @_;
 1085:     my $dom = $srch->{'srchdomain'};
 1086:     my %results;
 1087:     my %libserv = &all_library();
 1088:     my $query = 'usersearch';
 1089:     foreach my $tryserver (keys(%libserv)) {
 1090:         if (&host_domain($tryserver) eq $dom) {
 1091:             my $host=&hostname($tryserver);
 1092:             my $queryid=
 1093:                 &reply("querysend:".&escape($query).':'.
 1094:                        &escape($srch->{'srchby'}).':'.
 1095:                        &escape($srch->{'srchtype'}).':'.
 1096:                        &escape($srch->{'srchterm'}),$tryserver);
 1097:             if ($queryid !~/^\Q$host\E\_/) {
 1098:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1099:                 next;
 1100:             }
 1101:             my $reply = &get_query_reply($queryid);
 1102:             my $maxtries = 1;
 1103:             my $tries = 1;
 1104:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1105:                 $reply = &get_query_reply($queryid);
 1106:                 $tries ++;
 1107:             }
 1108:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1109:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1110:             } else {
 1111:                 my @matches;
 1112:                 if ($reply =~ /\n/) {
 1113:                     @matches = split(/\n/,$reply);
 1114:                 } else {
 1115:                     @matches = split(/\&/,$reply);
 1116:                 }
 1117:                 foreach my $match (@matches) {
 1118:                     my ($uname,$udom,%userhash);
 1119:                     foreach my $entry (split(/:/,$match)) {
 1120:                         my ($key,$value) =
 1121:                             map {&unescape($_);} split(/=/,$entry);
 1122:                         $userhash{$key} = $value;
 1123:                         if ($key eq 'username') {
 1124:                             $uname = $value;
 1125:                         } elsif ($key eq 'domain') {
 1126:                             $udom = $value;
 1127:                         }
 1128:                     }
 1129:                     $results{$uname.':'.$udom} = \%userhash;
 1130:                 }
 1131:             }
 1132:         }
 1133:     }
 1134:     return %results;
 1135: }
 1136: 
 1137: sub get_instuser {
 1138:     my ($udom,$uname,$id) = @_;
 1139:     my $homeserver = &domain($udom,'primary');
 1140:     my ($outcome,%results);
 1141:     if ($homeserver ne '') {
 1142:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1143:                            &escape($id).':'.&escape($udom),$homeserver);
 1144:         my $host=&hostname($homeserver);
 1145:         if ($queryid !~/^\Q$host\E\_/) {
 1146:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1147:             return;
 1148:         }
 1149:         my $response = &get_query_reply($queryid);
 1150:         my $maxtries = 5;
 1151:         my $tries = 1;
 1152:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1153:             $response = &get_query_reply($queryid);
 1154:             $tries ++;
 1155:         }
 1156:         if (!&error($response) && $response ne 'refused') {
 1157:             if ($response eq 'unavailable') {
 1158:                 $outcome = $response;
 1159:             } else {
 1160:                 $outcome = 'ok';
 1161:                 my @matches = split(/\n/,$response);
 1162:                 foreach my $match (@matches) {
 1163:                     my ($key,$value) = split(/=/,$match);
 1164:                     $results{&unescape($key)} = &thaw_unescape($value);
 1165:                 }
 1166:             }
 1167:         }
 1168:     }
 1169:     my %userinfo;
 1170:     if (ref($results{$uname}) eq 'HASH') {
 1171:         %userinfo = %{$results{$uname}};
 1172:     } 
 1173:     return ($outcome,%userinfo);
 1174: }
 1175: 
 1176: sub inst_rulecheck {
 1177:     my ($udom,$uname,$id,$item,$rules) = @_;
 1178:     my %returnhash;
 1179:     if ($udom ne '') {
 1180:         if (ref($rules) eq 'ARRAY') {
 1181:             @{$rules} = map {&escape($_);} (@{$rules});
 1182:             my $rulestr = join(':',@{$rules});
 1183:             my $homeserver=&domain($udom,'primary');
 1184:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1185:                 my $response;
 1186:                 if ($item eq 'username') {                
 1187:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1188:                                               ':'.&escape($uname).':'.$rulestr,
 1189:                                               $homeserver));
 1190:                 } elsif ($item eq 'id') {
 1191:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1192:                                               ':'.&escape($id).':'.$rulestr,
 1193:                                               $homeserver));
 1194:                 } elsif ($item eq 'selfcreate') {
 1195:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1196:                                                &escape($udom).':'.&escape($uname).
 1197:                                               ':'.$rulestr,$homeserver));
 1198:                 }
 1199:                 if ($response ne 'refused') {
 1200:                     my @pairs=split(/\&/,$response);
 1201:                     foreach my $item (@pairs) {
 1202:                         my ($key,$value)=split(/=/,$item,2);
 1203:                         $key = &unescape($key);
 1204:                         next if ($key =~ /^error: 2 /);
 1205:                         $returnhash{$key}=&thaw_unescape($value);
 1206:                     }
 1207:                 }
 1208:             }
 1209:         }
 1210:     }
 1211:     return %returnhash;
 1212: }
 1213: 
 1214: sub inst_userrules {
 1215:     my ($udom,$check) = @_;
 1216:     my (%ruleshash,@ruleorder);
 1217:     if ($udom ne '') {
 1218:         my $homeserver=&domain($udom,'primary');
 1219:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1220:             my $response;
 1221:             if ($check eq 'id') {
 1222:                 $response=&reply('instidrules:'.&escape($udom),
 1223:                                  $homeserver);
 1224:             } elsif ($check eq 'email') {
 1225:                 $response=&reply('instemailrules:'.&escape($udom),
 1226:                                  $homeserver);
 1227:             } else {
 1228:                 $response=&reply('instuserrules:'.&escape($udom),
 1229:                                  $homeserver);
 1230:             }
 1231:             if (($response ne 'refused') && ($response ne 'error') && 
 1232:                 ($response ne 'unknown_cmd') && 
 1233:                 ($response ne 'no_such_host')) {
 1234:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1235:                 my @pairs=split(/\&/,$hashitems);
 1236:                 foreach my $item (@pairs) {
 1237:                     my ($key,$value)=split(/=/,$item,2);
 1238:                     $key = &unescape($key);
 1239:                     next if ($key =~ /^error: 2 /);
 1240:                     $ruleshash{$key}=&thaw_unescape($value);
 1241:                 }
 1242:                 my @esc_order = split(/\&/,$orderitems);
 1243:                 foreach my $item (@esc_order) {
 1244:                     push(@ruleorder,&unescape($item));
 1245:                 }
 1246:             }
 1247:         }
 1248:     }
 1249:     return (\%ruleshash,\@ruleorder);
 1250: }
 1251: 
 1252: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1253: 
 1254: sub get_domain_defaults {
 1255:     my ($domain) = @_;
 1256:     my $cachetime = 60*60*24;
 1257:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1258:     if (defined($cached)) {
 1259:         if (ref($result) eq 'HASH') {
 1260:             return %{$result};
 1261:         }
 1262:     }
 1263:     my %domdefaults;
 1264:     my %domconfig =
 1265:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1266:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1267:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1268:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1269:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1270:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1271:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1272:     } else {
 1273:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1274:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1275:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1276:     }
 1277:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1278:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1279:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1280:         } else {
 1281:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1282:         } 
 1283:         my @usertools = ('aboutme','blog','portfolio');
 1284:         foreach my $item (@usertools) {
 1285:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1286:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1287:             }
 1288:         }
 1289:     }
 1290:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1291:         foreach my $item ('official','unofficial') {
 1292:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1293:         }
 1294:     }
 1295:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1296:                                   $cachetime);
 1297:     return %domdefaults;
 1298: }
 1299: 
 1300: # --------------------------------------------------- Assign a key to a student
 1301: 
 1302: sub assign_access_key {
 1303: #
 1304: # a valid key looks like uname:udom#comments
 1305: # comments are being appended
 1306: #
 1307:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1308:     $kdom=
 1309:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1310:     $knum=
 1311:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1312:     $cdom=
 1313:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1314:     $cnum=
 1315:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1316:     $udom=$env{'user.name'} unless (defined($udom));
 1317:     $uname=$env{'user.domain'} unless (defined($uname));
 1318:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1319:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1320:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1321:                                                   # assigned to this person
 1322:                                                   # - this should not happen,
 1323:                                                   # unless something went wrong
 1324:                                                   # the first time around
 1325: # ready to assign
 1326:         $logentry=$1.'; '.$logentry;
 1327:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1328:                                                  $kdom,$knum) eq 'ok') {
 1329: # key now belongs to user
 1330: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1331:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1332:                 &appenv({'environment.'.$envkey => $ckey});
 1333:                 return 'ok';
 1334:             } else {
 1335:                 return 
 1336:   'error: Count not permanently assign key, will need to be re-entered later.';
 1337: 	    }
 1338:         } else {
 1339:             return 'error: Could not assign key, try again later.';
 1340:         }
 1341:     } elsif (!$existing{$ckey}) {
 1342: # the key does not exist
 1343: 	return 'error: The key does not exist';
 1344:     } else {
 1345: # the key is somebody else's
 1346: 	return 'error: The key is already in use';
 1347:     }
 1348: }
 1349: 
 1350: # ------------------------------------------ put an additional comment on a key
 1351: 
 1352: sub comment_access_key {
 1353: #
 1354: # a valid key looks like uname:udom#comments
 1355: # comments are being appended
 1356: #
 1357:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1358:     $cdom=
 1359:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1360:     $cnum=
 1361:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1362:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1363:     if ($existing{$ckey}) {
 1364:         $existing{$ckey}.='; '.$logentry;
 1365: # ready to assign
 1366:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1367:                                                  $cdom,$cnum) eq 'ok') {
 1368: 	    return 'ok';
 1369:         } else {
 1370: 	    return 'error: Count not store comment.';
 1371:         }
 1372:     } else {
 1373: # the key does not exist
 1374: 	return 'error: The key does not exist';
 1375:     }
 1376: }
 1377: 
 1378: # ------------------------------------------------------ Generate a set of keys
 1379: 
 1380: sub generate_access_keys {
 1381:     my ($number,$cdom,$cnum,$logentry)=@_;
 1382:     $cdom=
 1383:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1384:     $cnum=
 1385:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1386:     unless (&allowed('mky',$cdom)) { return 0; }
 1387:     unless (($cdom) && ($cnum)) { return 0; }
 1388:     if ($number>10000) { return 0; }
 1389:     sleep(2); # make sure don't get same seed twice
 1390:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1391:     my $total=0;
 1392:     for (my $i=1;$i<=$number;$i++) {
 1393:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1394:                   sprintf("%lx",int(100000*rand)).'-'.
 1395:                   sprintf("%lx",int(100000*rand));
 1396:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1397:        $newkey=~s/0/h/g; # and also 0 and O
 1398:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1399:        if ($existing{$newkey}) {
 1400:            $i--;
 1401:        } else {
 1402: 	  if (&put('accesskeys',
 1403:               { $newkey => '# generated '.localtime().
 1404:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1405:                            '; '.$logentry },
 1406: 		   $cdom,$cnum) eq 'ok') {
 1407:               $total++;
 1408: 	  }
 1409:        }
 1410:     }
 1411:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1412:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1413:     return $total;
 1414: }
 1415: 
 1416: # ------------------------------------------------------- Validate an accesskey
 1417: 
 1418: sub validate_access_key {
 1419:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1420:     $cdom=
 1421:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1422:     $cnum=
 1423:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1424:     $udom=$env{'user.domain'} unless (defined($udom));
 1425:     $uname=$env{'user.name'} unless (defined($uname));
 1426:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1427:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1428: }
 1429: 
 1430: # ------------------------------------- Find the section of student in a course
 1431: sub devalidate_getsection_cache {
 1432:     my ($udom,$unam,$courseid)=@_;
 1433:     my $hashid="$udom:$unam:$courseid";
 1434:     &devalidate_cache_new('getsection',$hashid);
 1435: }
 1436: 
 1437: sub courseid_to_courseurl {
 1438:     my ($courseid) = @_;
 1439:     #already url style courseid
 1440:     return $courseid if ($courseid =~ m{^/});
 1441: 
 1442:     if (exists($env{'course.'.$courseid.'.num'})) {
 1443: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1444: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1445: 	return "/$cdom/$cnum";
 1446:     }
 1447: 
 1448:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1449:     if (exists($courseinfo{'num'})) {
 1450: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1451:     }
 1452: 
 1453:     return undef;
 1454: }
 1455: 
 1456: sub getsection {
 1457:     my ($udom,$unam,$courseid)=@_;
 1458:     my $cachetime=1800;
 1459: 
 1460:     my $hashid="$udom:$unam:$courseid";
 1461:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1462:     if (defined($cached)) { return $result; }
 1463: 
 1464:     my %Pending; 
 1465:     my %Expired;
 1466:     #
 1467:     # Each role can either have not started yet (pending), be active, 
 1468:     #    or have expired.
 1469:     #
 1470:     # If there is an active role, we are done.
 1471:     #
 1472:     # If there is more than one role which has not started yet, 
 1473:     #     choose the one which will start sooner
 1474:     # If there is one role which has not started yet, return it.
 1475:     #
 1476:     # If there is more than one expired role, choose the one which ended last.
 1477:     # If there is a role which has expired, return it.
 1478:     #
 1479:     $courseid = &courseid_to_courseurl($courseid);
 1480:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1481:     foreach my $key (keys(%roleshash)) {
 1482:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1483:         my $section=$1;
 1484:         if ($key eq $courseid.'_st') { $section=''; }
 1485:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1486:         my $now=time;
 1487:         if (defined($end) && $end && ($now > $end)) {
 1488:             $Expired{$end}=$section;
 1489:             next;
 1490:         }
 1491:         if (defined($start) && $start && ($now < $start)) {
 1492:             $Pending{$start}=$section;
 1493:             next;
 1494:         }
 1495:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1496:     }
 1497:     #
 1498:     # Presumedly there will be few matching roles from the above
 1499:     # loop and the sorting time will be negligible.
 1500:     if (scalar(keys(%Pending))) {
 1501:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1502:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1503:     } 
 1504:     if (scalar(keys(%Expired))) {
 1505:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1506:         my $time = pop(@sorted);
 1507:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1508:     }
 1509:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1510: }
 1511: 
 1512: sub save_cache {
 1513:     &purge_remembered();
 1514:     #&Apache::loncommon::validate_page();
 1515:     undef(%env);
 1516:     undef($env_loaded);
 1517: }
 1518: 
 1519: my $to_remember=-1;
 1520: my %remembered;
 1521: my %accessed;
 1522: my $kicks=0;
 1523: my $hits=0;
 1524: sub make_key {
 1525:     my ($name,$id) = @_;
 1526:     if (length($id) > 65 
 1527: 	&& length(&escape($id)) > 200) {
 1528: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1529:     }
 1530:     return &escape($name.':'.$id);
 1531: }
 1532: 
 1533: sub devalidate_cache_new {
 1534:     my ($name,$id,$debug) = @_;
 1535:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1536:     $id=&make_key($name,$id);
 1537:     $memcache->delete($id);
 1538:     delete($remembered{$id});
 1539:     delete($accessed{$id});
 1540: }
 1541: 
 1542: sub is_cached_new {
 1543:     my ($name,$id,$debug) = @_;
 1544:     $id=&make_key($name,$id);
 1545:     if (exists($remembered{$id})) {
 1546: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1547: 	$accessed{$id}=[&gettimeofday()];
 1548: 	$hits++;
 1549: 	return ($remembered{$id},1);
 1550:     }
 1551:     my $value = $memcache->get($id);
 1552:     if (!(defined($value))) {
 1553: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1554: 	return (undef,undef);
 1555:     }
 1556:     if ($value eq '__undef__') {
 1557: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1558: 	$value=undef;
 1559:     }
 1560:     &make_room($id,$value,$debug);
 1561:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1562:     return ($value,1);
 1563: }
 1564: 
 1565: sub do_cache_new {
 1566:     my ($name,$id,$value,$time,$debug) = @_;
 1567:     $id=&make_key($name,$id);
 1568:     my $setvalue=$value;
 1569:     if (!defined($setvalue)) {
 1570: 	$setvalue='__undef__';
 1571:     }
 1572:     if (!defined($time) ) {
 1573: 	$time=600;
 1574:     }
 1575:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1576:     my $result = $memcache->set($id,$setvalue,$time);
 1577:     if (! $result) {
 1578: 	&logthis("caching of id -> $id  failed");
 1579: 	$memcache->disconnect_all();
 1580:     }
 1581:     # need to make a copy of $value
 1582:     &make_room($id,$value,$debug);
 1583:     return $value;
 1584: }
 1585: 
 1586: sub make_room {
 1587:     my ($id,$value,$debug)=@_;
 1588: 
 1589:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1590:                                     : $value;
 1591:     if ($to_remember<0) { return; }
 1592:     $accessed{$id}=[&gettimeofday()];
 1593:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1594:     my $to_kick;
 1595:     my $max_time=0;
 1596:     foreach my $other (keys(%accessed)) {
 1597: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1598: 	    $to_kick=$other;
 1599: 	    $max_time=&tv_interval($accessed{$other});
 1600: 	}
 1601:     }
 1602:     delete($remembered{$to_kick});
 1603:     delete($accessed{$to_kick});
 1604:     $kicks++;
 1605:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1606:     return;
 1607: }
 1608: 
 1609: sub purge_remembered {
 1610:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1611:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1612:     undef(%remembered);
 1613:     undef(%accessed);
 1614: }
 1615: # ------------------------------------- Read an entry from a user's environment
 1616: 
 1617: sub userenvironment {
 1618:     my ($udom,$unam,@what)=@_;
 1619:     my $items;
 1620:     foreach my $item (@what) {
 1621:         $items.=&escape($item).'&';
 1622:     }
 1623:     $items=~s/\&$//;
 1624:     my %returnhash=();
 1625:     my @answer=split(/\&/,
 1626:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1627:                       &homeserver($unam,$udom)));
 1628:     my $i;
 1629:     for ($i=0;$i<=$#what;$i++) {
 1630: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1631:     }
 1632:     return %returnhash;
 1633: }
 1634: 
 1635: # ---------------------------------------------------------- Get a studentphoto
 1636: sub studentphoto {
 1637:     my ($udom,$unam,$ext) = @_;
 1638:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1639:     if (defined($env{'request.course.id'})) {
 1640:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1641:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1642:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1643:             } else {
 1644:                 my ($result,$perm_reqd)=
 1645: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1646:                 if ($result eq 'ok') {
 1647:                     if (!($perm_reqd eq 'yes')) {
 1648:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1649:                     }
 1650:                 }
 1651:             }
 1652:         }
 1653:     } else {
 1654:         my ($result,$perm_reqd) = 
 1655: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1656:         if ($result eq 'ok') {
 1657:             if (!($perm_reqd eq 'yes')) {
 1658:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1659:             }
 1660:         }
 1661:     }
 1662:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1663: }
 1664: 
 1665: sub retrievestudentphoto {
 1666:     my ($udom,$unam,$ext,$type) = @_;
 1667:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1668:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1669:     if ($ret eq 'ok') {
 1670:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1671:         if ($type eq 'thumbnail') {
 1672:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1673:         }
 1674:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1675:         return $tokenurl;
 1676:     } else {
 1677:         if ($type eq 'thumbnail') {
 1678:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1679:         } else { 
 1680:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1681:         }
 1682:     }
 1683: }
 1684: 
 1685: # -------------------------------------------------------------------- New chat
 1686: 
 1687: sub chatsend {
 1688:     my ($newentry,$anon,$group)=@_;
 1689:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1690:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1691:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1692:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1693: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1694: 		   &escape($newentry)).':'.$group,$chome);
 1695: }
 1696: 
 1697: # ------------------------------------------ Find current version of a resource
 1698: 
 1699: sub getversion {
 1700:     my $fname=&clutter(shift);
 1701:     unless ($fname=~/^\/res\//) { return -1; }
 1702:     return &currentversion(&filelocation('',$fname));
 1703: }
 1704: 
 1705: sub currentversion {
 1706:     my $fname=shift;
 1707:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1708:     if (defined($cached)) { return $result; }
 1709:     my $author=$fname;
 1710:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1711:     my ($udom,$uname)=split(/\//,$author);
 1712:     my $home=homeserver($uname,$udom);
 1713:     if ($home eq 'no_host') { 
 1714:         return -1; 
 1715:     }
 1716:     my $answer=reply("currentversion:$fname",$home);
 1717:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1718: 	return -1;
 1719:     }
 1720:     return &do_cache_new('resversion',$fname,$answer,600);
 1721: }
 1722: 
 1723: # ----------------------------- Subscribe to a resource, return URL if possible
 1724: 
 1725: sub subscribe {
 1726:     my $fname=shift;
 1727:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1728:     $fname=~s/[\n\r]//g;
 1729:     my $author=$fname;
 1730:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1731:     my ($udom,$uname)=split(/\//,$author);
 1732:     my $home=homeserver($uname,$udom);
 1733:     if ($home eq 'no_host') {
 1734:         return 'not_found';
 1735:     }
 1736:     my $answer=reply("sub:$fname",$home);
 1737:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1738: 	$answer.=' by '.$home;
 1739:     }
 1740:     return $answer;
 1741: }
 1742:     
 1743: # -------------------------------------------------------------- Replicate file
 1744: 
 1745: sub repcopy {
 1746:     my $filename=shift;
 1747:     $filename=~s/\/+/\//g;
 1748:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1749:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1750:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1751: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1752: 	return &repcopy_userfile($filename);
 1753:     }
 1754:     $filename=~s/[\n\r]//g;
 1755:     my $transname="$filename.in.transfer";
 1756: # FIXME: this should flock
 1757:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1758:     my $remoteurl=subscribe($filename);
 1759:     if ($remoteurl =~ /^con_lost by/) {
 1760: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1761:            return 'unavailable';
 1762:     } elsif ($remoteurl eq 'not_found') {
 1763: 	   #&logthis("Subscribe returned not_found: $filename");
 1764: 	   return 'not_found';
 1765:     } elsif ($remoteurl =~ /^rejected by/) {
 1766: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1767:            return 'forbidden';
 1768:     } elsif ($remoteurl eq 'directory') {
 1769:            return 'ok';
 1770:     } else {
 1771:         my $author=$filename;
 1772:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1773:         my ($udom,$uname)=split(/\//,$author);
 1774:         my $home=homeserver($uname,$udom);
 1775:         unless ($home eq $perlvar{'lonHostID'}) {
 1776:            my @parts=split(/\//,$filename);
 1777:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1778:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1779:                &logthis("Malconfiguration for replication: $filename");
 1780: 	       return 'bad_request';
 1781:            }
 1782:            my $count;
 1783:            for ($count=5;$count<$#parts;$count++) {
 1784:                $path.="/$parts[$count]";
 1785:                if ((-e $path)!=1) {
 1786: 		   mkdir($path,0777);
 1787:                }
 1788:            }
 1789:            my $ua=new LWP::UserAgent;
 1790:            my $request=new HTTP::Request('GET',"$remoteurl");
 1791:            my $response=$ua->request($request,$transname);
 1792:            if ($response->is_error()) {
 1793: 	       unlink($transname);
 1794:                my $message=$response->status_line;
 1795:                &logthis("<font color=\"blue\">WARNING:"
 1796:                        ." LWP get: $message: $filename</font>");
 1797:                return 'unavailable';
 1798:            } else {
 1799: 	       if ($remoteurl!~/\.meta$/) {
 1800:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1801:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1802:                   if ($mresponse->is_error()) {
 1803: 		      unlink($filename.'.meta');
 1804:                       &logthis(
 1805:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1806:                   }
 1807: 	       }
 1808:                rename($transname,$filename);
 1809:                return 'ok';
 1810:            }
 1811:        }
 1812:     }
 1813: }
 1814: 
 1815: # ------------------------------------------------ Get server side include body
 1816: sub ssi_body {
 1817:     my ($filelink,%form)=@_;
 1818:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1819:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1820:     }
 1821:     my $output='';
 1822:     my $response;
 1823:     if ($filelink=~/^https?\:/) {
 1824:        ($output,$response)=&externalssi($filelink);
 1825:     } else {
 1826:        ($output,$response)=&ssi($filelink,%form);
 1827:     }
 1828:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1829:     $output=~s/^.*?\<body[^\>]*\>//si;
 1830:     $output=~s/\<\/body\s*\>.*?$//si;
 1831:     if (wantarray) {
 1832:         return ($output, $response);
 1833:     } else {
 1834:         return $output;
 1835:     }
 1836: }
 1837: 
 1838: # --------------------------------------------------------- Server Side Include
 1839: 
 1840: sub absolute_url {
 1841:     my ($host_name) = @_;
 1842:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1843:     if ($host_name eq '') {
 1844: 	$host_name = $ENV{'SERVER_NAME'};
 1845:     }
 1846:     return $protocol.$host_name;
 1847: }
 1848: 
 1849: #
 1850: #   Server side include.
 1851: # Parameters:
 1852: #  fn     Possibly encrypted resource name/id.
 1853: #  form   Hash that describes how the rendering should be done
 1854: #         and other things.
 1855: # Returns:
 1856: #   Scalar context: The content of the response.
 1857: #   Array context:  2 element list of the content and the full response object.
 1858: #     
 1859: sub ssi {
 1860: 
 1861:     my ($fn,%form)=@_;
 1862:     my $ua=new LWP::UserAgent;
 1863:     my $request;
 1864: 
 1865:     $form{'no_update_last_known'}=1;
 1866:     &Apache::lonenc::check_encrypt(\$fn);
 1867:     if (%form) {
 1868:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1869:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1870:     } else {
 1871:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1872:     }
 1873: 
 1874:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1875:     my $response=$ua->request($request);
 1876: 
 1877:     if (wantarray) {
 1878: 	return ($response->content, $response);
 1879:     } else {
 1880: 	return $response->content;
 1881:     }
 1882: }
 1883: 
 1884: sub externalssi {
 1885:     my ($url)=@_;
 1886:     my $ua=new LWP::UserAgent;
 1887:     my $request=new HTTP::Request('GET',$url);
 1888:     my $response=$ua->request($request);
 1889:     if (wantarray) {
 1890:         return ($response->content, $response);
 1891:     } else {
 1892:         return $response->content;
 1893:     }
 1894: }
 1895: 
 1896: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1897: 
 1898: sub allowuploaded {
 1899:     my ($srcurl,$url)=@_;
 1900:     $url=&clutter(&declutter($url));
 1901:     my $dir=$url;
 1902:     $dir=~s/\/[^\/]+$//;
 1903:     my %httpref=();
 1904:     my $httpurl=&hreflocation('',$url);
 1905:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1906:     &Apache::lonnet::appenv(\%httpref);
 1907: }
 1908: 
 1909: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1910: # input: action, courseID, current domain, intended
 1911: #        path to file, source of file, instruction to parse file for objects,
 1912: #        ref to hash for embedded objects,
 1913: #        ref to hash for codebase of java objects.
 1914: #
 1915: # output: url to file (if action was uploaddoc), 
 1916: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1917: #
 1918: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1919: # course.
 1920: #
 1921: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1922: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1923: #          course's home server.
 1924: #
 1925: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1926: #          be copied from $source (current location) to 
 1927: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1928: #         and will then be copied to
 1929: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1930: #         course's home server.
 1931: #
 1932: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1933: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1934: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1935: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1936: #         in course's home server.
 1937: #
 1938: 
 1939: sub process_coursefile {
 1940:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1941:     my $fetchresult;
 1942:     my $home=&homeserver($docuname,$docudom);
 1943:     if ($action eq 'propagate') {
 1944:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1945: 			     $home);
 1946:     } else {
 1947:         my $fpath = '';
 1948:         my $fname = $file;
 1949:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1950:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1951:         my $filepath = &build_filepath($fpath);
 1952:         if ($action eq 'copy') {
 1953:             if ($source eq '') {
 1954:                 $fetchresult = 'no source file';
 1955:                 return $fetchresult;
 1956:             } else {
 1957:                 my $destination = $filepath.'/'.$fname;
 1958:                 rename($source,$destination);
 1959:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1960:                                  $home);
 1961:             }
 1962:         } elsif ($action eq 'uploaddoc') {
 1963:             open(my $fh,'>'.$filepath.'/'.$fname);
 1964:             print $fh $env{'form.'.$source};
 1965:             close($fh);
 1966:             if ($parser eq 'parse') {
 1967:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1968:                 unless ($parse_result eq 'ok') {
 1969:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1970:                 }
 1971:             }
 1972:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1973:                                  $home);
 1974:             if ($fetchresult eq 'ok') {
 1975:                 return '/uploaded/'.$fpath.'/'.$fname;
 1976:             } else {
 1977:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1978:                         ' to host '.$home.': '.$fetchresult);
 1979:                 return '/adm/notfound.html';
 1980:             }
 1981:         }
 1982:     }
 1983:     unless ( $fetchresult eq 'ok') {
 1984:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1985:              ' to host '.$home.': '.$fetchresult);
 1986:     }
 1987:     return $fetchresult;
 1988: }
 1989: 
 1990: sub build_filepath {
 1991:     my ($fpath) = @_;
 1992:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1993:     unless ($fpath eq '') {
 1994:         my @parts=split('/',$fpath);
 1995:         foreach my $part (@parts) {
 1996:             $filepath.= '/'.$part;
 1997:             if ((-e $filepath)!=1) {
 1998:                 mkdir($filepath,0777);
 1999:             }
 2000:         }
 2001:     }
 2002:     return $filepath;
 2003: }
 2004: 
 2005: sub store_edited_file {
 2006:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2007:     my $file = $primary_url;
 2008:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2009:     my $fpath = '';
 2010:     my $fname = $file;
 2011:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2012:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2013:     my $filepath = &build_filepath($fpath);
 2014:     open(my $fh,'>'.$filepath.'/'.$fname);
 2015:     print $fh $content;
 2016:     close($fh);
 2017:     my $home=&homeserver($docuname,$docudom);
 2018:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2019: 			  $home);
 2020:     if ($$fetchresult eq 'ok') {
 2021:         return '/uploaded/'.$fpath.'/'.$fname;
 2022:     } else {
 2023:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2024: 		 ' to host '.$home.': '.$$fetchresult);
 2025:         return '/adm/notfound.html';
 2026:     }
 2027: }
 2028: 
 2029: sub clean_filename {
 2030:     my ($fname,$args)=@_;
 2031: # Replace Windows backslashes by forward slashes
 2032:     $fname=~s/\\/\//g;
 2033:     if (!$args->{'keep_path'}) {
 2034:         # Get rid of everything but the actual filename
 2035: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2036:     }
 2037: # Replace spaces by underscores
 2038:     $fname=~s/\s+/\_/g;
 2039: # Replace all other weird characters by nothing
 2040:     $fname=~s{[^/\w\.\-]}{}g;
 2041: # Replace all .\d. sequences with _\d. so they no longer look like version
 2042: # numbers
 2043:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2044:     return $fname;
 2045: }
 2046: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2047: sub resizeImage {
 2048: 	my($img_url) = @_;	
 2049: 	my $ima = Image::Magick->new;                       
 2050:         $ima->Read($img_url);
 2051: 	if($ima->Get('width') > 400)
 2052: 	{
 2053: 		my $factor = $ima->Get('width')/400;
 2054:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2055: 	}
 2056: 	if($ima->Get('height') > 500)
 2057:         {
 2058:         	my $factor = $ima->Get('height')/500;
 2059:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2060:         } 
 2061: 		
 2062: 	$ima->Write($img_url);
 2063: }
 2064: 
 2065: #Wrapper function for userphotoupload
 2066: sub userphotoupload
 2067: {
 2068: 	my($formname,$subdir) = @_;
 2069: 	$upload_photo_form = 1;
 2070: 	return &userfileupload($formname,undef,$subdir);
 2071: }
 2072: 
 2073: # --------------- Take an uploaded file and put it into the userfiles directory
 2074: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2075: #                    the desired filenam is in $env{"form.$formname.filename"}
 2076: #        $coursedoc - if true up to the current course
 2077: #                     if false
 2078: #        $subdir - directory in userfile to store the file into
 2079: #        $parser - instruction to parse file for objects ($parser = parse)    
 2080: #        $allfiles - reference to hash for embedded objects
 2081: #        $codebase - reference to hash for codebase of java objects
 2082: #        $desuname - username for permanent storage of uploaded file
 2083: #        $dsetudom - domain for permanaent storage of uploaded file
 2084: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2085: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2086: # 
 2087: # output: url of file in userspace, or error: <message> 
 2088: #             or /adm/notfound.html if failure to upload occurse
 2089: 
 2090: 
 2091: sub userfileupload {
 2092:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2093:         $destudom,$thumbwidth,$thumbheight)=@_;
 2094:     if (!defined($subdir)) { $subdir='unknown'; }
 2095:     my $fname=$env{'form.'.$formname.'.filename'};
 2096:     $fname=&clean_filename($fname);
 2097: # See if there is anything left
 2098:     unless ($fname) { return 'error: no uploaded file'; }
 2099:     chop($env{'form.'.$formname});
 2100:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2101:         my $now = time;
 2102:         my $filepath = 'tmp/helprequests/'.$now;
 2103:         my @parts=split(/\//,$filepath);
 2104:         my $fullpath = $perlvar{'lonDaemons'};
 2105:         for (my $i=0;$i<@parts;$i++) {
 2106:             $fullpath .= '/'.$parts[$i];
 2107:             if ((-e $fullpath)!=1) {
 2108:                 mkdir($fullpath,0777);
 2109:             }
 2110:         }
 2111:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2112:         print $fh $env{'form.'.$formname};
 2113:         close($fh);
 2114:         return $fullpath.'/'.$fname;
 2115:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2116:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2117:                        '_'.$env{'user.domain'}.'/pending';
 2118:         my @parts=split(/\//,$filepath);
 2119:         my $fullpath = $perlvar{'lonDaemons'};
 2120:         for (my $i=0;$i<@parts;$i++) {
 2121:             $fullpath .= '/'.$parts[$i];
 2122:             if ((-e $fullpath)!=1) {
 2123:                 mkdir($fullpath,0777);
 2124:             }
 2125:         }
 2126:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2127:         print $fh $env{'form.'.$formname};
 2128:         close($fh);
 2129:         return $fullpath.'/'.$fname;
 2130:     }
 2131:     
 2132: # Create the directory if not present
 2133:     $fname="$subdir/$fname";
 2134:     if ($coursedoc) {
 2135: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2136: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2137:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2138:             return &finishuserfileupload($docuname,$docudom,
 2139: 					 $formname,$fname,$parser,$allfiles,
 2140: 					 $codebase,$thumbwidth,$thumbheight);
 2141:         } else {
 2142:             $fname=$env{'form.folder'}.'/'.$fname;
 2143:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2144: 				       $fname,$formname,$parser,
 2145: 				       $allfiles,$codebase);
 2146:         }
 2147:     } elsif (defined($destuname)) {
 2148:         my $docuname=$destuname;
 2149:         my $docudom=$destudom;
 2150: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2151: 				     $parser,$allfiles,$codebase,
 2152:                                      $thumbwidth,$thumbheight);
 2153:         
 2154:     } else {
 2155:         my $docuname=$env{'user.name'};
 2156:         my $docudom=$env{'user.domain'};
 2157:         if (exists($env{'form.group'})) {
 2158:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2159:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2160:         }
 2161: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2162: 				     $parser,$allfiles,$codebase,
 2163:                                      $thumbwidth,$thumbheight);
 2164:     }
 2165: }
 2166: 
 2167: sub finishuserfileupload {
 2168:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2169:         $thumbwidth,$thumbheight) = @_;
 2170:     my $path=$docudom.'/'.$docuname.'/';
 2171:     my $filepath=$perlvar{'lonDocRoot'};
 2172:   
 2173:     my ($fnamepath,$file,$fetchthumb);
 2174:     $file=$fname;
 2175:     if ($fname=~m|/|) {
 2176:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2177: 	$path.=$fnamepath.'/';
 2178:     }
 2179:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2180:     my $count;
 2181:     for ($count=4;$count<=$#parts;$count++) {
 2182:         $filepath.="/$parts[$count]";
 2183:         if ((-e $filepath)!=1) {
 2184: 	    mkdir($filepath,0777);
 2185:         }
 2186:     }
 2187: 
 2188: # Save the file
 2189:     {
 2190: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2191: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2192: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2193: 	    return '/adm/notfound.html';
 2194: 	}
 2195: 	if (!print FH ($env{'form.'.$formname})) {
 2196: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2197: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2198: 	    return '/adm/notfound.html';
 2199: 	}
 2200: 	close(FH);
 2201: 	if($upload_photo_form==1)
 2202: 	{
 2203: 		resizeImage($filepath.'/'.$file);		
 2204: 		$upload_photo_form = 0;
 2205: 	}
 2206:     }
 2207:     if ($parser eq 'parse') {
 2208:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2209: 						   $codebase);
 2210:         unless ($parse_result eq 'ok') {
 2211:             &logthis('Failed to parse '.$filepath.$file.
 2212: 		     ' for embedded media: '.$parse_result); 
 2213:         }
 2214:     }
 2215:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2216:         my $input = $filepath.'/'.$file;
 2217:         my $output = $filepath.'/'.'tn-'.$file;
 2218:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2219:         system("convert -sample $thumbsize $input $output");
 2220:         if (-e $filepath.'/'.'tn-'.$file) {
 2221:             $fetchthumb  = 1; 
 2222:         }
 2223:     }
 2224:  
 2225: # Notify homeserver to grep it
 2226: #
 2227:     my $docuhome=&homeserver($docuname,$docudom);	
 2228:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2229:     if ($fetchresult eq 'ok') {
 2230:         if ($fetchthumb) {
 2231:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2232:             if ($thumbresult ne 'ok') {
 2233:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2234:                          $docuhome.': '.$thumbresult);
 2235:             }
 2236:         }
 2237: #
 2238: # Return the URL to it
 2239:         return '/uploaded/'.$path.$file;
 2240:     } else {
 2241:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2242: 		 ': '.$fetchresult);
 2243:         return '/adm/notfound.html';
 2244:     }
 2245: }
 2246: 
 2247: sub extract_embedded_items {
 2248:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2249:     my @state = ();
 2250:     my %javafiles = (
 2251:                       codebase => '',
 2252:                       code => '',
 2253:                       archive => ''
 2254:                     );
 2255:     my %mediafiles = (
 2256:                       src => '',
 2257:                       movie => '',
 2258:                      );
 2259:     my $p;
 2260:     if ($content) {
 2261:         $p = HTML::LCParser->new($content);
 2262:     } else {
 2263:         $p = HTML::LCParser->new($fullpath);
 2264:     }
 2265:     while (my $t=$p->get_token()) {
 2266: 	if ($t->[0] eq 'S') {
 2267: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2268: 	    push(@state, $tagname);
 2269:             if (lc($tagname) eq 'allow') {
 2270:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2271:             }
 2272: 	    if (lc($tagname) eq 'img') {
 2273: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2274: 	    }
 2275: 	    if (lc($tagname) eq 'a') {
 2276: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2277: 	    }
 2278:             if (lc($tagname) eq 'script') {
 2279:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2280:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2281:                 } else {
 2282:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2283:                 }
 2284:             }
 2285:             if (lc($tagname) eq 'link') {
 2286:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2287:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2288:                 }
 2289:             }
 2290: 	    if (lc($tagname) eq 'object' ||
 2291: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2292: 		foreach my $item (keys(%javafiles)) {
 2293: 		    $javafiles{$item} = '';
 2294: 		}
 2295: 	    }
 2296: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2297: 		my $name = lc($attr->{'name'});
 2298: 		foreach my $item (keys(%javafiles)) {
 2299: 		    if ($name eq $item) {
 2300: 			$javafiles{$item} = $attr->{'value'};
 2301: 			last;
 2302: 		    }
 2303: 		}
 2304: 		foreach my $item (keys(%mediafiles)) {
 2305: 		    if ($name eq $item) {
 2306: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2307: 			last;
 2308: 		    }
 2309: 		}
 2310: 	    }
 2311: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2312: 		foreach my $item (keys(%javafiles)) {
 2313: 		    if ($attr->{$item}) {
 2314: 			$javafiles{$item} = $attr->{$item};
 2315: 			last;
 2316: 		    }
 2317: 		}
 2318: 		foreach my $item (keys(%mediafiles)) {
 2319: 		    if ($attr->{$item}) {
 2320: 			&add_filetype($allfiles,$attr->{$item},$item);
 2321: 			last;
 2322: 		    }
 2323: 		}
 2324: 	    }
 2325: 	} elsif ($t->[0] eq 'E') {
 2326: 	    my ($tagname) = ($t->[1]);
 2327: 	    if ($javafiles{'codebase'} ne '') {
 2328: 		$javafiles{'codebase'} .= '/';
 2329: 	    }  
 2330: 	    if (lc($tagname) eq 'applet' ||
 2331: 		lc($tagname) eq 'object' ||
 2332: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2333: 		) {
 2334: 		foreach my $item (keys(%javafiles)) {
 2335: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2336: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2337: 			&add_filetype($allfiles,$file,$item);
 2338: 		    }
 2339: 		}
 2340: 	    } 
 2341: 	    pop @state;
 2342: 	}
 2343:     }
 2344:     return 'ok';
 2345: }
 2346: 
 2347: sub add_filetype {
 2348:     my ($allfiles,$file,$type)=@_;
 2349:     if (exists($allfiles->{$file})) {
 2350: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2351: 	    push(@{$allfiles->{$file}}, &escape($type));
 2352: 	}
 2353:     } else {
 2354: 	@{$allfiles->{$file}} = (&escape($type));
 2355:     }
 2356: }
 2357: 
 2358: sub removeuploadedurl {
 2359:     my ($url)=@_;	
 2360:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2361:     return &removeuserfile($uname,$udom,$fname);
 2362: }
 2363: 
 2364: sub removeuserfile {
 2365:     my ($docuname,$docudom,$fname)=@_;
 2366:     my $home=&homeserver($docuname,$docudom);    
 2367:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2368:     if ($result eq 'ok') {	
 2369:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2370:             my $metafile = $fname.'.meta';
 2371:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2372: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2373:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2374:             my $sqlresult = 
 2375:                 &update_portfolio_table($docuname,$docudom,$file,
 2376:                                         'portfolio_metadata',$group,
 2377:                                         'delete');
 2378:         }
 2379:     }
 2380:     return $result;
 2381: }
 2382: 
 2383: sub mkdiruserfile {
 2384:     my ($docuname,$docudom,$dir)=@_;
 2385:     my $home=&homeserver($docuname,$docudom);
 2386:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2387: }
 2388: 
 2389: sub renameuserfile {
 2390:     my ($docuname,$docudom,$old,$new)=@_;
 2391:     my $home=&homeserver($docuname,$docudom);
 2392:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2393:                         &escape("$old").':'.&escape("$new"),$home);
 2394:     if ($result eq 'ok') {
 2395:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2396:             my $oldmeta = $old.'.meta';
 2397:             my $newmeta = $new.'.meta';
 2398:             my $metaresult = 
 2399:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2400: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2401:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2402:             my $sqlresult = 
 2403:                 &update_portfolio_table($docuname,$docudom,$file,
 2404:                                         'portfolio_metadata',$group,
 2405:                                         'delete');
 2406:         }
 2407:     }
 2408:     return $result;
 2409: }
 2410: 
 2411: # ------------------------------------------------------------------------- Log
 2412: 
 2413: sub log {
 2414:     my ($dom,$nam,$hom,$what)=@_;
 2415:     return critical("log:$dom:$nam:$what",$hom);
 2416: }
 2417: 
 2418: # ------------------------------------------------------------------ Course Log
 2419: #
 2420: # This routine flushes several buffers of non-mission-critical nature
 2421: #
 2422: 
 2423: sub flushcourselogs {
 2424:     &logthis('Flushing log buffers');
 2425: #
 2426: # course logs
 2427: # This is a log of all transactions in a course, which can be used
 2428: # for data mining purposes
 2429: #
 2430: # It also collects the courseid database, which lists last transaction
 2431: # times and course titles for all courseids
 2432: #
 2433:     my %courseidbuffer=();
 2434:     foreach my $crsid (keys(%courselogs)) {
 2435:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2436: 		          &escape($courselogs{$crsid}),
 2437: 		          $coursehombuf{$crsid}) eq 'ok') {
 2438: 	    delete $courselogs{$crsid};
 2439:         } else {
 2440:             &logthis('Failed to flush log buffer for '.$crsid);
 2441:             if (length($courselogs{$crsid})>40000) {
 2442:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2443:                         " exceeded maximum size, deleting.</font>");
 2444:                delete $courselogs{$crsid};
 2445:             }
 2446:         }
 2447:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2448:             'description' => $coursedescrbuf{$crsid},
 2449:             'inst_code'    => $courseinstcodebuf{$crsid},
 2450:             'type'        => $coursetypebuf{$crsid},
 2451:             'owner'       => $courseownerbuf{$crsid},
 2452:         };
 2453:     }
 2454: #
 2455: # Write course id database (reverse lookup) to homeserver of courses 
 2456: # Is used in pickcourse
 2457: #
 2458:     foreach my $crs_home (keys(%courseidbuffer)) {
 2459:         my $response = &courseidput(&host_domain($crs_home),
 2460:                                     $courseidbuffer{$crs_home},
 2461:                                     $crs_home,'timeonly');
 2462:     }
 2463: #
 2464: # File accesses
 2465: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2466: #
 2467:     foreach my $entry (keys(%accesshash)) {
 2468:         if ($entry =~ /___count$/) {
 2469:             my ($dom,$name);
 2470:             ($dom,$name,undef)=
 2471: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2472:             if (! defined($dom) || $dom eq '' || 
 2473:                 ! defined($name) || $name eq '') {
 2474:                 my $cid = $env{'request.course.id'};
 2475:                 $dom  = $env{'request.'.$cid.'.domain'};
 2476:                 $name = $env{'request.'.$cid.'.num'};
 2477:             }
 2478:             my $value = $accesshash{$entry};
 2479:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2480:             my %temphash=($url => $value);
 2481:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2482:             if ($result eq 'ok') {
 2483:                 delete $accesshash{$entry};
 2484:             } elsif ($result eq 'unknown_cmd') {
 2485:                 # Target server has old code running on it.
 2486:                 my %temphash=($entry => $value);
 2487:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2488:                     delete $accesshash{$entry};
 2489:                 }
 2490:             }
 2491:         } else {
 2492:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2493:             my %temphash=($entry => $accesshash{$entry});
 2494:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2495:                 delete $accesshash{$entry};
 2496:             }
 2497:         }
 2498:     }
 2499: #
 2500: # Roles
 2501: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2502: #
 2503:     foreach my $entry (keys(%userrolehash)) {
 2504:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2505: 	    split(/\:/,$entry);
 2506:         if (&Apache::lonnet::put('nohist_userroles',
 2507:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2508:                 $rudom,$runame) eq 'ok') {
 2509: 	    delete $userrolehash{$entry};
 2510:         }
 2511:     }
 2512: #
 2513: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2514: #
 2515:     my %domrolebuffer = ();
 2516:     foreach my $entry (keys %domainrolehash) {
 2517:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2518:         if ($domrolebuffer{$rudom}) {
 2519:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2520:                       '='.&escape($domainrolehash{$entry});
 2521:         } else {
 2522:             $domrolebuffer{$rudom}.=&escape($entry).
 2523:                       '='.&escape($domainrolehash{$entry});
 2524:         }
 2525:         delete $domainrolehash{$entry};
 2526:     }
 2527:     foreach my $dom (keys(%domrolebuffer)) {
 2528: 	my %servers = &get_servers($dom,'library');
 2529: 	foreach my $tryserver (keys(%servers)) {
 2530: 	    unless (&reply('domroleput:'.$dom.':'.
 2531: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2532: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2533: 	    }
 2534:         }
 2535:     }
 2536:     $dumpcount++;
 2537: }
 2538: 
 2539: sub courselog {
 2540:     my $what=shift;
 2541:     $what=time.':'.$what;
 2542:     unless ($env{'request.course.id'}) { return ''; }
 2543:     $coursedombuf{$env{'request.course.id'}}=
 2544:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2545:     $coursenumbuf{$env{'request.course.id'}}=
 2546:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2547:     $coursehombuf{$env{'request.course.id'}}=
 2548:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2549:     $coursedescrbuf{$env{'request.course.id'}}=
 2550:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2551:     $courseinstcodebuf{$env{'request.course.id'}}=
 2552:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2553:     $courseownerbuf{$env{'request.course.id'}}=
 2554:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2555:     $coursetypebuf{$env{'request.course.id'}}=
 2556:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2557:     if (defined $courselogs{$env{'request.course.id'}}) {
 2558: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2559:     } else {
 2560: 	$courselogs{$env{'request.course.id'}}.=$what;
 2561:     }
 2562:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2563: 	&flushcourselogs();
 2564:     }
 2565: }
 2566: 
 2567: sub courseacclog {
 2568:     my $fnsymb=shift;
 2569:     unless ($env{'request.course.id'}) { return ''; }
 2570:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2571:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2572:         $what.=':POST';
 2573:         # FIXME: Probably ought to escape things....
 2574: 	foreach my $key (keys(%env)) {
 2575:             if ($key=~/^form\.(.*)/) {
 2576:                 my $formitem = $1;
 2577:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2578:                     $what.=':'.$formitem.'='.$env{$key};
 2579:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2580:                     $what.=':'.$formitem.'='.$env{$key};
 2581:                 }
 2582:             }
 2583:         }
 2584:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2585:         # FIXME: We should not be depending on a form parameter that someone
 2586:         # editing lonsearchcat.pm might change in the future.
 2587:         if ($env{'form.phase'} eq 'course_search') {
 2588:             $what.= ':POST';
 2589:             # FIXME: Probably ought to escape things....
 2590:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2591:                                  'crsdiscuss') {
 2592:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2593:             }
 2594:         }
 2595:     }
 2596:     &courselog($what);
 2597: }
 2598: 
 2599: sub countacc {
 2600:     my $url=&declutter(shift);
 2601:     return if (! defined($url) || $url eq '');
 2602:     unless ($env{'request.course.id'}) { return ''; }
 2603:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2604:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2605:     $accesshash{$key}++;
 2606: }
 2607: 
 2608: sub linklog {
 2609:     my ($from,$to)=@_;
 2610:     $from=&declutter($from);
 2611:     $to=&declutter($to);
 2612:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2613:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2614: }
 2615:   
 2616: sub userrolelog {
 2617:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2618:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2619:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2620:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2621:         ($trole=~/^ta/)) {
 2622:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2623:        $userrolehash
 2624:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2625:                     =$tend.':'.$tstart;
 2626:     }
 2627:     if (($env{'request.role'} =~ /dc\./) &&
 2628: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2629: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2630: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2631:        $userrolehash
 2632:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2633:                     =$tend.':'.$tstart;
 2634:     }
 2635:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2636:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2637:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2638:         ($trole=~/^sc/)) {
 2639:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2640:        $domainrolehash
 2641:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2642:                     = $tend.':'.$tstart;
 2643:     }
 2644: }
 2645: 
 2646: sub courserolelog {
 2647:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2648:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2649:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2650:         ($trole eq 'ta') || ($trole eq 'st') ||
 2651:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2652:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2653:             my $cdom = $1;
 2654:             my $cnum = $2;
 2655:             my $sec = $3;
 2656:             my $namespace = 'rolelog';
 2657:             my %storehash = (
 2658:                                role    => $trole,
 2659:                                start   => $tstart,
 2660:                                end     => $tend,
 2661:                                selfenroll => $selfenroll,
 2662:                                context    => $context,
 2663:                             );
 2664:             if ($trole eq 'gr') {
 2665:                 $namespace = 'groupslog';
 2666:                 $storehash{'group'} = $sec;
 2667:             } else {
 2668:                 $storehash{'section'} = $sec;
 2669:             }
 2670:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2671:         }
 2672:     }
 2673:     return;
 2674: }
 2675: 
 2676: sub get_course_adv_roles {
 2677:     my ($cid,$codes) = @_;
 2678:     $cid=$env{'request.course.id'} unless (defined($cid));
 2679:     my %coursehash=&coursedescription($cid);
 2680:     my $crstype = &Apache::loncommon::course_type($cid);
 2681:     my %nothide=();
 2682:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2683:         if ($user !~ /:/) {
 2684: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2685:         } else {
 2686:             $nothide{$user}=1;
 2687:         }
 2688:     }
 2689:     my %returnhash=();
 2690:     my %dumphash=
 2691:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2692:     my $now=time;
 2693:     foreach my $entry (keys %dumphash) {
 2694: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2695:         if (($tstart) && ($tstart<0)) { next; }
 2696:         if (($tend) && ($tend<$now)) { next; }
 2697:         if (($tstart) && ($now<$tstart)) { next; }
 2698:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2699: 	if ($username eq '' || $domain eq '') { next; }
 2700: 	if ((&privileged($username,$domain)) && 
 2701: 	    (!$nothide{$username.':'.$domain})) { next; }
 2702: 	if ($role eq 'cr') { next; }
 2703:         if ($codes) {
 2704:             if ($section) { $role .= ':'.$section; }
 2705:             if ($returnhash{$role}) {
 2706:                 $returnhash{$role}.=','.$username.':'.$domain;
 2707:             } else {
 2708:                 $returnhash{$role}=$username.':'.$domain;
 2709:             }
 2710:         } else {
 2711:             my $key=&plaintext($role,$crstype);
 2712:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2713:             if ($returnhash{$key}) {
 2714: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2715:             } else {
 2716:                 $returnhash{$key}=$username.':'.$domain;
 2717:             }
 2718:         }
 2719:     }
 2720:     return %returnhash;
 2721: }
 2722: 
 2723: sub get_my_roles {
 2724:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2725:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2726:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2727:     my (%dumphash,%nothide);
 2728:     if ($context eq 'userroles') { 
 2729:         %dumphash = &dump('roles',$udom,$uname);
 2730:     } else {
 2731:         %dumphash=
 2732:             &dump('nohist_userroles',$udom,$uname);
 2733:         if ($hidepriv) {
 2734:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2735:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2736:                 if ($user !~ /:/) {
 2737:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2738:                 } else {
 2739:                     $nothide{$user} = 1;
 2740:                 }
 2741:             }
 2742:         }
 2743:     }
 2744:     my %returnhash=();
 2745:     my $now=time;
 2746:     foreach my $entry (keys(%dumphash)) {
 2747:         my ($role,$tend,$tstart);
 2748:         if ($context eq 'userroles') {
 2749: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2750:         } else {
 2751:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2752:         }
 2753:         if (($tstart) && ($tstart<0)) { next; }
 2754:         my $status = 'active';
 2755:         if (($tend) && ($tend<=$now)) {
 2756:             $status = 'previous';
 2757:         } 
 2758:         if (($tstart) && ($now<$tstart)) {
 2759:             $status = 'future';
 2760:         }
 2761:         if (ref($types) eq 'ARRAY') {
 2762:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2763:                 next;
 2764:             } 
 2765:         } else {
 2766:             if ($status ne 'active') {
 2767:                 next;
 2768:             }
 2769:         }
 2770:         my ($rolecode,$username,$domain,$section,$area);
 2771:         if ($context eq 'userroles') {
 2772:             ($area,$rolecode) = split(/_/,$entry);
 2773:             (undef,$domain,$username,$section) = split(/\//,$area);
 2774:         } else {
 2775:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2776:         }
 2777:         if (ref($roledoms) eq 'ARRAY') {
 2778:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2779:                 next;
 2780:             }
 2781:         }
 2782:         if (ref($roles) eq 'ARRAY') {
 2783:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2784:                 if ($role =~ /^cr\//) {
 2785:                     if (!grep(/^cr$/,@{$roles})) {
 2786:                         next;
 2787:                     }
 2788:                 } else {
 2789:                     next;
 2790:                 }
 2791:             }
 2792:         }
 2793:         if ($hidepriv) {
 2794:             if ((&privileged($username,$domain)) &&
 2795:                 (!$nothide{$username.':'.$domain})) { 
 2796:                 next;
 2797:             }
 2798:         }
 2799:         if ($withsec) {
 2800:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2801:                 $tstart.':'.$tend;
 2802:         } else {
 2803:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2804:         }
 2805:     }
 2806:     return %returnhash;
 2807: }
 2808: 
 2809: # ----------------------------------------------------- Frontpage Announcements
 2810: #
 2811: #
 2812: 
 2813: sub postannounce {
 2814:     my ($server,$text)=@_;
 2815:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2816:     unless ($text=~/\w/) { $text=''; }
 2817:     return &reply('setannounce:'.&escape($text),$server);
 2818: }
 2819: 
 2820: sub getannounce {
 2821: 
 2822:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2823: 	my $announcement='';
 2824: 	while (my $line = <$fh>) { $announcement .= $line; }
 2825: 	close($fh);
 2826: 	if ($announcement=~/\w/) { 
 2827: 	    return 
 2828:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2829:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2830: 	} else {
 2831: 	    return '';
 2832: 	}
 2833:     } else {
 2834: 	return '';
 2835:     }
 2836: }
 2837: 
 2838: # ---------------------------------------------------------- Course ID routines
 2839: # Deal with domain's nohist_courseid.db files
 2840: #
 2841: 
 2842: sub courseidput {
 2843:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2844:     my $outcome;
 2845:     if ($caller eq 'timeonly') {
 2846:         my $cids = '';
 2847:         foreach my $item (keys(%$storehash)) {
 2848:             $cids.=&escape($item).'&';
 2849:         }
 2850:         $cids=~s/\&$//;
 2851:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2852:                           $coursehome);       
 2853:     } else {
 2854:         my $items = '';
 2855:         foreach my $item (keys(%$storehash)) {
 2856:             $items.= &escape($item).'='.
 2857:                      &freeze_escape($$storehash{$item}).'&';
 2858:         }
 2859:         $items=~s/\&$//;
 2860:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2861:                           $coursehome);
 2862:     }
 2863:     if ($outcome eq 'unknown_cmd') {
 2864:         my $what;
 2865:         foreach my $cid (keys(%$storehash)) {
 2866:             $what .= &escape($cid).'=';
 2867:             foreach my $item ('description','inst_code','owner','type') {
 2868:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2869:             }
 2870:             $what =~ s/\:$/&/;
 2871:         }
 2872:         $what =~ s/\&$//;  
 2873:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2874:     } else {
 2875:         return $outcome;
 2876:     }
 2877: }
 2878: 
 2879: sub courseiddump {
 2880:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2881:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2882:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2883:     my $as_hash = 1;
 2884:     my %returnhash;
 2885:     if (!$domfilter) { $domfilter=''; }
 2886:     my %libserv = &all_library();
 2887:     foreach my $tryserver (keys(%libserv)) {
 2888:         if ( (  $hostidflag == 1 
 2889: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2890: 	     || (!defined($hostidflag)) ) {
 2891: 
 2892: 	    if (($domfilter eq '') ||
 2893: 		(&host_domain($tryserver) eq $domfilter)) {
 2894:                 my $rep = 
 2895:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2896:                          $sincefilter.':'.&escape($descfilter).':'.
 2897:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2898:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2899:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2900:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2901:                          $showhidden.':'.$caller,$tryserver);
 2902:                 my @pairs=split(/\&/,$rep);
 2903:                 foreach my $item (@pairs) {
 2904:                     my ($key,$value)=split(/\=/,$item,2);
 2905:                     $key = &unescape($key);
 2906:                     next if ($key =~ /^error: 2 /);
 2907:                     my $result = &thaw_unescape($value);
 2908:                     if (ref($result) eq 'HASH') {
 2909:                         $returnhash{$key}=$result;
 2910:                     } else {
 2911:                         my @responses = split(/:/,$value);
 2912:                         my @items = ('description','inst_code','owner','type');
 2913:                         for (my $i=0; $i<@responses; $i++) {
 2914:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2915:                         }
 2916:                     } 
 2917:                 }
 2918:             }
 2919:         }
 2920:     }
 2921:     return %returnhash;
 2922: }
 2923: 
 2924: # ---------------------------------------------------------- DC e-mail
 2925: 
 2926: sub dcmailput {
 2927:     my ($domain,$msgid,$message,$server)=@_;
 2928:     my $status = &Apache::lonnet::critical(
 2929:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2930:        &escape($message),$server);
 2931:     return $status;
 2932: }
 2933: 
 2934: sub dcmaildump {
 2935:     my ($dom,$startdate,$enddate,$senders) = @_;
 2936:     my %returnhash=();
 2937: 
 2938:     if (defined(&domain($dom,'primary'))) {
 2939:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2940:                                                          &escape($enddate).':';
 2941: 	my @esc_senders=map { &escape($_)} @$senders;
 2942: 	$cmd.=&escape(join('&',@esc_senders));
 2943: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2944:             my ($key,$value) = split(/\=/,$line,2);
 2945:             if (($key) && ($value)) {
 2946:                 $returnhash{&unescape($key)} = &unescape($value);
 2947:             }
 2948:         }
 2949:     }
 2950:     return %returnhash;
 2951: }
 2952: # ---------------------------------------------------------- Domain roles
 2953: 
 2954: sub get_domain_roles {
 2955:     my ($dom,$roles,$startdate,$enddate)=@_;
 2956:     if (undef($startdate) || $startdate eq '') {
 2957:         $startdate = '.';
 2958:     }
 2959:     if (undef($enddate) || $enddate eq '') {
 2960:         $enddate = '.';
 2961:     }
 2962:     my $rolelist;
 2963:     if (ref($roles) eq 'ARRAY') {
 2964:         $rolelist = join(':',@{$roles});
 2965:     }
 2966:     my %personnel = ();
 2967: 
 2968:     my %servers = &get_servers($dom,'library');
 2969:     foreach my $tryserver (keys(%servers)) {
 2970: 	%{$personnel{$tryserver}}=();
 2971: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2972: 					    &escape($startdate).':'.
 2973: 					    &escape($enddate).':'.
 2974: 					    &escape($rolelist), $tryserver))) {
 2975: 	    my ($key,$value) = split(/\=/,$line,2);
 2976: 	    if (($key) && ($value)) {
 2977: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2978: 	    }
 2979: 	}
 2980:     }
 2981:     return %personnel;
 2982: }
 2983: 
 2984: # ----------------------------------------------------------- Check out an item
 2985: 
 2986: sub get_first_access {
 2987:     my ($type,$argsymb)=@_;
 2988:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2989:     if ($argsymb) { $symb=$argsymb; }
 2990:     my ($map,$id,$res)=&decode_symb($symb);
 2991:     if ($type eq 'course') {
 2992: 	$res='course';
 2993:     } elsif ($type eq 'map') {
 2994: 	$res=&symbread($map);
 2995:     } else {
 2996: 	$res=$symb;
 2997:     }
 2998:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2999:     return $times{"$courseid\0$res"};
 3000: }
 3001: 
 3002: sub set_first_access {
 3003:     my ($type)=@_;
 3004:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3005:     my ($map,$id,$res)=&decode_symb($symb);
 3006:     if ($type eq 'course') {
 3007: 	$res='course';
 3008:     } elsif ($type eq 'map') {
 3009: 	$res=&symbread($map);
 3010:     } else {
 3011: 	$res=$symb;
 3012:     }
 3013:     my $firstaccess=&get_first_access($type,$symb);
 3014:     if (!$firstaccess) {
 3015: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3016:     }
 3017:     return 'already_set';
 3018: }
 3019: 
 3020: sub checkout {
 3021:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3022:     my $now=time;
 3023:     my $lonhost=$perlvar{'lonHostID'};
 3024:     my $infostr=&escape(
 3025:                  'CHECKOUTTOKEN&'.
 3026:                  $tuname.'&'.
 3027:                  $tudom.'&'.
 3028:                  $tcrsid.'&'.
 3029:                  $symb.'&'.
 3030: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3031:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3032:     if ($token=~/^error\:/) { 
 3033:         &logthis("<font color=\"blue\">WARNING: ".
 3034:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3035:                  "</font>");
 3036:         return ''; 
 3037:     }
 3038: 
 3039:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3040:     $token=~tr/a-z/A-Z/;
 3041: 
 3042:     my %infohash=('resource.0.outtoken' => $token,
 3043:                   'resource.0.checkouttime' => $now,
 3044:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3045: 
 3046:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3047:        return '';
 3048:     } else {
 3049:         &logthis("<font color=\"blue\">WARNING: ".
 3050:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3051:                  "</font>");
 3052:     }    
 3053: 
 3054:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3055:                          &escape('Checkout '.$infostr.' - '.
 3056:                                                  $token)) ne 'ok') {
 3057: 	return '';
 3058:     } else {
 3059:         &logthis("<font color=\"blue\">WARNING: ".
 3060:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3061:                  "</font>");
 3062:     }
 3063:     return $token;
 3064: }
 3065: 
 3066: # ------------------------------------------------------------ Check in an item
 3067: 
 3068: sub checkin {
 3069:     my $token=shift;
 3070:     my $now=time;
 3071:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3072:     $lonhost=~tr/A-Z/a-z/;
 3073:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3074:     $dtoken=~s/\W/\_/g;
 3075:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3076:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3077: 
 3078:     unless (($tuname) && ($tudom)) {
 3079:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3080:         return '';
 3081:     }
 3082:     
 3083:     unless (&allowed('mgr',$tcrsid)) {
 3084:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3085:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3086:         return '';
 3087:     }
 3088: 
 3089:     my %infohash=('resource.0.intoken' => $token,
 3090:                   'resource.0.checkintime' => $now,
 3091:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3092: 
 3093:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3094:        return '';
 3095:     }    
 3096: 
 3097:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3098:                          &escape('Checkin - '.$token)) ne 'ok') {
 3099: 	return '';
 3100:     }
 3101: 
 3102:     return ($symb,$tuname,$tudom,$tcrsid);    
 3103: }
 3104: 
 3105: # --------------------------------------------- Set Expire Date for Spreadsheet
 3106: 
 3107: sub expirespread {
 3108:     my ($uname,$udom,$stype,$usymb)=@_;
 3109:     my $cid=$env{'request.course.id'}; 
 3110:     if ($cid) {
 3111:        my $now=time;
 3112:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3113:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3114:                             $env{'course.'.$cid.'.num'}.
 3115: 	        	    ':nohist_expirationdates:'.
 3116:                             &escape($key).'='.$now,
 3117:                             $env{'course.'.$cid.'.home'})
 3118:     }
 3119:     return 'ok';
 3120: }
 3121: 
 3122: # ----------------------------------------------------- Devalidate Spreadsheets
 3123: 
 3124: sub devalidate {
 3125:     my ($symb,$uname,$udom)=@_;
 3126:     my $cid=$env{'request.course.id'}; 
 3127:     if ($cid) {
 3128:         # delete the stored spreadsheets for
 3129:         # - the student level sheet of this user in course's homespace
 3130:         # - the assessment level sheet for this resource 
 3131:         #   for this user in user's homespace
 3132: 	# - current conditional state info
 3133: 	my $key=$uname.':'.$udom.':';
 3134:         my $status=
 3135: 	    &del('nohist_calculatedsheets',
 3136: 		 [$key.'studentcalc:'],
 3137: 		 $env{'course.'.$cid.'.domain'},
 3138: 		 $env{'course.'.$cid.'.num'})
 3139: 		.' '.
 3140: 	    &del('nohist_calculatedsheets_'.$cid,
 3141: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3142:         unless ($status eq 'ok ok') {
 3143:            &logthis('Could not devalidate spreadsheet '.
 3144:                     $uname.' at '.$udom.' for '.
 3145: 		    $symb.': '.$status);
 3146:         }
 3147: 	&delenv('user.state.'.$cid);
 3148:     }
 3149: }
 3150: 
 3151: sub get_scalar {
 3152:     my ($string,$end) = @_;
 3153:     my $value;
 3154:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3155: 	$value = $1;
 3156:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3157: 	$value = $1;
 3158:     }
 3159:     return &unescape($value);
 3160: }
 3161: 
 3162: sub array2str {
 3163:   my (@array) = @_;
 3164:   my $result=&arrayref2str(\@array);
 3165:   $result=~s/^__ARRAY_REF__//;
 3166:   $result=~s/__END_ARRAY_REF__$//;
 3167:   return $result;
 3168: }
 3169: 
 3170: sub arrayref2str {
 3171:   my ($arrayref) = @_;
 3172:   my $result='__ARRAY_REF__';
 3173:   foreach my $elem (@$arrayref) {
 3174:     if(ref($elem) eq 'ARRAY') {
 3175:       $result.=&arrayref2str($elem).'&';
 3176:     } elsif(ref($elem) eq 'HASH') {
 3177:       $result.=&hashref2str($elem).'&';
 3178:     } elsif(ref($elem)) {
 3179:       #print("Got a ref of ".(ref($elem))." skipping.");
 3180:     } else {
 3181:       $result.=&escape($elem).'&';
 3182:     }
 3183:   }
 3184:   $result=~s/\&$//;
 3185:   $result .= '__END_ARRAY_REF__';
 3186:   return $result;
 3187: }
 3188: 
 3189: sub hash2str {
 3190:   my (%hash) = @_;
 3191:   my $result=&hashref2str(\%hash);
 3192:   $result=~s/^__HASH_REF__//;
 3193:   $result=~s/__END_HASH_REF__$//;
 3194:   return $result;
 3195: }
 3196: 
 3197: sub hashref2str {
 3198:   my ($hashref)=@_;
 3199:   my $result='__HASH_REF__';
 3200:   foreach my $key (sort(keys(%$hashref))) {
 3201:     if (ref($key) eq 'ARRAY') {
 3202:       $result.=&arrayref2str($key).'=';
 3203:     } elsif (ref($key) eq 'HASH') {
 3204:       $result.=&hashref2str($key).'=';
 3205:     } elsif (ref($key)) {
 3206:       $result.='=';
 3207:       #print("Got a ref of ".(ref($key))." skipping.");
 3208:     } else {
 3209: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3210:     }
 3211: 
 3212:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3213:       $result.=&arrayref2str($hashref->{$key}).'&';
 3214:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3215:       $result.=&hashref2str($hashref->{$key}).'&';
 3216:     } elsif(ref($hashref->{$key})) {
 3217:        $result.='&';
 3218:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3219:     } else {
 3220:       $result.=&escape($hashref->{$key}).'&';
 3221:     }
 3222:   }
 3223:   $result=~s/\&$//;
 3224:   $result .= '__END_HASH_REF__';
 3225:   return $result;
 3226: }
 3227: 
 3228: sub str2hash {
 3229:     my ($string)=@_;
 3230:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3231:     return %$hash;
 3232: }
 3233: 
 3234: sub str2hashref {
 3235:   my ($string) = @_;
 3236: 
 3237:   my %hash;
 3238: 
 3239:   if($string !~ /^__HASH_REF__/) {
 3240:       if (! ($string eq '' || !defined($string))) {
 3241: 	  $hash{'error'}='Not hash reference';
 3242:       }
 3243:       return (\%hash, $string);
 3244:   }
 3245: 
 3246:   $string =~ s/^__HASH_REF__//;
 3247: 
 3248:   while($string !~ /^__END_HASH_REF__/) {
 3249:       #key
 3250:       my $key='';
 3251:       if($string =~ /^__HASH_REF__/) {
 3252:           ($key, $string)=&str2hashref($string);
 3253:           if(defined($key->{'error'})) {
 3254:               $hash{'error'}='Bad data';
 3255:               return (\%hash, $string);
 3256:           }
 3257:       } elsif($string =~ /^__ARRAY_REF__/) {
 3258:           ($key, $string)=&str2arrayref($string);
 3259:           if($key->[0] eq 'Array reference error') {
 3260:               $hash{'error'}='Bad data';
 3261:               return (\%hash, $string);
 3262:           }
 3263:       } else {
 3264:           $string =~ s/^(.*?)=//;
 3265: 	  $key=&unescape($1);
 3266:       }
 3267:       $string =~ s/^=//;
 3268: 
 3269:       #value
 3270:       my $value='';
 3271:       if($string =~ /^__HASH_REF__/) {
 3272:           ($value, $string)=&str2hashref($string);
 3273:           if(defined($value->{'error'})) {
 3274:               $hash{'error'}='Bad data';
 3275:               return (\%hash, $string);
 3276:           }
 3277:       } elsif($string =~ /^__ARRAY_REF__/) {
 3278:           ($value, $string)=&str2arrayref($string);
 3279:           if($value->[0] eq 'Array reference error') {
 3280:               $hash{'error'}='Bad data';
 3281:               return (\%hash, $string);
 3282:           }
 3283:       } else {
 3284: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3285:       }
 3286:       $string =~ s/^&//;
 3287: 
 3288:       $hash{$key}=$value;
 3289:   }
 3290: 
 3291:   $string =~ s/^__END_HASH_REF__//;
 3292: 
 3293:   return (\%hash, $string);
 3294: }
 3295: 
 3296: sub str2array {
 3297:     my ($string)=@_;
 3298:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3299:     return @$array;
 3300: }
 3301: 
 3302: sub str2arrayref {
 3303:   my ($string) = @_;
 3304:   my @array;
 3305: 
 3306:   if($string !~ /^__ARRAY_REF__/) {
 3307:       if (! ($string eq '' || !defined($string))) {
 3308: 	  $array[0]='Array reference error';
 3309:       }
 3310:       return (\@array, $string);
 3311:   }
 3312: 
 3313:   $string =~ s/^__ARRAY_REF__//;
 3314: 
 3315:   while($string !~ /^__END_ARRAY_REF__/) {
 3316:       my $value='';
 3317:       if($string =~ /^__HASH_REF__/) {
 3318:           ($value, $string)=&str2hashref($string);
 3319:           if(defined($value->{'error'})) {
 3320:               $array[0] ='Array reference error';
 3321:               return (\@array, $string);
 3322:           }
 3323:       } elsif($string =~ /^__ARRAY_REF__/) {
 3324:           ($value, $string)=&str2arrayref($string);
 3325:           if($value->[0] eq 'Array reference error') {
 3326:               $array[0] ='Array reference error';
 3327:               return (\@array, $string);
 3328:           }
 3329:       } else {
 3330: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3331:       }
 3332:       $string =~ s/^&//;
 3333: 
 3334:       push(@array, $value);
 3335:   }
 3336: 
 3337:   $string =~ s/^__END_ARRAY_REF__//;
 3338: 
 3339:   return (\@array, $string);
 3340: }
 3341: 
 3342: # -------------------------------------------------------------------Temp Store
 3343: 
 3344: sub tmpreset {
 3345:   my ($symb,$namespace,$domain,$stuname) = @_;
 3346:   if (!$symb) {
 3347:     $symb=&symbread();
 3348:     if (!$symb) { $symb= $env{'request.url'}; }
 3349:   }
 3350:   $symb=escape($symb);
 3351: 
 3352:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3353:   $namespace=~s/\//\_/g;
 3354:   $namespace=~s/\W//g;
 3355: 
 3356:   if (!$domain) { $domain=$env{'user.domain'}; }
 3357:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3358:   if ($domain eq 'public' && $stuname eq 'public') {
 3359:       $stuname=$ENV{'REMOTE_ADDR'};
 3360:   }
 3361:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3362:   my %hash;
 3363:   if (tie(%hash,'GDBM_File',
 3364: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3365: 	  &GDBM_WRCREAT(),0640)) {
 3366:     foreach my $key (keys %hash) {
 3367:       if ($key=~ /:$symb/) {
 3368: 	delete($hash{$key});
 3369:       }
 3370:     }
 3371:   }
 3372: }
 3373: 
 3374: sub tmpstore {
 3375:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3376: 
 3377:   if (!$symb) {
 3378:     $symb=&symbread();
 3379:     if (!$symb) { $symb= $env{'request.url'}; }
 3380:   }
 3381:   $symb=escape($symb);
 3382: 
 3383:   if (!$namespace) {
 3384:     # I don't think we would ever want to store this for a course.
 3385:     # it seems this will only be used if we don't have a course.
 3386:     #$namespace=$env{'request.course.id'};
 3387:     #if (!$namespace) {
 3388:       $namespace=$env{'request.state'};
 3389:     #}
 3390:   }
 3391:   $namespace=~s/\//\_/g;
 3392:   $namespace=~s/\W//g;
 3393:   if (!$domain) { $domain=$env{'user.domain'}; }
 3394:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3395:   if ($domain eq 'public' && $stuname eq 'public') {
 3396:       $stuname=$ENV{'REMOTE_ADDR'};
 3397:   }
 3398:   my $now=time;
 3399:   my %hash;
 3400:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3401:   if (tie(%hash,'GDBM_File',
 3402: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3403: 	  &GDBM_WRCREAT(),0640)) {
 3404:     $hash{"version:$symb"}++;
 3405:     my $version=$hash{"version:$symb"};
 3406:     my $allkeys=''; 
 3407:     foreach my $key (keys(%$storehash)) {
 3408:       $allkeys.=$key.':';
 3409:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3410:     }
 3411:     $hash{"$version:$symb:timestamp"}=$now;
 3412:     $allkeys.='timestamp';
 3413:     $hash{"$version:keys:$symb"}=$allkeys;
 3414:     if (untie(%hash)) {
 3415:       return 'ok';
 3416:     } else {
 3417:       return "error:$!";
 3418:     }
 3419:   } else {
 3420:     return "error:$!";
 3421:   }
 3422: }
 3423: 
 3424: # -----------------------------------------------------------------Temp Restore
 3425: 
 3426: sub tmprestore {
 3427:   my ($symb,$namespace,$domain,$stuname) = @_;
 3428: 
 3429:   if (!$symb) {
 3430:     $symb=&symbread();
 3431:     if (!$symb) { $symb= $env{'request.url'}; }
 3432:   }
 3433:   $symb=escape($symb);
 3434: 
 3435:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3436: 
 3437:   if (!$domain) { $domain=$env{'user.domain'}; }
 3438:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3439:   if ($domain eq 'public' && $stuname eq 'public') {
 3440:       $stuname=$ENV{'REMOTE_ADDR'};
 3441:   }
 3442:   my %returnhash;
 3443:   $namespace=~s/\//\_/g;
 3444:   $namespace=~s/\W//g;
 3445:   my %hash;
 3446:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3447:   if (tie(%hash,'GDBM_File',
 3448: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3449: 	  &GDBM_READER(),0640)) {
 3450:     my $version=$hash{"version:$symb"};
 3451:     $returnhash{'version'}=$version;
 3452:     my $scope;
 3453:     for ($scope=1;$scope<=$version;$scope++) {
 3454:       my $vkeys=$hash{"$scope:keys:$symb"};
 3455:       my @keys=split(/:/,$vkeys);
 3456:       my $key;
 3457:       $returnhash{"$scope:keys"}=$vkeys;
 3458:       foreach $key (@keys) {
 3459: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3460: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3461:       }
 3462:     }
 3463:     if (!(untie(%hash))) {
 3464:       return "error:$!";
 3465:     }
 3466:   } else {
 3467:     return "error:$!";
 3468:   }
 3469:   return %returnhash;
 3470: }
 3471: 
 3472: # ----------------------------------------------------------------------- Store
 3473: 
 3474: sub store {
 3475:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3476:     my $home='';
 3477: 
 3478:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3479: 
 3480:     $symb=&symbclean($symb);
 3481:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3482: 
 3483:     if (!$domain) { $domain=$env{'user.domain'}; }
 3484:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3485: 
 3486:     &devalidate($symb,$stuname,$domain);
 3487: 
 3488:     $symb=escape($symb);
 3489:     if (!$namespace) { 
 3490:        unless ($namespace=$env{'request.course.id'}) { 
 3491:           return ''; 
 3492:        } 
 3493:     }
 3494:     if (!$home) { $home=$env{'user.home'}; }
 3495: 
 3496:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3497:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3498: 
 3499:     my $namevalue='';
 3500:     foreach my $key (keys(%$storehash)) {
 3501:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3502:     }
 3503:     $namevalue=~s/\&$//;
 3504:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3505:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3506: }
 3507: 
 3508: # -------------------------------------------------------------- Critical Store
 3509: 
 3510: sub cstore {
 3511:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3512:     my $home='';
 3513: 
 3514:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3515: 
 3516:     $symb=&symbclean($symb);
 3517:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3518: 
 3519:     if (!$domain) { $domain=$env{'user.domain'}; }
 3520:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3521: 
 3522:     &devalidate($symb,$stuname,$domain);
 3523: 
 3524:     $symb=escape($symb);
 3525:     if (!$namespace) { 
 3526:        unless ($namespace=$env{'request.course.id'}) { 
 3527:           return ''; 
 3528:        } 
 3529:     }
 3530:     if (!$home) { $home=$env{'user.home'}; }
 3531: 
 3532:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3533:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3534: 
 3535:     my $namevalue='';
 3536:     foreach my $key (keys(%$storehash)) {
 3537:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3538:     }
 3539:     $namevalue=~s/\&$//;
 3540:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3541:     return critical
 3542:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3543: }
 3544: 
 3545: # --------------------------------------------------------------------- Restore
 3546: 
 3547: sub restore {
 3548:     my ($symb,$namespace,$domain,$stuname) = @_;
 3549:     my $home='';
 3550: 
 3551:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3552: 
 3553:     if (!$symb) {
 3554:       unless ($symb=escape(&symbread())) { return ''; }
 3555:     } else {
 3556:       $symb=&escape(&symbclean($symb));
 3557:     }
 3558:     if (!$namespace) { 
 3559:        unless ($namespace=$env{'request.course.id'}) { 
 3560:           return ''; 
 3561:        } 
 3562:     }
 3563:     if (!$domain) { $domain=$env{'user.domain'}; }
 3564:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3565:     if (!$home) { $home=$env{'user.home'}; }
 3566:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3567: 
 3568:     my %returnhash=();
 3569:     foreach my $line (split(/\&/,$answer)) {
 3570: 	my ($name,$value)=split(/\=/,$line);
 3571:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3572:     }
 3573:     my $version;
 3574:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3575:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3576:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3577:        }
 3578:     }
 3579:     return %returnhash;
 3580: }
 3581: 
 3582: # ---------------------------------------------------------- Course Description
 3583: 
 3584: sub coursedescription {
 3585:     my ($courseid,$args)=@_;
 3586:     $courseid=~s/^\///;
 3587:     $courseid=~s/\_/\//g;
 3588:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3589:     my $chome=&homeserver($cnum,$cdomain);
 3590:     my $normalid=$cdomain.'_'.$cnum;
 3591:     # need to always cache even if we get errors otherwise we keep 
 3592:     # trying and trying and trying to get the course description.
 3593:     my %envhash=();
 3594:     my %returnhash=();
 3595:     
 3596:     my $expiretime=600;
 3597:     if ($env{'request.course.id'} eq $normalid) {
 3598: 	$expiretime=120;
 3599:     }
 3600: 
 3601:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3602:     if (!$args->{'freshen_cache'}
 3603: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3604: 	foreach my $key (keys(%env)) {
 3605: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3606: 	    my ($setting) = $1;
 3607: 	    $returnhash{$setting} = $env{$key};
 3608: 	}
 3609: 	return %returnhash;
 3610:     }
 3611: 
 3612:     # get the data agin
 3613:     if (!$args->{'one_time'}) {
 3614: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3615:     }
 3616: 
 3617:     if ($chome ne 'no_host') {
 3618:        %returnhash=&dump('environment',$cdomain,$cnum);
 3619:        if (!exists($returnhash{'con_lost'})) {
 3620:            $returnhash{'home'}= $chome;
 3621: 	   $returnhash{'domain'} = $cdomain;
 3622: 	   $returnhash{'num'} = $cnum;
 3623:            if (!defined($returnhash{'type'})) {
 3624:                $returnhash{'type'} = 'Course';
 3625:            }
 3626:            while (my ($name,$value) = each %returnhash) {
 3627:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3628:            }
 3629:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3630:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3631: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3632:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3633:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3634:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3635:        }
 3636:     }
 3637:     if (!$args->{'one_time'}) {
 3638: 	&appenv(\%envhash);
 3639:     }
 3640:     return %returnhash;
 3641: }
 3642: 
 3643: # -------------------------------------------------See if a user is privileged
 3644: 
 3645: sub privileged {
 3646:     my ($username,$domain)=@_;
 3647:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3648: 			&homeserver($username,$domain));
 3649:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3650:     my $now=time;
 3651:     if ($rolesdump ne '') {
 3652:         foreach my $entry (split(/&/,$rolesdump)) {
 3653: 	    if ($entry!~/^rolesdef_/) {
 3654: 		my ($area,$role)=split(/=/,$entry);
 3655: 		$area=~s/\_\w\w$//;
 3656: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3657: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3658: 		    my $active=1;
 3659: 		    if ($tend) {
 3660: 			if ($tend<$now) { $active=0; }
 3661: 		    }
 3662: 		    if ($tstart) {
 3663: 			if ($tstart>$now) { $active=0; }
 3664: 		    }
 3665: 		    if ($active) { return 1; }
 3666: 		}
 3667: 	    }
 3668: 	}
 3669:     }
 3670:     return 0;
 3671: }
 3672: 
 3673: # -------------------------------------------------------- Get user privileges
 3674: 
 3675: sub rolesinit {
 3676:     my ($domain,$username,$authhost)=@_;
 3677:     my %userroles;
 3678:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3679:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3680:     my %allroles=();
 3681:     my %allgroups=();   
 3682:     my $now=time;
 3683:     %userroles = ('user.login.time' => $now);
 3684:     my $group_privs;
 3685: 
 3686:     if ($rolesdump ne '') {
 3687:         foreach my $entry (split(/&/,$rolesdump)) {
 3688: 	  if ($entry!~/^rolesdef_/) {
 3689:             my ($area,$role)=split(/=/,$entry);
 3690: 	    $area=~s/\_\w\w$//;
 3691:             my ($trole,$tend,$tstart,$group_privs);
 3692: 	    if ($role=~/^cr/) { 
 3693: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3694: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3695: 		    ($tend,$tstart)=split('_',$trest);
 3696: 		} else {
 3697: 		    $trole=$role;
 3698: 		}
 3699:             } elsif ($role =~ m|^gr/|) {
 3700:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3701:                 ($trole,$group_privs) = split(/\//,$trole);
 3702:                 $group_privs = &unescape($group_privs);
 3703: 	    } else {
 3704: 		($trole,$tend,$tstart)=split(/_/,$role);
 3705: 	    }
 3706: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3707: 					 $username);
 3708: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3709:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3710:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3711:             if (($area ne '') && ($trole ne '')) {
 3712: 		my $spec=$trole.'.'.$area;
 3713: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3714: 		if ($trole =~ /^cr\//) {
 3715:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3716:                 } elsif ($trole eq 'gr') {
 3717:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3718: 		} else {
 3719:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3720: 		}
 3721:             }
 3722:           }
 3723:         }
 3724:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3725:         $userroles{'user.adv'}    = $adv;
 3726: 	$userroles{'user.author'} = $author;
 3727:         $env{'user.adv'}=$adv;
 3728:     }
 3729:     return \%userroles;  
 3730: }
 3731: 
 3732: sub set_arearole {
 3733:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3734: # log the associated role with the area
 3735:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3736:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3737: }
 3738: 
 3739: sub custom_roleprivs {
 3740:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3741:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3742:     my $homsvr=homeserver($rauthor,$rdomain);
 3743:     if (&hostname($homsvr) ne '') {
 3744:         my ($rdummy,$roledef)=
 3745:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3746:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3747:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3748:             if (defined($syspriv)) {
 3749:                 $$allroles{'cm./'}.=':'.$syspriv;
 3750:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3751:             }
 3752:             if ($tdomain ne '') {
 3753:                 if (defined($dompriv)) {
 3754:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3755:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3756:                 }
 3757:                 if (($trest ne '') && (defined($coursepriv))) {
 3758:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3759:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3760:                 }
 3761:             }
 3762:         }
 3763:     }
 3764: }
 3765: 
 3766: sub group_roleprivs {
 3767:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3768:     my $access = 1;
 3769:     my $now = time;
 3770:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3771:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3772:     if ($access) {
 3773:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3774:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3775:     }
 3776: }
 3777: 
 3778: sub standard_roleprivs {
 3779:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3780:     if (defined($pr{$trole.':s'})) {
 3781:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3782:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3783:     }
 3784:     if ($tdomain ne '') {
 3785:         if (defined($pr{$trole.':d'})) {
 3786:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3787:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3788:         }
 3789:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3790:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3791:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3792:         }
 3793:     }
 3794: }
 3795: 
 3796: sub set_userprivs {
 3797:     my ($userroles,$allroles,$allgroups) = @_; 
 3798:     my $author=0;
 3799:     my $adv=0;
 3800:     my %grouproles = ();
 3801:     if (keys(%{$allgroups}) > 0) {
 3802:         foreach my $role (keys %{$allroles}) {
 3803:             my ($trole,$area,$sec,$extendedarea);
 3804:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3805:                 $trole = $1;
 3806:                 $area = $2;
 3807:                 $sec = $3;
 3808:                 $extendedarea = $area.$sec;
 3809:                 if (exists($$allgroups{$area})) {
 3810:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3811:                         my $spec = $trole.'.'.$extendedarea;
 3812:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3813:                                                 $$allgroups{$area}{$group};
 3814:                     }
 3815:                 }
 3816:             }
 3817:         }
 3818:     }
 3819:     foreach my $group (keys(%grouproles)) {
 3820:         $$allroles{$group} = $grouproles{$group};
 3821:     }
 3822:     foreach my $role (keys(%{$allroles})) {
 3823:         my %thesepriv;
 3824:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3825:         foreach my $item (split(/:/,$$allroles{$role})) {
 3826:             if ($item ne '') {
 3827:                 my ($privilege,$restrictions)=split(/&/,$item);
 3828:                 if ($restrictions eq '') {
 3829:                     $thesepriv{$privilege}='F';
 3830:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3831:                     $thesepriv{$privilege}.=$restrictions;
 3832:                 }
 3833:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3834:             }
 3835:         }
 3836:         my $thesestr='';
 3837:         foreach my $priv (keys(%thesepriv)) {
 3838: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3839: 	}
 3840:         $userroles->{'user.priv.'.$role} = $thesestr;
 3841:     }
 3842:     return ($author,$adv);
 3843: }
 3844: 
 3845: # --------------------------------------------------------------- get interface
 3846: 
 3847: sub get {
 3848:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3849:    my $items='';
 3850:    foreach my $item (@$storearr) {
 3851:        $items.=&escape($item).'&';
 3852:    }
 3853:    $items=~s/\&$//;
 3854:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3855:    if (!$uname) { $uname=$env{'user.name'}; }
 3856:    my $uhome=&homeserver($uname,$udomain);
 3857: 
 3858:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3859:    my @pairs=split(/\&/,$rep);
 3860:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3861:      return @pairs;
 3862:    }
 3863:    my %returnhash=();
 3864:    my $i=0;
 3865:    foreach my $item (@$storearr) {
 3866:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3867:       $i++;
 3868:    }
 3869:    return %returnhash;
 3870: }
 3871: 
 3872: # --------------------------------------------------------------- del interface
 3873: 
 3874: sub del {
 3875:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3876:    my $items='';
 3877:    foreach my $item (@$storearr) {
 3878:        $items.=&escape($item).'&';
 3879:    }
 3880: 
 3881:    $items=~s/\&$//;
 3882:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3883:    if (!$uname) { $uname=$env{'user.name'}; }
 3884:    my $uhome=&homeserver($uname,$udomain);
 3885:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3886: }
 3887: 
 3888: # -------------------------------------------------------------- dump interface
 3889: 
 3890: sub dump {
 3891:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3892:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3893:     if (!$uname) { $uname=$env{'user.name'}; }
 3894:     my $uhome=&homeserver($uname,$udomain);
 3895:     if ($regexp) {
 3896: 	$regexp=&escape($regexp);
 3897:     } else {
 3898: 	$regexp='.';
 3899:     }
 3900:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3901:     my @pairs=split(/\&/,$rep);
 3902:     my %returnhash=();
 3903:     foreach my $item (@pairs) {
 3904: 	my ($key,$value)=split(/=/,$item,2);
 3905: 	$key = &unescape($key);
 3906: 	next if ($key =~ /^error: 2 /);
 3907: 	$returnhash{$key}=&thaw_unescape($value);
 3908:     }
 3909:     return %returnhash;
 3910: }
 3911: 
 3912: # --------------------------------------------------------- dumpstore interface
 3913: 
 3914: sub dumpstore {
 3915:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3916:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3917:    if (!$uname) { $uname=$env{'user.name'}; }
 3918:    my $uhome=&homeserver($uname,$udomain);
 3919:    if ($regexp) {
 3920:        $regexp=&escape($regexp);
 3921:    } else {
 3922:        $regexp='.';
 3923:    }
 3924:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3925:    my @pairs=split(/\&/,$rep);
 3926:    my %returnhash=();
 3927:    foreach my $item (@pairs) {
 3928:        my ($key,$value)=split(/=/,$item,2);
 3929:        next if ($key =~ /^error: 2 /);
 3930:        $returnhash{$key}=&thaw_unescape($value);
 3931:    }
 3932:    return %returnhash;
 3933: }
 3934: 
 3935: # -------------------------------------------------------------- keys interface
 3936: 
 3937: sub getkeys {
 3938:    my ($namespace,$udomain,$uname)=@_;
 3939:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3940:    if (!$uname) { $uname=$env{'user.name'}; }
 3941:    my $uhome=&homeserver($uname,$udomain);
 3942:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3943:    my @keyarray=();
 3944:    foreach my $key (split(/\&/,$rep)) {
 3945:       next if ($key =~ /^error: 2 /);
 3946:       push(@keyarray,&unescape($key));
 3947:    }
 3948:    return @keyarray;
 3949: }
 3950: 
 3951: # --------------------------------------------------------------- currentdump
 3952: sub currentdump {
 3953:    my ($courseid,$sdom,$sname)=@_;
 3954:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3955:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3956:    $sname    = $env{'user.name'}         if (! defined($sname));
 3957:    my $uhome = &homeserver($sname,$sdom);
 3958:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3959:    return if ($rep =~ /^(error:|no_such_host)/);
 3960:    #
 3961:    my %returnhash=();
 3962:    #
 3963:    if ($rep eq "unknown_cmd") { 
 3964:        # an old lond will not know currentdump
 3965:        # Do a dump and make it look like a currentdump
 3966:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3967:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3968:        my %hash = @tmp;
 3969:        @tmp=();
 3970:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3971:    } else {
 3972:        my @pairs=split(/\&/,$rep);
 3973:        foreach my $pair (@pairs) {
 3974:            my ($key,$value)=split(/=/,$pair,2);
 3975:            my ($symb,$param) = split(/:/,$key);
 3976:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3977:                                                         &thaw_unescape($value);
 3978:        }
 3979:    }
 3980:    return %returnhash;
 3981: }
 3982: 
 3983: sub convert_dump_to_currentdump{
 3984:     my %hash = %{shift()};
 3985:     my %returnhash;
 3986:     # Code ripped from lond, essentially.  The only difference
 3987:     # here is the unescaping done by lonnet::dump().  Conceivably
 3988:     # we might run in to problems with parameter names =~ /^v\./
 3989:     while (my ($key,$value) = each(%hash)) {
 3990:         my ($v,$symb,$param) = split(/:/,$key);
 3991: 	$symb  = &unescape($symb);
 3992: 	$param = &unescape($param);
 3993:         next if ($v eq 'version' || $symb eq 'keys');
 3994:         next if (exists($returnhash{$symb}) &&
 3995:                  exists($returnhash{$symb}->{$param}) &&
 3996:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3997:         $returnhash{$symb}->{$param}=$value;
 3998:         $returnhash{$symb}->{'v.'.$param}=$v;
 3999:     }
 4000:     #
 4001:     # Remove all of the keys in the hashes which keep track of
 4002:     # the version of the parameter.
 4003:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4004:         # use a foreach because we are going to delete from the hash.
 4005:         foreach my $key (keys(%$param_hash)) {
 4006:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4007:         }
 4008:     }
 4009:     return \%returnhash;
 4010: }
 4011: 
 4012: # ------------------------------------------------------ critical inc interface
 4013: 
 4014: sub cinc {
 4015:     return &inc(@_,'critical');
 4016: }
 4017: 
 4018: # --------------------------------------------------------------- inc interface
 4019: 
 4020: sub inc {
 4021:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4022:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4023:     if (!$uname) { $uname=$env{'user.name'}; }
 4024:     my $uhome=&homeserver($uname,$udomain);
 4025:     my $items='';
 4026:     if (! ref($store)) {
 4027:         # got a single value, so use that instead
 4028:         $items = &escape($store).'=&';
 4029:     } elsif (ref($store) eq 'SCALAR') {
 4030:         $items = &escape($$store).'=&';        
 4031:     } elsif (ref($store) eq 'ARRAY') {
 4032:         $items = join('=&',map {&escape($_);} @{$store});
 4033:     } elsif (ref($store) eq 'HASH') {
 4034:         while (my($key,$value) = each(%{$store})) {
 4035:             $items.= &escape($key).'='.&escape($value).'&';
 4036:         }
 4037:     }
 4038:     $items=~s/\&$//;
 4039:     if ($critical) {
 4040: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4041:     } else {
 4042: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4043:     }
 4044: }
 4045: 
 4046: # --------------------------------------------------------------- put interface
 4047: 
 4048: sub put {
 4049:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4050:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4051:    if (!$uname) { $uname=$env{'user.name'}; }
 4052:    my $uhome=&homeserver($uname,$udomain);
 4053:    my $items='';
 4054:    foreach my $item (keys(%$storehash)) {
 4055:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4056:    }
 4057:    $items=~s/\&$//;
 4058:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4059: }
 4060: 
 4061: # ------------------------------------------------------------ newput interface
 4062: 
 4063: sub newput {
 4064:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4065:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4066:    if (!$uname) { $uname=$env{'user.name'}; }
 4067:    my $uhome=&homeserver($uname,$udomain);
 4068:    my $items='';
 4069:    foreach my $key (keys(%$storehash)) {
 4070:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4071:    }
 4072:    $items=~s/\&$//;
 4073:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4074: }
 4075: 
 4076: # ---------------------------------------------------------  putstore interface
 4077: 
 4078: sub putstore {
 4079:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4080:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4081:    if (!$uname) { $uname=$env{'user.name'}; }
 4082:    my $uhome=&homeserver($uname,$udomain);
 4083:    my $items='';
 4084:    foreach my $key (keys(%$storehash)) {
 4085:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4086:    }
 4087:    $items=~s/\&$//;
 4088:    my $esc_symb=&escape($symb);
 4089:    my $esc_v=&escape($version);
 4090:    my $reply =
 4091:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4092: 	      $uhome);
 4093:    if ($reply eq 'unknown_cmd') {
 4094:        # gfall back to way things use to be done
 4095:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4096: 			    $uname);
 4097:    }
 4098:    return $reply;
 4099: }
 4100: 
 4101: sub old_putstore {
 4102:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4103:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4104:     if (!$uname) { $uname=$env{'user.name'}; }
 4105:     my $uhome=&homeserver($uname,$udomain);
 4106:     my %newstorehash;
 4107:     foreach my $item (keys(%$storehash)) {
 4108: 	my $key = $version.':'.&escape($symb).':'.$item;
 4109: 	$newstorehash{$key} = $storehash->{$item};
 4110:     }
 4111:     my $items='';
 4112:     my %allitems = ();
 4113:     foreach my $item (keys(%newstorehash)) {
 4114: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4115: 	    my $key = $1.':keys:'.$2;
 4116: 	    $allitems{$key} .= $3.':';
 4117: 	}
 4118: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4119:     }
 4120:     foreach my $item (keys(%allitems)) {
 4121: 	$allitems{$item} =~ s/\:$//;
 4122: 	$items.= $item.'='.$allitems{$item}.'&';
 4123:     }
 4124:     $items=~s/\&$//;
 4125:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4126: }
 4127: 
 4128: # ------------------------------------------------------ critical put interface
 4129: 
 4130: sub cput {
 4131:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4132:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4133:    if (!$uname) { $uname=$env{'user.name'}; }
 4134:    my $uhome=&homeserver($uname,$udomain);
 4135:    my $items='';
 4136:    foreach my $item (keys(%$storehash)) {
 4137:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4138:    }
 4139:    $items=~s/\&$//;
 4140:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4141: }
 4142: 
 4143: # -------------------------------------------------------------- eget interface
 4144: 
 4145: sub eget {
 4146:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4147:    my $items='';
 4148:    foreach my $item (@$storearr) {
 4149:        $items.=&escape($item).'&';
 4150:    }
 4151:    $items=~s/\&$//;
 4152:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4153:    if (!$uname) { $uname=$env{'user.name'}; }
 4154:    my $uhome=&homeserver($uname,$udomain);
 4155:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4156:    my @pairs=split(/\&/,$rep);
 4157:    my %returnhash=();
 4158:    my $i=0;
 4159:    foreach my $item (@$storearr) {
 4160:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4161:       $i++;
 4162:    }
 4163:    return %returnhash;
 4164: }
 4165: 
 4166: # ------------------------------------------------------------ tmpput interface
 4167: sub tmpput {
 4168:     my ($storehash,$server,$context)=@_;
 4169:     my $items='';
 4170:     foreach my $item (keys(%$storehash)) {
 4171: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4172:     }
 4173:     $items=~s/\&$//;
 4174:     if (defined($context)) {
 4175:         $items .= ':'.&escape($context);
 4176:     }
 4177:     return &reply("tmpput:$items",$server);
 4178: }
 4179: 
 4180: # ------------------------------------------------------------ tmpget interface
 4181: sub tmpget {
 4182:     my ($token,$server)=@_;
 4183:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4184:     my $rep=&reply("tmpget:$token",$server);
 4185:     my %returnhash;
 4186:     foreach my $item (split(/\&/,$rep)) {
 4187: 	my ($key,$value)=split(/=/,$item);
 4188:         next if ($key =~ /^error: 2 /);
 4189: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4190:     }
 4191:     return %returnhash;
 4192: }
 4193: 
 4194: # ------------------------------------------------------------ tmpget interface
 4195: sub tmpdel {
 4196:     my ($token,$server)=@_;
 4197:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4198:     return &reply("tmpdel:$token",$server);
 4199: }
 4200: 
 4201: # -------------------------------------------------- portfolio access checking
 4202: 
 4203: sub portfolio_access {
 4204:     my ($requrl) = @_;
 4205:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4206:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4207:     if ($result) {
 4208:         my %setters;
 4209:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4210:             my ($startblock,$endblock) =
 4211:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4212:             if ($startblock && $endblock) {
 4213:                 return 'B';
 4214:             }
 4215:         } else {
 4216:             my ($startblock,$endblock) =
 4217:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4218:             if ($startblock && $endblock) {
 4219:                 return 'B';
 4220:             }
 4221:         }
 4222:     }
 4223:     if ($result eq 'ok') {
 4224:        return 'F';
 4225:     } elsif ($result =~ /^[^:]+:guest_/) {
 4226:        return 'A';
 4227:     }
 4228:     return '';
 4229: }
 4230: 
 4231: sub get_portfolio_access {
 4232:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4233: 
 4234:     if (!ref($access_hash)) {
 4235: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4236: 	my %access_controls = &get_access_controls($current_perms,$group,
 4237: 						   $file_name);
 4238: 	$access_hash = $access_controls{$file_name};
 4239:     }
 4240: 
 4241:     my ($public,$guest,@domains,@users,@courses,@groups);
 4242:     my $now = time;
 4243:     if (ref($access_hash) eq 'HASH') {
 4244:         foreach my $key (keys(%{$access_hash})) {
 4245:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4246:             if ($start > $now) {
 4247:                 next;
 4248:             }
 4249:             if ($end && $end<$now) {
 4250:                 next;
 4251:             }
 4252:             if ($scope eq 'public') {
 4253:                 $public = $key;
 4254:                 last;
 4255:             } elsif ($scope eq 'guest') {
 4256:                 $guest = $key;
 4257:             } elsif ($scope eq 'domains') {
 4258:                 push(@domains,$key);
 4259:             } elsif ($scope eq 'users') {
 4260:                 push(@users,$key);
 4261:             } elsif ($scope eq 'course') {
 4262:                 push(@courses,$key);
 4263:             } elsif ($scope eq 'group') {
 4264:                 push(@groups,$key);
 4265:             }
 4266:         }
 4267:         if ($public) {
 4268:             return 'ok';
 4269:         }
 4270:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4271:             if ($guest) {
 4272:                 return $guest;
 4273:             }
 4274:         } else {
 4275:             if (@domains > 0) {
 4276:                 foreach my $domkey (@domains) {
 4277:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4278:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4279:                             return 'ok';
 4280:                         }
 4281:                     }
 4282:                 }
 4283:             }
 4284:             if (@users > 0) {
 4285:                 foreach my $userkey (@users) {
 4286:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4287:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4288:                             if (ref($item) eq 'HASH') {
 4289:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4290:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4291:                                     return 'ok';
 4292:                                 }
 4293:                             }
 4294:                         }
 4295:                     } 
 4296:                 }
 4297:             }
 4298:             my %roleshash;
 4299:             my @courses_and_groups = @courses;
 4300:             push(@courses_and_groups,@groups); 
 4301:             if (@courses_and_groups > 0) {
 4302:                 my (%allgroups,%allroles); 
 4303:                 my ($start,$end,$role,$sec,$group);
 4304:                 foreach my $envkey (%env) {
 4305:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4306:                         my $cid = $2.'_'.$3; 
 4307:                         if ($1 eq 'gr') {
 4308:                             $group = $4;
 4309:                             $allgroups{$cid}{$group} = $env{$envkey};
 4310:                         } else {
 4311:                             if ($4 eq '') {
 4312:                                 $sec = 'none';
 4313:                             } else {
 4314:                                 $sec = $4;
 4315:                             }
 4316:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4317:                         }
 4318:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4319:                         my $cid = $2.'_'.$3;
 4320:                         if ($4 eq '') {
 4321:                             $sec = 'none';
 4322:                         } else {
 4323:                             $sec = $4;
 4324:                         }
 4325:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4326:                     }
 4327:                 }
 4328:                 if (keys(%allroles) == 0) {
 4329:                     return;
 4330:                 }
 4331:                 foreach my $key (@courses_and_groups) {
 4332:                     my %content = %{$$access_hash{$key}};
 4333:                     my $cnum = $content{'number'};
 4334:                     my $cdom = $content{'domain'};
 4335:                     my $cid = $cdom.'_'.$cnum;
 4336:                     if (!exists($allroles{$cid})) {
 4337:                         next;
 4338:                     }    
 4339:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4340:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4341:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4342:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4343:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4344:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4345:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4346:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4347:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4348:                                         if (grep/^all$/,@sections) {
 4349:                                             return 'ok';
 4350:                                         } else {
 4351:                                             if (grep/^$sec$/,@sections) {
 4352:                                                 return 'ok';
 4353:                                             }
 4354:                                         }
 4355:                                     }
 4356:                                 }
 4357:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4358:                                     if (grep/^none$/,@groups) {
 4359:                                         return 'ok';
 4360:                                     }
 4361:                                 } else {
 4362:                                     if (grep/^all$/,@groups) {
 4363:                                         return 'ok';
 4364:                                     } 
 4365:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4366:                                         if (grep/^$group$/,@groups) {
 4367:                                             return 'ok';
 4368:                                         }
 4369:                                     }
 4370:                                 } 
 4371:                             }
 4372:                         }
 4373:                     }
 4374:                 }
 4375:             }
 4376:             if ($guest) {
 4377:                 return $guest;
 4378:             }
 4379:         }
 4380:     }
 4381:     return;
 4382: }
 4383: 
 4384: sub course_group_datechecker {
 4385:     my ($dates,$now,$status) = @_;
 4386:     my ($start,$end) = split(/\./,$dates);
 4387:     if (!$start && !$end) {
 4388:         return 'ok';
 4389:     }
 4390:     if (grep/^active$/,@{$status}) {
 4391:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4392:             return 'ok';
 4393:         }
 4394:     }
 4395:     if (grep/^previous$/,@{$status}) {
 4396:         if ($end > $now ) {
 4397:             return 'ok';
 4398:         }
 4399:     }
 4400:     if (grep/^future$/,@{$status}) {
 4401:         if ($start > $now) {
 4402:             return 'ok';
 4403:         }
 4404:     }
 4405:     return; 
 4406: }
 4407: 
 4408: sub parse_portfolio_url {
 4409:     my ($url) = @_;
 4410: 
 4411:     my ($type,$udom,$unum,$group,$file_name);
 4412:     
 4413:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4414: 	$type = 1;
 4415:         $udom = $1;
 4416:         $unum = $2;
 4417:         $file_name = $3;
 4418:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4419: 	$type = 2;
 4420:         $udom = $1;
 4421:         $unum = $2;
 4422:         $group = $3;
 4423:         $file_name = $3.'/'.$4;
 4424:     }
 4425:     if (wantarray) {
 4426: 	return ($type,$udom,$unum,$file_name,$group);
 4427:     }
 4428:     return $type;
 4429: }
 4430: 
 4431: sub is_portfolio_url {
 4432:     my ($url) = @_;
 4433:     return scalar(&parse_portfolio_url($url));
 4434: }
 4435: 
 4436: sub is_portfolio_file {
 4437:     my ($file) = @_;
 4438:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4439:         return 1;
 4440:     }
 4441:     return;
 4442: }
 4443: 
 4444: sub usertools_access {
 4445:     my ($uname,$udom,$tool,$action,$context) = @_;
 4446:     my ($access,%tools);
 4447:     if ($context eq '') {
 4448:         $context = 'tools';
 4449:     }
 4450:     if ($context eq 'requestcourses') {
 4451:         %tools = (
 4452:                       official   => 1,
 4453:                       unofficial => 1,
 4454:                  );
 4455:     } else {
 4456:         %tools = (
 4457:                       aboutme   => 1,
 4458:                       blog      => 1,
 4459:                       portfolio => 1,
 4460:                  );
 4461:     }
 4462:     return if (!defined($tools{$tool}));
 4463: 
 4464:     if ((!defined($udom)) || (!defined($uname))) {
 4465:         $udom = $env{'user.domain'};
 4466:         $uname = $env{'user.name'};
 4467:     }
 4468: 
 4469:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4470:         if ($action ne 'reload') {
 4471:             if ($context eq 'requestcourses') {
 4472:                 return $env{'environment.canrequest.'.$tool};
 4473:             } else {
 4474:                 return $env{'environment.availabletools.'.$tool};
 4475:             }
 4476:         }
 4477:     }
 4478: 
 4479:     my ($toolstatus,$inststatus);
 4480: 
 4481:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4482:          ($action ne 'reload')) {
 4483:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4484:         $inststatus = $env{'environment.inststatus'};
 4485:     } else {
 4486:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4487:         $toolstatus = $userenv{$context.'.'.$tool};
 4488:         $inststatus = $userenv{'inststatus'};
 4489:     }
 4490: 
 4491:     if ($toolstatus ne '') {
 4492:         if ($toolstatus) {
 4493:             $access = 1;
 4494:         } else {
 4495:             $access = 0;
 4496:         }
 4497:         return $access;
 4498:     }
 4499: 
 4500:     my $is_adv = &is_advanced_user($udom,$uname);
 4501:     my %domdef = &get_domain_defaults($udom);
 4502:     if (ref($domdef{$tool}) eq 'HASH') {
 4503:         if ($is_adv) {
 4504:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4505:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4506:                     $access = 1;
 4507:                 } else {
 4508:                     $access = 0;
 4509:                 }
 4510:                 return $access;
 4511:             }
 4512:         }
 4513:         if ($inststatus ne '') {
 4514:             my ($hasaccess,$hasnoaccess);
 4515:             foreach my $affiliation (split(/:/,$inststatus)) {
 4516:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4517:                     if ($domdef{$tool}{$affiliation}) {
 4518:                         $hasaccess = 1;
 4519:                     } else {
 4520:                         $hasnoaccess = 1;
 4521:                     }
 4522:                 }
 4523:             }
 4524:             if ($hasaccess || $hasnoaccess) {
 4525:                 if ($hasaccess) {
 4526:                     $access = 1;
 4527:                 } elsif ($hasnoaccess) {
 4528:                     $access = 0; 
 4529:                 }
 4530:                 return $access;
 4531:             }
 4532:         } else {
 4533:             if ($domdef{$tool}{'default'} ne '') {
 4534:                 if ($domdef{$tool}{'default'}) {
 4535:                     $access = 1;
 4536:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4537:                     $access = 0;
 4538:                 }
 4539:                 return $access;
 4540:             }
 4541:         }
 4542:     } else {
 4543:         if ($context eq 'tools') {
 4544:             $access = 1;
 4545:         } else {
 4546:             $access = 0;
 4547:         }
 4548:         return $access;
 4549:     }
 4550: }
 4551: 
 4552: sub is_advanced_user {
 4553:     my ($udom,$uname) = @_;
 4554:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4555:     my %allroles;
 4556:     my $is_adv;
 4557:     foreach my $role (keys(%roleshash)) {
 4558:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4559:         my $area = '/'.$tdomain.'/'.$trest;
 4560:         if ($sec ne '') {
 4561:             $area .= '/'.$sec;
 4562:         }
 4563:         if (($area ne '') && ($trole ne '')) {
 4564:             my $spec=$trole.'.'.$area;
 4565:             if ($trole =~ /^cr\//) {
 4566:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4567:             } elsif ($trole ne 'gr') {
 4568:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4569:             }
 4570:         }
 4571:     }
 4572:     foreach my $role (keys(%allroles)) {
 4573:         last if ($is_adv);
 4574:         foreach my $item (split(/:/,$allroles{$role})) {
 4575:             if ($item ne '') {
 4576:                 my ($privilege,$restrictions)=split(/&/,$item);
 4577:                 if ($privilege eq 'adv') {
 4578:                     $is_adv = 1;
 4579:                     last;
 4580:                 }
 4581:             }
 4582:         }
 4583:     }
 4584:     return $is_adv;
 4585: }
 4586: 
 4587: # ---------------------------------------------- Custom access rule evaluation
 4588: 
 4589: sub customaccess {
 4590:     my ($priv,$uri)=@_;
 4591:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4592:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4593:     $udom = &LONCAPA::clean_domain($udom);
 4594:     $ucrs = &LONCAPA::clean_username($ucrs);
 4595:     my $access=0;
 4596:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4597: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4598: 	if ($type eq 'user') {
 4599: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4600: 		my ($tdom,$tuname)=split(m{/},$scope);
 4601: 		if ($tdom) {
 4602: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4603: 		}
 4604: 		if ($tuname) {
 4605: 		    if ($tuname ne $env{'user.name'}) { next; }
 4606: 		}
 4607: 		$access=($effect eq 'allow');
 4608: 		last;
 4609: 	    }
 4610: 	} else {
 4611: 	    if ($role) {
 4612: 		if ($role ne $urole) { next; }
 4613: 	    }
 4614: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4615: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4616: 		if ($tdom) {
 4617: 		    if ($tdom ne $udom) { next; }
 4618: 		}
 4619: 		if ($tcrs) {
 4620: 		    if ($tcrs ne $ucrs) { next; }
 4621: 		}
 4622: 		if ($tsec) {
 4623: 		    if ($tsec ne $usec) { next; }
 4624: 		}
 4625: 		$access=($effect eq 'allow');
 4626: 		last;
 4627: 	    }
 4628: 	    if ($realm eq '' && $role eq '') {
 4629: 		$access=($effect eq 'allow');
 4630: 	    }
 4631: 	}
 4632:     }
 4633:     return $access;
 4634: }
 4635: 
 4636: # ------------------------------------------------- Check for a user privilege
 4637: 
 4638: sub allowed {
 4639:     my ($priv,$uri,$symb,$role)=@_;
 4640:     my $ver_orguri=$uri;
 4641:     $uri=&deversion($uri);
 4642:     my $orguri=$uri;
 4643:     $uri=&declutter($uri);
 4644: 
 4645:     if ($priv eq 'evb') {
 4646: # Evade communication block restrictions for specified role in a course
 4647:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4648:             return $1;
 4649:         } else {
 4650:             return;
 4651:         }
 4652:     }
 4653: 
 4654:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4655: # Free bre access to adm and meta resources
 4656:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4657: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4658: 	&& ($priv eq 'bre')) {
 4659: 	return 'F';
 4660:     }
 4661: 
 4662: # Free bre access to user's own portfolio contents
 4663:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4664:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4665: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4666:         my %setters;
 4667:         my ($startblock,$endblock) = 
 4668:             &Apache::loncommon::blockcheck(\%setters,'port');
 4669:         if ($startblock && $endblock) {
 4670:             return 'B';
 4671:         } else {
 4672:             return 'F';
 4673:         }
 4674:     }
 4675: 
 4676: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4677:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4678:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4679:         if (exists($env{'request.course.id'})) {
 4680:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4681:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4682:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4683:                 my $courseprivid=$env{'request.course.id'};
 4684:                 $courseprivid=~s/\_/\//;
 4685:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4686:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4687:                     return $1; 
 4688:                 } else {
 4689:                     if ($env{'request.course.sec'}) {
 4690:                         $courseprivid.='/'.$env{'request.course.sec'};
 4691:                     }
 4692:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4693:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4694:                         return $2;
 4695:                     }
 4696:                 }
 4697:             }
 4698:         }
 4699:     }
 4700: 
 4701: # Free bre to public access
 4702: 
 4703:     if ($priv eq 'bre') {
 4704:         my $copyright=&metadata($uri,'copyright');
 4705: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4706:            return 'F'; 
 4707:         }
 4708:         if ($copyright eq 'priv') {
 4709:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4710: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4711: 		return '';
 4712:             }
 4713:         }
 4714:         if ($copyright eq 'domain') {
 4715:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4716: 	    unless (($env{'user.domain'} eq $1) ||
 4717:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4718: 		return '';
 4719:             }
 4720:         }
 4721:         if ($env{'request.role'}=~ /li\.\//) {
 4722:             # Library role, so allow browsing of resources in this domain.
 4723:             return 'F';
 4724:         }
 4725:         if ($copyright eq 'custom') {
 4726: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4727:         }
 4728:     }
 4729:     # Domain coordinator is trying to create a course
 4730:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4731:         # uri is the requested domain in this case.
 4732:         # comparison to 'request.role.domain' shows if the user has selected
 4733:         # a role of dc for the domain in question.
 4734:         return 'F' if ($uri eq $env{'request.role.domain'});
 4735:     }
 4736: 
 4737:     my $thisallowed='';
 4738:     my $statecond=0;
 4739:     my $courseprivid='';
 4740: 
 4741: # Course
 4742: 
 4743:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4744:        $thisallowed.=$1;
 4745:     }
 4746: 
 4747: # Domain
 4748: 
 4749:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4750:        =~/\Q$priv\E\&([^\:]*)/) {
 4751:        $thisallowed.=$1;
 4752:     }
 4753: 
 4754: # Course: uri itself is a course
 4755:     my $courseuri=$uri;
 4756:     $courseuri=~s/\_(\d)/\/$1/;
 4757:     $courseuri=~s/^([^\/])/\/$1/;
 4758: 
 4759:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4760:        =~/\Q$priv\E\&([^\:]*)/) {
 4761:        $thisallowed.=$1;
 4762:     }
 4763: 
 4764: # URI is an uploaded document for this course, default permissions don't matter
 4765: # not allowing 'edit' access (editupload) to uploaded course docs
 4766:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4767: 	$thisallowed='';
 4768:         my ($match)=&is_on_map($uri);
 4769:         if ($match) {
 4770:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4771:                   =~/\Q$priv\E\&([^\:]*)/) {
 4772:                 $thisallowed.=$1;
 4773:             }
 4774:         } else {
 4775:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4776:             if ($refuri) {
 4777:                 if ($refuri =~ m|^/adm/|) {
 4778:                     $thisallowed='F';
 4779:                 } else {
 4780:                     $refuri=&declutter($refuri);
 4781:                     my ($match) = &is_on_map($refuri);
 4782:                     if ($match) {
 4783:                         $thisallowed='F';
 4784:                     }
 4785:                 }
 4786:             }
 4787:         }
 4788:     }
 4789: 
 4790:     if ($priv eq 'bre'
 4791: 	&& $thisallowed ne 'F' 
 4792: 	&& $thisallowed ne '2'
 4793: 	&& &is_portfolio_url($uri)) {
 4794: 	$thisallowed = &portfolio_access($uri);
 4795:     }
 4796:     
 4797: # Full access at system, domain or course-wide level? Exit.
 4798:     if ($thisallowed=~/F/) {
 4799: 	return 'F';
 4800:     }
 4801: 
 4802: # If this is generating or modifying users, exit with special codes
 4803: 
 4804:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4805: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4806: 	    my ($audom,$auname)=split('/',$uri);
 4807: # no author name given, so this just checks on the general right to make a co-author in this domain
 4808: 	    unless ($auname) { return $thisallowed; }
 4809: # an author name is given, so we are about to actually make a co-author for a certain account
 4810: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4811: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4812: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4813: 	}
 4814: 	return $thisallowed;
 4815:     }
 4816: #
 4817: # Gathered so far: system, domain and course wide privileges
 4818: #
 4819: # Course: See if uri or referer is an individual resource that is part of 
 4820: # the course
 4821: 
 4822:     if ($env{'request.course.id'}) {
 4823: 
 4824:        $courseprivid=$env{'request.course.id'};
 4825:        if ($env{'request.course.sec'}) {
 4826:           $courseprivid.='/'.$env{'request.course.sec'};
 4827:        }
 4828:        $courseprivid=~s/\_/\//;
 4829:        my $checkreferer=1;
 4830:        my ($match,$cond)=&is_on_map($uri);
 4831:        if ($match) {
 4832:            $statecond=$cond;
 4833:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4834:                =~/\Q$priv\E\&([^\:]*)/) {
 4835:                $thisallowed.=$1;
 4836:                $checkreferer=0;
 4837:            }
 4838:        }
 4839:        
 4840:        if ($checkreferer) {
 4841: 	  my $refuri=$env{'httpref.'.$orguri};
 4842:             unless ($refuri) {
 4843:                 foreach my $key (keys(%env)) {
 4844: 		    if ($key=~/^httpref\..*\*/) {
 4845: 			my $pattern=$key;
 4846:                         $pattern=~s/^httpref\.\/res\///;
 4847:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4848:                         $pattern=~s/\//\\\//g;
 4849:                         if ($orguri=~/$pattern/) {
 4850: 			    $refuri=$env{$key};
 4851:                         }
 4852:                     }
 4853:                 }
 4854:             }
 4855: 
 4856:          if ($refuri) { 
 4857: 	  $refuri=&declutter($refuri);
 4858:           my ($match,$cond)=&is_on_map($refuri);
 4859:             if ($match) {
 4860:               my $refstatecond=$cond;
 4861:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4862:                   =~/\Q$priv\E\&([^\:]*)/) {
 4863:                   $thisallowed.=$1;
 4864:                   $uri=$refuri;
 4865:                   $statecond=$refstatecond;
 4866:               }
 4867:           }
 4868:         }
 4869:        }
 4870:    }
 4871: 
 4872: #
 4873: # Gathered now: all privileges that could apply, and condition number
 4874: # 
 4875: #
 4876: # Full or no access?
 4877: #
 4878: 
 4879:     if ($thisallowed=~/F/) {
 4880: 	return 'F';
 4881:     }
 4882: 
 4883:     unless ($thisallowed) {
 4884:         return '';
 4885:     }
 4886: 
 4887: # Restrictions exist, deal with them
 4888: #
 4889: #   C:according to course preferences
 4890: #   R:according to resource settings
 4891: #   L:unless locked
 4892: #   X:according to user session state
 4893: #
 4894: 
 4895: # Possibly locked functionality, check all courses
 4896: # Locks might take effect only after 10 minutes cache expiration for other
 4897: # courses, and 2 minutes for current course
 4898: 
 4899:     my $envkey;
 4900:     if ($thisallowed=~/L/) {
 4901:         foreach $envkey (keys %env) {
 4902:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4903:                my $courseid=$2;
 4904:                my $roleid=$1.'.'.$2;
 4905:                $courseid=~s/^\///;
 4906:                my $expiretime=600;
 4907:                if ($env{'request.role'} eq $roleid) {
 4908: 		  $expiretime=120;
 4909:                }
 4910: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4911:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4912:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4913: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4914:                }
 4915:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4916:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4917: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4918:                        &log($env{'user.domain'},$env{'user.name'},
 4919:                             $env{'user.home'},
 4920:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4921:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4922:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4923: 		       return '';
 4924:                    }
 4925:                }
 4926:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4927:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4928: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4929:                        &log($env{'user.domain'},$env{'user.name'},
 4930:                             $env{'user.home'},
 4931:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4932:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4933:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4934: 		       return '';
 4935:                    }
 4936:                }
 4937: 	   }
 4938:        }
 4939:     }
 4940:    
 4941: #
 4942: # Rest of the restrictions depend on selected course
 4943: #
 4944: 
 4945:     unless ($env{'request.course.id'}) {
 4946: 	if ($thisallowed eq 'A') {
 4947: 	    return 'A';
 4948:         } elsif ($thisallowed eq 'B') {
 4949:             return 'B';
 4950: 	} else {
 4951: 	    return '1';
 4952: 	}
 4953:     }
 4954: 
 4955: #
 4956: # Now user is definitely in a course
 4957: #
 4958: 
 4959: 
 4960: # Course preferences
 4961: 
 4962:    if ($thisallowed=~/C/) {
 4963:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4964:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4965:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4966: 	   =~/\Q$rolecode\E/) {
 4967: 	   if ($priv ne 'pch') { 
 4968: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4969: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4970: 			$env{'request.course.id'});
 4971: 	   }
 4972:            return '';
 4973:        }
 4974: 
 4975:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4976: 	   =~/\Q$unamedom\E/) {
 4977: 	   if ($priv ne 'pch') { 
 4978: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4979: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4980: 			$env{'request.course.id'});
 4981: 	   }
 4982:            return '';
 4983:        }
 4984:    }
 4985: 
 4986: # Resource preferences
 4987: 
 4988:    if ($thisallowed=~/R/) {
 4989:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4990:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4991: 	   if ($priv ne 'pch') { 
 4992: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4993: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4994: 	   }
 4995: 	   return '';
 4996:        }
 4997:    }
 4998: 
 4999: # Restricted by state or randomout?
 5000: 
 5001:    if ($thisallowed=~/X/) {
 5002:       if ($env{'acc.randomout'}) {
 5003: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5004:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5005:             return ''; 
 5006:          }
 5007:       }
 5008:       if (&condval($statecond)) {
 5009: 	 return '2';
 5010:       } else {
 5011:          return '';
 5012:       }
 5013:    }
 5014: 
 5015:     if ($thisallowed eq 'A') {
 5016: 	return 'A';
 5017:     } elsif ($thisallowed eq 'B') {
 5018:         return 'B';
 5019:     }
 5020:    return 'F';
 5021: }
 5022: 
 5023: sub split_uri_for_cond {
 5024:     my $uri=&deversion(&declutter(shift));
 5025:     my @uriparts=split(/\//,$uri);
 5026:     my $filename=pop(@uriparts);
 5027:     my $pathname=join('/',@uriparts);
 5028:     return ($pathname,$filename);
 5029: }
 5030: # --------------------------------------------------- Is a resource on the map?
 5031: 
 5032: sub is_on_map {
 5033:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5034:     #Trying to find the conditional for the file
 5035:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5036: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5037:     if ($match) {
 5038: 	return (1,$1);
 5039:     } else {
 5040: 	return (0,0);
 5041:     }
 5042: }
 5043: 
 5044: # --------------------------------------------------------- Get symb from alias
 5045: 
 5046: sub get_symb_from_alias {
 5047:     my $symb=shift;
 5048:     my ($map,$resid,$url)=&decode_symb($symb);
 5049: # Already is a symb
 5050:     if ($url) { return $symb; }
 5051: # Must be an alias
 5052:     my $aliassymb='';
 5053:     my %bighash;
 5054:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5055:                             &GDBM_READER(),0640)) {
 5056:         my $rid=$bighash{'mapalias_'.$symb};
 5057: 	if ($rid) {
 5058: 	    my ($mapid,$resid)=split(/\./,$rid);
 5059: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5060: 				    $resid,$bighash{'src_'.$rid});
 5061: 	}
 5062:         untie %bighash;
 5063:     }
 5064:     return $aliassymb;
 5065: }
 5066: 
 5067: # ----------------------------------------------------------------- Define Role
 5068: 
 5069: sub definerole {
 5070:   if (allowed('mcr','/')) {
 5071:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5072:     foreach my $role (split(':',$sysrole)) {
 5073: 	my ($crole,$cqual)=split(/\&/,$role);
 5074:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5075:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5076: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5077:                return "refused:s:$crole&$cqual"; 
 5078:             }
 5079:         }
 5080:     }
 5081:     foreach my $role (split(':',$domrole)) {
 5082: 	my ($crole,$cqual)=split(/\&/,$role);
 5083:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5084:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5085: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5086:                return "refused:d:$crole&$cqual"; 
 5087:             }
 5088:         }
 5089:     }
 5090:     foreach my $role (split(':',$courole)) {
 5091: 	my ($crole,$cqual)=split(/\&/,$role);
 5092:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5093:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5094: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5095:                return "refused:c:$crole&$cqual"; 
 5096:             }
 5097:         }
 5098:     }
 5099:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5100:                 "$env{'user.domain'}:$env{'user.name'}:".
 5101: 	        "rolesdef_$rolename=".
 5102:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5103:     return reply($command,$env{'user.home'});
 5104:   } else {
 5105:     return 'refused';
 5106:   }
 5107: }
 5108: 
 5109: # ---------------- Make a metadata query against the network of library servers
 5110: 
 5111: sub metadata_query {
 5112:     my ($query,$custom,$customshow,$server_array)=@_;
 5113:     my %rhash;
 5114:     my %libserv = &all_library();
 5115:     my @server_list = (defined($server_array) ? @$server_array
 5116:                                               : keys(%libserv) );
 5117:     for my $server (@server_list) {
 5118: 	unless ($custom or $customshow) {
 5119: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5120: 	    $rhash{$server}=$reply;
 5121: 	}
 5122: 	else {
 5123: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5124: 			     &escape($custom).':'.&escape($customshow),
 5125: 			     $server);
 5126: 	    $rhash{$server}=$reply;
 5127: 	}
 5128:     }
 5129:     return \%rhash;
 5130: }
 5131: 
 5132: # ----------------------------------------- Send log queries and wait for reply
 5133: 
 5134: sub log_query {
 5135:     my ($uname,$udom,$query,%filters)=@_;
 5136:     my $uhome=&homeserver($uname,$udom);
 5137:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5138:     my $uhost=&hostname($uhome);
 5139:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5140:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5141:                        $uhome);
 5142:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5143:     return get_query_reply($queryid);
 5144: }
 5145: 
 5146: # -------------------------- Update MySQL table for portfolio file
 5147: 
 5148: sub update_portfolio_table {
 5149:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5150:     if ($group ne '') {
 5151:         $file_name =~s /^\Q$group\E//;
 5152:     }
 5153:     my $homeserver = &homeserver($uname,$udom);
 5154:     my $queryid=
 5155:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5156:                ':'.&escape($file_name).':'.$action,$homeserver);
 5157:     my $reply = &get_query_reply($queryid);
 5158:     return $reply;
 5159: }
 5160: 
 5161: # -------------------------- Update MySQL allusers table
 5162: 
 5163: sub update_allusers_table {
 5164:     my ($uname,$udom,$names) = @_;
 5165:     my $homeserver = &homeserver($uname,$udom);
 5166:     my $queryid=
 5167:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5168:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5169:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5170:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5171:                'generation='.&escape($names->{'generation'}).'%%'.
 5172:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5173:                'id='.&escape($names->{'id'}),$homeserver);
 5174:     my $reply = &get_query_reply($queryid);
 5175:     return $reply;
 5176: }
 5177: 
 5178: # ------- Request retrieval of institutional classlists for course(s)
 5179: 
 5180: sub fetch_enrollment_query {
 5181:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5182:     my $homeserver;
 5183:     my $maxtries = 1;
 5184:     if ($context eq 'automated') {
 5185:         $homeserver = $perlvar{'lonHostID'};
 5186:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5187:     } else {
 5188:         $homeserver = &homeserver($cnum,$dom);
 5189:     }
 5190:     my $host=&hostname($homeserver);
 5191:     my $cmd = '';
 5192:     foreach my $affiliate (keys %{$affiliatesref}) {
 5193:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5194:     }
 5195:     $cmd =~ s/%%$//;
 5196:     $cmd = &escape($cmd);
 5197:     my $query = 'fetchenrollment';
 5198:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5199:     unless ($queryid=~/^\Q$host\E\_/) { 
 5200:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5201:         return 'error: '.$queryid;
 5202:     }
 5203:     my $reply = &get_query_reply($queryid);
 5204:     my $tries = 1;
 5205:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5206:         $reply = &get_query_reply($queryid);
 5207:         $tries ++;
 5208:     }
 5209:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5210:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5211:     } else {
 5212:         my @responses = split(/:/,$reply);
 5213:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5214:             foreach my $line (@responses) {
 5215:                 my ($key,$value) = split(/=/,$line,2);
 5216:                 $$replyref{$key} = $value;
 5217:             }
 5218:         } else {
 5219:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5220:             foreach my $line (@responses) {
 5221:                 my ($key,$value) = split(/=/,$line);
 5222:                 $$replyref{$key} = $value;
 5223:                 if ($value > 0) {
 5224:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5225:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5226:                         my $destname = $pathname.'/'.$filename;
 5227:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5228:                         if ($xml_classlist =~ /^error/) {
 5229:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5230:                         } else {
 5231:                             if ( open(FILE,">$destname") ) {
 5232:                                 print FILE &unescape($xml_classlist);
 5233:                                 close(FILE);
 5234:                             } else {
 5235:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5236:                             }
 5237:                         }
 5238:                     }
 5239:                 }
 5240:             }
 5241:         }
 5242:         return 'ok';
 5243:     }
 5244:     return 'error';
 5245: }
 5246: 
 5247: sub get_query_reply {
 5248:     my $queryid=shift;
 5249:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5250:     my $reply='';
 5251:     for (1..100) {
 5252: 	sleep 2;
 5253:         if (-e $replyfile.'.end') {
 5254: 	    if (open(my $fh,$replyfile)) {
 5255: 		$reply = join('',<$fh>);
 5256: 		close($fh);
 5257: 	   } else { return 'error: reply_file_error'; }
 5258:            return &unescape($reply);
 5259: 	}
 5260:     }
 5261:     return 'timeout:'.$queryid;
 5262: }
 5263: 
 5264: sub courselog_query {
 5265: #
 5266: # possible filters:
 5267: # url: url or symb
 5268: # username
 5269: # domain
 5270: # action: view, submit, grade
 5271: # start: timestamp
 5272: # end: timestamp
 5273: #
 5274:     my (%filters)=@_;
 5275:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5276:     if ($filters{'url'}) {
 5277: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5278:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5279:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5280:     }
 5281:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5282:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5283:     return &log_query($cname,$cdom,'courselog',%filters);
 5284: }
 5285: 
 5286: sub userlog_query {
 5287: #
 5288: # possible filters:
 5289: # action: log check role
 5290: # start: timestamp
 5291: # end: timestamp
 5292: #
 5293:     my ($uname,$udom,%filters)=@_;
 5294:     return &log_query($uname,$udom,'userlog',%filters);
 5295: }
 5296: 
 5297: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5298: 
 5299: sub auto_run {
 5300:     my ($cnum,$cdom) = @_;
 5301:     my $response = 0;
 5302:     my $settings;
 5303:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5304:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5305:         $settings = $domconfig{'autoenroll'};
 5306:         if ($settings->{'run'} eq '1') {
 5307:             $response = 1;
 5308:         }
 5309:     } else {
 5310:         my $homeserver;
 5311:         if (&is_course($cdom,$cnum)) {
 5312:             $homeserver = &homeserver($cnum,$cdom);
 5313:         } else {
 5314:             $homeserver = &domain($cdom,'primary');
 5315:         }
 5316:         if ($homeserver ne 'no_host') {
 5317:             $response = &reply('autorun:'.$cdom,$homeserver);
 5318:         }
 5319:     }
 5320:     return $response;
 5321: }
 5322: 
 5323: sub auto_get_sections {
 5324:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5325:     my $homeserver = &homeserver($cnum,$cdom);
 5326:     my @secs = ();
 5327:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5328:     unless ($response eq 'refused') {
 5329:         @secs = split(/:/,$response);
 5330:     }
 5331:     return @secs;
 5332: }
 5333: 
 5334: sub auto_new_course {
 5335:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5336:     my $homeserver = &homeserver($cnum,$cdom);
 5337:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5338:     return $response;
 5339: }
 5340: 
 5341: sub auto_validate_courseID {
 5342:     my ($cnum,$cdom,$inst_course_id) = @_;
 5343:     my $homeserver = &homeserver($cnum,$cdom);
 5344:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5345:     return $response;
 5346: }
 5347: 
 5348: sub auto_create_password {
 5349:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5350:     my ($homeserver,$response);
 5351:     my $create_passwd = 0;
 5352:     my $authchk = '';
 5353:     if ($udom =~ /^$match_domain$/) {
 5354:         $homeserver = &domain($udom,'primary');
 5355:     }
 5356:     if ($homeserver eq '') {
 5357:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5358:             $homeserver = &homeserver($cnum,$cdom);
 5359:         }
 5360:     }
 5361:     if ($homeserver eq '') {
 5362:         $authchk = 'nodomain';
 5363:     } else {
 5364:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5365:         if ($response eq 'refused') {
 5366:             $authchk = 'refused';
 5367:         } else {
 5368:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5369:         }
 5370:     }
 5371:     return ($authparam,$create_passwd,$authchk);
 5372: }
 5373: 
 5374: sub auto_photo_permission {
 5375:     my ($cnum,$cdom,$students) = @_;
 5376:     my $homeserver = &homeserver($cnum,$cdom);
 5377:     my ($outcome,$perm_reqd,$conditions) = 
 5378: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5379:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5380: 	return (undef,undef);
 5381:     }
 5382:     return ($outcome,$perm_reqd,$conditions);
 5383: }
 5384: 
 5385: sub auto_checkphotos {
 5386:     my ($uname,$udom,$pid) = @_;
 5387:     my $homeserver = &homeserver($uname,$udom);
 5388:     my ($result,$resulttype);
 5389:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5390: 				   &escape($uname).':'.&escape($pid),
 5391: 				   $homeserver));
 5392:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5393: 	return (undef,undef);
 5394:     }
 5395:     if ($outcome) {
 5396:         ($result,$resulttype) = split(/:/,$outcome);
 5397:     } 
 5398:     return ($result,$resulttype);
 5399: }
 5400: 
 5401: sub auto_photochoice {
 5402:     my ($cnum,$cdom) = @_;
 5403:     my $homeserver = &homeserver($cnum,$cdom);
 5404:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5405: 						       &escape($cdom),
 5406: 						       $homeserver)));
 5407:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5408: 	return (undef,undef);
 5409:     }
 5410:     return ($update,$comment);
 5411: }
 5412: 
 5413: sub auto_photoupdate {
 5414:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5415:     my $homeserver = &homeserver($cnum,$dom);
 5416:     my $host=&hostname($homeserver);
 5417:     my $cmd = '';
 5418:     my $maxtries = 1;
 5419:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5420:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5421:     }
 5422:     $cmd =~ s/%%$//;
 5423:     $cmd = &escape($cmd);
 5424:     my $query = 'institutionalphotos';
 5425:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5426:     unless ($queryid=~/^\Q$host\E\_/) {
 5427:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5428:         return 'error: '.$queryid;
 5429:     }
 5430:     my $reply = &get_query_reply($queryid);
 5431:     my $tries = 1;
 5432:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5433:         $reply = &get_query_reply($queryid);
 5434:         $tries ++;
 5435:     }
 5436:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5437:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5438:     } else {
 5439:         my @responses = split(/:/,$reply);
 5440:         my $outcome = shift(@responses); 
 5441:         foreach my $item (@responses) {
 5442:             my ($key,$value) = split(/=/,$item);
 5443:             $$photo{$key} = $value;
 5444:         }
 5445:         return $outcome;
 5446:     }
 5447:     return 'error';
 5448: }
 5449: 
 5450: sub auto_instcode_format {
 5451:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5452: 	$cat_order) = @_;
 5453:     my $courses = '';
 5454:     my @homeservers;
 5455:     if ($caller eq 'global') {
 5456: 	my %servers = &get_servers($codedom,'library');
 5457: 	foreach my $tryserver (keys(%servers)) {
 5458: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5459: 		push(@homeservers,$tryserver);
 5460: 	    }
 5461:         }
 5462:     } else {
 5463:         push(@homeservers,&homeserver($caller,$codedom));
 5464:     }
 5465:     foreach my $code (keys(%{$instcodes})) {
 5466:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5467:     }
 5468:     chop($courses);
 5469:     my $ok_response = 0;
 5470:     my $response;
 5471:     while (@homeservers > 0 && $ok_response == 0) {
 5472:         my $server = shift(@homeservers); 
 5473:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5474:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5475:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5476: 		split(/:/,$response);
 5477:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5478:             push(@{$codetitles},&str2array($codetitles_str));
 5479:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5480:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5481:             $ok_response = 1;
 5482:         }
 5483:     }
 5484:     if ($ok_response) {
 5485:         return 'ok';
 5486:     } else {
 5487:         return $response;
 5488:     }
 5489: }
 5490: 
 5491: sub auto_instcode_defaults {
 5492:     my ($domain,$returnhash,$code_order) = @_;
 5493:     my @homeservers;
 5494: 
 5495:     my %servers = &get_servers($domain,'library');
 5496:     foreach my $tryserver (keys(%servers)) {
 5497: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5498: 	    push(@homeservers,$tryserver);
 5499: 	}
 5500:     }
 5501: 
 5502:     my $response;
 5503:     foreach my $server (@homeservers) {
 5504:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5505:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5506: 	
 5507: 	foreach my $pair (split(/\&/,$response)) {
 5508: 	    my ($name,$value)=split(/\=/,$pair);
 5509: 	    if ($name eq 'code_order') {
 5510: 		@{$code_order} = split(/\&/,&unescape($value));
 5511: 	    } else {
 5512: 		$returnhash->{&unescape($name)}=&unescape($value);
 5513: 	    }
 5514: 	}
 5515: 	return 'ok';
 5516:     }
 5517: 
 5518:     return $response;
 5519: } 
 5520: 
 5521: sub auto_validate_class_sec {
 5522:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5523:     my $homeserver = &homeserver($cnum,$cdom);
 5524:     my $ownerlist;
 5525:     if (ref($owners) eq 'ARRAY') {
 5526:         $ownerlist = join(',',@{$owners});
 5527:     } else {
 5528:         $ownerlist = $owners;
 5529:     }
 5530:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5531:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5532:     return $response;
 5533: }
 5534: 
 5535: # ------------------------------------------------------- Course Group routines
 5536: 
 5537: sub get_coursegroups {
 5538:     my ($cdom,$cnum,$group,$namespace) = @_;
 5539:     return(&dump($namespace,$cdom,$cnum,$group));
 5540: }
 5541: 
 5542: sub modify_coursegroup {
 5543:     my ($cdom,$cnum,$groupsettings) = @_;
 5544:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5545: }
 5546: 
 5547: sub toggle_coursegroup_status {
 5548:     my ($cdom,$cnum,$group,$action) = @_;
 5549:     my ($from_namespace,$to_namespace);
 5550:     if ($action eq 'delete') {
 5551:         $from_namespace = 'coursegroups';
 5552:         $to_namespace = 'deleted_groups';
 5553:     } else {
 5554:         $from_namespace = 'deleted_groups';
 5555:         $to_namespace = 'coursegroups';
 5556:     }
 5557:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5558:     if (my $tmp = &error(%curr_group)) {
 5559:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5560:         return ('read error',$tmp);
 5561:     } else {
 5562:         my %savedsettings = %curr_group; 
 5563:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5564:         my $deloutcome;
 5565:         if ($result eq 'ok') {
 5566:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5567:         } else {
 5568:             return ('write error',$result);
 5569:         }
 5570:         if ($deloutcome eq 'ok') {
 5571:             return 'ok';
 5572:         } else {
 5573:             return ('delete error',$deloutcome);
 5574:         }
 5575:     }
 5576: }
 5577: 
 5578: sub modify_group_roles {
 5579:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5580:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5581:     my $role = 'gr/'.&escape($userprivs);
 5582:     my ($uname,$udom) = split(/:/,$user);
 5583:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5584:     if ($result eq 'ok') {
 5585:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5586:     }
 5587:     return $result;
 5588: }
 5589: 
 5590: sub modify_coursegroup_membership {
 5591:     my ($cdom,$cnum,$membership) = @_;
 5592:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5593:     return $result;
 5594: }
 5595: 
 5596: sub get_active_groups {
 5597:     my ($udom,$uname,$cdom,$cnum) = @_;
 5598:     my $now = time;
 5599:     my %groups = ();
 5600:     foreach my $key (keys(%env)) {
 5601:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5602:             my ($start,$end) = split(/\./,$env{$key});
 5603:             if (($end!=0) && ($end<$now)) { next; }
 5604:             if (($start!=0) && ($start>$now)) { next; }
 5605:             if ($1 eq $cdom && $2 eq $cnum) {
 5606:                 $groups{$3} = $env{$key} ;
 5607:             }
 5608:         }
 5609:     }
 5610:     return %groups;
 5611: }
 5612: 
 5613: sub get_group_membership {
 5614:     my ($cdom,$cnum,$group) = @_;
 5615:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5616: }
 5617: 
 5618: sub get_users_groups {
 5619:     my ($udom,$uname,$courseid) = @_;
 5620:     my @usersgroups;
 5621:     my $cachetime=1800;
 5622: 
 5623:     my $hashid="$udom:$uname:$courseid";
 5624:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5625:     if (defined($cached)) {
 5626:         @usersgroups = split(/:/,$grouplist);
 5627:     } else {  
 5628:         $grouplist = '';
 5629:         my $courseurl = &courseid_to_courseurl($courseid);
 5630:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5631:         my $access_end = $env{'course.'.$courseid.
 5632:                               '.default_enrollment_end_date'};
 5633:         my $now = time;
 5634:         foreach my $key (keys(%roleshash)) {
 5635:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5636:                 my $group = $1;
 5637:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5638:                     my $start = $2;
 5639:                     my $end = $1;
 5640:                     if ($start == -1) { next; } # deleted from group
 5641:                     if (($start!=0) && ($start>$now)) { next; }
 5642:                     if (($end!=0) && ($end<$now)) {
 5643:                         if ($access_end && $access_end < $now) {
 5644:                             if ($access_end - $end < 86400) {
 5645:                                 push(@usersgroups,$group);
 5646:                             }
 5647:                         }
 5648:                         next;
 5649:                     }
 5650:                     push(@usersgroups,$group);
 5651:                 }
 5652:             }
 5653:         }
 5654:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5655:         $grouplist = join(':',@usersgroups);
 5656:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5657:     }
 5658:     return @usersgroups;
 5659: }
 5660: 
 5661: sub devalidate_getgroups_cache {
 5662:     my ($udom,$uname,$cdom,$cnum)=@_;
 5663:     my $courseid = $cdom.'_'.$cnum;
 5664: 
 5665:     my $hashid="$udom:$uname:$courseid";
 5666:     &devalidate_cache_new('getgroups',$hashid);
 5667: }
 5668: 
 5669: # ------------------------------------------------------------------ Plain Text
 5670: 
 5671: sub plaintext {
 5672:     my ($short,$type,$cid,$forcedefault) = @_;
 5673:     if ($short =~ /^cr/) {
 5674: 	return (split('/',$short))[-1];
 5675:     }
 5676:     if (!defined($cid)) {
 5677:         $cid = $env{'request.course.id'};
 5678:     }
 5679:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 5680:         unless ($forcedefault) {
 5681:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 5682:             &Apache::lonlocal::mt_escape(\$roletext);
 5683:             return &Apache::lonlocal::mt($roletext);
 5684:         }
 5685:     }
 5686:     my %rolenames = (
 5687:                       Course => 'std',
 5688:                       Group => 'alt1',
 5689:                     );
 5690:     if (defined($type) && 
 5691:          defined($rolenames{$type}) && 
 5692:          defined($prp{$short}{$rolenames{$type}})) {
 5693:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5694:     } else {
 5695:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5696:     }
 5697: }
 5698: 
 5699: # ----------------------------------------------------------------- Assign Role
 5700: 
 5701: sub assignrole {
 5702:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5703:         $context)=@_;
 5704:     my $mrole;
 5705:     if ($role =~ /^cr\//) {
 5706:         my $cwosec=$url;
 5707:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5708: 	unless (&allowed('ccr',$cwosec)) {
 5709:            &logthis('Refused custom assignrole: '.
 5710:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5711: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5712:            return 'refused'; 
 5713:         }
 5714:         $mrole='cr';
 5715:     } elsif ($role =~ /^gr\//) {
 5716:         my $cwogrp=$url;
 5717:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5718:         unless (&allowed('mdg',$cwogrp)) {
 5719:             &logthis('Refused group assignrole: '.
 5720:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5721:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5722:             return 'refused';
 5723:         }
 5724:         $mrole='gr';
 5725:     } else {
 5726:         my $cwosec=$url;
 5727:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5728:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5729:             my $refused;
 5730:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5731:                 if (!(&allowed('c'.$role,$url))) {
 5732:                     $refused = 1;
 5733:                 }
 5734:             } else {
 5735:                 $refused = 1;
 5736:             }
 5737:             if ($refused) {
 5738:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5739:                     $refused = '';
 5740:                 } else {
 5741:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5742:                              ' '.$role.' '.$end.' '.$start.' by '.
 5743: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5744:                     return 'refused';
 5745:                 }
 5746:             }
 5747:         }
 5748:         $mrole=$role;
 5749:     }
 5750:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5751:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5752:     if ($end) { $command.='_'.$end; }
 5753:     if ($start) {
 5754: 	if ($end) { 
 5755:            $command.='_'.$start; 
 5756:         } else {
 5757:            $command.='_0_'.$start;
 5758:         }
 5759:     }
 5760:     my $origstart = $start;
 5761:     my $origend = $end;
 5762:     my $delflag;
 5763: # actually delete
 5764:     if ($deleteflag) {
 5765: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5766: # modify command to delete the role
 5767:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5768:                 "$udom:$uname:$url".'_'."$mrole";
 5769: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5770: # set start and finish to negative values for userrolelog
 5771:            $start=-1;
 5772:            $end=-1;
 5773:            $delflag = 1;
 5774:         }
 5775:     }
 5776: # send command
 5777:     my $answer=&reply($command,&homeserver($uname,$udom));
 5778: # log new user role if status is ok
 5779:     if ($answer eq 'ok') {
 5780: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5781: # for course roles, perform group memberships changes triggered by role change.
 5782:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5783:         unless ($role =~ /^gr/) {
 5784:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5785:                                              $origstart,$selfenroll,$context);
 5786:         }
 5787:     }
 5788:     return $answer;
 5789: }
 5790: 
 5791: # -------------------------------------------------- Modify user authentication
 5792: # Overrides without validation
 5793: 
 5794: sub modifyuserauth {
 5795:     my ($udom,$uname,$umode,$upass)=@_;
 5796:     my $uhome=&homeserver($uname,$udom);
 5797:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5798:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5799:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5800:              ' in domain '.$env{'request.role.domain'});  
 5801:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5802: 		     &escape($upass),$uhome);
 5803:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5804:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5805:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5806:     &log($udom,,$uname,$uhome,
 5807:         'Authentication changed by '.$env{'user.domain'}.', '.
 5808:                                      $env{'user.name'}.', '.$umode.
 5809:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5810:     unless ($reply eq 'ok') {
 5811:         &logthis('Authentication mode error: '.$reply);
 5812: 	return 'error: '.$reply;
 5813:     }   
 5814:     return 'ok';
 5815: }
 5816: 
 5817: # --------------------------------------------------------------- Modify a user
 5818: 
 5819: sub modifyuser {
 5820:     my ($udom,    $uname, $uid,
 5821:         $umode,   $upass, $first,
 5822:         $middle,  $last,  $gene,
 5823:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5824:     $udom= &LONCAPA::clean_domain($udom);
 5825:     $uname=&LONCAPA::clean_username($uname);
 5826:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5827:              $umode.', '.$first.', '.$middle.', '.
 5828: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5829:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5830:                                      ' desiredhome not specified'). 
 5831:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5832:              ' in domain '.$env{'request.role.domain'});
 5833:     my $uhome=&homeserver($uname,$udom,'true');
 5834: # ----------------------------------------------------------------- Create User
 5835:     if (($uhome eq 'no_host') && 
 5836: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5837:         my $unhome='';
 5838:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5839:             $unhome = $desiredhome;
 5840: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5841: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5842:         } else { # load balancing routine for determining $unhome
 5843:             my $loadm=10000000;
 5844: 	    my %servers = &get_servers($udom,'library');
 5845: 	    foreach my $tryserver (keys(%servers)) {
 5846: 		my $answer=reply('load',$tryserver);
 5847: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5848: 		    $loadm=$answer;
 5849: 		    $unhome=$tryserver;
 5850: 		}
 5851: 	    }
 5852:         }
 5853:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5854: 	    return 'error: unable to find a home server for '.$uname.
 5855:                    ' in domain '.$udom;
 5856:         }
 5857:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5858:                          &escape($upass),$unhome);
 5859: 	unless ($reply eq 'ok') {
 5860:             return 'error: '.$reply;
 5861:         }   
 5862:         $uhome=&homeserver($uname,$udom,'true');
 5863:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5864: 	    return 'error: unable verify users home machine.';
 5865:         }
 5866:     }   # End of creation of new user
 5867: # ---------------------------------------------------------------------- Add ID
 5868:     if ($uid) {
 5869:        $uid=~tr/A-Z/a-z/;
 5870:        my %uidhash=&idrget($udom,$uname);
 5871:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5872:          && (!$forceid)) {
 5873: 	  unless ($uid eq $uidhash{$uname}) {
 5874: 	      return 'error: user id "'.$uid.'" does not match '.
 5875:                   'current user id "'.$uidhash{$uname}.'".';
 5876:           }
 5877:        } else {
 5878: 	  &idput($udom,($uname => $uid));
 5879:        }
 5880:     }
 5881: # -------------------------------------------------------------- Add names, etc
 5882:     my @tmp=&get('environment',
 5883: 		   ['firstname','middlename','lastname','generation','id',
 5884:                     'permanentemail','inststatus'],
 5885: 		   $udom,$uname);
 5886:     my %names;
 5887:     if ($tmp[0] =~ m/^error:.*/) { 
 5888:         %names=(); 
 5889:     } else {
 5890:         %names = @tmp;
 5891:     }
 5892: #
 5893: # Make sure to not trash student environment if instructor does not bother
 5894: # to supply name and email information
 5895: #
 5896:     if ($first)  { $names{'firstname'}  = $first; }
 5897:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5898:     if ($last)   { $names{'lastname'}   = $last; }
 5899:     if (defined($gene))   { $names{'generation'} = $gene; }
 5900:     if ($email) {
 5901:        $email=~s/[^\w\@\.\-\,]//gs;
 5902:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5903:     }
 5904:     if ($uid) { $names{'id'}  = $uid; }
 5905:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5906:     my $reply = &put('environment', \%names, $udom,$uname);
 5907:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5908:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5909:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5910:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5911:                  $umode.', '.$first.', '.$middle.', '.
 5912: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5913:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5914:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5915:     } else {
 5916:         $logmsg .= ' during self creation';
 5917:     }
 5918:     &logthis($logmsg);
 5919:     return 'ok';
 5920: }
 5921: 
 5922: # -------------------------------------------------------------- Modify student
 5923: 
 5924: sub modifystudent {
 5925:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5926:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5927:         $selfenroll,$context)=@_;
 5928:     if (!$cid) {
 5929: 	unless ($cid=$env{'request.course.id'}) {
 5930: 	    return 'not_in_class';
 5931: 	}
 5932:     }
 5933: # --------------------------------------------------------------- Make the user
 5934:     my $reply=&modifyuser
 5935: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5936:          $desiredhome,$email);
 5937:     unless ($reply eq 'ok') { return $reply; }
 5938:     # This will cause &modify_student_enrollment to get the uid from the
 5939:     # students environment
 5940:     $uid = undef if (!$forceid);
 5941:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5942: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5943:     return $reply;
 5944: }
 5945: 
 5946: sub modify_student_enrollment {
 5947:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5948:     my ($cdom,$cnum,$chome);
 5949:     if (!$cid) {
 5950: 	unless ($cid=$env{'request.course.id'}) {
 5951: 	    return 'not_in_class';
 5952: 	}
 5953: 	$cdom=$env{'course.'.$cid.'.domain'};
 5954: 	$cnum=$env{'course.'.$cid.'.num'};
 5955:     } else {
 5956: 	($cdom,$cnum)=split(/_/,$cid);
 5957:     }
 5958:     $chome=$env{'course.'.$cid.'.home'};
 5959:     if (!$chome) {
 5960: 	$chome=&homeserver($cnum,$cdom);
 5961:     }
 5962:     if (!$chome) { return 'unknown_course'; }
 5963:     # Make sure the user exists
 5964:     my $uhome=&homeserver($uname,$udom);
 5965:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5966: 	return 'error: no such user';
 5967:     }
 5968:     # Get student data if we were not given enough information
 5969:     if (!defined($first)  || $first  eq '' || 
 5970:         !defined($last)   || $last   eq '' || 
 5971:         !defined($uid)    || $uid    eq '' || 
 5972:         !defined($middle) || $middle eq '' || 
 5973:         !defined($gene)   || $gene   eq '') {
 5974:         # They did not supply us with enough data to enroll the student, so
 5975:         # we need to pick up more information.
 5976:         my %tmp = &get('environment',
 5977:                        ['firstname','middlename','lastname', 'generation','id']
 5978:                        ,$udom,$uname);
 5979: 
 5980:         #foreach my $key (keys(%tmp)) {
 5981:         #    &logthis("key $key = ".$tmp{$key});
 5982:         #}
 5983:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5984:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5985:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5986:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5987:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5988:     }
 5989:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5990:     my $reply=cput('classlist',
 5991: 		   {"$uname:$udom" => 
 5992: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5993: 		   $cdom,$cnum);
 5994:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5995: 	return 'error: '.$reply;
 5996:     } else {
 5997: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5998:     }
 5999:     # Add student role to user
 6000:     my $uurl='/'.$cid;
 6001:     $uurl=~s/\_/\//g;
 6002:     if ($usec) {
 6003: 	$uurl.='/'.$usec;
 6004:     }
 6005:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6006: }
 6007: 
 6008: sub format_name {
 6009:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6010:     my $name;
 6011:     if ($first ne 'lastname') {
 6012: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6013:     } else {
 6014: 	if ($lastname=~/\S/) {
 6015: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6016: 	    $name=~s/\s+,/,/;
 6017: 	} else {
 6018: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6019: 	}
 6020:     }
 6021:     $name=~s/^\s+//;
 6022:     $name=~s/\s+$//;
 6023:     $name=~s/\s+/ /g;
 6024:     return $name;
 6025: }
 6026: 
 6027: # ------------------------------------------------- Write to course preferences
 6028: 
 6029: sub writecoursepref {
 6030:     my ($courseid,%prefs)=@_;
 6031:     $courseid=~s/^\///;
 6032:     $courseid=~s/\_/\//g;
 6033:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6034:     my $chome=homeserver($cnum,$cdomain);
 6035:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6036: 	return 'error: no such course';
 6037:     }
 6038:     my $cstring='';
 6039:     foreach my $pref (keys(%prefs)) {
 6040: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6041:     }
 6042:     $cstring=~s/\&$//;
 6043:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6044: }
 6045: 
 6046: # ---------------------------------------------------------- Make/modify course
 6047: 
 6048: sub createcourse {
 6049:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6050:         $course_owner,$crstype)=@_;
 6051:     $url=&declutter($url);
 6052:     my $cid='';
 6053:     unless (&allowed('ccc',$udom)) {
 6054:         return 'refused';
 6055:     }
 6056: # ------------------------------------------------------------------- Create ID
 6057:    my $uname=int(1+rand(9)).
 6058:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6059:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6060:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6061: # ----------------------------------------------- Make sure that does not exist
 6062:    my $uhome=&homeserver($uname,$udom,'true');
 6063:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6064:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6065:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6066:        $uhome=&homeserver($uname,$udom,'true');       
 6067:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6068:            return 'error: unable to generate unique course-ID';
 6069:        } 
 6070:    }
 6071: # ------------------------------------------------ Check supplied server name
 6072:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6073:     if (! &is_library($course_server)) {
 6074:         return 'error:bad server name '.$course_server;
 6075:     }
 6076: # ------------------------------------------------------------- Make the course
 6077:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6078:                       $course_server);
 6079:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6080:     $uhome=&homeserver($uname,$udom,'true');
 6081:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6082: 	return 'error: no such course';
 6083:     }
 6084: # ----------------------------------------------------------------- Course made
 6085: # log existence
 6086:     my $newcourse = {
 6087:                     $udom.'_'.$uname => {
 6088:                                      description => $description,
 6089:                                      inst_code   => $inst_code,
 6090:                                      owner       => $course_owner,
 6091:                                      type        => $crstype,
 6092:                                                 },
 6093:                     };
 6094:     &courseidput($udom,$newcourse,$uhome,'notime');
 6095: # set toplevel url
 6096:     my $topurl=$url;
 6097:     unless ($nonstandard) {
 6098: # ------------------------------------------ For standard courses, make top url
 6099:         my $mapurl=&clutter($url);
 6100:         if ($mapurl eq '/res/') { $mapurl=''; }
 6101:         $env{'form.initmap'}=(<<ENDINITMAP);
 6102: <map>
 6103: <resource id="1" type="start"></resource>
 6104: <resource id="2" src="$mapurl"></resource>
 6105: <resource id="3" type="finish"></resource>
 6106: <link index="1" from="1" to="2"></link>
 6107: <link index="2" from="2" to="3"></link>
 6108: </map>
 6109: ENDINITMAP
 6110:         $topurl=&declutter(
 6111:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6112:                           );
 6113:     }
 6114: # ----------------------------------------------------------- Write preferences
 6115:     &writecoursepref($udom.'_'.$uname,
 6116:                      ('description' => $description,
 6117:                       'url'         => $topurl));
 6118:     return '/'.$udom.'/'.$uname;
 6119: }
 6120: 
 6121: sub is_course {
 6122:     my ($cdom,$cnum) = @_;
 6123:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6124: 				undef,'.');
 6125:     if (exists($courses{$cdom.'_'.$cnum})) {
 6126:         return 1;
 6127:     }
 6128:     return 0;
 6129: }
 6130: 
 6131: # ---------------------------------------------------------- Assign Custom Role
 6132: 
 6133: sub assigncustomrole {
 6134:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6135:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6136:                        $end,$start,$deleteflag,$selfenroll,$context);
 6137: }
 6138: 
 6139: # ----------------------------------------------------------------- Revoke Role
 6140: 
 6141: sub revokerole {
 6142:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6143:     my $now=time;
 6144:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6145: }
 6146: 
 6147: # ---------------------------------------------------------- Revoke Custom Role
 6148: 
 6149: sub revokecustomrole {
 6150:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6151:     my $now=time;
 6152:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6153:            $deleteflag,$selfenroll,$context);
 6154: }
 6155: 
 6156: # ------------------------------------------------------------ Disk usage
 6157: sub diskusage {
 6158:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6159:     $directorypath =~ s/\/$//;
 6160:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6161:                        .&escape($getpropath).':'.&escape($uname).':'
 6162:                        .&escape($udom),homeserver($uname,$udom));
 6163:     if ($listing eq 'unknown_cmd') {
 6164:         if ($getpropath) {
 6165:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6166:         }
 6167:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6168:     }
 6169:     return $listing;
 6170: }
 6171: 
 6172: sub is_locked {
 6173:     my ($file_name, $domain, $user) = @_;
 6174:     my @check;
 6175:     my $is_locked;
 6176:     push @check, $file_name;
 6177:     my %locked = &get('file_permissions',\@check,
 6178: 		      $env{'user.domain'},$env{'user.name'});
 6179:     my ($tmp)=keys(%locked);
 6180:     if ($tmp=~/^error:/) { undef(%locked); }
 6181:     
 6182:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6183:         $is_locked = 'false';
 6184:         foreach my $entry (@{$locked{$file_name}}) {
 6185:            if (ref($entry) eq 'ARRAY') { 
 6186:                $is_locked = 'true';
 6187:                last;
 6188:            }
 6189:        }
 6190:     } else {
 6191:         $is_locked = 'false';
 6192:     }
 6193: }
 6194: 
 6195: sub declutter_portfile {
 6196:     my ($file) = @_;
 6197:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6198:     return $file;
 6199: }
 6200: 
 6201: # ------------------------------------------------------------- Mark as Read Only
 6202: 
 6203: sub mark_as_readonly {
 6204:     my ($domain,$user,$files,$what) = @_;
 6205:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6206:     my ($tmp)=keys(%current_permissions);
 6207:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6208:     foreach my $file (@{$files}) {
 6209: 	$file = &declutter_portfile($file);
 6210:         push(@{$current_permissions{$file}},$what);
 6211:     }
 6212:     &put('file_permissions',\%current_permissions,$domain,$user);
 6213:     return;
 6214: }
 6215: 
 6216: # ------------------------------------------------------------Save Selected Files
 6217: 
 6218: sub save_selected_files {
 6219:     my ($user, $path, @files) = @_;
 6220:     my $filename = $user."savedfiles";
 6221:     my @other_files = &files_not_in_path($user, $path);
 6222:     open (OUT, '>'.$tmpdir.$filename);
 6223:     foreach my $file (@files) {
 6224:         print (OUT $env{'form.currentpath'}.$file."\n");
 6225:     }
 6226:     foreach my $file (@other_files) {
 6227:         print (OUT $file."\n");
 6228:     }
 6229:     close (OUT);
 6230:     return 'ok';
 6231: }
 6232: 
 6233: sub clear_selected_files {
 6234:     my ($user) = @_;
 6235:     my $filename = $user."savedfiles";
 6236:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6237:     print (OUT undef);
 6238:     close (OUT);
 6239:     return ("ok");    
 6240: }
 6241: 
 6242: sub files_in_path {
 6243:     my ($user, $path) = @_;
 6244:     my $filename = $user."savedfiles";
 6245:     my %return_files;
 6246:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6247:     while (my $line_in = <IN>) {
 6248:         chomp ($line_in);
 6249:         my @paths_and_file = split (m!/!, $line_in);
 6250:         my $file_part = pop (@paths_and_file);
 6251:         my $path_part = join ('/', @paths_and_file);
 6252:         $path_part.='/';
 6253:         my $path_and_file = $path_part.$file_part;
 6254:         if ($path_part eq $path) {
 6255:             $return_files{$file_part}= 'selected';
 6256:         }
 6257:     }
 6258:     close (IN);
 6259:     return (\%return_files);
 6260: }
 6261: 
 6262: # called in portfolio select mode, to show files selected NOT in current directory
 6263: sub files_not_in_path {
 6264:     my ($user, $path) = @_;
 6265:     my $filename = $user."savedfiles";
 6266:     my @return_files;
 6267:     my $path_part;
 6268:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6269:     while (my $line = <IN>) {
 6270:         #ok, I know it's clunky, but I want it to work
 6271:         my @paths_and_file = split(m|/|, $line);
 6272:         my $file_part = pop(@paths_and_file);
 6273:         chomp($file_part);
 6274:         my $path_part = join('/', @paths_and_file);
 6275:         $path_part .= '/';
 6276:         my $path_and_file = $path_part.$file_part;
 6277:         if ($path_part ne $path) {
 6278:             push(@return_files, ($path_and_file));
 6279:         }
 6280:     }
 6281:     close(OUT);
 6282:     return (@return_files);
 6283: }
 6284: 
 6285: #----------------------------------------------Get portfolio file permissions
 6286: 
 6287: sub get_portfile_permissions {
 6288:     my ($domain,$user) = @_;
 6289:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6290:     my ($tmp)=keys(%current_permissions);
 6291:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6292:     return \%current_permissions;
 6293: }
 6294: 
 6295: #---------------------------------------------Get portfolio file access controls
 6296: 
 6297: sub get_access_controls {
 6298:     my ($current_permissions,$group,$file) = @_;
 6299:     my %access;
 6300:     my $real_file = $file;
 6301:     $file =~ s/\.meta$//;
 6302:     if (defined($file)) {
 6303:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6304:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6305:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6306:             }
 6307:         }
 6308:     } else {
 6309:         foreach my $key (keys(%{$current_permissions})) {
 6310:             if ($key =~ /\0accesscontrol$/) {
 6311:                 if (defined($group)) {
 6312:                     if ($key !~ m-^\Q$group\E/-) {
 6313:                         next;
 6314:                     }
 6315:                 }
 6316:                 my ($fullpath) = split(/\0/,$key);
 6317:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6318:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6319:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6320:                     }
 6321:                 }
 6322:             }
 6323:         }
 6324:     }
 6325:     return %access;
 6326: }
 6327: 
 6328: sub modify_access_controls {
 6329:     my ($file_name,$changes,$domain,$user)=@_;
 6330:     my ($outcome,$deloutcome);
 6331:     my %store_permissions;
 6332:     my %new_values;
 6333:     my %new_control;
 6334:     my %translation;
 6335:     my @deletions = ();
 6336:     my $now = time;
 6337:     if (exists($$changes{'activate'})) {
 6338:         if (ref($$changes{'activate'}) eq 'HASH') {
 6339:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6340:             my $numnew = scalar(@newitems);
 6341:             for (my $i=0; $i<$numnew; $i++) {
 6342:                 my $newkey = $newitems[$i];
 6343:                 my $newid = &Apache::loncommon::get_cgi_id();
 6344:                 if ($newkey =~ /^\d+:/) { 
 6345:                     $newkey =~ s/^(\d+)/$newid/;
 6346:                     $translation{$1} = $newid;
 6347:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6348:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6349:                     $translation{$1} = $newid;
 6350:                 }
 6351:                 $new_values{$file_name."\0".$newkey} = 
 6352:                                           $$changes{'activate'}{$newitems[$i]};
 6353:                 $new_control{$newkey} = $now;
 6354:             }
 6355:         }
 6356:     }
 6357:     my %todelete;
 6358:     my %changed_items;
 6359:     foreach my $action ('delete','update') {
 6360:         if (exists($$changes{$action})) {
 6361:             if (ref($$changes{$action}) eq 'HASH') {
 6362:                 foreach my $key (keys(%{$$changes{$action}})) {
 6363:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6364:                     if ($action eq 'delete') { 
 6365:                         $todelete{$itemnum} = 1;
 6366:                     } else {
 6367:                         $changed_items{$itemnum} = $key;
 6368:                     }
 6369:                 }
 6370:             }
 6371:         }
 6372:     }
 6373:     # get lock on access controls for file.
 6374:     my $lockhash = {
 6375:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6376:                                                        ':'.$env{'user.domain'},
 6377:                    }; 
 6378:     my $tries = 0;
 6379:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6380:    
 6381:     while (($gotlock ne 'ok') && $tries <3) {
 6382:         $tries ++;
 6383:         sleep 1;
 6384:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6385:     }
 6386:     if ($gotlock eq 'ok') {
 6387:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6388:         my ($tmp)=keys(%curr_permissions);
 6389:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6390:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6391:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6392:             if (ref($curr_controls) eq 'HASH') {
 6393:                 foreach my $control_item (keys(%{$curr_controls})) {
 6394:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6395:                     if (defined($todelete{$itemnum})) {
 6396:                         push(@deletions,$file_name."\0".$control_item);
 6397:                     } else {
 6398:                         if (defined($changed_items{$itemnum})) {
 6399:                             $new_control{$changed_items{$itemnum}} = $now;
 6400:                             push(@deletions,$file_name."\0".$control_item);
 6401:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6402:                         } else {
 6403:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6404:                         }
 6405:                     }
 6406:                 }
 6407:             }
 6408:         }
 6409:         my ($group);
 6410:         if (&is_course($domain,$user)) {
 6411:             ($group,my $file) = split(/\//,$file_name,2);
 6412:         }
 6413:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6414:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6415:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6416:         #  remove lock
 6417:         my @del_lock = ($file_name."\0".'locked_access_records');
 6418:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6419:         my $sqlresult =
 6420:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6421:                                     $group);
 6422:     } else {
 6423:         $outcome = "error: could not obtain lockfile\n";  
 6424:     }
 6425:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6426: }
 6427: 
 6428: sub make_public_indefinitely {
 6429:     my ($requrl) = @_;
 6430:     my $now = time;
 6431:     my $action = 'activate';
 6432:     my $aclnum = 0;
 6433:     if (&is_portfolio_url($requrl)) {
 6434:         my (undef,$udom,$unum,$file_name,$group) =
 6435:             &parse_portfolio_url($requrl);
 6436:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6437:         my %access_controls = &get_access_controls($current_perms,
 6438:                                                    $group,$file_name);
 6439:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6440:             my ($num,$scope,$end,$start) = 
 6441:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6442:             if ($scope eq 'public') {
 6443:                 if ($start <= $now && $end == 0) {
 6444:                     $action = 'none';
 6445:                 } else {
 6446:                     $action = 'update';
 6447:                     $aclnum = $num;
 6448:                 }
 6449:                 last;
 6450:             }
 6451:         }
 6452:         if ($action eq 'none') {
 6453:              return 'ok';
 6454:         } else {
 6455:             my %changes;
 6456:             my $newend = 0;
 6457:             my $newstart = $now;
 6458:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6459:             $changes{$action}{$newkey} = {
 6460:                 type => 'public',
 6461:                 time => {
 6462:                     start => $newstart,
 6463:                     end   => $newend,
 6464:                 },
 6465:             };
 6466:             my ($outcome,$deloutcome,$new_values,$translation) =
 6467:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6468:             return $outcome;
 6469:         }
 6470:     } else {
 6471:         return 'invalid';
 6472:     }
 6473: }
 6474: 
 6475: #------------------------------------------------------Get Marked as Read Only
 6476: 
 6477: sub get_marked_as_readonly {
 6478:     my ($domain,$user,$what,$group) = @_;
 6479:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6480:     my @readonly_files;
 6481:     my $cmp1=$what;
 6482:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6483:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6484:         if (defined($group)) {
 6485:             if ($file_name !~ m-^\Q$group\E/-) {
 6486:                 next;
 6487:             }
 6488:         }
 6489:         if (ref($value) eq "ARRAY"){
 6490:             foreach my $stored_what (@{$value}) {
 6491:                 my $cmp2=$stored_what;
 6492:                 if (ref($stored_what) eq 'ARRAY') {
 6493:                     $cmp2=join('',@{$stored_what});
 6494:                 }
 6495:                 if ($cmp1 eq $cmp2) {
 6496:                     push(@readonly_files, $file_name);
 6497:                     last;
 6498:                 } elsif (!defined($what)) {
 6499:                     push(@readonly_files, $file_name);
 6500:                     last;
 6501:                 }
 6502:             }
 6503:         }
 6504:     }
 6505:     return @readonly_files;
 6506: }
 6507: #-----------------------------------------------------------Get Marked as Read Only Hash
 6508: 
 6509: sub get_marked_as_readonly_hash {
 6510:     my ($current_permissions,$group,$what) = @_;
 6511:     my %readonly_files;
 6512:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6513:         if (defined($group)) {
 6514:             if ($file_name !~ m-^\Q$group\E/-) {
 6515:                 next;
 6516:             }
 6517:         }
 6518:         if (ref($value) eq "ARRAY"){
 6519:             foreach my $stored_what (@{$value}) {
 6520:                 if (ref($stored_what) eq 'ARRAY') {
 6521:                     foreach my $lock_descriptor(@{$stored_what}) {
 6522:                         if ($lock_descriptor eq 'graded') {
 6523:                             $readonly_files{$file_name} = 'graded';
 6524:                         } elsif ($lock_descriptor eq 'handback') {
 6525:                             $readonly_files{$file_name} = 'handback';
 6526:                         } else {
 6527:                             if (!exists($readonly_files{$file_name})) {
 6528:                                 $readonly_files{$file_name} = 'locked';
 6529:                             }
 6530:                         }
 6531:                     }
 6532:                 } 
 6533:             }
 6534:         } 
 6535:     }
 6536:     return %readonly_files;
 6537: }
 6538: # ------------------------------------------------------------ Unmark as Read Only
 6539: 
 6540: sub unmark_as_readonly {
 6541:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6542:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6543:     my ($domain,$user,$what,$file_name,$group) = @_;
 6544:     $file_name = &declutter_portfile($file_name);
 6545:     my $symb_crs = $what;
 6546:     if (ref($what)) { $symb_crs=join('',@$what); }
 6547:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6548:     my ($tmp)=keys(%current_permissions);
 6549:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6550:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6551:     foreach my $file (@readonly_files) {
 6552: 	my $clean_file = &declutter_portfile($file);
 6553: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6554: 	my $current_locks = $current_permissions{$file};
 6555:         my @new_locks;
 6556:         my @del_keys;
 6557:         if (ref($current_locks) eq "ARRAY"){
 6558:             foreach my $locker (@{$current_locks}) {
 6559:                 my $compare=$locker;
 6560:                 if (ref($locker) eq 'ARRAY') {
 6561:                     $compare=join('',@{$locker});
 6562:                     if ($compare ne $symb_crs) {
 6563:                         push(@new_locks, $locker);
 6564:                     }
 6565:                 }
 6566:             }
 6567:             if (scalar(@new_locks) > 0) {
 6568:                 $current_permissions{$file} = \@new_locks;
 6569:             } else {
 6570:                 push(@del_keys, $file);
 6571:                 &del('file_permissions',\@del_keys, $domain, $user);
 6572:                 delete($current_permissions{$file});
 6573:             }
 6574:         }
 6575:     }
 6576:     &put('file_permissions',\%current_permissions,$domain,$user);
 6577:     return;
 6578: }
 6579: 
 6580: # ------------------------------------------------------------ Directory lister
 6581: 
 6582: sub dirlist {
 6583:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6584:     $uri=~s/^\///;
 6585:     $uri=~s/\/$//;
 6586:     my ($udom, $uname);
 6587:     if ($getuserdir) {
 6588:         $udom = $userdomain;
 6589:         $uname = $username;
 6590:     } else {
 6591:         (undef,$udom,$uname)=split(/\//,$uri);
 6592:         if(defined($userdomain)) {
 6593:             $udom = $userdomain;
 6594:         }
 6595:         if(defined($username)) {
 6596:             $uname = $username;
 6597:         }
 6598:     }
 6599:     my ($dirRoot,$listing,@listing_results);
 6600: 
 6601:     $dirRoot = $perlvar{'lonDocRoot'};
 6602:     if (defined($getpropath)) {
 6603:         $dirRoot = &propath($udom,$uname);
 6604:         $dirRoot =~ s/\/$//;
 6605:     } elsif (defined($getuserdir)) {
 6606:         my $subdir=$uname.'__';
 6607:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6608:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6609:                    ."/$udom/$subdir/$uname";
 6610:     } elsif (defined($alternateRoot)) {
 6611:         $dirRoot = $alternateRoot;
 6612:     }
 6613: 
 6614:     if($udom) {
 6615:         if($uname) {
 6616:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6617:                               .$getuserdir.':'.&escape($dirRoot)
 6618:                               .':'.&escape($uname).':'.&escape($udom),
 6619:                               &homeserver($uname,$udom));
 6620:             if ($listing eq 'unknown_cmd') {
 6621:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6622:                                   &homeserver($uname,$udom));
 6623:             } else {
 6624:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6625:             }
 6626:             if ($listing eq 'unknown_cmd') {
 6627:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6628: 				  &homeserver($uname,$udom));
 6629:                 @listing_results = split(/:/,$listing);
 6630:             } else {
 6631:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6632:             }
 6633:             return @listing_results;
 6634:         } elsif(!$alternateRoot) {
 6635:             my %allusers;
 6636: 	    my %servers = &get_servers($udom,'library');
 6637:  	    foreach my $tryserver (keys(%servers)) {
 6638:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6639:                                   &escape($udom),$tryserver);
 6640:                 if ($listing eq 'unknown_cmd') {
 6641: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6642: 				      $udom, $tryserver);
 6643:                 } else {
 6644:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6645:                 }
 6646: 		if ($listing eq 'unknown_cmd') {
 6647: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6648: 				      $udom, $tryserver);
 6649: 		    @listing_results = split(/:/,$listing);
 6650: 		} else {
 6651: 		    @listing_results =
 6652: 			map { &unescape($_); } split(/:/,$listing);
 6653: 		}
 6654: 		if ($listing_results[0] ne 'no_such_dir' && 
 6655: 		    $listing_results[0] ne 'empty'       &&
 6656: 		    $listing_results[0] ne 'con_lost') {
 6657: 		    foreach my $line (@listing_results) {
 6658: 			my ($entry) = split(/&/,$line,2);
 6659: 			$allusers{$entry} = 1;
 6660: 		    }
 6661: 		}
 6662:             }
 6663:             my $alluserstr='';
 6664:             foreach my $user (sort(keys(%allusers))) {
 6665:                 $alluserstr.=$user.'&user:';
 6666:             }
 6667:             $alluserstr=~s/:$//;
 6668:             return split(/:/,$alluserstr);
 6669:         } else {
 6670:             return ('missing user name');
 6671:         }
 6672:     } elsif(!defined($getpropath)) {
 6673:         my @all_domains = sort(&all_domains());
 6674:         foreach my $domain (@all_domains) {
 6675:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6676:         }
 6677:         return @all_domains;
 6678:     } else {
 6679:         return ('missing domain');
 6680:     }
 6681: }
 6682: 
 6683: # --------------------------------------------- GetFileTimestamp
 6684: # This function utilizes dirlist and returns the date stamp for
 6685: # when it was last modified.  It will also return an error of -1
 6686: # if an error occurs
 6687: 
 6688: sub GetFileTimestamp {
 6689:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6690:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6691:     $studentName   = &LONCAPA::clean_username($studentName);
 6692:     my ($fileStat) = 
 6693:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6694:                                  undef,$getuserdir);
 6695:     my @stats = split('&', $fileStat);
 6696:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6697:         # @stats contains first the filename, then the stat output
 6698:         return $stats[10]; # so this is 10 instead of 9.
 6699:     } else {
 6700:         return -1;
 6701:     }
 6702: }
 6703: 
 6704: sub stat_file {
 6705:     my ($uri) = @_;
 6706:     $uri = &clutter_with_no_wrapper($uri);
 6707: 
 6708:     my ($udom,$uname,$file);
 6709:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6710: 	($udom,$uname,$file) =
 6711: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6712: 	$file = 'userfiles/'.$file;
 6713:     }
 6714:     if ($uri =~ m-^/res/-) {
 6715: 	($udom,$uname) = 
 6716: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6717: 	$file = $uri;
 6718:     }
 6719: 
 6720:     if (!$udom || !$uname || !$file) {
 6721: 	# unable to handle the uri
 6722: 	return ();
 6723:     }
 6724:     my $getpropath;
 6725:     if ($file =~ /^userfiles\//) {
 6726:         $getpropath = 1;
 6727:     }
 6728:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6729:     my @stats = split('&', $result);
 6730:     
 6731:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6732: 	shift(@stats); #filename is first
 6733: 	return @stats;
 6734:     }
 6735:     return ();
 6736: }
 6737: 
 6738: # -------------------------------------------------------- Value of a Condition
 6739: 
 6740: # gets the value of a specific preevaluated condition
 6741: #    stored in the string  $env{user.state.<cid>}
 6742: # or looks up a condition reference in the bighash and if if hasn't
 6743: # already been evaluated recurses into docondval to get the value of
 6744: # the condition, then memoizing it to 
 6745: #   $env{user.state.<cid>.<condition>}
 6746: sub directcondval {
 6747:     my $number=shift;
 6748:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6749: 	&Apache::lonuserstate::evalstate();
 6750:     }
 6751:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6752: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6753:     } elsif ($number =~ /^_/) {
 6754: 	my $sub_condition;
 6755: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6756: 		&GDBM_READER(),0640)) {
 6757: 	    $sub_condition=$bighash{'conditions'.$number};
 6758: 	    untie(%bighash);
 6759: 	}
 6760: 	my $value = &docondval($sub_condition);
 6761: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6762: 	return $value;
 6763:     }
 6764:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6765:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6766:     } else {
 6767:        return 2;
 6768:     }
 6769: }
 6770: 
 6771: # get the collection of conditions for this resource
 6772: sub condval {
 6773:     my $condidx=shift;
 6774:     my $allpathcond='';
 6775:     foreach my $cond (split(/\|/,$condidx)) {
 6776: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6777: 	    $allpathcond.=
 6778: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6779: 	}
 6780:     }
 6781:     $allpathcond=~s/\|$//;
 6782:     return &docondval($allpathcond);
 6783: }
 6784: 
 6785: #evaluates an expression of conditions
 6786: sub docondval {
 6787:     my ($allpathcond) = @_;
 6788:     my $result=0;
 6789:     if ($env{'request.course.id'}
 6790: 	&& defined($allpathcond)) {
 6791: 	my $operand='|';
 6792: 	my @stack;
 6793: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6794: 	    if ($chunk eq '(') {
 6795: 		push @stack,($operand,$result);
 6796: 	    } elsif ($chunk eq ')') {
 6797: 		my $before=pop @stack;
 6798: 		if (pop @stack eq '&') {
 6799: 		    $result=$result>$before?$before:$result;
 6800: 		} else {
 6801: 		    $result=$result>$before?$result:$before;
 6802: 		}
 6803: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6804: 		$operand=$chunk;
 6805: 	    } else {
 6806: 		my $new=directcondval($chunk);
 6807: 		if ($operand eq '&') {
 6808: 		    $result=$result>$new?$new:$result;
 6809: 		} else {
 6810: 		    $result=$result>$new?$result:$new;
 6811: 		}
 6812: 	    }
 6813: 	}
 6814:     }
 6815:     return $result;
 6816: }
 6817: 
 6818: # ---------------------------------------------------- Devalidate courseresdata
 6819: 
 6820: sub devalidatecourseresdata {
 6821:     my ($coursenum,$coursedomain)=@_;
 6822:     my $hashid=$coursenum.':'.$coursedomain;
 6823:     &devalidate_cache_new('courseres',$hashid);
 6824: }
 6825: 
 6826: 
 6827: # --------------------------------------------------- Course Resourcedata Query
 6828: #
 6829: #  Parameters:
 6830: #      $coursenum    - Number of the course.
 6831: #      $coursedomain - Domain at which the course was created.
 6832: #  Returns:
 6833: #     A hash of the course parameters along (I think) with timestamps
 6834: #     and version info.
 6835: 
 6836: sub get_courseresdata {
 6837:     my ($coursenum,$coursedomain)=@_;
 6838:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6839:     my $hashid=$coursenum.':'.$coursedomain;
 6840:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6841:     my %dumpreply;
 6842:     unless (defined($cached)) {
 6843: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6844: 	$result=\%dumpreply;
 6845: 	my ($tmp) = keys(%dumpreply);
 6846: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6847: 	    &do_cache_new('courseres',$hashid,$result,600);
 6848: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6849: 	    return $tmp;
 6850: 	} elsif ($tmp =~ /^(error)/) {
 6851: 	    $result=undef;
 6852: 	    &do_cache_new('courseres',$hashid,$result,600);
 6853: 	}
 6854:     }
 6855:     return $result;
 6856: }
 6857: 
 6858: sub devalidateuserresdata {
 6859:     my ($uname,$udom)=@_;
 6860:     my $hashid="$udom:$uname";
 6861:     &devalidate_cache_new('userres',$hashid);
 6862: }
 6863: 
 6864: sub get_userresdata {
 6865:     my ($uname,$udom)=@_;
 6866:     #most student don\'t have any data set, check if there is some data
 6867:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6868: 
 6869:     my $hashid="$udom:$uname";
 6870:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6871:     if (!defined($cached)) {
 6872: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6873: 	$result=\%resourcedata;
 6874: 	&do_cache_new('userres',$hashid,$result,600);
 6875:     }
 6876:     my ($tmp)=keys(%$result);
 6877:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6878: 	return $result;
 6879:     }
 6880:     #error 2 occurs when the .db doesn't exist
 6881:     if ($tmp!~/error: 2 /) {
 6882: 	&logthis("<font color=\"blue\">WARNING:".
 6883: 		 " Trying to get resource data for ".
 6884: 		 $uname." at ".$udom.": ".
 6885: 		 $tmp."</font>");
 6886:     } elsif ($tmp=~/error: 2 /) {
 6887: 	#&EXT_cache_set($udom,$uname);
 6888: 	&do_cache_new('userres',$hashid,undef,600);
 6889: 	undef($tmp); # not really an error so don't send it back
 6890:     }
 6891:     return $tmp;
 6892: }
 6893: #----------------------------------------------- resdata - return resource data
 6894: #  Purpose:
 6895: #    Return resource data for either users or for a course.
 6896: #  Parameters:
 6897: #     $name      - Course/user name.
 6898: #     $domain    - Name of the domain the user/course is registered on.
 6899: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6900: #     @which     - Array of names of resources desired.
 6901: #  Returns:
 6902: #     The value of the first reasource in @which that is found in the
 6903: #     resource hash.
 6904: #  Exceptional Conditions:
 6905: #     If the $type passed in is not valid (not the string 'course' or 
 6906: #     'user', an undefined  reference is returned.
 6907: #     If none of the resources are found, an undef is returned
 6908: sub resdata {
 6909:     my ($name,$domain,$type,@which)=@_;
 6910:     my $result;
 6911:     if ($type eq 'course') {
 6912: 	$result=&get_courseresdata($name,$domain);
 6913:     } elsif ($type eq 'user') {
 6914: 	$result=&get_userresdata($name,$domain);
 6915:     }
 6916:     if (!ref($result)) { return $result; }    
 6917:     foreach my $item (@which) {
 6918: 	if (defined($result->{$item->[0]})) {
 6919: 	    return [$result->{$item->[0]},$item->[1]];
 6920: 	}
 6921:     }
 6922:     return undef;
 6923: }
 6924: 
 6925: #
 6926: # EXT resource caching routines
 6927: #
 6928: 
 6929: sub clear_EXT_cache_status {
 6930:     &delenv('cache.EXT.');
 6931: }
 6932: 
 6933: sub EXT_cache_status {
 6934:     my ($target_domain,$target_user) = @_;
 6935:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6936:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6937:         # We know already the user has no data
 6938:         return 1;
 6939:     } else {
 6940:         return 0;
 6941:     }
 6942: }
 6943: 
 6944: sub EXT_cache_set {
 6945:     my ($target_domain,$target_user) = @_;
 6946:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6947:     #&appenv({$cachename => time});
 6948: }
 6949: 
 6950: # --------------------------------------------------------- Value of a Variable
 6951: sub EXT {
 6952: 
 6953:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6954:     unless ($varname) { return ''; }
 6955:     #get real user name/domain, courseid and symb
 6956:     my $courseid;
 6957:     my $publicuser;
 6958:     if ($symbparm) {
 6959: 	$symbparm=&get_symb_from_alias($symbparm);
 6960:     }
 6961:     if (!($uname && $udom)) {
 6962:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6963:       if (!$symbparm) {	$symbparm=$cursymb; }
 6964:     } else {
 6965: 	$courseid=$env{'request.course.id'};
 6966:     }
 6967:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6968:     my $rest;
 6969:     if (defined($therest[0])) {
 6970:        $rest=join('.',@therest);
 6971:     } else {
 6972:        $rest='';
 6973:     }
 6974: 
 6975:     my $qualifierrest=$qualifier;
 6976:     if ($rest) { $qualifierrest.='.'.$rest; }
 6977:     my $spacequalifierrest=$space;
 6978:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6979:     if ($realm eq 'user') {
 6980: # --------------------------------------------------------------- user.resource
 6981: 	if ($space eq 'resource') {
 6982: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6983: 		  || defined($Apache::lonhomework::parsing_a_task))
 6984: 		 &&
 6985: 		 ($symbparm eq &symbread()) ) {	
 6986: 		# if we are in the middle of processing the resource the
 6987: 		# get the value we are planning on committing
 6988:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6989:                     return $Apache::lonhomework::results{$qualifierrest};
 6990:                 } else {
 6991:                     return $Apache::lonhomework::history{$qualifierrest};
 6992:                 }
 6993: 	    } else {
 6994: 		my %restored;
 6995: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6996: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6997: 		} else {
 6998: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6999: 		}
 7000: 		return $restored{$qualifierrest};
 7001: 	    }
 7002: # ----------------------------------------------------------------- user.access
 7003:         } elsif ($space eq 'access') {
 7004: 	    # FIXME - not supporting calls for a specific user
 7005:             return &allowed($qualifier,$rest);
 7006: # ------------------------------------------ user.preferences, user.environment
 7007:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7008: 	    if (($uname eq $env{'user.name'}) &&
 7009: 		($udom eq $env{'user.domain'})) {
 7010: 		return $env{join('.',('environment',$qualifierrest))};
 7011: 	    } else {
 7012: 		my %returnhash;
 7013: 		if (!$publicuser) {
 7014: 		    %returnhash=&userenvironment($udom,$uname,
 7015: 						 $qualifierrest);
 7016: 		}
 7017: 		return $returnhash{$qualifierrest};
 7018: 	    }
 7019: # ----------------------------------------------------------------- user.course
 7020:         } elsif ($space eq 'course') {
 7021: 	    # FIXME - not supporting calls for a specific user
 7022:             return $env{join('.',('request.course',$qualifier))};
 7023: # ------------------------------------------------------------------- user.role
 7024:         } elsif ($space eq 'role') {
 7025: 	    # FIXME - not supporting calls for a specific user
 7026:             my ($role,$where)=split(/\./,$env{'request.role'});
 7027:             if ($qualifier eq 'value') {
 7028: 		return $role;
 7029:             } elsif ($qualifier eq 'extent') {
 7030:                 return $where;
 7031:             }
 7032: # ----------------------------------------------------------------- user.domain
 7033:         } elsif ($space eq 'domain') {
 7034:             return $udom;
 7035: # ------------------------------------------------------------------- user.name
 7036:         } elsif ($space eq 'name') {
 7037:             return $uname;
 7038: # ---------------------------------------------------- Any other user namespace
 7039:         } else {
 7040: 	    my %reply;
 7041: 	    if (!$publicuser) {
 7042: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7043: 	    }
 7044: 	    return $reply{$qualifierrest};
 7045:         }
 7046:     } elsif ($realm eq 'query') {
 7047: # ---------------------------------------------- pull stuff out of query string
 7048:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7049: 						[$spacequalifierrest]);
 7050: 	return $env{'form.'.$spacequalifierrest}; 
 7051:    } elsif ($realm eq 'request') {
 7052: # ------------------------------------------------------------- request.browser
 7053:         if ($space eq 'browser') {
 7054: 	    if ($qualifier eq 'textremote') {
 7055: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7056: 		    return 1;
 7057: 		} else {
 7058: 		    return 0;
 7059: 		}
 7060: 	    } else {
 7061: 		return $env{'browser.'.$qualifier};
 7062: 	    }
 7063: # ------------------------------------------------------------ request.filename
 7064:         } else {
 7065:             return $env{'request.'.$spacequalifierrest};
 7066:         }
 7067:     } elsif ($realm eq 'course') {
 7068: # ---------------------------------------------------------- course.description
 7069:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7070:     } elsif ($realm eq 'resource') {
 7071: 
 7072: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7073: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7074: 	}
 7075: 
 7076: 	if ($space eq 'title') {
 7077: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7078: 	    return &gettitle($symbparm);
 7079: 	}
 7080: 	
 7081: 	if ($space eq 'map') {
 7082: 	    my ($map) = &decode_symb($symbparm);
 7083: 	    return &symbread($map);
 7084: 	}
 7085: 	if ($space eq 'filename') {
 7086: 	    if ($symbparm) {
 7087: 		return &clutter((&decode_symb($symbparm))[2]);
 7088: 	    }
 7089: 	    return &hreflocation('',$env{'request.filename'});
 7090: 	}
 7091: 
 7092: 	my ($section, $group, @groups);
 7093: 	my ($courselevelm,$courselevel);
 7094: 	if ($symbparm && defined($courseid) && 
 7095: 	    $courseid eq $env{'request.course.id'}) {
 7096: 
 7097: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7098: 
 7099: # ----------------------------------------------------- Cascading lookup scheme
 7100: 	    my $symbp=$symbparm;
 7101: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7102: 
 7103: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7104: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7105: 
 7106: 	    if (($env{'user.name'} eq $uname) &&
 7107: 		($env{'user.domain'} eq $udom)) {
 7108: 		$section=$env{'request.course.sec'};
 7109:                 @groups = split(/:/,$env{'request.course.groups'});  
 7110:                 @groups=&sort_course_groups($courseid,@groups); 
 7111: 	    } else {
 7112: 		if (! defined($usection)) {
 7113: 		    $section=&getsection($udom,$uname,$courseid);
 7114: 		} else {
 7115: 		    $section = $usection;
 7116: 		}
 7117:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7118: 	    }
 7119: 
 7120: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7121: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7122: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7123: 
 7124: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7125: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7126: 	    $courselevelm=$courseid.'.'.$mapparm;
 7127: 
 7128: # ----------------------------------------------------------- first, check user
 7129: 
 7130: 	    my $userreply=&resdata($uname,$udom,'user',
 7131: 				       ([$courselevelr,'resource'],
 7132: 					[$courselevelm,'map'     ],
 7133: 					[$courselevel, 'course'  ]));
 7134: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7135: 
 7136: # ------------------------------------------------ second, check some of course
 7137:             my $coursereply;
 7138:             if (@groups > 0) {
 7139:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7140:                                        $mapparm,$spacequalifierrest);
 7141:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7142:             }
 7143: 
 7144: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7145: 				  $env{'course.'.$courseid.'.domain'},
 7146: 				  'course',
 7147: 				  ([$seclevelr,   'resource'],
 7148: 				   [$seclevelm,   'map'     ],
 7149: 				   [$seclevel,    'course'  ],
 7150: 				   [$courselevelr,'resource']));
 7151: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7152: 
 7153: # ------------------------------------------------------ third, check map parms
 7154: 	    my %parmhash=();
 7155: 	    my $thisparm='';
 7156: 	    if (tie(%parmhash,'GDBM_File',
 7157: 		    $env{'request.course.fn'}.'_parms.db',
 7158: 		    &GDBM_READER(),0640)) {
 7159: 		$thisparm=$parmhash{$symbparm};
 7160: 		untie(%parmhash);
 7161: 	    }
 7162: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7163: 	}
 7164: # ------------------------------------------ fourth, look in resource metadata
 7165: 
 7166: 	$spacequalifierrest=~s/\./\_/;
 7167: 	my $filename;
 7168: 	if (!$symbparm) { $symbparm=&symbread(); }
 7169: 	if ($symbparm) {
 7170: 	    $filename=(&decode_symb($symbparm))[2];
 7171: 	} else {
 7172: 	    $filename=$env{'request.filename'};
 7173: 	}
 7174: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7175: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7176: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7177: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7178: 
 7179: # ---------------------------------------------- fourth, look in rest of course
 7180: 	if ($symbparm && defined($courseid) && 
 7181: 	    $courseid eq $env{'request.course.id'}) {
 7182: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7183: 				     $env{'course.'.$courseid.'.domain'},
 7184: 				     'course',
 7185: 				     ([$courselevelm,'map'   ],
 7186: 				      [$courselevel, 'course']));
 7187: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7188: 	}
 7189: # ------------------------------------------------------------------ Cascade up
 7190: 	unless ($space eq '0') {
 7191: 	    my @parts=split(/_/,$space);
 7192: 	    my $id=pop(@parts);
 7193: 	    my $part=join('_',@parts);
 7194: 	    if ($part eq '') { $part='0'; }
 7195: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7196: 				 $symbparm,$udom,$uname,$section,1);
 7197: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7198: 	}
 7199: 	if ($recurse) { return undef; }
 7200: 	my $pack_def=&packages_tab_default($filename,$varname);
 7201: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7202: # ---------------------------------------------------- Any other user namespace
 7203:     } elsif ($realm eq 'environment') {
 7204: # ----------------------------------------------------------------- environment
 7205: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7206: 	    return $env{'environment.'.$spacequalifierrest};
 7207: 	} else {
 7208: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7209: 		return '';
 7210: 	    }
 7211: 	    my %returnhash=&userenvironment($udom,$uname,
 7212: 					    $spacequalifierrest);
 7213: 	    return $returnhash{$spacequalifierrest};
 7214: 	}
 7215:     } elsif ($realm eq 'system') {
 7216: # ----------------------------------------------------------------- system.time
 7217: 	if ($space eq 'time') {
 7218: 	    return time;
 7219:         }
 7220:     } elsif ($realm eq 'server') {
 7221: # ----------------------------------------------------------------- system.time
 7222: 	if ($space eq 'name') {
 7223: 	    return $ENV{'SERVER_NAME'};
 7224:         }
 7225:     }
 7226:     return '';
 7227: }
 7228: 
 7229: sub get_reply {
 7230:     my ($reply_value) = @_;
 7231:     if (ref($reply_value) eq 'ARRAY') {
 7232:         if (wantarray) {
 7233: 	    return @$reply_value;
 7234:         }
 7235:         return $reply_value->[0];
 7236:     } else {
 7237:         return $reply_value;
 7238:     }
 7239: }
 7240: 
 7241: sub check_group_parms {
 7242:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7243:     my @groupitems = ();
 7244:     my $resultitem;
 7245:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7246:     foreach my $group (@{$groups}) {
 7247:         foreach my $level (@levels) {
 7248:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7249:              push(@groupitems,[$item,$level->[1]]);
 7250:         }
 7251:     }
 7252:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7253:                             $env{'course.'.$courseid.'.domain'},
 7254:                                      'course',@groupitems);
 7255:     return $coursereply;
 7256: }
 7257: 
 7258: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7259:     my ($courseid,@groups) = @_;
 7260:     @groups = sort(@groups);
 7261:     return @groups;
 7262: }
 7263: 
 7264: sub packages_tab_default {
 7265:     my ($uri,$varname)=@_;
 7266:     my (undef,$part,$name)=split(/\./,$varname);
 7267: 
 7268:     my (@extension,@specifics,$do_default);
 7269:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7270: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7271: 	if ($pack_type eq 'default') {
 7272: 	    $do_default=1;
 7273: 	} elsif ($pack_type eq 'extension') {
 7274: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7275: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7276: 	    # only look at packages defaults for packages that this id is
 7277: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7278: 	}
 7279:     }
 7280:     # first look for a package that matches the requested part id
 7281:     foreach my $package (@specifics) {
 7282: 	my (undef,$pack_type,$pack_part)=@{$package};
 7283: 	next if ($pack_part ne $part);
 7284: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7285: 	    return $packagetab{"$pack_type&$name&default"};
 7286: 	}
 7287:     }
 7288:     # look for any possible matching non extension_ package
 7289:     foreach my $package (@specifics) {
 7290: 	my (undef,$pack_type,$pack_part)=@{$package};
 7291: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7292: 	    return $packagetab{"$pack_type&$name&default"};
 7293: 	}
 7294: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7295: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7296: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7297: 	}
 7298:     }
 7299:     # look for any posible extension_ match
 7300:     foreach my $package (@extension) {
 7301: 	my ($package,$pack_type)=@{$package};
 7302: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7303: 	    return $packagetab{"$pack_type&$name&default"};
 7304: 	}
 7305: 	if (defined($packagetab{$package."&$name&default"})) {
 7306: 	    return $packagetab{$package."&$name&default"};
 7307: 	}
 7308:     }
 7309:     # look for a global default setting
 7310:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7311: 	return $packagetab{"default&$name&default"};
 7312:     }
 7313:     return undef;
 7314: }
 7315: 
 7316: sub add_prefix_and_part {
 7317:     my ($prefix,$part)=@_;
 7318:     my $keyroot;
 7319:     if (defined($prefix) && $prefix !~ /^__/) {
 7320: 	# prefix that has a part already
 7321: 	$keyroot=$prefix;
 7322:     } elsif (defined($prefix)) {
 7323: 	# prefix that is missing a part
 7324: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7325:     } else {
 7326: 	# no prefix at all
 7327: 	if (defined($part)) { $keyroot='_'.$part; }
 7328:     }
 7329:     return $keyroot;
 7330: }
 7331: 
 7332: # ---------------------------------------------------------------- Get metadata
 7333: 
 7334: my %metaentry;
 7335: sub metadata {
 7336:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7337:     $uri=&declutter($uri);
 7338:     # if it is a non metadata possible uri return quickly
 7339:     if (($uri eq '') || 
 7340: 	(($uri =~ m|^/*adm/|) && 
 7341: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7342:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7343: 	return undef;
 7344:     }
 7345:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7346: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7347: 	return undef;
 7348:     }
 7349:     my $filename=$uri;
 7350:     $uri=~s/\.meta$//;
 7351: #
 7352: # Is the metadata already cached?
 7353: # Look at timestamp of caching
 7354: # Everything is cached by the main uri, libraries are never directly cached
 7355: #
 7356:     if (!defined($liburi)) {
 7357: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7358: 	if (defined($cached)) { return $result->{':'.$what}; }
 7359:     }
 7360:     {
 7361: #
 7362: # Is this a recursive call for a library?
 7363: #
 7364: #	if (! exists($metacache{$uri})) {
 7365: #	    $metacache{$uri}={};
 7366: #	}
 7367: 	my $cachetime = 60*60;
 7368:         if ($liburi) {
 7369: 	    $liburi=&declutter($liburi);
 7370:             $filename=$liburi;
 7371:         } else {
 7372: 	    &devalidate_cache_new('meta',$uri);
 7373: 	    undef(%metaentry);
 7374: 	}
 7375:         my %metathesekeys=();
 7376:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7377: 	my $metastring;
 7378: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7379: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7380: 	    $metastring = 
 7381: 		&Apache::lonnet::ssi_body($which,
 7382: 					  ('grade_target' => 'meta'));
 7383: 	    $cachetime = 1; # only want this cached in the child not long term
 7384: 	} elsif ($uri !~ m -^(editupload)/-) {
 7385: 	    my $file=&filelocation('',&clutter($filename));
 7386: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7387: 	    $metastring=&getfile($file);
 7388: 	}
 7389:         my $parser=HTML::LCParser->new(\$metastring);
 7390:         my $token;
 7391:         undef %metathesekeys;
 7392:         while ($token=$parser->get_token) {
 7393: 	    if ($token->[0] eq 'S') {
 7394: 		if (defined($token->[2]->{'package'})) {
 7395: #
 7396: # This is a package - get package info
 7397: #
 7398: 		    my $package=$token->[2]->{'package'};
 7399: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7400: 		    if (defined($token->[2]->{'id'})) { 
 7401: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7402: 		    }
 7403: 		    if ($metaentry{':packages'}) {
 7404: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7405: 		    } else {
 7406: 			$metaentry{':packages'}=$package.$keyroot;
 7407: 		    }
 7408: 		    foreach my $pack_entry (keys(%packagetab)) {
 7409: 			my $part=$keyroot;
 7410: 			$part=~s/^\_//;
 7411: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7412: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7413: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7414: 			    # ignore package.tab specified default values
 7415:                             # here &package_tab_default() will fetch those
 7416: 			    if ($subp eq 'default') { next; }
 7417: 			    my $value=$packagetab{$pack_entry};
 7418: 			    my $unikey;
 7419: 			    if ($pack =~ /_0$/) {
 7420: 				$unikey='parameter_0_'.$name;
 7421: 				$part=0;
 7422: 			    } else {
 7423: 				$unikey='parameter'.$keyroot.'_'.$name;
 7424: 			    }
 7425: 			    if ($subp eq 'display') {
 7426: 				$value.=' [Part: '.$part.']';
 7427: 			    }
 7428: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7429: 			    $metathesekeys{$unikey}=1;
 7430: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7431: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7432: 			    }
 7433: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7434: 				$metaentry{':'.$unikey}=
 7435: 				    $metaentry{':'.$unikey.'.default'};
 7436: 			    }
 7437: 			}
 7438: 		    }
 7439: 		} else {
 7440: #
 7441: # This is not a package - some other kind of start tag
 7442: #
 7443: 		    my $entry=$token->[1];
 7444: 		    my $unikey;
 7445: 		    if ($entry eq 'import') {
 7446: 			$unikey='';
 7447: 		    } else {
 7448: 			$unikey=$entry;
 7449: 		    }
 7450: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7451: 
 7452: 		    if (defined($token->[2]->{'id'})) { 
 7453: 			$unikey.='_'.$token->[2]->{'id'}; 
 7454: 		    }
 7455: 
 7456: 		    if ($entry eq 'import') {
 7457: #
 7458: # Importing a library here
 7459: #
 7460: 			if ($depthcount<20) {
 7461: 			    my $location=$parser->get_text('/import');
 7462: 			    my $dir=$filename;
 7463: 			    $dir=~s|[^/]*$||;
 7464: 			    $location=&filelocation($dir,$location);
 7465: 			    my $metadata = 
 7466: 				&metadata($uri,'keys', $location,$unikey,
 7467: 					  $depthcount+1);
 7468: 			    foreach my $meta (split(',',$metadata)) {
 7469: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7470: 				$metathesekeys{$meta}=1;
 7471: 			    }
 7472: 			}
 7473: 		    } else { 
 7474: 			
 7475: 			if (defined($token->[2]->{'name'})) { 
 7476: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7477: 			}
 7478: 			$metathesekeys{$unikey}=1;
 7479: 			foreach my $param (@{$token->[3]}) {
 7480: 			    $metaentry{':'.$unikey.'.'.$param} =
 7481: 				$token->[2]->{$param};
 7482: 			}
 7483: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7484: 			my $default=$metaentry{':'.$unikey.'.default'};
 7485: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7486: 		 # only ws inside the tag, and not in default, so use default
 7487: 		 # as value
 7488: 			    $metaentry{':'.$unikey}=$default;
 7489: 			} elsif ( $internaltext =~ /\S/ ) {
 7490: 		  # something interesting inside the tag
 7491: 			    $metaentry{':'.$unikey}=$internaltext;
 7492: 			} else {
 7493: 		  # no interesting values, don't set a default
 7494: 			}
 7495: # end of not-a-package not-a-library import
 7496: 		    }
 7497: # end of not-a-package start tag
 7498: 		}
 7499: # the next is the end of "start tag"
 7500: 	    }
 7501: 	}
 7502: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7503: 	$extension = lc($extension);
 7504: 	if ($extension eq 'htm') { $extension='html'; }
 7505: 
 7506: 	foreach my $key (keys(%packagetab)) {
 7507: 	    #no specific packages #how's our extension
 7508: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7509: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7510: 					 \%metathesekeys);
 7511: 	}
 7512: 
 7513: 	if (!exists($metaentry{':packages'})
 7514: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7515: 	    foreach my $key (keys(%packagetab)) {
 7516: 		#no specific packages well let's get default then
 7517: 		if ($key!~/^default&/) { next; }
 7518: 		&metadata_create_package_def($uri,$key,'default',
 7519: 					     \%metathesekeys);
 7520: 	    }
 7521: 	}
 7522: # are there custom rights to evaluate
 7523: 	if ($metaentry{':copyright'} eq 'custom') {
 7524: 
 7525:     #
 7526:     # Importing a rights file here
 7527:     #
 7528: 	    unless ($depthcount) {
 7529: 		my $location=$metaentry{':customdistributionfile'};
 7530: 		my $dir=$filename;
 7531: 		$dir=~s|[^/]*$||;
 7532: 		$location=&filelocation($dir,$location);
 7533: 		my $rights_metadata =
 7534: 		    &metadata($uri,'keys',$location,'_rights',
 7535: 			      $depthcount+1);
 7536: 		foreach my $rights (split(',',$rights_metadata)) {
 7537: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7538: 		    $metathesekeys{$rights}=1;
 7539: 		}
 7540: 	    }
 7541: 	}
 7542: 	# uniqifiy package listing
 7543: 	my %seen;
 7544: 	my @uniq_packages =
 7545: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7546: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7547: 
 7548: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7549: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7550: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7551: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7552: # this is the end of "was not already recently cached
 7553:     }
 7554:     return $metaentry{':'.$what};
 7555: }
 7556: 
 7557: sub metadata_create_package_def {
 7558:     my ($uri,$key,$package,$metathesekeys)=@_;
 7559:     my ($pack,$name,$subp)=split(/\&/,$key);
 7560:     if ($subp eq 'default') { next; }
 7561:     
 7562:     if (defined($metaentry{':packages'})) {
 7563: 	$metaentry{':packages'}.=','.$package;
 7564:     } else {
 7565: 	$metaentry{':packages'}=$package;
 7566:     }
 7567:     my $value=$packagetab{$key};
 7568:     my $unikey;
 7569:     $unikey='parameter_0_'.$name;
 7570:     $metaentry{':'.$unikey.'.part'}=0;
 7571:     $$metathesekeys{$unikey}=1;
 7572:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7573: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7574:     }
 7575:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7576: 	$metaentry{':'.$unikey}=
 7577: 	    $metaentry{':'.$unikey.'.default'};
 7578:     }
 7579: }
 7580: 
 7581: sub metadata_generate_part0 {
 7582:     my ($metadata,$metacache,$uri) = @_;
 7583:     my %allnames;
 7584:     foreach my $metakey (keys(%$metadata)) {
 7585: 	if ($metakey=~/^parameter\_(.*)/) {
 7586: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7587: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7588: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7589: 	    $allnames{$name}=$part;
 7590: 	  }
 7591: 	}
 7592:     }
 7593:     foreach my $name (keys(%allnames)) {
 7594:       $$metadata{"parameter_0_$name"}=1;
 7595:       my $key=":parameter_0_$name";
 7596:       $$metacache{"$key.part"}='0';
 7597:       $$metacache{"$key.name"}=$name;
 7598:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7599: 					   $allnames{$name}.'_'.$name.
 7600: 					   '.type'};
 7601:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7602: 			     '.display'};
 7603:       my $expr='[Part: '.$allnames{$name}.']';
 7604:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7605:       $$metacache{"$key.display"}=$olddis;
 7606:     }
 7607: }
 7608: 
 7609: # ------------------------------------------------------ Devalidate title cache
 7610: 
 7611: sub devalidate_title_cache {
 7612:     my ($url)=@_;
 7613:     if (!$env{'request.course.id'}) { return; }
 7614:     my $symb=&symbread($url);
 7615:     if (!$symb) { return; }
 7616:     my $key=$env{'request.course.id'}."\0".$symb;
 7617:     &devalidate_cache_new('title',$key);
 7618: }
 7619: 
 7620: # ------------------------------------------------- Get the title of a resource
 7621: 
 7622: sub gettitle {
 7623:     my $urlsymb=shift;
 7624:     my $symb=&symbread($urlsymb);
 7625:     if ($symb) {
 7626: 	my $key=$env{'request.course.id'}."\0".$symb;
 7627: 	my ($result,$cached)=&is_cached_new('title',$key);
 7628: 	if (defined($cached)) { 
 7629: 	    return $result;
 7630: 	}
 7631: 	my ($map,$resid,$url)=&decode_symb($symb);
 7632: 	my $title='';
 7633: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7634: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7635: 	} else {
 7636: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7637: 		    &GDBM_READER(),0640)) {
 7638: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7639: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7640: 		untie(%bighash);
 7641: 	    }
 7642: 	}
 7643: 	$title=~s/\&colon\;/\:/gs;
 7644: 	if ($title) {
 7645: 	    return &do_cache_new('title',$key,$title,600);
 7646: 	}
 7647: 	$urlsymb=$url;
 7648:     }
 7649:     my $title=&metadata($urlsymb,'title');
 7650:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7651:     return $title;
 7652: }
 7653: 
 7654: sub get_slot {
 7655:     my ($which,$cnum,$cdom)=@_;
 7656:     if (!$cnum || !$cdom) {
 7657: 	(undef,my $courseid)=&whichuser();
 7658: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7659: 	$cnum=$env{'course.'.$courseid.'.num'};
 7660:     }
 7661:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7662:     my %slotinfo;
 7663:     if (exists($remembered{$key})) {
 7664: 	$slotinfo{$which} = $remembered{$key};
 7665:     } else {
 7666: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7667: 	&Apache::lonhomework::showhash(%slotinfo);
 7668: 	my ($tmp)=keys(%slotinfo);
 7669: 	if ($tmp=~/^error:/) { return (); }
 7670: 	$remembered{$key} = $slotinfo{$which};
 7671:     }
 7672:     if (ref($slotinfo{$which}) eq 'HASH') {
 7673: 	return %{$slotinfo{$which}};
 7674:     }
 7675:     return $slotinfo{$which};
 7676: }
 7677: # ------------------------------------------------- Update symbolic store links
 7678: 
 7679: sub symblist {
 7680:     my ($mapname,%newhash)=@_;
 7681:     $mapname=&deversion(&declutter($mapname));
 7682:     my %hash;
 7683:     if (($env{'request.course.fn'}) && (%newhash)) {
 7684:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7685:                       &GDBM_WRCREAT(),0640)) {
 7686: 	    foreach my $url (keys %newhash) {
 7687: 		next if ($url eq 'last_known'
 7688: 			 && $env{'form.no_update_last_known'});
 7689: 		$hash{declutter($url)}=&encode_symb($mapname,
 7690: 						    $newhash{$url}->[1],
 7691: 						    $newhash{$url}->[0]);
 7692:             }
 7693:             if (untie(%hash)) {
 7694: 		return 'ok';
 7695:             }
 7696:         }
 7697:     }
 7698:     return 'error';
 7699: }
 7700: 
 7701: # --------------------------------------------------------------- Verify a symb
 7702: 
 7703: sub symbverify {
 7704:     my ($symb,$thisurl)=@_;
 7705:     my $thisfn=$thisurl;
 7706:     $thisfn=&declutter($thisfn);
 7707: # direct jump to resource in page or to a sequence - will construct own symbs
 7708:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7709: # check URL part
 7710:     my ($map,$resid,$url)=&decode_symb($symb);
 7711: 
 7712:     unless ($url eq $thisfn) { return 0; }
 7713: 
 7714:     $symb=&symbclean($symb);
 7715:     $thisurl=&deversion($thisurl);
 7716:     $thisfn=&deversion($thisfn);
 7717: 
 7718:     my %bighash;
 7719:     my $okay=0;
 7720: 
 7721:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7722:                             &GDBM_READER(),0640)) {
 7723:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7724:         unless ($ids) { 
 7725:            $ids=$bighash{'ids_/'.$thisurl};
 7726:         }
 7727:         if ($ids) {
 7728: # ------------------------------------------------------------------- Has ID(s)
 7729: 	    foreach my $id (split(/\,/,$ids)) {
 7730: 	       my ($mapid,$resid)=split(/\./,$id);
 7731:                if (
 7732:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7733:    eq $symb) { 
 7734: 		   if (($env{'request.role.adv'}) ||
 7735: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7736: 		       $okay=1; 
 7737: 		   }
 7738: 	       }
 7739: 	   }
 7740:         }
 7741: 	untie(%bighash);
 7742:     }
 7743:     return $okay;
 7744: }
 7745: 
 7746: # --------------------------------------------------------------- Clean-up symb
 7747: 
 7748: sub symbclean {
 7749:     my $symb=shift;
 7750:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7751: # remove version from map
 7752:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7753: 
 7754: # remove version from URL
 7755:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7756: 
 7757: # remove wrapper
 7758: 
 7759:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7760:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7761:     return $symb;
 7762: }
 7763: 
 7764: # ---------------------------------------------- Split symb to find map and url
 7765: 
 7766: sub encode_symb {
 7767:     my ($map,$resid,$url)=@_;
 7768:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7769: }
 7770: 
 7771: sub decode_symb {
 7772:     my $symb=shift;
 7773:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7774:     my ($map,$resid,$url)=split(/___/,$symb);
 7775:     return (&fixversion($map),$resid,&fixversion($url));
 7776: }
 7777: 
 7778: sub fixversion {
 7779:     my $fn=shift;
 7780:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7781:     my %bighash;
 7782:     my $uri=&clutter($fn);
 7783:     my $key=$env{'request.course.id'}.'_'.$uri;
 7784: # is this cached?
 7785:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7786:     if (defined($cached)) { return $result; }
 7787: # unfortunately not cached, or expired
 7788:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7789: 	    &GDBM_READER(),0640)) {
 7790:  	if ($bighash{'version_'.$uri}) {
 7791:  	    my $version=$bighash{'version_'.$uri};
 7792:  	    unless (($version eq 'mostrecent') || 
 7793: 		    ($version==&getversion($uri))) {
 7794:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7795:  	    }
 7796:  	}
 7797:  	untie %bighash;
 7798:     }
 7799:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7800: }
 7801: 
 7802: sub deversion {
 7803:     my $url=shift;
 7804:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7805:     return $url;
 7806: }
 7807: 
 7808: # ------------------------------------------------------ Return symb list entry
 7809: 
 7810: sub symbread {
 7811:     my ($thisfn,$donotrecurse)=@_;
 7812:     my $cache_str='request.symbread.cached.'.$thisfn;
 7813:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7814: # no filename provided? try from environment
 7815:     unless ($thisfn) {
 7816:         if ($env{'request.symb'}) {
 7817: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7818: 	}
 7819: 	$thisfn=$env{'request.filename'};
 7820:     }
 7821:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7822: # is that filename actually a symb? Verify, clean, and return
 7823:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7824: 	if (&symbverify($thisfn,$1)) {
 7825: 	    return $env{$cache_str}=&symbclean($thisfn);
 7826: 	}
 7827:     }
 7828:     $thisfn=declutter($thisfn);
 7829:     my %hash;
 7830:     my %bighash;
 7831:     my $syval='';
 7832:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7833:         my $targetfn = $thisfn;
 7834:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7835:             $targetfn = 'adm/wrapper/'.$thisfn;
 7836:         }
 7837: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7838: 	    $targetfn=$1;
 7839: 	}
 7840:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7841:                       &GDBM_READER(),0640)) {
 7842: 	    $syval=$hash{$targetfn};
 7843:             untie(%hash);
 7844:         }
 7845: # ---------------------------------------------------------- There was an entry
 7846:         if ($syval) {
 7847: 	    #unless ($syval=~/\_\d+$/) {
 7848: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7849: 		    #&appenv({'request.ambiguous' => $thisfn});
 7850: 		    #return $env{$cache_str}='';
 7851: 		#}    
 7852: 		#$syval.=$1;
 7853: 	    #}
 7854:         } else {
 7855: # ------------------------------------------------------- Was not in symb table
 7856:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7857:                             &GDBM_READER(),0640)) {
 7858: # ---------------------------------------------- Get ID(s) for current resource
 7859:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7860:               unless ($ids) { 
 7861:                  $ids=$bighash{'ids_/'.$thisfn};
 7862:               }
 7863:               unless ($ids) {
 7864: # alias?
 7865: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7866:               }
 7867:               if ($ids) {
 7868: # ------------------------------------------------------------------- Has ID(s)
 7869:                  my @possibilities=split(/\,/,$ids);
 7870:                  if ($#possibilities==0) {
 7871: # ----------------------------------------------- There is only one possibility
 7872: 		     my ($mapid,$resid)=split(/\./,$ids);
 7873: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7874: 						    $resid,$thisfn);
 7875:                  } elsif (!$donotrecurse) {
 7876: # ------------------------------------------ There is more than one possibility
 7877:                      my $realpossible=0;
 7878:                      foreach my $id (@possibilities) {
 7879: 			 my $file=$bighash{'src_'.$id};
 7880:                          if (&allowed('bre',$file)) {
 7881:          		    my ($mapid,$resid)=split(/\./,$id);
 7882:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7883: 				$realpossible++;
 7884:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7885: 						    $resid,$thisfn);
 7886:                             }
 7887: 			 }
 7888:                      }
 7889: 		     if ($realpossible!=1) { $syval=''; }
 7890:                  } else {
 7891:                      $syval='';
 7892:                  }
 7893: 	      }
 7894:               untie(%bighash)
 7895:            }
 7896:         }
 7897:         if ($syval) {
 7898: 	    return $env{$cache_str}=$syval;
 7899:         }
 7900:     }
 7901:     &appenv({'request.ambiguous' => $thisfn});
 7902:     return $env{$cache_str}='';
 7903: }
 7904: 
 7905: # ---------------------------------------------------------- Return random seed
 7906: 
 7907: sub numval {
 7908:     my $txt=shift;
 7909:     $txt=~tr/A-J/0-9/;
 7910:     $txt=~tr/a-j/0-9/;
 7911:     $txt=~tr/K-T/0-9/;
 7912:     $txt=~tr/k-t/0-9/;
 7913:     $txt=~tr/U-Z/0-5/;
 7914:     $txt=~tr/u-z/0-5/;
 7915:     $txt=~s/\D//g;
 7916:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7917:     return int($txt);
 7918: }
 7919: 
 7920: sub numval2 {
 7921:     my $txt=shift;
 7922:     $txt=~tr/A-J/0-9/;
 7923:     $txt=~tr/a-j/0-9/;
 7924:     $txt=~tr/K-T/0-9/;
 7925:     $txt=~tr/k-t/0-9/;
 7926:     $txt=~tr/U-Z/0-5/;
 7927:     $txt=~tr/u-z/0-5/;
 7928:     $txt=~s/\D//g;
 7929:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7930:     my $total;
 7931:     foreach my $val (@txts) { $total+=$val; }
 7932:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7933:     return int($total);
 7934: }
 7935: 
 7936: sub numval3 {
 7937:     use integer;
 7938:     my $txt=shift;
 7939:     $txt=~tr/A-J/0-9/;
 7940:     $txt=~tr/a-j/0-9/;
 7941:     $txt=~tr/K-T/0-9/;
 7942:     $txt=~tr/k-t/0-9/;
 7943:     $txt=~tr/U-Z/0-5/;
 7944:     $txt=~tr/u-z/0-5/;
 7945:     $txt=~s/\D//g;
 7946:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7947:     my $total;
 7948:     foreach my $val (@txts) { $total+=$val; }
 7949:     if ($_64bit) { $total=(($total<<32)>>32); }
 7950:     return $total;
 7951: }
 7952: 
 7953: sub digest {
 7954:     my ($data)=@_;
 7955:     my $digest=&Digest::MD5::md5($data);
 7956:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7957:     my ($e,$f);
 7958:     {
 7959:         use integer;
 7960:         $e=($a+$b);
 7961:         $f=($c+$d);
 7962:         if ($_64bit) {
 7963:             $e=(($e<<32)>>32);
 7964:             $f=(($f<<32)>>32);
 7965:         }
 7966:     }
 7967:     if (wantarray) {
 7968: 	return ($e,$f);
 7969:     } else {
 7970: 	my $g;
 7971: 	{
 7972: 	    use integer;
 7973: 	    $g=($e+$f);
 7974: 	    if ($_64bit) {
 7975: 		$g=(($g<<32)>>32);
 7976: 	    }
 7977: 	}
 7978: 	return $g;
 7979:     }
 7980: }
 7981: 
 7982: sub latest_rnd_algorithm_id {
 7983:     return '64bit5';
 7984: }
 7985: 
 7986: sub get_rand_alg {
 7987:     my ($courseid)=@_;
 7988:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7989:     if ($courseid) {
 7990: 	return $env{"course.$courseid.rndseed"};
 7991:     }
 7992:     return &latest_rnd_algorithm_id();
 7993: }
 7994: 
 7995: sub validCODE {
 7996:     my ($CODE)=@_;
 7997:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7998:     return 0;
 7999: }
 8000: 
 8001: sub getCODE {
 8002:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8003:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8004: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8005: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8006: 	return $Apache::lonhomework::history{'resource.CODE'};
 8007:     }
 8008:     return undef;
 8009: }
 8010: 
 8011: sub rndseed {
 8012:     my ($symb,$courseid,$domain,$username)=@_;
 8013:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8014:     if (!defined($symb)) {
 8015: 	unless ($symb=$wsymb) { return time; }
 8016:     }
 8017:     if (!$courseid) { $courseid=$wcourseid; }
 8018:     if (!$domain) { $domain=$wdomain; }
 8019:     if (!$username) { $username=$wusername }
 8020:     my $which=&get_rand_alg();
 8021: 
 8022:     if (defined(&getCODE())) {
 8023: 	if ($which eq '64bit5') {
 8024: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8025: 	} elsif ($which eq '64bit4') {
 8026: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8027: 	} else {
 8028: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8029: 	}
 8030:     } elsif ($which eq '64bit5') {
 8031: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8032:     } elsif ($which eq '64bit4') {
 8033: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8034:     } elsif ($which eq '64bit3') {
 8035: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8036:     } elsif ($which eq '64bit2') {
 8037: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8038:     } elsif ($which eq '64bit') {
 8039: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8040:     }
 8041:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8042: }
 8043: 
 8044: sub rndseed_32bit {
 8045:     my ($symb,$courseid,$domain,$username)=@_;
 8046:     {
 8047: 	use integer;
 8048: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8049: 	my $symbseed=numval($symb) << 22;
 8050: 	my $namechck=unpack("%32C*",$username) << 17;
 8051: 	my $nameseed=numval($username) << 12;
 8052: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8053: 	my $courseseed=unpack("%32C*",$courseid);
 8054: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8055: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8056: 	#&logthis("rndseed :$num:$symb");
 8057: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8058: 	return $num;
 8059:     }
 8060: }
 8061: 
 8062: sub rndseed_64bit {
 8063:     my ($symb,$courseid,$domain,$username)=@_;
 8064:     {
 8065: 	use integer;
 8066: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8067: 	my $symbseed=numval($symb) << 10;
 8068: 	my $namechck=unpack("%32S*",$username);
 8069: 	
 8070: 	my $nameseed=numval($username) << 21;
 8071: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8072: 	my $courseseed=unpack("%32S*",$courseid);
 8073: 	
 8074: 	my $num1=$symbchck+$symbseed+$namechck;
 8075: 	my $num2=$nameseed+$domainseed+$courseseed;
 8076: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8077: 	#&logthis("rndseed :$num:$symb");
 8078: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8079: 	return "$num1,$num2";
 8080:     }
 8081: }
 8082: 
 8083: sub rndseed_64bit2 {
 8084:     my ($symb,$courseid,$domain,$username)=@_;
 8085:     {
 8086: 	use integer;
 8087: 	# strings need to be an even # of cahracters long, it it is odd the
 8088:         # last characters gets thrown away
 8089: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8090: 	my $symbseed=numval($symb) << 10;
 8091: 	my $namechck=unpack("%32S*",$username.' ');
 8092: 	
 8093: 	my $nameseed=numval($username) << 21;
 8094: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8095: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8096: 	
 8097: 	my $num1=$symbchck+$symbseed+$namechck;
 8098: 	my $num2=$nameseed+$domainseed+$courseseed;
 8099: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8100: 	#&logthis("rndseed :$num:$symb");
 8101: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8102: 	return "$num1,$num2";
 8103:     }
 8104: }
 8105: 
 8106: sub rndseed_64bit3 {
 8107:     my ($symb,$courseid,$domain,$username)=@_;
 8108:     {
 8109: 	use integer;
 8110: 	# strings need to be an even # of cahracters long, it it is odd the
 8111:         # last characters gets thrown away
 8112: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8113: 	my $symbseed=numval2($symb) << 10;
 8114: 	my $namechck=unpack("%32S*",$username.' ');
 8115: 	
 8116: 	my $nameseed=numval2($username) << 21;
 8117: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8118: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8119: 	
 8120: 	my $num1=$symbchck+$symbseed+$namechck;
 8121: 	my $num2=$nameseed+$domainseed+$courseseed;
 8122: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8123: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8124: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8125: 	
 8126: 	return "$num1:$num2";
 8127:     }
 8128: }
 8129: 
 8130: sub rndseed_64bit4 {
 8131:     my ($symb,$courseid,$domain,$username)=@_;
 8132:     {
 8133: 	use integer;
 8134: 	# strings need to be an even # of cahracters long, it it is odd the
 8135:         # last characters gets thrown away
 8136: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8137: 	my $symbseed=numval3($symb) << 10;
 8138: 	my $namechck=unpack("%32S*",$username.' ');
 8139: 	
 8140: 	my $nameseed=numval3($username) << 21;
 8141: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8142: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8143: 	
 8144: 	my $num1=$symbchck+$symbseed+$namechck;
 8145: 	my $num2=$nameseed+$domainseed+$courseseed;
 8146: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8147: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8148: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8149: 	
 8150: 	return "$num1:$num2";
 8151:     }
 8152: }
 8153: 
 8154: sub rndseed_64bit5 {
 8155:     my ($symb,$courseid,$domain,$username)=@_;
 8156:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8157:     return "$num1:$num2";
 8158: }
 8159: 
 8160: sub rndseed_CODE_64bit {
 8161:     my ($symb,$courseid,$domain,$username)=@_;
 8162:     {
 8163: 	use integer;
 8164: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8165: 	my $symbseed=numval2($symb);
 8166: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8167: 	my $CODEseed=numval(&getCODE());
 8168: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8169: 	my $num1=$symbseed+$CODEchck;
 8170: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8171: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8172: 	#&logthis("rndseed :$num1:$num2:$symb");
 8173: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8174: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8175: 	return "$num1:$num2";
 8176:     }
 8177: }
 8178: 
 8179: sub rndseed_CODE_64bit4 {
 8180:     my ($symb,$courseid,$domain,$username)=@_;
 8181:     {
 8182: 	use integer;
 8183: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8184: 	my $symbseed=numval3($symb);
 8185: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8186: 	my $CODEseed=numval3(&getCODE());
 8187: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8188: 	my $num1=$symbseed+$CODEchck;
 8189: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8190: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8191: 	#&logthis("rndseed :$num1:$num2:$symb");
 8192: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8193: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8194: 	return "$num1:$num2";
 8195:     }
 8196: }
 8197: 
 8198: sub rndseed_CODE_64bit5 {
 8199:     my ($symb,$courseid,$domain,$username)=@_;
 8200:     my $code = &getCODE();
 8201:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8202:     return "$num1:$num2";
 8203: }
 8204: 
 8205: sub setup_random_from_rndseed {
 8206:     my ($rndseed)=@_;
 8207:     if ($rndseed =~/([,:])/) {
 8208: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8209: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8210:     } else {
 8211: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8212:     }
 8213: }
 8214: 
 8215: sub latest_receipt_algorithm_id {
 8216:     return 'receipt3';
 8217: }
 8218: 
 8219: sub recunique {
 8220:     my $fucourseid=shift;
 8221:     my $unique;
 8222:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8223: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8224: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8225:     } else {
 8226: 	$unique=$perlvar{'lonReceipt'};
 8227:     }
 8228:     return unpack("%32C*",$unique);
 8229: }
 8230: 
 8231: sub recprefix {
 8232:     my $fucourseid=shift;
 8233:     my $prefix;
 8234:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8235: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8236: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8237:     } else {
 8238: 	$prefix=$perlvar{'lonHostID'};
 8239:     }
 8240:     return unpack("%32C*",$prefix);
 8241: }
 8242: 
 8243: sub ireceipt {
 8244:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8245: 
 8246:     my $return =&recprefix($fucourseid).'-';
 8247: 
 8248:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8249: 	$env{'request.state'} eq 'construct') {
 8250: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8251: 	return $return;
 8252:     }
 8253: 
 8254:     my $cuname=unpack("%32C*",$funame);
 8255:     my $cudom=unpack("%32C*",$fudom);
 8256:     my $cucourseid=unpack("%32C*",$fucourseid);
 8257:     my $cusymb=unpack("%32C*",$fusymb);
 8258:     my $cunique=&recunique($fucourseid);
 8259:     my $cpart=unpack("%32S*",$part);
 8260:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8261: 
 8262: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8263: 			       
 8264: 	$return.= ($cunique%$cuname+
 8265: 		   $cunique%$cudom+
 8266: 		   $cusymb%$cuname+
 8267: 		   $cusymb%$cudom+
 8268: 		   $cucourseid%$cuname+
 8269: 		   $cucourseid%$cudom+
 8270: 		   $cpart%$cuname+
 8271: 		   $cpart%$cudom);
 8272:     } else {
 8273: 	$return.= ($cunique%$cuname+
 8274: 		   $cunique%$cudom+
 8275: 		   $cusymb%$cuname+
 8276: 		   $cusymb%$cudom+
 8277: 		   $cucourseid%$cuname+
 8278: 		   $cucourseid%$cudom);
 8279:     }
 8280:     return $return;
 8281: }
 8282: 
 8283: sub receipt {
 8284:     my ($part)=@_;
 8285:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8286:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8287: }
 8288: 
 8289: sub whichuser {
 8290:     my ($passedsymb)=@_;
 8291:     my ($symb,$courseid,$domain,$name,$publicuser);
 8292:     if (defined($env{'form.grade_symb'})) {
 8293: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8294: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8295: 	if (!$allowed &&
 8296: 	    exists($env{'request.course.sec'}) &&
 8297: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8298: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8299: 			      '/'.$env{'request.course.sec'});
 8300: 	}
 8301: 	if ($allowed) {
 8302: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8303: 	    $courseid=$tmp_courseid;
 8304: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8305: 	    ($name)=&get_env_multiple('form.grade_username');
 8306: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8307: 	}
 8308:     }
 8309:     if (!$passedsymb) {
 8310: 	$symb=&symbread();
 8311:     } else {
 8312: 	$symb=$passedsymb;
 8313:     }
 8314:     $courseid=$env{'request.course.id'};
 8315:     $domain=$env{'user.domain'};
 8316:     $name=$env{'user.name'};
 8317:     if ($name eq 'public' && $domain eq 'public') {
 8318: 	if (!defined($env{'form.username'})) {
 8319: 	    $env{'form.username'}.=time.rand(10000000);
 8320: 	}
 8321: 	$name.=$env{'form.username'};
 8322:     }
 8323:     return ($symb,$courseid,$domain,$name,$publicuser);
 8324: 
 8325: }
 8326: 
 8327: # ------------------------------------------------------------ Serves up a file
 8328: # returns either the contents of the file or 
 8329: # -1 if the file doesn't exist
 8330: #
 8331: # if the target is a file that was uploaded via DOCS, 
 8332: # a check will be made to see if a current copy exists on the local server,
 8333: # if it does this will be served, otherwise a copy will be retrieved from
 8334: # the home server for the course and stored in /home/httpd/html/userfiles on
 8335: # the local server.   
 8336: 
 8337: sub getfile {
 8338:     my ($file) = @_;
 8339:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8340:     &repcopy($file);
 8341:     return &readfile($file);
 8342: }
 8343: 
 8344: sub repcopy_userfile {
 8345:     my ($file)=@_;
 8346:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8347:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8348:     my ($cdom,$cnum,$filename) = 
 8349: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8350:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8351:     if (-e "$file") {
 8352: # we already have a local copy, check it out
 8353: 	my @fileinfo = stat($file);
 8354: 	my $rtncode;
 8355: 	my $info;
 8356: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8357: 	if ($lwpresp ne 'ok') {
 8358: # there is no such file anymore, even though we had a local copy
 8359: 	    if ($rtncode eq '404') {
 8360: 		unlink($file);
 8361: 	    }
 8362: 	    return -1;
 8363: 	}
 8364: 	if ($info < $fileinfo[9]) {
 8365: # nice, the file we have is up-to-date, just say okay
 8366: 	    return 'ok';
 8367: 	} else {
 8368: # the file is outdated, get rid of it
 8369: 	    unlink($file);
 8370: 	}
 8371:     }
 8372: # one way or the other, at this point, we don't have the file
 8373: # construct the correct path for the file
 8374:     my @parts = ($cdom,$cnum); 
 8375:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8376: 	push @parts, split(/\//,$1);
 8377:     }
 8378:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8379:     foreach my $part (@parts) {
 8380: 	$path .= '/'.$part;
 8381: 	if (!-e $path) {
 8382: 	    mkdir($path,0770);
 8383: 	}
 8384:     }
 8385: # now the path exists for sure
 8386: # get a user agent
 8387:     my $ua=new LWP::UserAgent;
 8388:     my $transferfile=$file.'.in.transfer';
 8389: # FIXME: this should flock
 8390:     if (-e $transferfile) { return 'ok'; }
 8391:     my $request;
 8392:     $uri=~s/^\///;
 8393:     my $homeserver = &homeserver($cnum,$cdom);
 8394:     my $protocol = $protocol{$homeserver};
 8395:     $protocol = 'http' if ($protocol ne 'https');
 8396:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8397:     my $response=$ua->request($request,$transferfile);
 8398: # did it work?
 8399:     if ($response->is_error()) {
 8400: 	unlink($transferfile);
 8401: 	&logthis("Userfile repcopy failed for $uri");
 8402: 	return -1;
 8403:     }
 8404: # worked, rename the transfer file
 8405:     rename($transferfile,$file);
 8406:     return 'ok';
 8407: }
 8408: 
 8409: sub tokenwrapper {
 8410:     my $uri=shift;
 8411:     $uri=~s|^https?\://([^/]+)||;
 8412:     $uri=~s|^/||;
 8413:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8414:     my $token=$1;
 8415:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8416:     if ($udom && $uname && $file) {
 8417: 	$file=~s|(\?\.*)*$||;
 8418:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8419:         my $homeserver = &homeserver($uname,$udom);
 8420:         my $protocol = $protocol{$homeserver};
 8421:         $protocol = 'http' if ($protocol ne 'https');
 8422:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8423:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8424:                                '&tokenissued='.$perlvar{'lonHostID'};
 8425:     } else {
 8426:         return '/adm/notfound.html';
 8427:     }
 8428: }
 8429: 
 8430: # call with reqtype HEAD: get last modification time
 8431: # call with reqtype GET: get the file contents
 8432: # Do not call this with reqtype GET for large files! It loads everything into memory
 8433: #
 8434: sub getuploaded {
 8435:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8436:     $uri=~s/^\///;
 8437:     my $homeserver = &homeserver($cnum,$cdom);
 8438:     my $protocol = $protocol{$homeserver};
 8439:     $protocol = 'http' if ($protocol ne 'https');
 8440:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8441:     my $ua=new LWP::UserAgent;
 8442:     my $request=new HTTP::Request($reqtype,$uri);
 8443:     my $response=$ua->request($request);
 8444:     $$rtncode = $response->code;
 8445:     if (! $response->is_success()) {
 8446: 	return 'failed';
 8447:     }      
 8448:     if ($reqtype eq 'HEAD') {
 8449: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8450:     } elsif ($reqtype eq 'GET') {
 8451: 	$$info = $response->content;
 8452:     }
 8453:     return 'ok';
 8454: }
 8455: 
 8456: sub readfile {
 8457:     my $file = shift;
 8458:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8459:     my $fh;
 8460:     open($fh,"<$file");
 8461:     my $a='';
 8462:     while (my $line = <$fh>) { $a .= $line; }
 8463:     return $a;
 8464: }
 8465: 
 8466: sub filelocation {
 8467:     my ($dir,$file) = @_;
 8468:     my $location;
 8469:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8470: 
 8471:     if ($file =~ m-^/adm/-) {
 8472: 	$file=~s-^/adm/wrapper/-/-;
 8473: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8474:     }
 8475: 
 8476:     if ($file=~m:^/~:) { # is a contruction space reference
 8477:         $location = $file;
 8478:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8479:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8480: 	# is a correct contruction space reference
 8481:         $location = $file;
 8482:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8483:         $location = $file;
 8484:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8485:         my ($udom,$uname,$filename)=
 8486:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8487:         my $home=&homeserver($uname,$udom);
 8488:         my $is_me=0;
 8489:         my @ids=&current_machine_ids();
 8490:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8491:         if ($is_me) {
 8492:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8493:         } else {
 8494:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8495:   	      $udom.'/'.$uname.'/'.$filename;
 8496:         }
 8497:     } elsif ($file =~ m-^/adm/-) {
 8498: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8499:     } else {
 8500:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8501:         $file=~s:^/res/:/:;
 8502:         if ( !( $file =~ m:^/:) ) {
 8503:             $location = $dir. '/'.$file;
 8504:         } else {
 8505:             $location = '/home/httpd/html/res'.$file;
 8506:         }
 8507:     }
 8508:     $location=~s://+:/:g; # remove duplicate /
 8509:     while ($location=~m{/\.\./}) {
 8510: 	if ($location =~ m{/[^/]+/\.\./}) {
 8511: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8512: 	} else {
 8513: 	    $location=~ s{/\.\./}{/}g;
 8514: 	}
 8515:     } #remove dir/..
 8516:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8517:     return $location;
 8518: }
 8519: 
 8520: sub hreflocation {
 8521:     my ($dir,$file)=@_;
 8522:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8523: 	$file=filelocation($dir,$file);
 8524:     } elsif ($file=~m-^/adm/-) {
 8525: 	$file=~s-^/adm/wrapper/-/-;
 8526: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8527:     }
 8528:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8529: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8530:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8531: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8532:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8533: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8534: 	    -/uploaded/$1/$2/-x;
 8535:     }
 8536:     if ($file=~ m{^/userfiles/}) {
 8537: 	$file =~ s{^/userfiles/}{/uploaded/};
 8538:     }
 8539:     return $file;
 8540: }
 8541: 
 8542: sub current_machine_domains {
 8543:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8544: }
 8545: 
 8546: sub machine_domains {
 8547:     my ($hostname) = @_;
 8548:     my @domains;
 8549:     my %hostname = &all_hostnames();
 8550:     while( my($id, $name) = each(%hostname)) {
 8551: #	&logthis("-$id-$name-$hostname-");
 8552: 	if ($hostname eq $name) {
 8553: 	    push(@domains,&host_domain($id));
 8554: 	}
 8555:     }
 8556:     return @domains;
 8557: }
 8558: 
 8559: sub current_machine_ids {
 8560:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8561: }
 8562: 
 8563: sub machine_ids {
 8564:     my ($hostname) = @_;
 8565:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8566:     my @ids;
 8567:     my %name_to_host = &all_names();
 8568:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8569: 	return @{ $name_to_host{$hostname} };
 8570:     }
 8571:     return;
 8572: }
 8573: 
 8574: sub additional_machine_domains {
 8575:     my @domains;
 8576:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8577:     while( my $line = <$fh>) {
 8578:         $line =~ s/\s//g;
 8579:         push(@domains,$line);
 8580:     }
 8581:     return @domains;
 8582: }
 8583: 
 8584: sub default_login_domain {
 8585:     my $domain = $perlvar{'lonDefDomain'};
 8586:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8587:     foreach my $posdom (&current_machine_domains(),
 8588:                         &additional_machine_domains()) {
 8589:         if (lc($posdom) eq lc($testdomain)) {
 8590:             $domain=$posdom;
 8591:             last;
 8592:         }
 8593:     }
 8594:     return $domain;
 8595: }
 8596: 
 8597: # ------------------------------------------------------------- Declutters URLs
 8598: 
 8599: sub declutter {
 8600:     my $thisfn=shift;
 8601:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8602:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8603:     $thisfn=~s/^\///;
 8604:     $thisfn=~s|^adm/wrapper/||;
 8605:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8606:     $thisfn=~s/^res\///;
 8607:     $thisfn=~s/\?.+$//;
 8608:     return $thisfn;
 8609: }
 8610: 
 8611: # ------------------------------------------------------------- Clutter up URLs
 8612: 
 8613: sub clutter {
 8614:     my $thisfn='/'.&declutter(shift);
 8615:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8616: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8617:        $thisfn='/res'.$thisfn; 
 8618:     }
 8619:     if ($thisfn !~m|/adm|) {
 8620: 	if ($thisfn =~ m|/ext/|) {
 8621: 	    $thisfn='/adm/wrapper'.$thisfn;
 8622: 	} else {
 8623: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8624: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8625: 	    if ($embstyle eq 'ssi'
 8626: 		|| ($embstyle eq 'hdn')
 8627: 		|| ($embstyle eq 'rat')
 8628: 		|| ($embstyle eq 'prv')
 8629: 		|| ($embstyle eq 'ign')) {
 8630: 		#do nothing with these
 8631: 	    } elsif (($embstyle eq 'img') 
 8632: 		|| ($embstyle eq 'emb')
 8633: 		|| ($embstyle eq 'wrp')) {
 8634: 		$thisfn='/adm/wrapper'.$thisfn;
 8635: 	    } elsif ($embstyle eq 'unk'
 8636: 		     && $thisfn!~/\.(sequence|page)$/) {
 8637: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8638: 	    } else {
 8639: #		&logthis("Got a blank emb style");
 8640: 	    }
 8641: 	}
 8642:     }
 8643:     return $thisfn;
 8644: }
 8645: 
 8646: sub clutter_with_no_wrapper {
 8647:     my $uri = &clutter(shift);
 8648:     if ($uri =~ m-^/adm/-) {
 8649: 	$uri =~ s-^/adm/wrapper/-/-;
 8650: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8651:     }
 8652:     return $uri;
 8653: }
 8654: 
 8655: sub freeze_escape {
 8656:     my ($value)=@_;
 8657:     if (ref($value)) {
 8658: 	$value=&nfreeze($value);
 8659: 	return '__FROZEN__'.&escape($value);
 8660:     }
 8661:     return &escape($value);
 8662: }
 8663: 
 8664: 
 8665: sub thaw_unescape {
 8666:     my ($value)=@_;
 8667:     if ($value =~ /^__FROZEN__/) {
 8668: 	substr($value,0,10,undef);
 8669: 	$value=&unescape($value);
 8670: 	return &thaw($value);
 8671:     }
 8672:     return &unescape($value);
 8673: }
 8674: 
 8675: sub correct_line_ends {
 8676:     my ($result)=@_;
 8677:     $$result =~s/\r\n/\n/mg;
 8678:     $$result =~s/\r/\n/mg;
 8679: }
 8680: # ================================================================ Main Program
 8681: 
 8682: sub goodbye {
 8683:    &logthis("Starting Shut down");
 8684: #not converted to using infrastruture and probably shouldn't be
 8685:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8686: #converted
 8687: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8688:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8689: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8690: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8691: #1.1 only
 8692: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8693: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8694: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8695: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8696:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8697:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8698:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8699:    &flushcourselogs();
 8700:    &logthis("Shutting down");
 8701: }
 8702: 
 8703: sub get_dns {
 8704:     my ($url,$func,$ignore_cache) = @_;
 8705:     if (!$ignore_cache) {
 8706: 	my ($content,$cached)=
 8707: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8708: 	if ($cached) {
 8709: 	    &$func($content);
 8710: 	    return;
 8711: 	}
 8712:     }
 8713: 
 8714:     my %alldns;
 8715:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8716:     foreach my $dns (<$config>) {
 8717: 	next if ($dns !~ /^\^(\S*)/x);
 8718:         my $line = $1;
 8719:         my ($host,$protocol) = split(/:/,$line);
 8720:         if ($protocol ne 'https') {
 8721:             $protocol = 'http';
 8722:         }
 8723: 	$alldns{$host} = $protocol;
 8724:     }
 8725:     while (%alldns) {
 8726: 	my ($dns) = keys(%alldns);
 8727: 	my $ua=new LWP::UserAgent;
 8728: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8729: 	my $response=$ua->request($request);
 8730:         delete($alldns{$dns});
 8731: 	next if ($response->is_error());
 8732: 	my @content = split("\n",$response->content);
 8733: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8734: 	&$func(\@content);
 8735: 	return;
 8736:     }
 8737:     close($config);
 8738:     my $which = (split('/',$url))[3];
 8739:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8740:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8741:     my @content = <$config>;
 8742:     &$func(\@content);
 8743:     return;
 8744: }
 8745: # ------------------------------------------------------------ Read domain file
 8746: {
 8747:     my $loaded;
 8748:     my %domain;
 8749: 
 8750:     sub parse_domain_tab {
 8751: 	my ($lines) = @_;
 8752: 	foreach my $line (@$lines) {
 8753: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8754: 
 8755: 	    chomp($line);
 8756: 	    my ($name,@elements) = split(/:/,$line,9);
 8757: 	    my %this_domain;
 8758: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8759: 			       'lang_def', 'city', 'longi', 'lati',
 8760: 			       'primary') {
 8761: 		$this_domain{$field} = shift(@elements);
 8762: 	    }
 8763: 	    $domain{$name} = \%this_domain;
 8764: 	}
 8765:     }
 8766: 
 8767:     sub reset_domain_info {
 8768: 	undef($loaded);
 8769: 	undef(%domain);
 8770:     }
 8771: 
 8772:     sub load_domain_tab {
 8773: 	my ($ignore_cache) = @_;
 8774: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8775: 	my $fh;
 8776: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8777: 	    my @lines = <$fh>;
 8778: 	    &parse_domain_tab(\@lines);
 8779: 	}
 8780: 	close($fh);
 8781: 	$loaded = 1;
 8782:     }
 8783: 
 8784:     sub domain {
 8785: 	&load_domain_tab() if (!$loaded);
 8786: 
 8787: 	my ($name,$what) = @_;
 8788: 	return if ( !exists($domain{$name}) );
 8789: 
 8790: 	if (!$what) {
 8791: 	    return $domain{$name}{'description'};
 8792: 	}
 8793: 	return $domain{$name}{$what};
 8794:     }
 8795: 
 8796:     sub domain_info {
 8797:         &load_domain_tab() if (!$loaded);
 8798:         return %domain;
 8799:     }
 8800: 
 8801: }
 8802: 
 8803: 
 8804: # ------------------------------------------------------------- Read hosts file
 8805: {
 8806:     my %hostname;
 8807:     my %hostdom;
 8808:     my %libserv;
 8809:     my $loaded;
 8810:     my %name_to_host;
 8811: 
 8812:     sub parse_hosts_tab {
 8813: 	my ($file) = @_;
 8814: 	foreach my $configline (@$file) {
 8815: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8816: 	    next if ($configline =~ /^\^/);
 8817: 	    chomp($configline);
 8818: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8819: 	    $name=~s/\s//g;
 8820: 	    if ($id && $domain && $role && $name) {
 8821: 		$hostname{$id}=$name;
 8822: 		push(@{$name_to_host{$name}}, $id);
 8823: 		$hostdom{$id}=$domain;
 8824: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8825:                 if (defined($protocol)) {
 8826:                     if ($protocol eq 'https') {
 8827:                         $protocol{$id} = $protocol;
 8828:                     } else {
 8829:                         $protocol{$id} = 'http'; 
 8830:                     }
 8831:                 } else {
 8832:                     $protocol{$id} = 'http';
 8833:                 }
 8834: 	    }
 8835: 	}
 8836:     }
 8837:     
 8838:     sub reset_hosts_info {
 8839: 	&purge_remembered();
 8840: 	&reset_domain_info();
 8841: 	&reset_hosts_ip_info();
 8842: 	undef(%name_to_host);
 8843: 	undef(%hostname);
 8844: 	undef(%hostdom);
 8845: 	undef(%libserv);
 8846: 	undef($loaded);
 8847:     }
 8848: 
 8849:     sub load_hosts_tab {
 8850: 	my ($ignore_cache) = @_;
 8851: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8852: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8853: 	my @config = <$config>;
 8854: 	&parse_hosts_tab(\@config);
 8855: 	close($config);
 8856: 	$loaded=1;
 8857:     }
 8858: 
 8859:     sub hostname {
 8860: 	&load_hosts_tab() if (!$loaded);
 8861: 
 8862: 	my ($lonid) = @_;
 8863: 	return $hostname{$lonid};
 8864:     }
 8865: 
 8866:     sub all_hostnames {
 8867: 	&load_hosts_tab() if (!$loaded);
 8868: 
 8869: 	return %hostname;
 8870:     }
 8871: 
 8872:     sub all_names {
 8873: 	&load_hosts_tab() if (!$loaded);
 8874: 
 8875: 	return %name_to_host;
 8876:     }
 8877: 
 8878:     sub all_host_domain {
 8879:         &load_hosts_tab() if (!$loaded);
 8880:         return %hostdom;
 8881:     }
 8882: 
 8883:     sub is_library {
 8884: 	&load_hosts_tab() if (!$loaded);
 8885: 
 8886: 	return exists($libserv{$_[0]});
 8887:     }
 8888: 
 8889:     sub all_library {
 8890: 	&load_hosts_tab() if (!$loaded);
 8891: 
 8892: 	return %libserv;
 8893:     }
 8894: 
 8895:     sub get_servers {
 8896: 	&load_hosts_tab() if (!$loaded);
 8897: 
 8898: 	my ($domain,$type) = @_;
 8899: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8900: 	                                          : %hostname;
 8901: 	my %result;
 8902: 	if (ref($domain) eq 'ARRAY') {
 8903: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8904: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8905: 		    $result{$host} = $hostname;
 8906: 		}
 8907: 	    }
 8908: 	} else {
 8909: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8910: 		if ($hostdom{$host} eq $domain) {
 8911: 		    $result{$host} = $hostname;
 8912: 		}
 8913: 	    }
 8914: 	}
 8915: 	return %result;
 8916:     }
 8917: 
 8918:     sub host_domain {
 8919: 	&load_hosts_tab() if (!$loaded);
 8920: 
 8921: 	my ($lonid) = @_;
 8922: 	return $hostdom{$lonid};
 8923:     }
 8924: 
 8925:     sub all_domains {
 8926: 	&load_hosts_tab() if (!$loaded);
 8927: 
 8928: 	my %seen;
 8929: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8930: 	return @uniq;
 8931:     }
 8932: }
 8933: 
 8934: { 
 8935:     my %iphost;
 8936:     my %name_to_ip;
 8937:     my %lonid_to_ip;
 8938: 
 8939:     sub get_hosts_from_ip {
 8940: 	my ($ip) = @_;
 8941: 	my %iphosts = &get_iphost();
 8942: 	if (ref($iphosts{$ip})) {
 8943: 	    return @{$iphosts{$ip}};
 8944: 	}
 8945: 	return;
 8946:     }
 8947:     
 8948:     sub reset_hosts_ip_info {
 8949: 	undef(%iphost);
 8950: 	undef(%name_to_ip);
 8951: 	undef(%lonid_to_ip);
 8952:     }
 8953: 
 8954:     sub get_host_ip {
 8955: 	my ($lonid) = @_;
 8956: 	if (exists($lonid_to_ip{$lonid})) {
 8957: 	    return $lonid_to_ip{$lonid};
 8958: 	}
 8959: 	my $name=&hostname($lonid);
 8960:    	my $ip = gethostbyname($name);
 8961: 	return if (!$ip || length($ip) ne 4);
 8962: 	$ip=inet_ntoa($ip);
 8963: 	$name_to_ip{$name}   = $ip;
 8964: 	$lonid_to_ip{$lonid} = $ip;
 8965: 	return $ip;
 8966:     }
 8967:     
 8968:     sub get_iphost {
 8969: 	my ($ignore_cache) = @_;
 8970: 
 8971: 	if (!$ignore_cache) {
 8972: 	    if (%iphost) {
 8973: 		return %iphost;
 8974: 	    }
 8975: 	    my ($ip_info,$cached)=
 8976: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8977: 	    if ($cached) {
 8978: 		%iphost      = %{$ip_info->[0]};
 8979: 		%name_to_ip  = %{$ip_info->[1]};
 8980: 		%lonid_to_ip = %{$ip_info->[2]};
 8981: 		return %iphost;
 8982: 	    }
 8983: 	}
 8984: 
 8985: 	# get yesterday's info for fallback
 8986: 	my %old_name_to_ip;
 8987: 	my ($ip_info,$cached)=
 8988: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8989: 	if ($cached) {
 8990: 	    %old_name_to_ip = %{$ip_info->[1]};
 8991: 	}
 8992: 
 8993: 	my %name_to_host = &all_names();
 8994: 	foreach my $name (keys(%name_to_host)) {
 8995: 	    my $ip;
 8996: 	    if (!exists($name_to_ip{$name})) {
 8997: 		$ip = gethostbyname($name);
 8998: 		if (!$ip || length($ip) ne 4) {
 8999: 		    if (defined($old_name_to_ip{$name})) {
 9000: 			$ip = $old_name_to_ip{$name};
 9001: 			&logthis("Can't find $name defaulting to old $ip");
 9002: 		    } else {
 9003: 			&logthis("Name $name no IP found");
 9004: 			next;
 9005: 		    }
 9006: 		} else {
 9007: 		    $ip=inet_ntoa($ip);
 9008: 		}
 9009: 		$name_to_ip{$name} = $ip;
 9010: 	    } else {
 9011: 		$ip = $name_to_ip{$name};
 9012: 	    }
 9013: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9014: 		$lonid_to_ip{$id} = $ip;
 9015: 	    }
 9016: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9017: 	}
 9018: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9019: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9020: 				      48*60*60);
 9021: 
 9022: 	return %iphost;
 9023:     }
 9024: }
 9025: 
 9026: #
 9027: #  Given a DNS returns the loncapa host name for that DNS 
 9028: # 
 9029: sub host_from_dns {
 9030:     my ($dns) = @_;
 9031:     my @hosts;
 9032:     my $ip;
 9033: 
 9034:     $ip = gethostbyname($dns);	# Initial translation to IP is in net order.
 9035:     if (length($ip) == 4) { 
 9036: 	$ip   = &IO::Socket::inet_ntoa($ip);
 9037: 	@hosts = get_hosts_from_ip($ip);
 9038: 	return $hosts[0];
 9039:     }
 9040:     return undef;
 9041: }
 9042: 
 9043: BEGIN {
 9044: 
 9045: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9046:     unless ($readit) {
 9047: {
 9048:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9049:     %perlvar = (%perlvar,%{$configvars});
 9050: }
 9051: 
 9052: 
 9053: # ------------------------------------------------------ Read spare server file
 9054: {
 9055:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9056: 
 9057:     while (my $configline=<$config>) {
 9058:        chomp($configline);
 9059:        if ($configline) {
 9060: 	   my ($host,$type) = split(':',$configline,2);
 9061: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9062: 	   push(@{ $spareid{$type} }, $host);
 9063:        }
 9064:     }
 9065:     close($config);
 9066: }
 9067: # ------------------------------------------------------------ Read permissions
 9068: {
 9069:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9070: 
 9071:     while (my $configline=<$config>) {
 9072: 	chomp($configline);
 9073: 	if ($configline) {
 9074: 	    my ($role,$perm)=split(/ /,$configline);
 9075: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9076: 	}
 9077:     }
 9078:     close($config);
 9079: }
 9080: 
 9081: # -------------------------------------------- Read plain texts for permissions
 9082: {
 9083:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9084: 
 9085:     while (my $configline=<$config>) {
 9086: 	chomp($configline);
 9087: 	if ($configline) {
 9088: 	    my ($short,@plain)=split(/:/,$configline);
 9089:             %{$prp{$short}} = ();
 9090: 	    if (@plain > 0) {
 9091:                 $prp{$short}{'std'} = $plain[0];
 9092:                 for (my $i=1; $i<@plain; $i++) {
 9093:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9094:                 }
 9095:             }
 9096: 	}
 9097:     }
 9098:     close($config);
 9099: }
 9100: 
 9101: # ---------------------------------------------------------- Read package table
 9102: {
 9103:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9104: 
 9105:     while (my $configline=<$config>) {
 9106: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9107: 	chomp($configline);
 9108: 	my ($short,$plain)=split(/:/,$configline);
 9109: 	my ($pack,$name)=split(/\&/,$short);
 9110: 	if ($plain ne '') {
 9111: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9112: 	    $packagetab{$short}=$plain; 
 9113: 	}
 9114:     }
 9115:     close($config);
 9116: }
 9117: 
 9118: # ------------- set up temporary directory
 9119: {
 9120:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9121: 
 9122: }
 9123: 
 9124: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9125: 				'compress_threshold'=> 20_000,
 9126:  			        });
 9127: 
 9128: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9129: $dumpcount=0;
 9130: $locknum=0;
 9131: 
 9132: &logtouch();
 9133: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9134: $readit=1;
 9135:     {
 9136: 	use integer;
 9137: 	my $test=(2**32)+1;
 9138: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9139: 	&logthis(" Detected 64bit platform ($_64bit)");
 9140:     }
 9141: }
 9142: }
 9143: 
 9144: 1;
 9145: __END__
 9146: 
 9147: =pod
 9148: 
 9149: =head1 NAME
 9150: 
 9151: Apache::lonnet - Subroutines to ask questions about things in the network.
 9152: 
 9153: =head1 SYNOPSIS
 9154: 
 9155: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9156: 
 9157:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9158: 
 9159: Common parameters:
 9160: 
 9161: =over 4
 9162: 
 9163: =item *
 9164: 
 9165: $uname : an internal username (if $cname expecting a course Id specifically)
 9166: 
 9167: =item *
 9168: 
 9169: $udom : a domain (if $cdom expecting a course's domain specifically)
 9170: 
 9171: =item *
 9172: 
 9173: $symb : a resource instance identifier
 9174: 
 9175: =item *
 9176: 
 9177: $namespace : the name of a .db file that contains the data needed or
 9178: being set.
 9179: 
 9180: =back
 9181: 
 9182: =head1 OVERVIEW
 9183: 
 9184: lonnet provides subroutines which interact with the
 9185: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9186: about classes, users, and resources.
 9187: 
 9188: For many of these objects you can also use this to store data about
 9189: them or modify them in various ways.
 9190: 
 9191: =head2 Symbs
 9192: 
 9193: To identify a specific instance of a resource, LON-CAPA uses symbols
 9194: or "symbs"X<symb>. These identifiers are built from the URL of the
 9195: map, the resource number of the resource in the map, and the URL of
 9196: the resource itself. The latter is somewhat redundant, but might help
 9197: if maps change.
 9198: 
 9199: An example is
 9200: 
 9201:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9202: 
 9203: The respective map entry is
 9204: 
 9205:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9206:   title="Problem 2">
 9207:  </resource>
 9208: 
 9209: Symbs are used by the random number generator, as well as to store and
 9210: restore data specific to a certain instance of for example a problem.
 9211: 
 9212: =head2 Storing And Retrieving Data
 9213: 
 9214: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9215: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9216: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9217: is is the non-critical message twin of cstore. These functions are for
 9218: handlers to store a perl hash to a user's permanent data space in an
 9219: easy manner, and to retrieve it again on another call. It is expected
 9220: that a handler would use this once at the beginning to retrieve data,
 9221: and then again once at the end to send only the new data back.
 9222: 
 9223: The data is stored in the user's data directory on the user's
 9224: homeserver under the ID of the course.
 9225: 
 9226: The hash that is returned by restore will have all of the previous
 9227: value for all of the elements of the hash.
 9228: 
 9229: Example:
 9230: 
 9231:  #creating a hash
 9232:  my %hash;
 9233:  $hash{'foo'}='bar';
 9234: 
 9235:  #storing it
 9236:  &Apache::lonnet::cstore(\%hash);
 9237: 
 9238:  #changing a value
 9239:  $hash{'foo'}='notbar';
 9240: 
 9241:  #adding a new value
 9242:  $hash{'bar'}='foo';
 9243:  &Apache::lonnet::cstore(\%hash);
 9244: 
 9245:  #retrieving the hash
 9246:  my %history=&Apache::lonnet::restore();
 9247: 
 9248:  #print the hash
 9249:  foreach my $key (sort(keys(%history))) {
 9250:    print("\%history{$key} = $history{$key}");
 9251:  }
 9252: 
 9253: Will print out:
 9254: 
 9255:  %history{1:foo} = bar
 9256:  %history{1:keys} = foo:timestamp
 9257:  %history{1:timestamp} = 990455579
 9258:  %history{2:bar} = foo
 9259:  %history{2:foo} = notbar
 9260:  %history{2:keys} = foo:bar:timestamp
 9261:  %history{2:timestamp} = 990455580
 9262:  %history{bar} = foo
 9263:  %history{foo} = notbar
 9264:  %history{timestamp} = 990455580
 9265:  %history{version} = 2
 9266: 
 9267: Note that the special hash entries C<keys>, C<version> and
 9268: C<timestamp> were added to the hash. C<version> will be equal to the
 9269: total number of versions of the data that have been stored. The
 9270: C<timestamp> attribute will be the UNIX time the hash was
 9271: stored. C<keys> is available in every historical section to list which
 9272: keys were added or changed at a specific historical revision of a
 9273: hash.
 9274: 
 9275: B<Warning>: do not store the hash that restore returns directly. This
 9276: will cause a mess since it will restore the historical keys as if the
 9277: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9278: 
 9279: Calling convention:
 9280: 
 9281:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9282:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9283: 
 9284: For more detailed information, see lonnet specific documentation.
 9285: 
 9286: =head1 RETURN MESSAGES
 9287: 
 9288: =over 4
 9289: 
 9290: =item * B<con_lost>: unable to contact remote host
 9291: 
 9292: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9293: when the connection is brought back up
 9294: 
 9295: =item * B<con_failed>: unable to contact remote host and unable to save message
 9296: for later delivery
 9297: 
 9298: =item * B<error:>: an error a occurred, a description of the error follows the :
 9299: 
 9300: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9301: that was requested
 9302: 
 9303: =back
 9304: 
 9305: =head1 PUBLIC SUBROUTINES
 9306: 
 9307: =head2 Session Environment Functions
 9308: 
 9309: =over 4
 9310: 
 9311: =item * 
 9312: X<appenv()>
 9313: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9314: the user envirnoment file, and will be restored for each access this
 9315: user makes during this session, also modifies the %env for the current
 9316: process. Optional rolesarrayref - if defined contains a reference to an array
 9317: of roles which are exempt from the restriction on modifying user.role entries 
 9318: in the user's environment.db and in %env.    
 9319: 
 9320: =item *
 9321: X<delenv()>
 9322: B<delenv($delthis,$regexp)>: removes all items from the session
 9323: environment file that begin with $delthis. If the 
 9324: optional second arg - $regexp - is true, $delthis is treated as a 
 9325: regular expression, otherwise \Q$delthis\E is used. 
 9326: The values are also deleted from the current processes %env.
 9327: 
 9328: =item * get_env_multiple($name) 
 9329: 
 9330: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9331: values may be defined and end up as an array ref.
 9332: 
 9333: returns an array of values
 9334: 
 9335: =back
 9336: 
 9337: =head2 User Information
 9338: 
 9339: =over 4
 9340: 
 9341: =item *
 9342: X<queryauthenticate()>
 9343: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9344: authentication scheme
 9345: 
 9346: =item *
 9347: X<authenticate()>
 9348: B<authenticate($uname,$upass,$udom)>: try to
 9349: authenticate user from domain's lib servers (first use the current
 9350: one). C<$upass> should be the users password.
 9351: 
 9352: =item *
 9353: X<homeserver()>
 9354: B<homeserver($uname,$udom)>: find the server which has
 9355: the user's directory and files (there must be only one), this caches
 9356: the answer, and also caches if there is a borken connection.
 9357: 
 9358: =item *
 9359: X<idget()>
 9360: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9361: (IDs are a unique resource in a domain, there must be only 1 ID per
 9362: username, and only 1 username per ID in a specific domain) (returns
 9363: hash: id=>name,id=>name)
 9364: 
 9365: =item *
 9366: X<idrget()>
 9367: B<idrget($udom,@unames)>: find the IDs behind a list of
 9368: usernames (returns hash: name=>id,name=>id)
 9369: 
 9370: =item *
 9371: X<idput()>
 9372: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9373: 
 9374: =item *
 9375: X<rolesinit()>
 9376: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9377: 
 9378: =item *
 9379: X<getsection()>
 9380: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9381: course $cname, return section name/number or '' for "not in course"
 9382: and '-1' for "no section"
 9383: 
 9384: =item *
 9385: X<userenvironment()>
 9386: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9387: passed in @what from the requested user's environment, returns a hash
 9388: 
 9389: =item * 
 9390: X<userlog_query()>
 9391: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9392: activity.log file. %filters defines filters applied when parsing the
 9393: log file. These can be start or end timestamps, or the type of action
 9394: - log to look for Login or Logout events, check for Checkin or
 9395: Checkout, role for role selection. The response is in the form
 9396: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9397: escaped strings of the action recorded in the activity.log file.
 9398: 
 9399: =back
 9400: 
 9401: =head2 User Roles
 9402: 
 9403: =over 4
 9404: 
 9405: =item *
 9406: 
 9407: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9408:  F: full access
 9409:  U,I,K: authentication modes (cxx only)
 9410:  '': forbidden
 9411:  1: user needs to choose course
 9412:  2: browse allowed
 9413:  A: passphrase authentication needed
 9414: 
 9415: =item *
 9416: 
 9417: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9418: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9419: and course level
 9420: 
 9421: =item *
 9422: 
 9423: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9424: (rolesplain.tab); plain text explanation of a user role term.
 9425: $type is Course (default) or Group.
 9426: If $forcedefault evaluates to true, text returned will be default 
 9427: text for $type. Otherwise, if this is a course, the text returned 
 9428: will be a custom name for the role (if defined in the course's 
 9429: environment).  If no custom name is defined the default is returned.
 9430:    
 9431: =item *
 9432: 
 9433: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9434: All arguments are optional. Returns a hash of a roles, either for
 9435: co-author/assistant author roles for a user's Construction Space
 9436: (default), or if $context is 'userroles', roles for the user himself,
 9437: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9438: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9439: For each key, value is set to colon-separated start and end times for
 9440: the role.  If no username and domain are specified, will default to
 9441: current user/domain. Types, roles, and roledoms are references to arrays
 9442: of role statuses (active, future or previous), roles 
 9443: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9444: to restrict the list of roles reported. If no array ref is 
 9445: provided for types, will default to return only active roles.
 9446: 
 9447: =back
 9448: 
 9449: =head2 User Modification
 9450: 
 9451: =over 4
 9452: 
 9453: =item *
 9454: 
 9455: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9456: user for the level given by URL.  Optional start and end dates (leave empty
 9457: string or zero for "no date")
 9458: 
 9459: =item *
 9460: 
 9461: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9462: change a users, password, possible return values are: ok,
 9463: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9464: refused
 9465: 
 9466: =item *
 9467: 
 9468: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9469: 
 9470: =item *
 9471: 
 9472: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9473:            $forceid,$desiredhome,$email,$inststatus) : 
 9474: modify user
 9475: 
 9476: =item *
 9477: 
 9478: modifystudent
 9479: 
 9480: modify a student's enrollment and identification information.
 9481: The course id is resolved based on the current users environment.  
 9482: This means the envoking user must be a course coordinator or otherwise
 9483: associated with a course.
 9484: 
 9485: This call is essentially a wrapper for lonnet::modifyuser and
 9486: lonnet::modify_student_enrollment
 9487: 
 9488: Inputs: 
 9489: 
 9490: =over 4
 9491: 
 9492: =item B<$udom> Student's loncapa domain
 9493: 
 9494: =item B<$uname> Student's loncapa login name
 9495: 
 9496: =item B<$uid> Student/Employee ID
 9497: 
 9498: =item B<$umode> Student's authentication mode
 9499: 
 9500: =item B<$upass> Student's password
 9501: 
 9502: =item B<$first> Student's first name
 9503: 
 9504: =item B<$middle> Student's middle name
 9505: 
 9506: =item B<$last> Student's last name
 9507: 
 9508: =item B<$gene> Student's generation
 9509: 
 9510: =item B<$usec> Student's section in course
 9511: 
 9512: =item B<$end> Unix time of the roles expiration
 9513: 
 9514: =item B<$start> Unix time of the roles start date
 9515: 
 9516: =item B<$forceid> If defined, allow $uid to be changed
 9517: 
 9518: =item B<$desiredhome> server to use as home server for student
 9519: 
 9520: =item B<$email> Student's permanent e-mail address
 9521: 
 9522: =item B<$type> Type of enrollment (auto or manual)
 9523: 
 9524: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9525: 
 9526: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9527: 
 9528: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9529: 
 9530: =item B<$context> role change context (shown in User Management Logs display in a course)
 9531: 
 9532: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9533: 
 9534: =back
 9535: 
 9536: =item *
 9537: 
 9538: modify_student_enrollment
 9539: 
 9540: Change a students enrollment status in a class.  The environment variable
 9541: 'role.request.course' must be defined for this function to proceed.
 9542: 
 9543: Inputs:
 9544: 
 9545: =over 4
 9546: 
 9547: =item $udom, students domain
 9548: 
 9549: =item $uname, students name
 9550: 
 9551: =item $uid, students user id
 9552: 
 9553: =item $first, students first name
 9554: 
 9555: =item $middle
 9556: 
 9557: =item $last
 9558: 
 9559: =item $gene
 9560: 
 9561: =item $usec
 9562: 
 9563: =item $end
 9564: 
 9565: =item $start
 9566: 
 9567: =item $type
 9568: 
 9569: =item $locktype
 9570: 
 9571: =item $cid
 9572: 
 9573: =item $selfenroll
 9574: 
 9575: =item $context
 9576: 
 9577: =back
 9578: 
 9579: 
 9580: =item *
 9581: 
 9582: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9583: custom role; give a custom role to a user for the level given by URL.  Specify
 9584: name and domain of role author, and role name
 9585: 
 9586: =item *
 9587: 
 9588: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9589: 
 9590: =item *
 9591: 
 9592: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9593: 
 9594: =back
 9595: 
 9596: =head2 Course Infomation
 9597: 
 9598: =over 4
 9599: 
 9600: =item *
 9601: 
 9602: coursedescription($courseid) : returns a hash of information about the
 9603: specified course id, including all environment settings for the
 9604: course, the description of the course will be in the hash under the
 9605: key 'description'
 9606: 
 9607: =item *
 9608: 
 9609: resdata($name,$domain,$type,@which) : request for current parameter
 9610: setting for a specific $type, where $type is either 'course' or 'user',
 9611: @what should be a list of parameters to ask about. This routine caches
 9612: answers for 5 minutes.
 9613: 
 9614: =item *
 9615: 
 9616: get_courseresdata($courseid, $domain) : dump the entire course resource
 9617: data base, returning a hash that is keyed by the resource name and has
 9618: values that are the resource value.  I believe that the timestamps and
 9619: versions are also returned.
 9620: 
 9621: 
 9622: =back
 9623: 
 9624: =head2 Course Modification
 9625: 
 9626: =over 4
 9627: 
 9628: =item *
 9629: 
 9630: writecoursepref($courseid,%prefs) : write preferences (environment
 9631: database) for a course
 9632: 
 9633: =item *
 9634: 
 9635: createcourse($udom,$description,$url) : make/modify course
 9636: 
 9637: =back
 9638: 
 9639: =head2 Resource Subroutines
 9640: 
 9641: =over 4
 9642: 
 9643: =item *
 9644: 
 9645: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9646: 
 9647: =item *
 9648: 
 9649: repcopy($filename) : subscribes to the requested file, and attempts to
 9650: replicate from the owning library server, Might return
 9651: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9652: 'bad_request', also attempts to grab the metadata for the
 9653: resource. Expects the local filesystem pathname
 9654: (/home/httpd/html/res/....)
 9655: 
 9656: =back
 9657: 
 9658: =head2 Resource Information
 9659: 
 9660: =over 4
 9661: 
 9662: =item *
 9663: 
 9664: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9665: a vairety of different possible values, $varname should be a request
 9666: string, and the other parameters can be used to specify who and what
 9667: one is asking about.
 9668: 
 9669: Possible values for $varname are environment.lastname (or other item
 9670: from the envirnment hash), user.name (or someother aspect about the
 9671: user), resource.0.maxtries (or some other part and parameter of a
 9672: resource)
 9673: 
 9674: =item *
 9675: 
 9676: directcondval($number) : get current value of a condition; reads from a state
 9677: string
 9678: 
 9679: =item *
 9680: 
 9681: condval($condidx) : value of condition index based on state
 9682: 
 9683: =item *
 9684: 
 9685: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9686: resource's metadata, $what should be either a specific key, or either
 9687: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9688: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9689: 
 9690: this function automatically caches all requests
 9691: 
 9692: =item *
 9693: 
 9694: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9695: network of library servers; returns file handle of where SQL and regex results
 9696: will be stored for query
 9697: 
 9698: =item *
 9699: 
 9700: symbread($filename) : return symbolic list entry (filename argument optional);
 9701: returns the data handle
 9702: 
 9703: =item *
 9704: 
 9705: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9706: a possible symb for the URL in $thisfn, and if is an encryypted
 9707: resource that the user accessed using /enc/ returns a 1 on success, 0
 9708: on failure, user must be in a course, as it assumes the existance of
 9709: the course initial hash, and uses $env('request.course.id'}
 9710: 
 9711: 
 9712: =item *
 9713: 
 9714: symbclean($symb) : removes versions numbers from a symb, returns the
 9715: cleaned symb
 9716: 
 9717: =item *
 9718: 
 9719: is_on_map($uri) : checks if the $uri is somewhere on the current
 9720: course map, user must be in a course for it to work.
 9721: 
 9722: =item *
 9723: 
 9724: numval($salt) : return random seed value (addend for rndseed)
 9725: 
 9726: =item *
 9727: 
 9728: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9729: a random seed, all arguments are optional, if they aren't sent it uses the
 9730: environment to derive them. Note: if symb isn't sent and it can't get one
 9731: from &symbread it will use the current time as its return value
 9732: 
 9733: =item *
 9734: 
 9735: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9736: unfakeable, receipt
 9737: 
 9738: =item *
 9739: 
 9740: receipt() : API to ireceipt working off of env values; given out to users
 9741: 
 9742: =item *
 9743: 
 9744: countacc($url) : count the number of accesses to a given URL
 9745: 
 9746: =item *
 9747: 
 9748: 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
 9749: 
 9750: =item *
 9751: 
 9752: 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)
 9753: 
 9754: =item *
 9755: 
 9756: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9757: 
 9758: =item *
 9759: 
 9760: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9761: forcing spreadsheet to reevaluate the resource scores next time.
 9762: 
 9763: =back
 9764: 
 9765: =head2 Storing/Retreiving Data
 9766: 
 9767: =over 4
 9768: 
 9769: =item *
 9770: 
 9771: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9772: for this url; hashref needs to be given and should be a \%hashname; the
 9773: remaining args aren't required and if they aren't passed or are '' they will
 9774: be derived from the env
 9775: 
 9776: =item *
 9777: 
 9778: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9779: uses critical subroutine
 9780: 
 9781: =item *
 9782: 
 9783: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9784: all args are optional
 9785: 
 9786: =item *
 9787: 
 9788: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9789: dumps the complete (or key matching regexp) namespace into a hash
 9790: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9791: normally &store()ed into
 9792: 
 9793: $range should be either an integer '100' (give me the first 100
 9794:                                            matching records)
 9795:               or be  two integers sperated by a - with no spaces
 9796:                  '30-50' (give me the 30th through the 50th matching
 9797:                           records)
 9798: 
 9799: 
 9800: =item *
 9801: 
 9802: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9803: replaces a &store() version of data with a replacement set of data
 9804: for a particular resource in a namespace passed in the $storehash hash 
 9805: reference
 9806: 
 9807: =item *
 9808: 
 9809: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9810: works very similar to store/cstore, but all data is stored in a
 9811: temporary location and can be reset using tmpreset, $storehash should
 9812: be a hash reference, returns nothing on success
 9813: 
 9814: =item *
 9815: 
 9816: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9817: similar to restore, but all data is stored in a temporary location and
 9818: can be reset using tmpreset. Returns a hash of values on success,
 9819: error string otherwise.
 9820: 
 9821: =item *
 9822: 
 9823: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9824: deltes all keys for $symb form the temporary storage hash.
 9825: 
 9826: =item *
 9827: 
 9828: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9829: reference filled in from namesp ($udom and $uname are optional)
 9830: 
 9831: =item *
 9832: 
 9833: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9834: namesp ($udom and $uname are optional)
 9835: 
 9836: =item *
 9837: 
 9838: dump($namespace,$udom,$uname,$regexp,$range) : 
 9839: dumps the complete (or key matching regexp) namespace into a hash
 9840: ($udom, $uname, $regexp, $range are optional)
 9841: 
 9842: $range should be either an integer '100' (give me the first 100
 9843:                                            matching records)
 9844:               or be  two integers sperated by a - with no spaces
 9845:                  '30-50' (give me the 30th through the 50th matching
 9846:                           records)
 9847: =item *
 9848: 
 9849: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9850: $store can be a scalar, an array reference, or if the amount to be 
 9851: incremented is > 1, a hash reference.
 9852: 
 9853: ($udom and $uname are optional)
 9854: 
 9855: =item *
 9856: 
 9857: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9858: ($udom and $uname are optional)
 9859: 
 9860: =item *
 9861: 
 9862: cput($namespace,$storehash,$udom,$uname) : critical put
 9863: ($udom and $uname are optional)
 9864: 
 9865: =item *
 9866: 
 9867: newput($namespace,$storehash,$udom,$uname) :
 9868: 
 9869: Attempts to store the items in the $storehash, but only if they don't
 9870: currently exist, if this succeeds you can be certain that you have 
 9871: successfully created a new key value pair in the $namespace db.
 9872: 
 9873: 
 9874: Args:
 9875:  $namespace: name of database to store values to
 9876:  $storehash: hashref to store to the db
 9877:  $udom: (optional) domain of user containing the db
 9878:  $uname: (optional) name of user caontaining the db
 9879: 
 9880: Returns:
 9881:  'ok' -> succeeded in storing all keys of $storehash
 9882:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9883:                         least <key> already existed in the db (other
 9884:                         requested keys may also already exist)
 9885:  'error: <msg>' -> unable to tie the DB or other error occurred
 9886:  'con_lost' -> unable to contact request server
 9887:  'refused' -> action was not allowed by remote machine
 9888: 
 9889: 
 9890: =item *
 9891: 
 9892: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9893: reference filled in from namesp (encrypts the return communication)
 9894: ($udom and $uname are optional)
 9895: 
 9896: =item *
 9897: 
 9898: log($udom,$name,$home,$message) : write to permanent log for user; use
 9899: critical subroutine
 9900: 
 9901: =item *
 9902: 
 9903: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9904: array reference filled in from namespace found in domain level on either
 9905: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9906: 
 9907: =item *
 9908: 
 9909: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9910: domain level either on specified domain server ($uhome) or primary domain 
 9911: server ($udom and $uhome are optional)
 9912: 
 9913: =item * 
 9914: 
 9915: get_domain_defaults($target_domain) : returns hash with defaults for
 9916: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9917: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9918: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9919: Values are retrieved from cache (if current), or from domain's configuration.db
 9920: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9921: or lonTabs/domain.tab. 
 9922: 
 9923: %domdefaults = &get_auth_defaults($target_domain);
 9924: 
 9925: =back
 9926: 
 9927: =head2 Network Status Functions
 9928: 
 9929: =over 4
 9930: 
 9931: =item *
 9932: 
 9933: dirlist($uri) : return directory list based on URI
 9934: 
 9935: =item *
 9936: 
 9937: spareserver() : find server with least workload from spare.tab
 9938: 
 9939: 
 9940: =item *
 9941: 
 9942: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
 9943: if there is no corresponding loncapa host.
 9944: 
 9945: =back
 9946: 
 9947: 
 9948: =head2 Apache Request
 9949: 
 9950: =over 4
 9951: 
 9952: =item *
 9953: 
 9954: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9955: localhost, posts hash
 9956: 
 9957: =back
 9958: 
 9959: =head2 Data to String to Data
 9960: 
 9961: =over 4
 9962: 
 9963: =item *
 9964: 
 9965: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9966: and '&' separators, supports elements that are arrayrefs and hashrefs
 9967: 
 9968: =item *
 9969: 
 9970: hashref2str($hashref) : convert a hashref into a string complete with
 9971: escaping and '=' and '&' separators, supports elements that are
 9972: arrayrefs and hashrefs
 9973: 
 9974: =item *
 9975: 
 9976: arrayref2str($arrayref) : convert an arrayref into a string complete
 9977: with escaping and '&' separators, supports elements that are arrayrefs
 9978: and hashrefs
 9979: 
 9980: =item *
 9981: 
 9982: str2hash($string) : convert string to hash using unescaping and
 9983: splitting on '=' and '&', supports elements that are arrayrefs and
 9984: hashrefs
 9985: 
 9986: =item *
 9987: 
 9988: str2array($string) : convert string to hash using unescaping and
 9989: splitting on '&', supports elements that are arrayrefs and hashrefs
 9990: 
 9991: =back
 9992: 
 9993: =head2 Logging Routines
 9994: 
 9995: =over 4
 9996: 
 9997: These routines allow one to make log messages in the lonnet.log and
 9998: lonnet.perm logfiles.
 9999: 
10000: =item *
10001: 
10002: logtouch() : make sure the logfile, lonnet.log, exists
10003: 
10004: =item *
10005: 
10006: logthis() : append message to the normal lonnet.log file, it gets
10007: preiodically rolled over and deleted.
10008: 
10009: =item *
10010: 
10011: logperm() : append a permanent message to lonnet.perm.log, this log
10012: file never gets deleted by any automated portion of the system, only
10013: messages of critical importance should go in here.
10014: 
10015: =back
10016: 
10017: =head2 General File Helper Routines
10018: 
10019: =over 4
10020: 
10021: =item *
10022: 
10023: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10024: (a) files in /uploaded
10025:   (i) If a local copy of the file exists - 
10026:       compares modification date of local copy with last-modified date for 
10027:       definitive version stored on home server for course. If local copy is 
10028:       stale, requests a new version from the home server and stores it. 
10029:       If the original has been removed from the home server, then local copy 
10030:       is unlinked.
10031:   (ii) If local copy does not exist -
10032:       requests the file from the home server and stores it. 
10033:   
10034:   If $caller is 'uploadrep':  
10035:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10036:     for request for files originally uploaded via DOCS. 
10037:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10038:   
10039:   Otherwise:
10040:      This indicates a call from the content generation phase of the request.
10041:      -  returns the entire contents of the file or -1.
10042:      
10043: (b) files in /res
10044:    - returns the entire contents of a file or -1; 
10045:    it properly subscribes to and replicates the file if neccessary.
10046: 
10047: 
10048: =item *
10049: 
10050: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10051:                   reference
10052: 
10053: returns either a stat() list of data about the file or an empty list
10054: if the file doesn't exist or couldn't find out about it (connection
10055: problems or user unknown)
10056: 
10057: =item *
10058: 
10059: filelocation($dir,$file) : returns file system location of a file
10060: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10061: directory that relative $file lookups are to looked in ($dir of /a/dir
10062: and a file of ../bob will become /a/bob)
10063: 
10064: =item *
10065: 
10066: hreflocation($dir,$file) : returns file system location or a URL; same as
10067: filelocation except for hrefs
10068: 
10069: =item *
10070: 
10071: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10072: 
10073: =back
10074: 
10075: =head2 Usererfile file routines (/uploaded*)
10076: 
10077: =over 4
10078: 
10079: =item *
10080: 
10081: userfileupload(): main rotine for putting a file in a user or course's
10082:                   filespace, arguments are,
10083: 
10084:  formname - required - this is the name of the element in $env where the
10085:            filename, and the contents of the file to create/modifed exist
10086:            the filename is in $env{'form.'.$formname.'.filename'} and the
10087:            contents of the file is located in $env{'form.'.$formname}
10088:  coursedoc - if true, store the file in the course of the active role
10089:              of the current user
10090:  subdir - required - subdirectory to put the file in under ../userfiles/
10091:          if undefined, it will be placed in "unknown"
10092: 
10093:  (This routine calls clean_filename() to remove any dangerous
10094:  characters from the filename, and then calls finuserfileupload() to
10095:  complete the transaction)
10096: 
10097:  returns either the url of the uploaded file (/uploaded/....) if successful
10098:  and /adm/notfound.html if unsuccessful
10099: 
10100: =item *
10101: 
10102: clean_filename(): routine for cleaing a filename up for storage in
10103:                  userfile space, argument is:
10104: 
10105:  filename - proposed filename
10106: 
10107: returns: the new clean filename
10108: 
10109: =item *
10110: 
10111: finishuserfileupload(): routine that creaes and sends the file to
10112: userspace, probably shouldn't be called directly
10113: 
10114:   docuname: username or courseid of destination for the file
10115:   docudom: domain of user/course of destination for the file
10116:   formname: same as for userfileupload()
10117:   fname: filename (inculding subdirectories) for the file
10118: 
10119:  returns either the url of the uploaded file (/uploaded/....) if successful
10120:  and /adm/notfound.html if unsuccessful
10121: 
10122: =item *
10123: 
10124: renameuserfile(): renames an existing userfile to a new name
10125: 
10126:   Args:
10127:    docuname: username or courseid of destination for the file
10128:    docudom: domain of user/course of destination for the file
10129:    old: current file name (including any subdirs under userfiles)
10130:    new: desired file name (including any subdirs under userfiles)
10131: 
10132: =item *
10133: 
10134: mkdiruserfile(): creates a directory is a userfiles dir
10135: 
10136:   Args:
10137:    docuname: username or courseid of destination for the file
10138:    docudom: domain of user/course of destination for the file
10139:    dir: dir to create (including any subdirs under userfiles)
10140: 
10141: =item *
10142: 
10143: removeuserfile(): removes a file that exists in userfiles
10144: 
10145:   Args:
10146:    docuname: username or courseid of destination for the file
10147:    docudom: domain of user/course of destination for the file
10148:    fname: filname to delete (including any subdirs under userfiles)
10149: 
10150: =item *
10151: 
10152: removeuploadedurl(): convience function for removeuserfile()
10153: 
10154:   Args:
10155:    url:  a full /uploaded/... url to delete
10156: 
10157: =item * 
10158: 
10159: get_portfile_permissions():
10160:   Args:
10161:     domain: domain of user or course contain the portfolio files
10162:     user: name of user or num of course contain the portfolio files
10163:   Returns:
10164:     hashref of a dump of the proper file_permissions.db
10165:    
10166: 
10167: =item * 
10168: 
10169: get_access_controls():
10170: 
10171: Args:
10172:   current_permissions: the hash ref returned from get_portfile_permissions()
10173:   group: (optional) the group you want the files associated with
10174:   file: (optional) the file you want access info on
10175: 
10176: Returns:
10177:     a hash (keys are file names) of hashes containing
10178:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10179:         values are XML containing access control settings (see below) 
10180: 
10181: Internal notes:
10182: 
10183:  access controls are stored in file_permissions.db as key=value pairs.
10184:     key -> path to file/file_name\0uniqueID:scope_end_start
10185:         where scope -> public,guest,course,group,domains or users.
10186:               end -> UNIX time for end of access (0 -> no end date)
10187:               start -> UNIX time for start of access
10188: 
10189:     value -> XML description of access control
10190:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10191:             <start></start>
10192:             <end></end>
10193: 
10194:             <password></password>  for scope type = guest
10195: 
10196:             <domain></domain>     for scope type = course or group
10197:             <number></number>
10198:             <roles id="">
10199:              <role></role>
10200:              <access></access>
10201:              <section></section>
10202:              <group></group>
10203:             </roles>
10204: 
10205:             <dom></dom>         for scope type = domains
10206: 
10207:             <users>             for scope type = users
10208:              <user>
10209:               <uname></uname>
10210:               <udom></udom>
10211:              </user>
10212:             </users>
10213:            </scope> 
10214:               
10215:  Access data is also aggregated for each file in an additional key=value pair:
10216:  key -> path to file/file_name\0accesscontrol 
10217:  value -> reference to hash
10218:           hash contains key = value pairs
10219:           where key = uniqueID:scope_end_start
10220:                 value = UNIX time record was last updated
10221: 
10222:           Used to improve speed of look-ups of access controls for each file.  
10223:  
10224:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10225: 
10226: modify_access_controls():
10227: 
10228: Modifies access controls for a portfolio file
10229: Args
10230: 1. file name
10231: 2. reference to hash of required changes,
10232: 3. domain
10233: 4. username
10234:   where domain,username are the domain of the portfolio owner 
10235:   (either a user or a course) 
10236: 
10237: Returns:
10238: 1. result of additions or updates ('ok' or 'error', with error message). 
10239: 2. result of deletions ('ok' or 'error', with error message).
10240: 3. reference to hash of any new or updated access controls.
10241: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10242:    key = integer (inbound ID)
10243:    value = uniqueID  
10244: 
10245: =back
10246: 
10247: =head2 HTTP Helper Routines
10248: 
10249: =over 4
10250: 
10251: =item *
10252: 
10253: escape() : unpack non-word characters into CGI-compatible hex codes
10254: 
10255: =item *
10256: 
10257: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10258: 
10259: =back
10260: 
10261: =head1 PRIVATE SUBROUTINES
10262: 
10263: =head2 Underlying communication routines (Shouldn't call)
10264: 
10265: =over 4
10266: 
10267: =item *
10268: 
10269: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10270: 
10271: =item *
10272: 
10273: reply() : uses subreply to send a message to remote machine, logs all failures
10274: 
10275: =item *
10276: 
10277: critical() : passes a critical message to another server; if cannot
10278: get through then place message in connection buffer directory and
10279: returns con_delayed, if incapable of saving message, returns
10280: con_failed
10281: 
10282: =item *
10283: 
10284: reconlonc() : tries to reconnect lonc client processes.
10285: 
10286: =back
10287: 
10288: =head2 Resource Access Logging
10289: 
10290: =over 4
10291: 
10292: =item *
10293: 
10294: flushcourselogs() : flush (save) buffer logs and access logs
10295: 
10296: =item *
10297: 
10298: courselog($what) : save message for course in hash
10299: 
10300: =item *
10301: 
10302: courseacclog($what) : save message for course using &courselog().  Perform
10303: special processing for specific resource types (problems, exams, quizzes, etc).
10304: 
10305: =item *
10306: 
10307: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10308: as a PerlChildExitHandler
10309: 
10310: =back
10311: 
10312: =head2 Other
10313: 
10314: =over 4
10315: 
10316: =item *
10317: 
10318: symblist($mapname,%newhash) : update symbolic storage links
10319: 
10320: =back
10321: 
10322: =cut
10323: 

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