File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.990: download - view: text, annotated - select for diffs
Mon Mar 9 05:25:44 2009 UTC (15 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Setting Institutional Affiliation(s).
- institutional affiliation saved as inststatus in user's environment.db is a colon-separated list of escaped affiliations.

- Domain Coordinators in user's domain (have mau priv.) can modify institutional status of a user via "Modify User" or "Upload List of Users".

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.990 2009/03/09 05:25:44 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:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1009:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1010:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1011:         %returnhash = %{$domdefs{'inststatustypes'}};
 1012:         @order = @{$domdefs{'inststatusorder'}};
 1013:     } else {
 1014:         if (defined(&domain($udom,'primary'))) {
 1015:             my $uhome=&domain($udom,'primary');
 1016:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1017:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1018:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1019:                 return (\%returnhash,\@order);
 1020:             }
 1021:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1022:             my @pairs=split(/\&/,$hashitems);
 1023:             foreach my $item (@pairs) {
 1024:                 my ($key,$value)=split(/=/,$item,2);
 1025:                 $key = &unescape($key);
 1026:                 next if ($key =~ /^error: 2 /);
 1027:                 $returnhash{$key}=&thaw_unescape($value);
 1028:             }
 1029:             my @esc_order = split(/\&/,$orderitems);
 1030:             foreach my $item (@esc_order) {
 1031:                 push(@order,&unescape($item));
 1032:             }
 1033:         } else {
 1034:             &logthis("get_dom failed - no primary domain server for $udom");
 1035:         }
 1036:     }
 1037:     return (\%returnhash,\@order);
 1038: }
 1039: 
 1040: sub is_domainimage {
 1041:     my ($url) = @_;
 1042:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1043:         if (&domain($1) ne '') {
 1044:             return '1';
 1045:         }
 1046:     }
 1047:     return;
 1048: }
 1049: 
 1050: sub inst_directory_query {
 1051:     my ($srch) = @_;
 1052:     my $udom = $srch->{'srchdomain'};
 1053:     my %results;
 1054:     my $homeserver = &domain($udom,'primary');
 1055:     my $outcome;
 1056:     if ($homeserver ne '') {
 1057: 	my $queryid=&reply("querysend:instdirsearch:".
 1058: 			   &escape($srch->{'srchby'}).':'.
 1059: 			   &escape($srch->{'srchterm'}).':'.
 1060: 			   &escape($srch->{'srchtype'}),$homeserver);
 1061: 	my $host=&hostname($homeserver);
 1062: 	if ($queryid !~/^\Q$host\E\_/) {
 1063: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1064: 	    return;
 1065: 	}
 1066: 	my $response = &get_query_reply($queryid);
 1067: 	my $maxtries = 5;
 1068: 	my $tries = 1;
 1069: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1070: 	    $response = &get_query_reply($queryid);
 1071: 	    $tries ++;
 1072: 	}
 1073: 
 1074:         if (!&error($response) && $response ne 'refused') {
 1075:             if ($response eq 'unavailable') {
 1076:                 $outcome = $response;
 1077:             } else {
 1078:                 $outcome = 'ok';
 1079:                 my @matches = split(/\n/,$response);
 1080:                 foreach my $match (@matches) {
 1081:                     my ($key,$value) = split(/=/,$match);
 1082:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1083:                 }
 1084:             }
 1085:         }
 1086:     }
 1087:     return ($outcome,%results);
 1088: }
 1089: 
 1090: sub usersearch {
 1091:     my ($srch) = @_;
 1092:     my $dom = $srch->{'srchdomain'};
 1093:     my %results;
 1094:     my %libserv = &all_library();
 1095:     my $query = 'usersearch';
 1096:     foreach my $tryserver (keys(%libserv)) {
 1097:         if (&host_domain($tryserver) eq $dom) {
 1098:             my $host=&hostname($tryserver);
 1099:             my $queryid=
 1100:                 &reply("querysend:".&escape($query).':'.
 1101:                        &escape($srch->{'srchby'}).':'.
 1102:                        &escape($srch->{'srchtype'}).':'.
 1103:                        &escape($srch->{'srchterm'}),$tryserver);
 1104:             if ($queryid !~/^\Q$host\E\_/) {
 1105:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1106:                 next;
 1107:             }
 1108:             my $reply = &get_query_reply($queryid);
 1109:             my $maxtries = 1;
 1110:             my $tries = 1;
 1111:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1112:                 $reply = &get_query_reply($queryid);
 1113:                 $tries ++;
 1114:             }
 1115:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1116:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1117:             } else {
 1118:                 my @matches;
 1119:                 if ($reply =~ /\n/) {
 1120:                     @matches = split(/\n/,$reply);
 1121:                 } else {
 1122:                     @matches = split(/\&/,$reply);
 1123:                 }
 1124:                 foreach my $match (@matches) {
 1125:                     my ($uname,$udom,%userhash);
 1126:                     foreach my $entry (split(/:/,$match)) {
 1127:                         my ($key,$value) =
 1128:                             map {&unescape($_);} split(/=/,$entry);
 1129:                         $userhash{$key} = $value;
 1130:                         if ($key eq 'username') {
 1131:                             $uname = $value;
 1132:                         } elsif ($key eq 'domain') {
 1133:                             $udom = $value;
 1134:                         }
 1135:                     }
 1136:                     $results{$uname.':'.$udom} = \%userhash;
 1137:                 }
 1138:             }
 1139:         }
 1140:     }
 1141:     return %results;
 1142: }
 1143: 
 1144: sub get_instuser {
 1145:     my ($udom,$uname,$id) = @_;
 1146:     my $homeserver = &domain($udom,'primary');
 1147:     my ($outcome,%results);
 1148:     if ($homeserver ne '') {
 1149:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1150:                            &escape($id).':'.&escape($udom),$homeserver);
 1151:         my $host=&hostname($homeserver);
 1152:         if ($queryid !~/^\Q$host\E\_/) {
 1153:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1154:             return;
 1155:         }
 1156:         my $response = &get_query_reply($queryid);
 1157:         my $maxtries = 5;
 1158:         my $tries = 1;
 1159:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1160:             $response = &get_query_reply($queryid);
 1161:             $tries ++;
 1162:         }
 1163:         if (!&error($response) && $response ne 'refused') {
 1164:             if ($response eq 'unavailable') {
 1165:                 $outcome = $response;
 1166:             } else {
 1167:                 $outcome = 'ok';
 1168:                 my @matches = split(/\n/,$response);
 1169:                 foreach my $match (@matches) {
 1170:                     my ($key,$value) = split(/=/,$match);
 1171:                     $results{&unescape($key)} = &thaw_unescape($value);
 1172:                 }
 1173:             }
 1174:         }
 1175:     }
 1176:     my %userinfo;
 1177:     if (ref($results{$uname}) eq 'HASH') {
 1178:         %userinfo = %{$results{$uname}};
 1179:     } 
 1180:     return ($outcome,%userinfo);
 1181: }
 1182: 
 1183: sub inst_rulecheck {
 1184:     my ($udom,$uname,$id,$item,$rules) = @_;
 1185:     my %returnhash;
 1186:     if ($udom ne '') {
 1187:         if (ref($rules) eq 'ARRAY') {
 1188:             @{$rules} = map {&escape($_);} (@{$rules});
 1189:             my $rulestr = join(':',@{$rules});
 1190:             my $homeserver=&domain($udom,'primary');
 1191:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1192:                 my $response;
 1193:                 if ($item eq 'username') {                
 1194:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1195:                                               ':'.&escape($uname).':'.$rulestr,
 1196:                                               $homeserver));
 1197:                 } elsif ($item eq 'id') {
 1198:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1199:                                               ':'.&escape($id).':'.$rulestr,
 1200:                                               $homeserver));
 1201:                 } elsif ($item eq 'selfcreate') {
 1202:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1203:                                                &escape($udom).':'.&escape($uname).
 1204:                                               ':'.$rulestr,$homeserver));
 1205:                 }
 1206:                 if ($response ne 'refused') {
 1207:                     my @pairs=split(/\&/,$response);
 1208:                     foreach my $item (@pairs) {
 1209:                         my ($key,$value)=split(/=/,$item,2);
 1210:                         $key = &unescape($key);
 1211:                         next if ($key =~ /^error: 2 /);
 1212:                         $returnhash{$key}=&thaw_unescape($value);
 1213:                     }
 1214:                 }
 1215:             }
 1216:         }
 1217:     }
 1218:     return %returnhash;
 1219: }
 1220: 
 1221: sub inst_userrules {
 1222:     my ($udom,$check) = @_;
 1223:     my (%ruleshash,@ruleorder);
 1224:     if ($udom ne '') {
 1225:         my $homeserver=&domain($udom,'primary');
 1226:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1227:             my $response;
 1228:             if ($check eq 'id') {
 1229:                 $response=&reply('instidrules:'.&escape($udom),
 1230:                                  $homeserver);
 1231:             } elsif ($check eq 'email') {
 1232:                 $response=&reply('instemailrules:'.&escape($udom),
 1233:                                  $homeserver);
 1234:             } else {
 1235:                 $response=&reply('instuserrules:'.&escape($udom),
 1236:                                  $homeserver);
 1237:             }
 1238:             if (($response ne 'refused') && ($response ne 'error') && 
 1239:                 ($response ne 'unknown_cmd') && 
 1240:                 ($response ne 'no_such_host')) {
 1241:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1242:                 my @pairs=split(/\&/,$hashitems);
 1243:                 foreach my $item (@pairs) {
 1244:                     my ($key,$value)=split(/=/,$item,2);
 1245:                     $key = &unescape($key);
 1246:                     next if ($key =~ /^error: 2 /);
 1247:                     $ruleshash{$key}=&thaw_unescape($value);
 1248:                 }
 1249:                 my @esc_order = split(/\&/,$orderitems);
 1250:                 foreach my $item (@esc_order) {
 1251:                     push(@ruleorder,&unescape($item));
 1252:                 }
 1253:             }
 1254:         }
 1255:     }
 1256:     return (\%ruleshash,\@ruleorder);
 1257: }
 1258: 
 1259: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1260: 
 1261: sub get_domain_defaults {
 1262:     my ($domain) = @_;
 1263:     my $cachetime = 60*60*24;
 1264:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1265:     if (defined($cached)) {
 1266:         if (ref($result) eq 'HASH') {
 1267:             return %{$result};
 1268:         }
 1269:     }
 1270:     my %domdefaults;
 1271:     my %domconfig =
 1272:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1273:                                   'requestcourses','inststatus'],$domain);
 1274:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1275:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1276:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1277:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1278:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1279:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1280:     } else {
 1281:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1282:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1283:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1284:     }
 1285:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1286:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1287:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1288:         } else {
 1289:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1290:         } 
 1291:         my @usertools = ('aboutme','blog','portfolio');
 1292:         foreach my $item (@usertools) {
 1293:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1294:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1295:             }
 1296:         }
 1297:     }
 1298:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1299:         foreach my $item ('official','unofficial') {
 1300:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1301:         }
 1302:     }
 1303:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1304:         foreach my $item ('inststatustypes','inststatusorder') {
 1305:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1306:         }
 1307:     }
 1308:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1309:                                   $cachetime);
 1310:     return %domdefaults;
 1311: }
 1312: 
 1313: # --------------------------------------------------- Assign a key to a student
 1314: 
 1315: sub assign_access_key {
 1316: #
 1317: # a valid key looks like uname:udom#comments
 1318: # comments are being appended
 1319: #
 1320:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1321:     $kdom=
 1322:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1323:     $knum=
 1324:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1325:     $cdom=
 1326:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1327:     $cnum=
 1328:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1329:     $udom=$env{'user.name'} unless (defined($udom));
 1330:     $uname=$env{'user.domain'} unless (defined($uname));
 1331:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1332:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1333:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1334:                                                   # assigned to this person
 1335:                                                   # - this should not happen,
 1336:                                                   # unless something went wrong
 1337:                                                   # the first time around
 1338: # ready to assign
 1339:         $logentry=$1.'; '.$logentry;
 1340:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1341:                                                  $kdom,$knum) eq 'ok') {
 1342: # key now belongs to user
 1343: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1344:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1345:                 &appenv({'environment.'.$envkey => $ckey});
 1346:                 return 'ok';
 1347:             } else {
 1348:                 return 
 1349:   'error: Count not permanently assign key, will need to be re-entered later.';
 1350: 	    }
 1351:         } else {
 1352:             return 'error: Could not assign key, try again later.';
 1353:         }
 1354:     } elsif (!$existing{$ckey}) {
 1355: # the key does not exist
 1356: 	return 'error: The key does not exist';
 1357:     } else {
 1358: # the key is somebody else's
 1359: 	return 'error: The key is already in use';
 1360:     }
 1361: }
 1362: 
 1363: # ------------------------------------------ put an additional comment on a key
 1364: 
 1365: sub comment_access_key {
 1366: #
 1367: # a valid key looks like uname:udom#comments
 1368: # comments are being appended
 1369: #
 1370:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1371:     $cdom=
 1372:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1373:     $cnum=
 1374:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1375:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1376:     if ($existing{$ckey}) {
 1377:         $existing{$ckey}.='; '.$logentry;
 1378: # ready to assign
 1379:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1380:                                                  $cdom,$cnum) eq 'ok') {
 1381: 	    return 'ok';
 1382:         } else {
 1383: 	    return 'error: Count not store comment.';
 1384:         }
 1385:     } else {
 1386: # the key does not exist
 1387: 	return 'error: The key does not exist';
 1388:     }
 1389: }
 1390: 
 1391: # ------------------------------------------------------ Generate a set of keys
 1392: 
 1393: sub generate_access_keys {
 1394:     my ($number,$cdom,$cnum,$logentry)=@_;
 1395:     $cdom=
 1396:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1397:     $cnum=
 1398:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1399:     unless (&allowed('mky',$cdom)) { return 0; }
 1400:     unless (($cdom) && ($cnum)) { return 0; }
 1401:     if ($number>10000) { return 0; }
 1402:     sleep(2); # make sure don't get same seed twice
 1403:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1404:     my $total=0;
 1405:     for (my $i=1;$i<=$number;$i++) {
 1406:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1407:                   sprintf("%lx",int(100000*rand)).'-'.
 1408:                   sprintf("%lx",int(100000*rand));
 1409:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1410:        $newkey=~s/0/h/g; # and also 0 and O
 1411:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1412:        if ($existing{$newkey}) {
 1413:            $i--;
 1414:        } else {
 1415: 	  if (&put('accesskeys',
 1416:               { $newkey => '# generated '.localtime().
 1417:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1418:                            '; '.$logentry },
 1419: 		   $cdom,$cnum) eq 'ok') {
 1420:               $total++;
 1421: 	  }
 1422:        }
 1423:     }
 1424:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1425:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1426:     return $total;
 1427: }
 1428: 
 1429: # ------------------------------------------------------- Validate an accesskey
 1430: 
 1431: sub validate_access_key {
 1432:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1433:     $cdom=
 1434:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1435:     $cnum=
 1436:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1437:     $udom=$env{'user.domain'} unless (defined($udom));
 1438:     $uname=$env{'user.name'} unless (defined($uname));
 1439:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1440:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1441: }
 1442: 
 1443: # ------------------------------------- Find the section of student in a course
 1444: sub devalidate_getsection_cache {
 1445:     my ($udom,$unam,$courseid)=@_;
 1446:     my $hashid="$udom:$unam:$courseid";
 1447:     &devalidate_cache_new('getsection',$hashid);
 1448: }
 1449: 
 1450: sub courseid_to_courseurl {
 1451:     my ($courseid) = @_;
 1452:     #already url style courseid
 1453:     return $courseid if ($courseid =~ m{^/});
 1454: 
 1455:     if (exists($env{'course.'.$courseid.'.num'})) {
 1456: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1457: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1458: 	return "/$cdom/$cnum";
 1459:     }
 1460: 
 1461:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1462:     if (exists($courseinfo{'num'})) {
 1463: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1464:     }
 1465: 
 1466:     return undef;
 1467: }
 1468: 
 1469: sub getsection {
 1470:     my ($udom,$unam,$courseid)=@_;
 1471:     my $cachetime=1800;
 1472: 
 1473:     my $hashid="$udom:$unam:$courseid";
 1474:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1475:     if (defined($cached)) { return $result; }
 1476: 
 1477:     my %Pending; 
 1478:     my %Expired;
 1479:     #
 1480:     # Each role can either have not started yet (pending), be active, 
 1481:     #    or have expired.
 1482:     #
 1483:     # If there is an active role, we are done.
 1484:     #
 1485:     # If there is more than one role which has not started yet, 
 1486:     #     choose the one which will start sooner
 1487:     # If there is one role which has not started yet, return it.
 1488:     #
 1489:     # If there is more than one expired role, choose the one which ended last.
 1490:     # If there is a role which has expired, return it.
 1491:     #
 1492:     $courseid = &courseid_to_courseurl($courseid);
 1493:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1494:     foreach my $key (keys(%roleshash)) {
 1495:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1496:         my $section=$1;
 1497:         if ($key eq $courseid.'_st') { $section=''; }
 1498:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1499:         my $now=time;
 1500:         if (defined($end) && $end && ($now > $end)) {
 1501:             $Expired{$end}=$section;
 1502:             next;
 1503:         }
 1504:         if (defined($start) && $start && ($now < $start)) {
 1505:             $Pending{$start}=$section;
 1506:             next;
 1507:         }
 1508:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1509:     }
 1510:     #
 1511:     # Presumedly there will be few matching roles from the above
 1512:     # loop and the sorting time will be negligible.
 1513:     if (scalar(keys(%Pending))) {
 1514:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1515:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1516:     } 
 1517:     if (scalar(keys(%Expired))) {
 1518:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1519:         my $time = pop(@sorted);
 1520:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1521:     }
 1522:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1523: }
 1524: 
 1525: sub save_cache {
 1526:     &purge_remembered();
 1527:     #&Apache::loncommon::validate_page();
 1528:     undef(%env);
 1529:     undef($env_loaded);
 1530: }
 1531: 
 1532: my $to_remember=-1;
 1533: my %remembered;
 1534: my %accessed;
 1535: my $kicks=0;
 1536: my $hits=0;
 1537: sub make_key {
 1538:     my ($name,$id) = @_;
 1539:     if (length($id) > 65 
 1540: 	&& length(&escape($id)) > 200) {
 1541: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1542:     }
 1543:     return &escape($name.':'.$id);
 1544: }
 1545: 
 1546: sub devalidate_cache_new {
 1547:     my ($name,$id,$debug) = @_;
 1548:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1549:     $id=&make_key($name,$id);
 1550:     $memcache->delete($id);
 1551:     delete($remembered{$id});
 1552:     delete($accessed{$id});
 1553: }
 1554: 
 1555: sub is_cached_new {
 1556:     my ($name,$id,$debug) = @_;
 1557:     $id=&make_key($name,$id);
 1558:     if (exists($remembered{$id})) {
 1559: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1560: 	$accessed{$id}=[&gettimeofday()];
 1561: 	$hits++;
 1562: 	return ($remembered{$id},1);
 1563:     }
 1564:     my $value = $memcache->get($id);
 1565:     if (!(defined($value))) {
 1566: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1567: 	return (undef,undef);
 1568:     }
 1569:     if ($value eq '__undef__') {
 1570: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1571: 	$value=undef;
 1572:     }
 1573:     &make_room($id,$value,$debug);
 1574:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1575:     return ($value,1);
 1576: }
 1577: 
 1578: sub do_cache_new {
 1579:     my ($name,$id,$value,$time,$debug) = @_;
 1580:     $id=&make_key($name,$id);
 1581:     my $setvalue=$value;
 1582:     if (!defined($setvalue)) {
 1583: 	$setvalue='__undef__';
 1584:     }
 1585:     if (!defined($time) ) {
 1586: 	$time=600;
 1587:     }
 1588:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1589:     my $result = $memcache->set($id,$setvalue,$time);
 1590:     if (! $result) {
 1591: 	&logthis("caching of id -> $id  failed");
 1592: 	$memcache->disconnect_all();
 1593:     }
 1594:     # need to make a copy of $value
 1595:     &make_room($id,$value,$debug);
 1596:     return $value;
 1597: }
 1598: 
 1599: sub make_room {
 1600:     my ($id,$value,$debug)=@_;
 1601: 
 1602:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1603:                                     : $value;
 1604:     if ($to_remember<0) { return; }
 1605:     $accessed{$id}=[&gettimeofday()];
 1606:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1607:     my $to_kick;
 1608:     my $max_time=0;
 1609:     foreach my $other (keys(%accessed)) {
 1610: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1611: 	    $to_kick=$other;
 1612: 	    $max_time=&tv_interval($accessed{$other});
 1613: 	}
 1614:     }
 1615:     delete($remembered{$to_kick});
 1616:     delete($accessed{$to_kick});
 1617:     $kicks++;
 1618:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1619:     return;
 1620: }
 1621: 
 1622: sub purge_remembered {
 1623:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1624:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1625:     undef(%remembered);
 1626:     undef(%accessed);
 1627: }
 1628: # ------------------------------------- Read an entry from a user's environment
 1629: 
 1630: sub userenvironment {
 1631:     my ($udom,$unam,@what)=@_;
 1632:     my $items;
 1633:     foreach my $item (@what) {
 1634:         $items.=&escape($item).'&';
 1635:     }
 1636:     $items=~s/\&$//;
 1637:     my %returnhash=();
 1638:     my @answer=split(/\&/,
 1639:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1640:                       &homeserver($unam,$udom)));
 1641:     my $i;
 1642:     for ($i=0;$i<=$#what;$i++) {
 1643: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1644:     }
 1645:     return %returnhash;
 1646: }
 1647: 
 1648: # ---------------------------------------------------------- Get a studentphoto
 1649: sub studentphoto {
 1650:     my ($udom,$unam,$ext) = @_;
 1651:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1652:     if (defined($env{'request.course.id'})) {
 1653:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1654:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1655:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1656:             } else {
 1657:                 my ($result,$perm_reqd)=
 1658: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1659:                 if ($result eq 'ok') {
 1660:                     if (!($perm_reqd eq 'yes')) {
 1661:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1662:                     }
 1663:                 }
 1664:             }
 1665:         }
 1666:     } else {
 1667:         my ($result,$perm_reqd) = 
 1668: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1669:         if ($result eq 'ok') {
 1670:             if (!($perm_reqd eq 'yes')) {
 1671:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1672:             }
 1673:         }
 1674:     }
 1675:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1676: }
 1677: 
 1678: sub retrievestudentphoto {
 1679:     my ($udom,$unam,$ext,$type) = @_;
 1680:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1681:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1682:     if ($ret eq 'ok') {
 1683:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1684:         if ($type eq 'thumbnail') {
 1685:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1686:         }
 1687:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1688:         return $tokenurl;
 1689:     } else {
 1690:         if ($type eq 'thumbnail') {
 1691:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1692:         } else { 
 1693:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1694:         }
 1695:     }
 1696: }
 1697: 
 1698: # -------------------------------------------------------------------- New chat
 1699: 
 1700: sub chatsend {
 1701:     my ($newentry,$anon,$group)=@_;
 1702:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1703:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1704:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1705:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1706: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1707: 		   &escape($newentry)).':'.$group,$chome);
 1708: }
 1709: 
 1710: # ------------------------------------------ Find current version of a resource
 1711: 
 1712: sub getversion {
 1713:     my $fname=&clutter(shift);
 1714:     unless ($fname=~/^\/res\//) { return -1; }
 1715:     return &currentversion(&filelocation('',$fname));
 1716: }
 1717: 
 1718: sub currentversion {
 1719:     my $fname=shift;
 1720:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1721:     if (defined($cached)) { return $result; }
 1722:     my $author=$fname;
 1723:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1724:     my ($udom,$uname)=split(/\//,$author);
 1725:     my $home=homeserver($uname,$udom);
 1726:     if ($home eq 'no_host') { 
 1727:         return -1; 
 1728:     }
 1729:     my $answer=reply("currentversion:$fname",$home);
 1730:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1731: 	return -1;
 1732:     }
 1733:     return &do_cache_new('resversion',$fname,$answer,600);
 1734: }
 1735: 
 1736: # ----------------------------- Subscribe to a resource, return URL if possible
 1737: 
 1738: sub subscribe {
 1739:     my $fname=shift;
 1740:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1741:     $fname=~s/[\n\r]//g;
 1742:     my $author=$fname;
 1743:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1744:     my ($udom,$uname)=split(/\//,$author);
 1745:     my $home=homeserver($uname,$udom);
 1746:     if ($home eq 'no_host') {
 1747:         return 'not_found';
 1748:     }
 1749:     my $answer=reply("sub:$fname",$home);
 1750:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1751: 	$answer.=' by '.$home;
 1752:     }
 1753:     return $answer;
 1754: }
 1755:     
 1756: # -------------------------------------------------------------- Replicate file
 1757: 
 1758: sub repcopy {
 1759:     my $filename=shift;
 1760:     $filename=~s/\/+/\//g;
 1761:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1762:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1763:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1764: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1765: 	return &repcopy_userfile($filename);
 1766:     }
 1767:     $filename=~s/[\n\r]//g;
 1768:     my $transname="$filename.in.transfer";
 1769: # FIXME: this should flock
 1770:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1771:     my $remoteurl=subscribe($filename);
 1772:     if ($remoteurl =~ /^con_lost by/) {
 1773: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1774:            return 'unavailable';
 1775:     } elsif ($remoteurl eq 'not_found') {
 1776: 	   #&logthis("Subscribe returned not_found: $filename");
 1777: 	   return 'not_found';
 1778:     } elsif ($remoteurl =~ /^rejected by/) {
 1779: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1780:            return 'forbidden';
 1781:     } elsif ($remoteurl eq 'directory') {
 1782:            return 'ok';
 1783:     } else {
 1784:         my $author=$filename;
 1785:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1786:         my ($udom,$uname)=split(/\//,$author);
 1787:         my $home=homeserver($uname,$udom);
 1788:         unless ($home eq $perlvar{'lonHostID'}) {
 1789:            my @parts=split(/\//,$filename);
 1790:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1791:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1792:                &logthis("Malconfiguration for replication: $filename");
 1793: 	       return 'bad_request';
 1794:            }
 1795:            my $count;
 1796:            for ($count=5;$count<$#parts;$count++) {
 1797:                $path.="/$parts[$count]";
 1798:                if ((-e $path)!=1) {
 1799: 		   mkdir($path,0777);
 1800:                }
 1801:            }
 1802:            my $ua=new LWP::UserAgent;
 1803:            my $request=new HTTP::Request('GET',"$remoteurl");
 1804:            my $response=$ua->request($request,$transname);
 1805:            if ($response->is_error()) {
 1806: 	       unlink($transname);
 1807:                my $message=$response->status_line;
 1808:                &logthis("<font color=\"blue\">WARNING:"
 1809:                        ." LWP get: $message: $filename</font>");
 1810:                return 'unavailable';
 1811:            } else {
 1812: 	       if ($remoteurl!~/\.meta$/) {
 1813:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1814:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1815:                   if ($mresponse->is_error()) {
 1816: 		      unlink($filename.'.meta');
 1817:                       &logthis(
 1818:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1819:                   }
 1820: 	       }
 1821:                rename($transname,$filename);
 1822:                return 'ok';
 1823:            }
 1824:        }
 1825:     }
 1826: }
 1827: 
 1828: # ------------------------------------------------ Get server side include body
 1829: sub ssi_body {
 1830:     my ($filelink,%form)=@_;
 1831:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1832:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1833:     }
 1834:     my $output='';
 1835:     my $response;
 1836:     if ($filelink=~/^https?\:/) {
 1837:        ($output,$response)=&externalssi($filelink);
 1838:     } else {
 1839:        ($output,$response)=&ssi($filelink,%form);
 1840:     }
 1841:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1842:     $output=~s/^.*?\<body[^\>]*\>//si;
 1843:     $output=~s/\<\/body\s*\>.*?$//si;
 1844:     if (wantarray) {
 1845:         return ($output, $response);
 1846:     } else {
 1847:         return $output;
 1848:     }
 1849: }
 1850: 
 1851: # --------------------------------------------------------- Server Side Include
 1852: 
 1853: sub absolute_url {
 1854:     my ($host_name) = @_;
 1855:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1856:     if ($host_name eq '') {
 1857: 	$host_name = $ENV{'SERVER_NAME'};
 1858:     }
 1859:     return $protocol.$host_name;
 1860: }
 1861: 
 1862: #
 1863: #   Server side include.
 1864: # Parameters:
 1865: #  fn     Possibly encrypted resource name/id.
 1866: #  form   Hash that describes how the rendering should be done
 1867: #         and other things.
 1868: # Returns:
 1869: #   Scalar context: The content of the response.
 1870: #   Array context:  2 element list of the content and the full response object.
 1871: #     
 1872: sub ssi {
 1873: 
 1874:     my ($fn,%form)=@_;
 1875:     my $ua=new LWP::UserAgent;
 1876:     my $request;
 1877: 
 1878:     $form{'no_update_last_known'}=1;
 1879:     &Apache::lonenc::check_encrypt(\$fn);
 1880:     if (%form) {
 1881:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1882:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1883:     } else {
 1884:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1885:     }
 1886: 
 1887:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1888:     my $response=$ua->request($request);
 1889: 
 1890:     if (wantarray) {
 1891: 	return ($response->content, $response);
 1892:     } else {
 1893: 	return $response->content;
 1894:     }
 1895: }
 1896: 
 1897: sub externalssi {
 1898:     my ($url)=@_;
 1899:     my $ua=new LWP::UserAgent;
 1900:     my $request=new HTTP::Request('GET',$url);
 1901:     my $response=$ua->request($request);
 1902:     if (wantarray) {
 1903:         return ($response->content, $response);
 1904:     } else {
 1905:         return $response->content;
 1906:     }
 1907: }
 1908: 
 1909: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1910: 
 1911: sub allowuploaded {
 1912:     my ($srcurl,$url)=@_;
 1913:     $url=&clutter(&declutter($url));
 1914:     my $dir=$url;
 1915:     $dir=~s/\/[^\/]+$//;
 1916:     my %httpref=();
 1917:     my $httpurl=&hreflocation('',$url);
 1918:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1919:     &Apache::lonnet::appenv(\%httpref);
 1920: }
 1921: 
 1922: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1923: # input: action, courseID, current domain, intended
 1924: #        path to file, source of file, instruction to parse file for objects,
 1925: #        ref to hash for embedded objects,
 1926: #        ref to hash for codebase of java objects.
 1927: #
 1928: # output: url to file (if action was uploaddoc), 
 1929: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1930: #
 1931: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1932: # course.
 1933: #
 1934: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1935: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1936: #          course's home server.
 1937: #
 1938: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1939: #          be copied from $source (current location) to 
 1940: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1941: #         and will then be copied to
 1942: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1943: #         course's home server.
 1944: #
 1945: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1946: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1947: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1948: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1949: #         in course's home server.
 1950: #
 1951: 
 1952: sub process_coursefile {
 1953:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1954:     my $fetchresult;
 1955:     my $home=&homeserver($docuname,$docudom);
 1956:     if ($action eq 'propagate') {
 1957:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1958: 			     $home);
 1959:     } else {
 1960:         my $fpath = '';
 1961:         my $fname = $file;
 1962:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1963:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1964:         my $filepath = &build_filepath($fpath);
 1965:         if ($action eq 'copy') {
 1966:             if ($source eq '') {
 1967:                 $fetchresult = 'no source file';
 1968:                 return $fetchresult;
 1969:             } else {
 1970:                 my $destination = $filepath.'/'.$fname;
 1971:                 rename($source,$destination);
 1972:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1973:                                  $home);
 1974:             }
 1975:         } elsif ($action eq 'uploaddoc') {
 1976:             open(my $fh,'>'.$filepath.'/'.$fname);
 1977:             print $fh $env{'form.'.$source};
 1978:             close($fh);
 1979:             if ($parser eq 'parse') {
 1980:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1981:                 unless ($parse_result eq 'ok') {
 1982:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1983:                 }
 1984:             }
 1985:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1986:                                  $home);
 1987:             if ($fetchresult eq 'ok') {
 1988:                 return '/uploaded/'.$fpath.'/'.$fname;
 1989:             } else {
 1990:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1991:                         ' to host '.$home.': '.$fetchresult);
 1992:                 return '/adm/notfound.html';
 1993:             }
 1994:         }
 1995:     }
 1996:     unless ( $fetchresult eq 'ok') {
 1997:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1998:              ' to host '.$home.': '.$fetchresult);
 1999:     }
 2000:     return $fetchresult;
 2001: }
 2002: 
 2003: sub build_filepath {
 2004:     my ($fpath) = @_;
 2005:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2006:     unless ($fpath eq '') {
 2007:         my @parts=split('/',$fpath);
 2008:         foreach my $part (@parts) {
 2009:             $filepath.= '/'.$part;
 2010:             if ((-e $filepath)!=1) {
 2011:                 mkdir($filepath,0777);
 2012:             }
 2013:         }
 2014:     }
 2015:     return $filepath;
 2016: }
 2017: 
 2018: sub store_edited_file {
 2019:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2020:     my $file = $primary_url;
 2021:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2022:     my $fpath = '';
 2023:     my $fname = $file;
 2024:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2025:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2026:     my $filepath = &build_filepath($fpath);
 2027:     open(my $fh,'>'.$filepath.'/'.$fname);
 2028:     print $fh $content;
 2029:     close($fh);
 2030:     my $home=&homeserver($docuname,$docudom);
 2031:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2032: 			  $home);
 2033:     if ($$fetchresult eq 'ok') {
 2034:         return '/uploaded/'.$fpath.'/'.$fname;
 2035:     } else {
 2036:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2037: 		 ' to host '.$home.': '.$$fetchresult);
 2038:         return '/adm/notfound.html';
 2039:     }
 2040: }
 2041: 
 2042: sub clean_filename {
 2043:     my ($fname,$args)=@_;
 2044: # Replace Windows backslashes by forward slashes
 2045:     $fname=~s/\\/\//g;
 2046:     if (!$args->{'keep_path'}) {
 2047:         # Get rid of everything but the actual filename
 2048: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2049:     }
 2050: # Replace spaces by underscores
 2051:     $fname=~s/\s+/\_/g;
 2052: # Replace all other weird characters by nothing
 2053:     $fname=~s{[^/\w\.\-]}{}g;
 2054: # Replace all .\d. sequences with _\d. so they no longer look like version
 2055: # numbers
 2056:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2057:     return $fname;
 2058: }
 2059: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2060: sub resizeImage {
 2061: 	my($img_url) = @_;	
 2062: 	my $ima = Image::Magick->new;                       
 2063:         $ima->Read($img_url);
 2064: 	if($ima->Get('width') > 400)
 2065: 	{
 2066: 		my $factor = $ima->Get('width')/400;
 2067:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2068: 	}
 2069: 	if($ima->Get('height') > 500)
 2070:         {
 2071:         	my $factor = $ima->Get('height')/500;
 2072:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2073:         } 
 2074: 		
 2075: 	$ima->Write($img_url);
 2076: }
 2077: 
 2078: #Wrapper function for userphotoupload
 2079: sub userphotoupload
 2080: {
 2081: 	my($formname,$subdir) = @_;
 2082: 	$upload_photo_form = 1;
 2083: 	return &userfileupload($formname,undef,$subdir);
 2084: }
 2085: 
 2086: # --------------- Take an uploaded file and put it into the userfiles directory
 2087: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2088: #                    the desired filenam is in $env{"form.$formname.filename"}
 2089: #        $coursedoc - if true up to the current course
 2090: #                     if false
 2091: #        $subdir - directory in userfile to store the file into
 2092: #        $parser - instruction to parse file for objects ($parser = parse)    
 2093: #        $allfiles - reference to hash for embedded objects
 2094: #        $codebase - reference to hash for codebase of java objects
 2095: #        $desuname - username for permanent storage of uploaded file
 2096: #        $dsetudom - domain for permanaent storage of uploaded file
 2097: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2098: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2099: # 
 2100: # output: url of file in userspace, or error: <message> 
 2101: #             or /adm/notfound.html if failure to upload occurse
 2102: 
 2103: 
 2104: sub userfileupload {
 2105:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2106:         $destudom,$thumbwidth,$thumbheight)=@_;
 2107:     if (!defined($subdir)) { $subdir='unknown'; }
 2108:     my $fname=$env{'form.'.$formname.'.filename'};
 2109:     $fname=&clean_filename($fname);
 2110: # See if there is anything left
 2111:     unless ($fname) { return 'error: no uploaded file'; }
 2112:     chop($env{'form.'.$formname});
 2113:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2114:         my $now = time;
 2115:         my $filepath = 'tmp/helprequests/'.$now;
 2116:         my @parts=split(/\//,$filepath);
 2117:         my $fullpath = $perlvar{'lonDaemons'};
 2118:         for (my $i=0;$i<@parts;$i++) {
 2119:             $fullpath .= '/'.$parts[$i];
 2120:             if ((-e $fullpath)!=1) {
 2121:                 mkdir($fullpath,0777);
 2122:             }
 2123:         }
 2124:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2125:         print $fh $env{'form.'.$formname};
 2126:         close($fh);
 2127:         return $fullpath.'/'.$fname;
 2128:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2129:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2130:                        '_'.$env{'user.domain'}.'/pending';
 2131:         my @parts=split(/\//,$filepath);
 2132:         my $fullpath = $perlvar{'lonDaemons'};
 2133:         for (my $i=0;$i<@parts;$i++) {
 2134:             $fullpath .= '/'.$parts[$i];
 2135:             if ((-e $fullpath)!=1) {
 2136:                 mkdir($fullpath,0777);
 2137:             }
 2138:         }
 2139:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2140:         print $fh $env{'form.'.$formname};
 2141:         close($fh);
 2142:         return $fullpath.'/'.$fname;
 2143:     }
 2144:     
 2145: # Create the directory if not present
 2146:     $fname="$subdir/$fname";
 2147:     if ($coursedoc) {
 2148: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2149: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2150:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2151:             return &finishuserfileupload($docuname,$docudom,
 2152: 					 $formname,$fname,$parser,$allfiles,
 2153: 					 $codebase,$thumbwidth,$thumbheight);
 2154:         } else {
 2155:             $fname=$env{'form.folder'}.'/'.$fname;
 2156:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2157: 				       $fname,$formname,$parser,
 2158: 				       $allfiles,$codebase);
 2159:         }
 2160:     } elsif (defined($destuname)) {
 2161:         my $docuname=$destuname;
 2162:         my $docudom=$destudom;
 2163: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2164: 				     $parser,$allfiles,$codebase,
 2165:                                      $thumbwidth,$thumbheight);
 2166:         
 2167:     } else {
 2168:         my $docuname=$env{'user.name'};
 2169:         my $docudom=$env{'user.domain'};
 2170:         if (exists($env{'form.group'})) {
 2171:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2172:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2173:         }
 2174: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2175: 				     $parser,$allfiles,$codebase,
 2176:                                      $thumbwidth,$thumbheight);
 2177:     }
 2178: }
 2179: 
 2180: sub finishuserfileupload {
 2181:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2182:         $thumbwidth,$thumbheight) = @_;
 2183:     my $path=$docudom.'/'.$docuname.'/';
 2184:     my $filepath=$perlvar{'lonDocRoot'};
 2185:   
 2186:     my ($fnamepath,$file,$fetchthumb);
 2187:     $file=$fname;
 2188:     if ($fname=~m|/|) {
 2189:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2190: 	$path.=$fnamepath.'/';
 2191:     }
 2192:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2193:     my $count;
 2194:     for ($count=4;$count<=$#parts;$count++) {
 2195:         $filepath.="/$parts[$count]";
 2196:         if ((-e $filepath)!=1) {
 2197: 	    mkdir($filepath,0777);
 2198:         }
 2199:     }
 2200: 
 2201: # Save the file
 2202:     {
 2203: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2204: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2205: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2206: 	    return '/adm/notfound.html';
 2207: 	}
 2208: 	if (!print FH ($env{'form.'.$formname})) {
 2209: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2210: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2211: 	    return '/adm/notfound.html';
 2212: 	}
 2213: 	close(FH);
 2214: 	if($upload_photo_form==1)
 2215: 	{
 2216: 		resizeImage($filepath.'/'.$file);		
 2217: 		$upload_photo_form = 0;
 2218: 	}
 2219:     }
 2220:     if ($parser eq 'parse') {
 2221:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2222: 						   $codebase);
 2223:         unless ($parse_result eq 'ok') {
 2224:             &logthis('Failed to parse '.$filepath.$file.
 2225: 		     ' for embedded media: '.$parse_result); 
 2226:         }
 2227:     }
 2228:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2229:         my $input = $filepath.'/'.$file;
 2230:         my $output = $filepath.'/'.'tn-'.$file;
 2231:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2232:         system("convert -sample $thumbsize $input $output");
 2233:         if (-e $filepath.'/'.'tn-'.$file) {
 2234:             $fetchthumb  = 1; 
 2235:         }
 2236:     }
 2237:  
 2238: # Notify homeserver to grep it
 2239: #
 2240:     my $docuhome=&homeserver($docuname,$docudom);	
 2241:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2242:     if ($fetchresult eq 'ok') {
 2243:         if ($fetchthumb) {
 2244:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2245:             if ($thumbresult ne 'ok') {
 2246:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2247:                          $docuhome.': '.$thumbresult);
 2248:             }
 2249:         }
 2250: #
 2251: # Return the URL to it
 2252:         return '/uploaded/'.$path.$file;
 2253:     } else {
 2254:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2255: 		 ': '.$fetchresult);
 2256:         return '/adm/notfound.html';
 2257:     }
 2258: }
 2259: 
 2260: sub extract_embedded_items {
 2261:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2262:     my @state = ();
 2263:     my %javafiles = (
 2264:                       codebase => '',
 2265:                       code => '',
 2266:                       archive => ''
 2267:                     );
 2268:     my %mediafiles = (
 2269:                       src => '',
 2270:                       movie => '',
 2271:                      );
 2272:     my $p;
 2273:     if ($content) {
 2274:         $p = HTML::LCParser->new($content);
 2275:     } else {
 2276:         $p = HTML::LCParser->new($fullpath);
 2277:     }
 2278:     while (my $t=$p->get_token()) {
 2279: 	if ($t->[0] eq 'S') {
 2280: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2281: 	    push(@state, $tagname);
 2282:             if (lc($tagname) eq 'allow') {
 2283:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2284:             }
 2285: 	    if (lc($tagname) eq 'img') {
 2286: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2287: 	    }
 2288: 	    if (lc($tagname) eq 'a') {
 2289: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2290: 	    }
 2291:             if (lc($tagname) eq 'script') {
 2292:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2293:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2294:                 } else {
 2295:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2296:                 }
 2297:             }
 2298:             if (lc($tagname) eq 'link') {
 2299:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2300:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2301:                 }
 2302:             }
 2303: 	    if (lc($tagname) eq 'object' ||
 2304: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2305: 		foreach my $item (keys(%javafiles)) {
 2306: 		    $javafiles{$item} = '';
 2307: 		}
 2308: 	    }
 2309: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2310: 		my $name = lc($attr->{'name'});
 2311: 		foreach my $item (keys(%javafiles)) {
 2312: 		    if ($name eq $item) {
 2313: 			$javafiles{$item} = $attr->{'value'};
 2314: 			last;
 2315: 		    }
 2316: 		}
 2317: 		foreach my $item (keys(%mediafiles)) {
 2318: 		    if ($name eq $item) {
 2319: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2320: 			last;
 2321: 		    }
 2322: 		}
 2323: 	    }
 2324: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2325: 		foreach my $item (keys(%javafiles)) {
 2326: 		    if ($attr->{$item}) {
 2327: 			$javafiles{$item} = $attr->{$item};
 2328: 			last;
 2329: 		    }
 2330: 		}
 2331: 		foreach my $item (keys(%mediafiles)) {
 2332: 		    if ($attr->{$item}) {
 2333: 			&add_filetype($allfiles,$attr->{$item},$item);
 2334: 			last;
 2335: 		    }
 2336: 		}
 2337: 	    }
 2338: 	} elsif ($t->[0] eq 'E') {
 2339: 	    my ($tagname) = ($t->[1]);
 2340: 	    if ($javafiles{'codebase'} ne '') {
 2341: 		$javafiles{'codebase'} .= '/';
 2342: 	    }  
 2343: 	    if (lc($tagname) eq 'applet' ||
 2344: 		lc($tagname) eq 'object' ||
 2345: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2346: 		) {
 2347: 		foreach my $item (keys(%javafiles)) {
 2348: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2349: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2350: 			&add_filetype($allfiles,$file,$item);
 2351: 		    }
 2352: 		}
 2353: 	    } 
 2354: 	    pop @state;
 2355: 	}
 2356:     }
 2357:     return 'ok';
 2358: }
 2359: 
 2360: sub add_filetype {
 2361:     my ($allfiles,$file,$type)=@_;
 2362:     if (exists($allfiles->{$file})) {
 2363: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2364: 	    push(@{$allfiles->{$file}}, &escape($type));
 2365: 	}
 2366:     } else {
 2367: 	@{$allfiles->{$file}} = (&escape($type));
 2368:     }
 2369: }
 2370: 
 2371: sub removeuploadedurl {
 2372:     my ($url)=@_;	
 2373:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2374:     return &removeuserfile($uname,$udom,$fname);
 2375: }
 2376: 
 2377: sub removeuserfile {
 2378:     my ($docuname,$docudom,$fname)=@_;
 2379:     my $home=&homeserver($docuname,$docudom);    
 2380:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2381:     if ($result eq 'ok') {	
 2382:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2383:             my $metafile = $fname.'.meta';
 2384:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2385: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2386:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2387:             my $sqlresult = 
 2388:                 &update_portfolio_table($docuname,$docudom,$file,
 2389:                                         'portfolio_metadata',$group,
 2390:                                         'delete');
 2391:         }
 2392:     }
 2393:     return $result;
 2394: }
 2395: 
 2396: sub mkdiruserfile {
 2397:     my ($docuname,$docudom,$dir)=@_;
 2398:     my $home=&homeserver($docuname,$docudom);
 2399:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2400: }
 2401: 
 2402: sub renameuserfile {
 2403:     my ($docuname,$docudom,$old,$new)=@_;
 2404:     my $home=&homeserver($docuname,$docudom);
 2405:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2406:                         &escape("$old").':'.&escape("$new"),$home);
 2407:     if ($result eq 'ok') {
 2408:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2409:             my $oldmeta = $old.'.meta';
 2410:             my $newmeta = $new.'.meta';
 2411:             my $metaresult = 
 2412:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2413: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2414:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2415:             my $sqlresult = 
 2416:                 &update_portfolio_table($docuname,$docudom,$file,
 2417:                                         'portfolio_metadata',$group,
 2418:                                         'delete');
 2419:         }
 2420:     }
 2421:     return $result;
 2422: }
 2423: 
 2424: # ------------------------------------------------------------------------- Log
 2425: 
 2426: sub log {
 2427:     my ($dom,$nam,$hom,$what)=@_;
 2428:     return critical("log:$dom:$nam:$what",$hom);
 2429: }
 2430: 
 2431: # ------------------------------------------------------------------ Course Log
 2432: #
 2433: # This routine flushes several buffers of non-mission-critical nature
 2434: #
 2435: 
 2436: sub flushcourselogs {
 2437:     &logthis('Flushing log buffers');
 2438: #
 2439: # course logs
 2440: # This is a log of all transactions in a course, which can be used
 2441: # for data mining purposes
 2442: #
 2443: # It also collects the courseid database, which lists last transaction
 2444: # times and course titles for all courseids
 2445: #
 2446:     my %courseidbuffer=();
 2447:     foreach my $crsid (keys(%courselogs)) {
 2448:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2449: 		          &escape($courselogs{$crsid}),
 2450: 		          $coursehombuf{$crsid}) eq 'ok') {
 2451: 	    delete $courselogs{$crsid};
 2452:         } else {
 2453:             &logthis('Failed to flush log buffer for '.$crsid);
 2454:             if (length($courselogs{$crsid})>40000) {
 2455:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2456:                         " exceeded maximum size, deleting.</font>");
 2457:                delete $courselogs{$crsid};
 2458:             }
 2459:         }
 2460:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2461:             'description' => $coursedescrbuf{$crsid},
 2462:             'inst_code'    => $courseinstcodebuf{$crsid},
 2463:             'type'        => $coursetypebuf{$crsid},
 2464:             'owner'       => $courseownerbuf{$crsid},
 2465:         };
 2466:     }
 2467: #
 2468: # Write course id database (reverse lookup) to homeserver of courses 
 2469: # Is used in pickcourse
 2470: #
 2471:     foreach my $crs_home (keys(%courseidbuffer)) {
 2472:         my $response = &courseidput(&host_domain($crs_home),
 2473:                                     $courseidbuffer{$crs_home},
 2474:                                     $crs_home,'timeonly');
 2475:     }
 2476: #
 2477: # File accesses
 2478: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2479: #
 2480:     foreach my $entry (keys(%accesshash)) {
 2481:         if ($entry =~ /___count$/) {
 2482:             my ($dom,$name);
 2483:             ($dom,$name,undef)=
 2484: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2485:             if (! defined($dom) || $dom eq '' || 
 2486:                 ! defined($name) || $name eq '') {
 2487:                 my $cid = $env{'request.course.id'};
 2488:                 $dom  = $env{'request.'.$cid.'.domain'};
 2489:                 $name = $env{'request.'.$cid.'.num'};
 2490:             }
 2491:             my $value = $accesshash{$entry};
 2492:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2493:             my %temphash=($url => $value);
 2494:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2495:             if ($result eq 'ok') {
 2496:                 delete $accesshash{$entry};
 2497:             } elsif ($result eq 'unknown_cmd') {
 2498:                 # Target server has old code running on it.
 2499:                 my %temphash=($entry => $value);
 2500:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2501:                     delete $accesshash{$entry};
 2502:                 }
 2503:             }
 2504:         } else {
 2505:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2506:             my %temphash=($entry => $accesshash{$entry});
 2507:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2508:                 delete $accesshash{$entry};
 2509:             }
 2510:         }
 2511:     }
 2512: #
 2513: # Roles
 2514: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2515: #
 2516:     foreach my $entry (keys(%userrolehash)) {
 2517:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2518: 	    split(/\:/,$entry);
 2519:         if (&Apache::lonnet::put('nohist_userroles',
 2520:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2521:                 $rudom,$runame) eq 'ok') {
 2522: 	    delete $userrolehash{$entry};
 2523:         }
 2524:     }
 2525: #
 2526: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2527: #
 2528:     my %domrolebuffer = ();
 2529:     foreach my $entry (keys %domainrolehash) {
 2530:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2531:         if ($domrolebuffer{$rudom}) {
 2532:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2533:                       '='.&escape($domainrolehash{$entry});
 2534:         } else {
 2535:             $domrolebuffer{$rudom}.=&escape($entry).
 2536:                       '='.&escape($domainrolehash{$entry});
 2537:         }
 2538:         delete $domainrolehash{$entry};
 2539:     }
 2540:     foreach my $dom (keys(%domrolebuffer)) {
 2541: 	my %servers = &get_servers($dom,'library');
 2542: 	foreach my $tryserver (keys(%servers)) {
 2543: 	    unless (&reply('domroleput:'.$dom.':'.
 2544: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2545: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2546: 	    }
 2547:         }
 2548:     }
 2549:     $dumpcount++;
 2550: }
 2551: 
 2552: sub courselog {
 2553:     my $what=shift;
 2554:     $what=time.':'.$what;
 2555:     unless ($env{'request.course.id'}) { return ''; }
 2556:     $coursedombuf{$env{'request.course.id'}}=
 2557:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2558:     $coursenumbuf{$env{'request.course.id'}}=
 2559:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2560:     $coursehombuf{$env{'request.course.id'}}=
 2561:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2562:     $coursedescrbuf{$env{'request.course.id'}}=
 2563:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2564:     $courseinstcodebuf{$env{'request.course.id'}}=
 2565:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2566:     $courseownerbuf{$env{'request.course.id'}}=
 2567:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2568:     $coursetypebuf{$env{'request.course.id'}}=
 2569:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2570:     if (defined $courselogs{$env{'request.course.id'}}) {
 2571: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2572:     } else {
 2573: 	$courselogs{$env{'request.course.id'}}.=$what;
 2574:     }
 2575:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2576: 	&flushcourselogs();
 2577:     }
 2578: }
 2579: 
 2580: sub courseacclog {
 2581:     my $fnsymb=shift;
 2582:     unless ($env{'request.course.id'}) { return ''; }
 2583:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2584:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2585:         $what.=':POST';
 2586:         # FIXME: Probably ought to escape things....
 2587: 	foreach my $key (keys(%env)) {
 2588:             if ($key=~/^form\.(.*)/) {
 2589:                 my $formitem = $1;
 2590:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2591:                     $what.=':'.$formitem.'='.$env{$key};
 2592:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2593:                     $what.=':'.$formitem.'='.$env{$key};
 2594:                 }
 2595:             }
 2596:         }
 2597:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2598:         # FIXME: We should not be depending on a form parameter that someone
 2599:         # editing lonsearchcat.pm might change in the future.
 2600:         if ($env{'form.phase'} eq 'course_search') {
 2601:             $what.= ':POST';
 2602:             # FIXME: Probably ought to escape things....
 2603:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2604:                                  'crsdiscuss') {
 2605:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2606:             }
 2607:         }
 2608:     }
 2609:     &courselog($what);
 2610: }
 2611: 
 2612: sub countacc {
 2613:     my $url=&declutter(shift);
 2614:     return if (! defined($url) || $url eq '');
 2615:     unless ($env{'request.course.id'}) { return ''; }
 2616:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2617:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2618:     $accesshash{$key}++;
 2619: }
 2620: 
 2621: sub linklog {
 2622:     my ($from,$to)=@_;
 2623:     $from=&declutter($from);
 2624:     $to=&declutter($to);
 2625:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2626:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2627: }
 2628:   
 2629: sub userrolelog {
 2630:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2631:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2632:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2633:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2634:         ($trole=~/^ta/)) {
 2635:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2636:        $userrolehash
 2637:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2638:                     =$tend.':'.$tstart;
 2639:     }
 2640:     if (($env{'request.role'} =~ /dc\./) &&
 2641: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2642: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2643: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2644:        $userrolehash
 2645:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2646:                     =$tend.':'.$tstart;
 2647:     }
 2648:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2649:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2650:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2651:         ($trole=~/^sc/)) {
 2652:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2653:        $domainrolehash
 2654:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2655:                     = $tend.':'.$tstart;
 2656:     }
 2657: }
 2658: 
 2659: sub courserolelog {
 2660:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2661:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2662:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2663:         ($trole eq 'ta') || ($trole eq 'st') ||
 2664:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2665:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2666:             my $cdom = $1;
 2667:             my $cnum = $2;
 2668:             my $sec = $3;
 2669:             my $namespace = 'rolelog';
 2670:             my %storehash = (
 2671:                                role    => $trole,
 2672:                                start   => $tstart,
 2673:                                end     => $tend,
 2674:                                selfenroll => $selfenroll,
 2675:                                context    => $context,
 2676:                             );
 2677:             if ($trole eq 'gr') {
 2678:                 $namespace = 'groupslog';
 2679:                 $storehash{'group'} = $sec;
 2680:             } else {
 2681:                 $storehash{'section'} = $sec;
 2682:             }
 2683:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2684:         }
 2685:     }
 2686:     return;
 2687: }
 2688: 
 2689: sub get_course_adv_roles {
 2690:     my ($cid,$codes) = @_;
 2691:     $cid=$env{'request.course.id'} unless (defined($cid));
 2692:     my %coursehash=&coursedescription($cid);
 2693:     my $crstype = &Apache::loncommon::course_type($cid);
 2694:     my %nothide=();
 2695:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2696:         if ($user !~ /:/) {
 2697: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2698:         } else {
 2699:             $nothide{$user}=1;
 2700:         }
 2701:     }
 2702:     my %returnhash=();
 2703:     my %dumphash=
 2704:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2705:     my $now=time;
 2706:     foreach my $entry (keys %dumphash) {
 2707: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2708:         if (($tstart) && ($tstart<0)) { next; }
 2709:         if (($tend) && ($tend<$now)) { next; }
 2710:         if (($tstart) && ($now<$tstart)) { next; }
 2711:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2712: 	if ($username eq '' || $domain eq '') { next; }
 2713: 	if ((&privileged($username,$domain)) && 
 2714: 	    (!$nothide{$username.':'.$domain})) { next; }
 2715: 	if ($role eq 'cr') { next; }
 2716:         if ($codes) {
 2717:             if ($section) { $role .= ':'.$section; }
 2718:             if ($returnhash{$role}) {
 2719:                 $returnhash{$role}.=','.$username.':'.$domain;
 2720:             } else {
 2721:                 $returnhash{$role}=$username.':'.$domain;
 2722:             }
 2723:         } else {
 2724:             my $key=&plaintext($role,$crstype);
 2725:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2726:             if ($returnhash{$key}) {
 2727: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2728:             } else {
 2729:                 $returnhash{$key}=$username.':'.$domain;
 2730:             }
 2731:         }
 2732:     }
 2733:     return %returnhash;
 2734: }
 2735: 
 2736: sub get_my_roles {
 2737:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2738:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2739:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2740:     my (%dumphash,%nothide);
 2741:     if ($context eq 'userroles') { 
 2742:         %dumphash = &dump('roles',$udom,$uname);
 2743:     } else {
 2744:         %dumphash=
 2745:             &dump('nohist_userroles',$udom,$uname);
 2746:         if ($hidepriv) {
 2747:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2748:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2749:                 if ($user !~ /:/) {
 2750:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2751:                 } else {
 2752:                     $nothide{$user} = 1;
 2753:                 }
 2754:             }
 2755:         }
 2756:     }
 2757:     my %returnhash=();
 2758:     my $now=time;
 2759:     foreach my $entry (keys(%dumphash)) {
 2760:         my ($role,$tend,$tstart);
 2761:         if ($context eq 'userroles') {
 2762: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2763:         } else {
 2764:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2765:         }
 2766:         if (($tstart) && ($tstart<0)) { next; }
 2767:         my $status = 'active';
 2768:         if (($tend) && ($tend<=$now)) {
 2769:             $status = 'previous';
 2770:         } 
 2771:         if (($tstart) && ($now<$tstart)) {
 2772:             $status = 'future';
 2773:         }
 2774:         if (ref($types) eq 'ARRAY') {
 2775:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2776:                 next;
 2777:             } 
 2778:         } else {
 2779:             if ($status ne 'active') {
 2780:                 next;
 2781:             }
 2782:         }
 2783:         my ($rolecode,$username,$domain,$section,$area);
 2784:         if ($context eq 'userroles') {
 2785:             ($area,$rolecode) = split(/_/,$entry);
 2786:             (undef,$domain,$username,$section) = split(/\//,$area);
 2787:         } else {
 2788:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2789:         }
 2790:         if (ref($roledoms) eq 'ARRAY') {
 2791:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2792:                 next;
 2793:             }
 2794:         }
 2795:         if (ref($roles) eq 'ARRAY') {
 2796:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2797:                 if ($role =~ /^cr\//) {
 2798:                     if (!grep(/^cr$/,@{$roles})) {
 2799:                         next;
 2800:                     }
 2801:                 } else {
 2802:                     next;
 2803:                 }
 2804:             }
 2805:         }
 2806:         if ($hidepriv) {
 2807:             if ((&privileged($username,$domain)) &&
 2808:                 (!$nothide{$username.':'.$domain})) { 
 2809:                 next;
 2810:             }
 2811:         }
 2812:         if ($withsec) {
 2813:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2814:                 $tstart.':'.$tend;
 2815:         } else {
 2816:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2817:         }
 2818:     }
 2819:     return %returnhash;
 2820: }
 2821: 
 2822: # ----------------------------------------------------- Frontpage Announcements
 2823: #
 2824: #
 2825: 
 2826: sub postannounce {
 2827:     my ($server,$text)=@_;
 2828:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2829:     unless ($text=~/\w/) { $text=''; }
 2830:     return &reply('setannounce:'.&escape($text),$server);
 2831: }
 2832: 
 2833: sub getannounce {
 2834: 
 2835:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2836: 	my $announcement='';
 2837: 	while (my $line = <$fh>) { $announcement .= $line; }
 2838: 	close($fh);
 2839: 	if ($announcement=~/\w/) { 
 2840: 	    return 
 2841:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2842:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2843: 	} else {
 2844: 	    return '';
 2845: 	}
 2846:     } else {
 2847: 	return '';
 2848:     }
 2849: }
 2850: 
 2851: # ---------------------------------------------------------- Course ID routines
 2852: # Deal with domain's nohist_courseid.db files
 2853: #
 2854: 
 2855: sub courseidput {
 2856:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2857:     my $outcome;
 2858:     if ($caller eq 'timeonly') {
 2859:         my $cids = '';
 2860:         foreach my $item (keys(%$storehash)) {
 2861:             $cids.=&escape($item).'&';
 2862:         }
 2863:         $cids=~s/\&$//;
 2864:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2865:                           $coursehome);       
 2866:     } else {
 2867:         my $items = '';
 2868:         foreach my $item (keys(%$storehash)) {
 2869:             $items.= &escape($item).'='.
 2870:                      &freeze_escape($$storehash{$item}).'&';
 2871:         }
 2872:         $items=~s/\&$//;
 2873:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2874:                           $coursehome);
 2875:     }
 2876:     if ($outcome eq 'unknown_cmd') {
 2877:         my $what;
 2878:         foreach my $cid (keys(%$storehash)) {
 2879:             $what .= &escape($cid).'=';
 2880:             foreach my $item ('description','inst_code','owner','type') {
 2881:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2882:             }
 2883:             $what =~ s/\:$/&/;
 2884:         }
 2885:         $what =~ s/\&$//;  
 2886:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2887:     } else {
 2888:         return $outcome;
 2889:     }
 2890: }
 2891: 
 2892: sub courseiddump {
 2893:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2894:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2895:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2896:     my $as_hash = 1;
 2897:     my %returnhash;
 2898:     if (!$domfilter) { $domfilter=''; }
 2899:     my %libserv = &all_library();
 2900:     foreach my $tryserver (keys(%libserv)) {
 2901:         if ( (  $hostidflag == 1 
 2902: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2903: 	     || (!defined($hostidflag)) ) {
 2904: 
 2905: 	    if (($domfilter eq '') ||
 2906: 		(&host_domain($tryserver) eq $domfilter)) {
 2907:                 my $rep = 
 2908:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2909:                          $sincefilter.':'.&escape($descfilter).':'.
 2910:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2911:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2912:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2913:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2914:                          $showhidden.':'.$caller,$tryserver);
 2915:                 my @pairs=split(/\&/,$rep);
 2916:                 foreach my $item (@pairs) {
 2917:                     my ($key,$value)=split(/\=/,$item,2);
 2918:                     $key = &unescape($key);
 2919:                     next if ($key =~ /^error: 2 /);
 2920:                     my $result = &thaw_unescape($value);
 2921:                     if (ref($result) eq 'HASH') {
 2922:                         $returnhash{$key}=$result;
 2923:                     } else {
 2924:                         my @responses = split(/:/,$value);
 2925:                         my @items = ('description','inst_code','owner','type');
 2926:                         for (my $i=0; $i<@responses; $i++) {
 2927:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2928:                         }
 2929:                     } 
 2930:                 }
 2931:             }
 2932:         }
 2933:     }
 2934:     return %returnhash;
 2935: }
 2936: 
 2937: # ---------------------------------------------------------- DC e-mail
 2938: 
 2939: sub dcmailput {
 2940:     my ($domain,$msgid,$message,$server)=@_;
 2941:     my $status = &Apache::lonnet::critical(
 2942:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2943:        &escape($message),$server);
 2944:     return $status;
 2945: }
 2946: 
 2947: sub dcmaildump {
 2948:     my ($dom,$startdate,$enddate,$senders) = @_;
 2949:     my %returnhash=();
 2950: 
 2951:     if (defined(&domain($dom,'primary'))) {
 2952:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2953:                                                          &escape($enddate).':';
 2954: 	my @esc_senders=map { &escape($_)} @$senders;
 2955: 	$cmd.=&escape(join('&',@esc_senders));
 2956: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2957:             my ($key,$value) = split(/\=/,$line,2);
 2958:             if (($key) && ($value)) {
 2959:                 $returnhash{&unescape($key)} = &unescape($value);
 2960:             }
 2961:         }
 2962:     }
 2963:     return %returnhash;
 2964: }
 2965: # ---------------------------------------------------------- Domain roles
 2966: 
 2967: sub get_domain_roles {
 2968:     my ($dom,$roles,$startdate,$enddate)=@_;
 2969:     if (undef($startdate) || $startdate eq '') {
 2970:         $startdate = '.';
 2971:     }
 2972:     if (undef($enddate) || $enddate eq '') {
 2973:         $enddate = '.';
 2974:     }
 2975:     my $rolelist;
 2976:     if (ref($roles) eq 'ARRAY') {
 2977:         $rolelist = join(':',@{$roles});
 2978:     }
 2979:     my %personnel = ();
 2980: 
 2981:     my %servers = &get_servers($dom,'library');
 2982:     foreach my $tryserver (keys(%servers)) {
 2983: 	%{$personnel{$tryserver}}=();
 2984: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2985: 					    &escape($startdate).':'.
 2986: 					    &escape($enddate).':'.
 2987: 					    &escape($rolelist), $tryserver))) {
 2988: 	    my ($key,$value) = split(/\=/,$line,2);
 2989: 	    if (($key) && ($value)) {
 2990: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2991: 	    }
 2992: 	}
 2993:     }
 2994:     return %personnel;
 2995: }
 2996: 
 2997: # ----------------------------------------------------------- Check out an item
 2998: 
 2999: sub get_first_access {
 3000:     my ($type,$argsymb)=@_;
 3001:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3002:     if ($argsymb) { $symb=$argsymb; }
 3003:     my ($map,$id,$res)=&decode_symb($symb);
 3004:     if ($type eq 'course') {
 3005: 	$res='course';
 3006:     } elsif ($type eq 'map') {
 3007: 	$res=&symbread($map);
 3008:     } else {
 3009: 	$res=$symb;
 3010:     }
 3011:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3012:     return $times{"$courseid\0$res"};
 3013: }
 3014: 
 3015: sub set_first_access {
 3016:     my ($type)=@_;
 3017:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3018:     my ($map,$id,$res)=&decode_symb($symb);
 3019:     if ($type eq 'course') {
 3020: 	$res='course';
 3021:     } elsif ($type eq 'map') {
 3022: 	$res=&symbread($map);
 3023:     } else {
 3024: 	$res=$symb;
 3025:     }
 3026:     my $firstaccess=&get_first_access($type,$symb);
 3027:     if (!$firstaccess) {
 3028: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3029:     }
 3030:     return 'already_set';
 3031: }
 3032: 
 3033: sub checkout {
 3034:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3035:     my $now=time;
 3036:     my $lonhost=$perlvar{'lonHostID'};
 3037:     my $infostr=&escape(
 3038:                  'CHECKOUTTOKEN&'.
 3039:                  $tuname.'&'.
 3040:                  $tudom.'&'.
 3041:                  $tcrsid.'&'.
 3042:                  $symb.'&'.
 3043: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3044:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3045:     if ($token=~/^error\:/) { 
 3046:         &logthis("<font color=\"blue\">WARNING: ".
 3047:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3048:                  "</font>");
 3049:         return ''; 
 3050:     }
 3051: 
 3052:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3053:     $token=~tr/a-z/A-Z/;
 3054: 
 3055:     my %infohash=('resource.0.outtoken' => $token,
 3056:                   'resource.0.checkouttime' => $now,
 3057:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3058: 
 3059:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3060:        return '';
 3061:     } else {
 3062:         &logthis("<font color=\"blue\">WARNING: ".
 3063:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3064:                  "</font>");
 3065:     }    
 3066: 
 3067:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3068:                          &escape('Checkout '.$infostr.' - '.
 3069:                                                  $token)) ne 'ok') {
 3070: 	return '';
 3071:     } else {
 3072:         &logthis("<font color=\"blue\">WARNING: ".
 3073:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3074:                  "</font>");
 3075:     }
 3076:     return $token;
 3077: }
 3078: 
 3079: # ------------------------------------------------------------ Check in an item
 3080: 
 3081: sub checkin {
 3082:     my $token=shift;
 3083:     my $now=time;
 3084:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3085:     $lonhost=~tr/A-Z/a-z/;
 3086:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3087:     $dtoken=~s/\W/\_/g;
 3088:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3089:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3090: 
 3091:     unless (($tuname) && ($tudom)) {
 3092:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3093:         return '';
 3094:     }
 3095:     
 3096:     unless (&allowed('mgr',$tcrsid)) {
 3097:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3098:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3099:         return '';
 3100:     }
 3101: 
 3102:     my %infohash=('resource.0.intoken' => $token,
 3103:                   'resource.0.checkintime' => $now,
 3104:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3105: 
 3106:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3107:        return '';
 3108:     }    
 3109: 
 3110:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3111:                          &escape('Checkin - '.$token)) ne 'ok') {
 3112: 	return '';
 3113:     }
 3114: 
 3115:     return ($symb,$tuname,$tudom,$tcrsid);    
 3116: }
 3117: 
 3118: # --------------------------------------------- Set Expire Date for Spreadsheet
 3119: 
 3120: sub expirespread {
 3121:     my ($uname,$udom,$stype,$usymb)=@_;
 3122:     my $cid=$env{'request.course.id'}; 
 3123:     if ($cid) {
 3124:        my $now=time;
 3125:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3126:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3127:                             $env{'course.'.$cid.'.num'}.
 3128: 	        	    ':nohist_expirationdates:'.
 3129:                             &escape($key).'='.$now,
 3130:                             $env{'course.'.$cid.'.home'})
 3131:     }
 3132:     return 'ok';
 3133: }
 3134: 
 3135: # ----------------------------------------------------- Devalidate Spreadsheets
 3136: 
 3137: sub devalidate {
 3138:     my ($symb,$uname,$udom)=@_;
 3139:     my $cid=$env{'request.course.id'}; 
 3140:     if ($cid) {
 3141:         # delete the stored spreadsheets for
 3142:         # - the student level sheet of this user in course's homespace
 3143:         # - the assessment level sheet for this resource 
 3144:         #   for this user in user's homespace
 3145: 	# - current conditional state info
 3146: 	my $key=$uname.':'.$udom.':';
 3147:         my $status=
 3148: 	    &del('nohist_calculatedsheets',
 3149: 		 [$key.'studentcalc:'],
 3150: 		 $env{'course.'.$cid.'.domain'},
 3151: 		 $env{'course.'.$cid.'.num'})
 3152: 		.' '.
 3153: 	    &del('nohist_calculatedsheets_'.$cid,
 3154: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3155:         unless ($status eq 'ok ok') {
 3156:            &logthis('Could not devalidate spreadsheet '.
 3157:                     $uname.' at '.$udom.' for '.
 3158: 		    $symb.': '.$status);
 3159:         }
 3160: 	&delenv('user.state.'.$cid);
 3161:     }
 3162: }
 3163: 
 3164: sub get_scalar {
 3165:     my ($string,$end) = @_;
 3166:     my $value;
 3167:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3168: 	$value = $1;
 3169:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3170: 	$value = $1;
 3171:     }
 3172:     return &unescape($value);
 3173: }
 3174: 
 3175: sub array2str {
 3176:   my (@array) = @_;
 3177:   my $result=&arrayref2str(\@array);
 3178:   $result=~s/^__ARRAY_REF__//;
 3179:   $result=~s/__END_ARRAY_REF__$//;
 3180:   return $result;
 3181: }
 3182: 
 3183: sub arrayref2str {
 3184:   my ($arrayref) = @_;
 3185:   my $result='__ARRAY_REF__';
 3186:   foreach my $elem (@$arrayref) {
 3187:     if(ref($elem) eq 'ARRAY') {
 3188:       $result.=&arrayref2str($elem).'&';
 3189:     } elsif(ref($elem) eq 'HASH') {
 3190:       $result.=&hashref2str($elem).'&';
 3191:     } elsif(ref($elem)) {
 3192:       #print("Got a ref of ".(ref($elem))." skipping.");
 3193:     } else {
 3194:       $result.=&escape($elem).'&';
 3195:     }
 3196:   }
 3197:   $result=~s/\&$//;
 3198:   $result .= '__END_ARRAY_REF__';
 3199:   return $result;
 3200: }
 3201: 
 3202: sub hash2str {
 3203:   my (%hash) = @_;
 3204:   my $result=&hashref2str(\%hash);
 3205:   $result=~s/^__HASH_REF__//;
 3206:   $result=~s/__END_HASH_REF__$//;
 3207:   return $result;
 3208: }
 3209: 
 3210: sub hashref2str {
 3211:   my ($hashref)=@_;
 3212:   my $result='__HASH_REF__';
 3213:   foreach my $key (sort(keys(%$hashref))) {
 3214:     if (ref($key) eq 'ARRAY') {
 3215:       $result.=&arrayref2str($key).'=';
 3216:     } elsif (ref($key) eq 'HASH') {
 3217:       $result.=&hashref2str($key).'=';
 3218:     } elsif (ref($key)) {
 3219:       $result.='=';
 3220:       #print("Got a ref of ".(ref($key))." skipping.");
 3221:     } else {
 3222: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3223:     }
 3224: 
 3225:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3226:       $result.=&arrayref2str($hashref->{$key}).'&';
 3227:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3228:       $result.=&hashref2str($hashref->{$key}).'&';
 3229:     } elsif(ref($hashref->{$key})) {
 3230:        $result.='&';
 3231:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3232:     } else {
 3233:       $result.=&escape($hashref->{$key}).'&';
 3234:     }
 3235:   }
 3236:   $result=~s/\&$//;
 3237:   $result .= '__END_HASH_REF__';
 3238:   return $result;
 3239: }
 3240: 
 3241: sub str2hash {
 3242:     my ($string)=@_;
 3243:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3244:     return %$hash;
 3245: }
 3246: 
 3247: sub str2hashref {
 3248:   my ($string) = @_;
 3249: 
 3250:   my %hash;
 3251: 
 3252:   if($string !~ /^__HASH_REF__/) {
 3253:       if (! ($string eq '' || !defined($string))) {
 3254: 	  $hash{'error'}='Not hash reference';
 3255:       }
 3256:       return (\%hash, $string);
 3257:   }
 3258: 
 3259:   $string =~ s/^__HASH_REF__//;
 3260: 
 3261:   while($string !~ /^__END_HASH_REF__/) {
 3262:       #key
 3263:       my $key='';
 3264:       if($string =~ /^__HASH_REF__/) {
 3265:           ($key, $string)=&str2hashref($string);
 3266:           if(defined($key->{'error'})) {
 3267:               $hash{'error'}='Bad data';
 3268:               return (\%hash, $string);
 3269:           }
 3270:       } elsif($string =~ /^__ARRAY_REF__/) {
 3271:           ($key, $string)=&str2arrayref($string);
 3272:           if($key->[0] eq 'Array reference error') {
 3273:               $hash{'error'}='Bad data';
 3274:               return (\%hash, $string);
 3275:           }
 3276:       } else {
 3277:           $string =~ s/^(.*?)=//;
 3278: 	  $key=&unescape($1);
 3279:       }
 3280:       $string =~ s/^=//;
 3281: 
 3282:       #value
 3283:       my $value='';
 3284:       if($string =~ /^__HASH_REF__/) {
 3285:           ($value, $string)=&str2hashref($string);
 3286:           if(defined($value->{'error'})) {
 3287:               $hash{'error'}='Bad data';
 3288:               return (\%hash, $string);
 3289:           }
 3290:       } elsif($string =~ /^__ARRAY_REF__/) {
 3291:           ($value, $string)=&str2arrayref($string);
 3292:           if($value->[0] eq 'Array reference error') {
 3293:               $hash{'error'}='Bad data';
 3294:               return (\%hash, $string);
 3295:           }
 3296:       } else {
 3297: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3298:       }
 3299:       $string =~ s/^&//;
 3300: 
 3301:       $hash{$key}=$value;
 3302:   }
 3303: 
 3304:   $string =~ s/^__END_HASH_REF__//;
 3305: 
 3306:   return (\%hash, $string);
 3307: }
 3308: 
 3309: sub str2array {
 3310:     my ($string)=@_;
 3311:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3312:     return @$array;
 3313: }
 3314: 
 3315: sub str2arrayref {
 3316:   my ($string) = @_;
 3317:   my @array;
 3318: 
 3319:   if($string !~ /^__ARRAY_REF__/) {
 3320:       if (! ($string eq '' || !defined($string))) {
 3321: 	  $array[0]='Array reference error';
 3322:       }
 3323:       return (\@array, $string);
 3324:   }
 3325: 
 3326:   $string =~ s/^__ARRAY_REF__//;
 3327: 
 3328:   while($string !~ /^__END_ARRAY_REF__/) {
 3329:       my $value='';
 3330:       if($string =~ /^__HASH_REF__/) {
 3331:           ($value, $string)=&str2hashref($string);
 3332:           if(defined($value->{'error'})) {
 3333:               $array[0] ='Array reference error';
 3334:               return (\@array, $string);
 3335:           }
 3336:       } elsif($string =~ /^__ARRAY_REF__/) {
 3337:           ($value, $string)=&str2arrayref($string);
 3338:           if($value->[0] eq 'Array reference error') {
 3339:               $array[0] ='Array reference error';
 3340:               return (\@array, $string);
 3341:           }
 3342:       } else {
 3343: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3344:       }
 3345:       $string =~ s/^&//;
 3346: 
 3347:       push(@array, $value);
 3348:   }
 3349: 
 3350:   $string =~ s/^__END_ARRAY_REF__//;
 3351: 
 3352:   return (\@array, $string);
 3353: }
 3354: 
 3355: # -------------------------------------------------------------------Temp Store
 3356: 
 3357: sub tmpreset {
 3358:   my ($symb,$namespace,$domain,$stuname) = @_;
 3359:   if (!$symb) {
 3360:     $symb=&symbread();
 3361:     if (!$symb) { $symb= $env{'request.url'}; }
 3362:   }
 3363:   $symb=escape($symb);
 3364: 
 3365:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3366:   $namespace=~s/\//\_/g;
 3367:   $namespace=~s/\W//g;
 3368: 
 3369:   if (!$domain) { $domain=$env{'user.domain'}; }
 3370:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3371:   if ($domain eq 'public' && $stuname eq 'public') {
 3372:       $stuname=$ENV{'REMOTE_ADDR'};
 3373:   }
 3374:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3375:   my %hash;
 3376:   if (tie(%hash,'GDBM_File',
 3377: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3378: 	  &GDBM_WRCREAT(),0640)) {
 3379:     foreach my $key (keys %hash) {
 3380:       if ($key=~ /:$symb/) {
 3381: 	delete($hash{$key});
 3382:       }
 3383:     }
 3384:   }
 3385: }
 3386: 
 3387: sub tmpstore {
 3388:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3389: 
 3390:   if (!$symb) {
 3391:     $symb=&symbread();
 3392:     if (!$symb) { $symb= $env{'request.url'}; }
 3393:   }
 3394:   $symb=escape($symb);
 3395: 
 3396:   if (!$namespace) {
 3397:     # I don't think we would ever want to store this for a course.
 3398:     # it seems this will only be used if we don't have a course.
 3399:     #$namespace=$env{'request.course.id'};
 3400:     #if (!$namespace) {
 3401:       $namespace=$env{'request.state'};
 3402:     #}
 3403:   }
 3404:   $namespace=~s/\//\_/g;
 3405:   $namespace=~s/\W//g;
 3406:   if (!$domain) { $domain=$env{'user.domain'}; }
 3407:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3408:   if ($domain eq 'public' && $stuname eq 'public') {
 3409:       $stuname=$ENV{'REMOTE_ADDR'};
 3410:   }
 3411:   my $now=time;
 3412:   my %hash;
 3413:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3414:   if (tie(%hash,'GDBM_File',
 3415: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3416: 	  &GDBM_WRCREAT(),0640)) {
 3417:     $hash{"version:$symb"}++;
 3418:     my $version=$hash{"version:$symb"};
 3419:     my $allkeys=''; 
 3420:     foreach my $key (keys(%$storehash)) {
 3421:       $allkeys.=$key.':';
 3422:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3423:     }
 3424:     $hash{"$version:$symb:timestamp"}=$now;
 3425:     $allkeys.='timestamp';
 3426:     $hash{"$version:keys:$symb"}=$allkeys;
 3427:     if (untie(%hash)) {
 3428:       return 'ok';
 3429:     } else {
 3430:       return "error:$!";
 3431:     }
 3432:   } else {
 3433:     return "error:$!";
 3434:   }
 3435: }
 3436: 
 3437: # -----------------------------------------------------------------Temp Restore
 3438: 
 3439: sub tmprestore {
 3440:   my ($symb,$namespace,$domain,$stuname) = @_;
 3441: 
 3442:   if (!$symb) {
 3443:     $symb=&symbread();
 3444:     if (!$symb) { $symb= $env{'request.url'}; }
 3445:   }
 3446:   $symb=escape($symb);
 3447: 
 3448:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3449: 
 3450:   if (!$domain) { $domain=$env{'user.domain'}; }
 3451:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3452:   if ($domain eq 'public' && $stuname eq 'public') {
 3453:       $stuname=$ENV{'REMOTE_ADDR'};
 3454:   }
 3455:   my %returnhash;
 3456:   $namespace=~s/\//\_/g;
 3457:   $namespace=~s/\W//g;
 3458:   my %hash;
 3459:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3460:   if (tie(%hash,'GDBM_File',
 3461: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3462: 	  &GDBM_READER(),0640)) {
 3463:     my $version=$hash{"version:$symb"};
 3464:     $returnhash{'version'}=$version;
 3465:     my $scope;
 3466:     for ($scope=1;$scope<=$version;$scope++) {
 3467:       my $vkeys=$hash{"$scope:keys:$symb"};
 3468:       my @keys=split(/:/,$vkeys);
 3469:       my $key;
 3470:       $returnhash{"$scope:keys"}=$vkeys;
 3471:       foreach $key (@keys) {
 3472: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3473: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3474:       }
 3475:     }
 3476:     if (!(untie(%hash))) {
 3477:       return "error:$!";
 3478:     }
 3479:   } else {
 3480:     return "error:$!";
 3481:   }
 3482:   return %returnhash;
 3483: }
 3484: 
 3485: # ----------------------------------------------------------------------- Store
 3486: 
 3487: sub store {
 3488:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3489:     my $home='';
 3490: 
 3491:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3492: 
 3493:     $symb=&symbclean($symb);
 3494:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3495: 
 3496:     if (!$domain) { $domain=$env{'user.domain'}; }
 3497:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3498: 
 3499:     &devalidate($symb,$stuname,$domain);
 3500: 
 3501:     $symb=escape($symb);
 3502:     if (!$namespace) { 
 3503:        unless ($namespace=$env{'request.course.id'}) { 
 3504:           return ''; 
 3505:        } 
 3506:     }
 3507:     if (!$home) { $home=$env{'user.home'}; }
 3508: 
 3509:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3510:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3511: 
 3512:     my $namevalue='';
 3513:     foreach my $key (keys(%$storehash)) {
 3514:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3515:     }
 3516:     $namevalue=~s/\&$//;
 3517:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3518:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3519: }
 3520: 
 3521: # -------------------------------------------------------------- Critical Store
 3522: 
 3523: sub cstore {
 3524:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3525:     my $home='';
 3526: 
 3527:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3528: 
 3529:     $symb=&symbclean($symb);
 3530:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3531: 
 3532:     if (!$domain) { $domain=$env{'user.domain'}; }
 3533:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3534: 
 3535:     &devalidate($symb,$stuname,$domain);
 3536: 
 3537:     $symb=escape($symb);
 3538:     if (!$namespace) { 
 3539:        unless ($namespace=$env{'request.course.id'}) { 
 3540:           return ''; 
 3541:        } 
 3542:     }
 3543:     if (!$home) { $home=$env{'user.home'}; }
 3544: 
 3545:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3546:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3547: 
 3548:     my $namevalue='';
 3549:     foreach my $key (keys(%$storehash)) {
 3550:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3551:     }
 3552:     $namevalue=~s/\&$//;
 3553:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3554:     return critical
 3555:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3556: }
 3557: 
 3558: # --------------------------------------------------------------------- Restore
 3559: 
 3560: sub restore {
 3561:     my ($symb,$namespace,$domain,$stuname) = @_;
 3562:     my $home='';
 3563: 
 3564:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3565: 
 3566:     if (!$symb) {
 3567:       unless ($symb=escape(&symbread())) { return ''; }
 3568:     } else {
 3569:       $symb=&escape(&symbclean($symb));
 3570:     }
 3571:     if (!$namespace) { 
 3572:        unless ($namespace=$env{'request.course.id'}) { 
 3573:           return ''; 
 3574:        } 
 3575:     }
 3576:     if (!$domain) { $domain=$env{'user.domain'}; }
 3577:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3578:     if (!$home) { $home=$env{'user.home'}; }
 3579:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3580: 
 3581:     my %returnhash=();
 3582:     foreach my $line (split(/\&/,$answer)) {
 3583: 	my ($name,$value)=split(/\=/,$line);
 3584:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3585:     }
 3586:     my $version;
 3587:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3588:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3589:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3590:        }
 3591:     }
 3592:     return %returnhash;
 3593: }
 3594: 
 3595: # ---------------------------------------------------------- Course Description
 3596: 
 3597: sub coursedescription {
 3598:     my ($courseid,$args)=@_;
 3599:     $courseid=~s/^\///;
 3600:     $courseid=~s/\_/\//g;
 3601:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3602:     my $chome=&homeserver($cnum,$cdomain);
 3603:     my $normalid=$cdomain.'_'.$cnum;
 3604:     # need to always cache even if we get errors otherwise we keep 
 3605:     # trying and trying and trying to get the course description.
 3606:     my %envhash=();
 3607:     my %returnhash=();
 3608:     
 3609:     my $expiretime=600;
 3610:     if ($env{'request.course.id'} eq $normalid) {
 3611: 	$expiretime=120;
 3612:     }
 3613: 
 3614:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3615:     if (!$args->{'freshen_cache'}
 3616: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3617: 	foreach my $key (keys(%env)) {
 3618: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3619: 	    my ($setting) = $1;
 3620: 	    $returnhash{$setting} = $env{$key};
 3621: 	}
 3622: 	return %returnhash;
 3623:     }
 3624: 
 3625:     # get the data agin
 3626:     if (!$args->{'one_time'}) {
 3627: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3628:     }
 3629: 
 3630:     if ($chome ne 'no_host') {
 3631:        %returnhash=&dump('environment',$cdomain,$cnum);
 3632:        if (!exists($returnhash{'con_lost'})) {
 3633:            $returnhash{'home'}= $chome;
 3634: 	   $returnhash{'domain'} = $cdomain;
 3635: 	   $returnhash{'num'} = $cnum;
 3636:            if (!defined($returnhash{'type'})) {
 3637:                $returnhash{'type'} = 'Course';
 3638:            }
 3639:            while (my ($name,$value) = each %returnhash) {
 3640:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3641:            }
 3642:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3643:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3644: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3645:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3646:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3647:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3648:        }
 3649:     }
 3650:     if (!$args->{'one_time'}) {
 3651: 	&appenv(\%envhash);
 3652:     }
 3653:     return %returnhash;
 3654: }
 3655: 
 3656: # -------------------------------------------------See if a user is privileged
 3657: 
 3658: sub privileged {
 3659:     my ($username,$domain)=@_;
 3660:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3661: 			&homeserver($username,$domain));
 3662:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3663:     my $now=time;
 3664:     if ($rolesdump ne '') {
 3665:         foreach my $entry (split(/&/,$rolesdump)) {
 3666: 	    if ($entry!~/^rolesdef_/) {
 3667: 		my ($area,$role)=split(/=/,$entry);
 3668: 		$area=~s/\_\w\w$//;
 3669: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3670: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3671: 		    my $active=1;
 3672: 		    if ($tend) {
 3673: 			if ($tend<$now) { $active=0; }
 3674: 		    }
 3675: 		    if ($tstart) {
 3676: 			if ($tstart>$now) { $active=0; }
 3677: 		    }
 3678: 		    if ($active) { return 1; }
 3679: 		}
 3680: 	    }
 3681: 	}
 3682:     }
 3683:     return 0;
 3684: }
 3685: 
 3686: # -------------------------------------------------------- Get user privileges
 3687: 
 3688: sub rolesinit {
 3689:     my ($domain,$username,$authhost)=@_;
 3690:     my %userroles;
 3691:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3692:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3693:     my %allroles=();
 3694:     my %allgroups=();   
 3695:     my $now=time;
 3696:     %userroles = ('user.login.time' => $now);
 3697:     my $group_privs;
 3698: 
 3699:     if ($rolesdump ne '') {
 3700:         foreach my $entry (split(/&/,$rolesdump)) {
 3701: 	  if ($entry!~/^rolesdef_/) {
 3702:             my ($area,$role)=split(/=/,$entry);
 3703: 	    $area=~s/\_\w\w$//;
 3704:             my ($trole,$tend,$tstart,$group_privs);
 3705: 	    if ($role=~/^cr/) { 
 3706: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3707: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3708: 		    ($tend,$tstart)=split('_',$trest);
 3709: 		} else {
 3710: 		    $trole=$role;
 3711: 		}
 3712:             } elsif ($role =~ m|^gr/|) {
 3713:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3714:                 ($trole,$group_privs) = split(/\//,$trole);
 3715:                 $group_privs = &unescape($group_privs);
 3716: 	    } else {
 3717: 		($trole,$tend,$tstart)=split(/_/,$role);
 3718: 	    }
 3719: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3720: 					 $username);
 3721: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3722:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3723:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3724:             if (($area ne '') && ($trole ne '')) {
 3725: 		my $spec=$trole.'.'.$area;
 3726: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3727: 		if ($trole =~ /^cr\//) {
 3728:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3729:                 } elsif ($trole eq 'gr') {
 3730:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3731: 		} else {
 3732:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3733: 		}
 3734:             }
 3735:           }
 3736:         }
 3737:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3738:         $userroles{'user.adv'}    = $adv;
 3739: 	$userroles{'user.author'} = $author;
 3740:         $env{'user.adv'}=$adv;
 3741:     }
 3742:     return \%userroles;  
 3743: }
 3744: 
 3745: sub set_arearole {
 3746:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3747: # log the associated role with the area
 3748:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3749:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3750: }
 3751: 
 3752: sub custom_roleprivs {
 3753:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3754:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3755:     my $homsvr=homeserver($rauthor,$rdomain);
 3756:     if (&hostname($homsvr) ne '') {
 3757:         my ($rdummy,$roledef)=
 3758:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3759:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3760:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3761:             if (defined($syspriv)) {
 3762:                 $$allroles{'cm./'}.=':'.$syspriv;
 3763:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3764:             }
 3765:             if ($tdomain ne '') {
 3766:                 if (defined($dompriv)) {
 3767:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3768:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3769:                 }
 3770:                 if (($trest ne '') && (defined($coursepriv))) {
 3771:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3772:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3773:                 }
 3774:             }
 3775:         }
 3776:     }
 3777: }
 3778: 
 3779: sub group_roleprivs {
 3780:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3781:     my $access = 1;
 3782:     my $now = time;
 3783:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3784:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3785:     if ($access) {
 3786:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3787:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3788:     }
 3789: }
 3790: 
 3791: sub standard_roleprivs {
 3792:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3793:     if (defined($pr{$trole.':s'})) {
 3794:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3795:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3796:     }
 3797:     if ($tdomain ne '') {
 3798:         if (defined($pr{$trole.':d'})) {
 3799:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3800:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3801:         }
 3802:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3803:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3804:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3805:         }
 3806:     }
 3807: }
 3808: 
 3809: sub set_userprivs {
 3810:     my ($userroles,$allroles,$allgroups) = @_; 
 3811:     my $author=0;
 3812:     my $adv=0;
 3813:     my %grouproles = ();
 3814:     if (keys(%{$allgroups}) > 0) {
 3815:         foreach my $role (keys %{$allroles}) {
 3816:             my ($trole,$area,$sec,$extendedarea);
 3817:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3818:                 $trole = $1;
 3819:                 $area = $2;
 3820:                 $sec = $3;
 3821:                 $extendedarea = $area.$sec;
 3822:                 if (exists($$allgroups{$area})) {
 3823:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3824:                         my $spec = $trole.'.'.$extendedarea;
 3825:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3826:                                                 $$allgroups{$area}{$group};
 3827:                     }
 3828:                 }
 3829:             }
 3830:         }
 3831:     }
 3832:     foreach my $group (keys(%grouproles)) {
 3833:         $$allroles{$group} = $grouproles{$group};
 3834:     }
 3835:     foreach my $role (keys(%{$allroles})) {
 3836:         my %thesepriv;
 3837:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3838:         foreach my $item (split(/:/,$$allroles{$role})) {
 3839:             if ($item ne '') {
 3840:                 my ($privilege,$restrictions)=split(/&/,$item);
 3841:                 if ($restrictions eq '') {
 3842:                     $thesepriv{$privilege}='F';
 3843:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3844:                     $thesepriv{$privilege}.=$restrictions;
 3845:                 }
 3846:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3847:             }
 3848:         }
 3849:         my $thesestr='';
 3850:         foreach my $priv (keys(%thesepriv)) {
 3851: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3852: 	}
 3853:         $userroles->{'user.priv.'.$role} = $thesestr;
 3854:     }
 3855:     return ($author,$adv);
 3856: }
 3857: 
 3858: # --------------------------------------------------------------- get interface
 3859: 
 3860: sub get {
 3861:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3862:    my $items='';
 3863:    foreach my $item (@$storearr) {
 3864:        $items.=&escape($item).'&';
 3865:    }
 3866:    $items=~s/\&$//;
 3867:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3868:    if (!$uname) { $uname=$env{'user.name'}; }
 3869:    my $uhome=&homeserver($uname,$udomain);
 3870: 
 3871:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3872:    my @pairs=split(/\&/,$rep);
 3873:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3874:      return @pairs;
 3875:    }
 3876:    my %returnhash=();
 3877:    my $i=0;
 3878:    foreach my $item (@$storearr) {
 3879:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3880:       $i++;
 3881:    }
 3882:    return %returnhash;
 3883: }
 3884: 
 3885: # --------------------------------------------------------------- del interface
 3886: 
 3887: sub del {
 3888:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3889:    my $items='';
 3890:    foreach my $item (@$storearr) {
 3891:        $items.=&escape($item).'&';
 3892:    }
 3893: 
 3894:    $items=~s/\&$//;
 3895:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3896:    if (!$uname) { $uname=$env{'user.name'}; }
 3897:    my $uhome=&homeserver($uname,$udomain);
 3898:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3899: }
 3900: 
 3901: # -------------------------------------------------------------- dump interface
 3902: 
 3903: sub dump {
 3904:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3905:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3906:     if (!$uname) { $uname=$env{'user.name'}; }
 3907:     my $uhome=&homeserver($uname,$udomain);
 3908:     if ($regexp) {
 3909: 	$regexp=&escape($regexp);
 3910:     } else {
 3911: 	$regexp='.';
 3912:     }
 3913:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3914:     my @pairs=split(/\&/,$rep);
 3915:     my %returnhash=();
 3916:     foreach my $item (@pairs) {
 3917: 	my ($key,$value)=split(/=/,$item,2);
 3918: 	$key = &unescape($key);
 3919: 	next if ($key =~ /^error: 2 /);
 3920: 	$returnhash{$key}=&thaw_unescape($value);
 3921:     }
 3922:     return %returnhash;
 3923: }
 3924: 
 3925: # --------------------------------------------------------- dumpstore interface
 3926: 
 3927: sub dumpstore {
 3928:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3929:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3930:    if (!$uname) { $uname=$env{'user.name'}; }
 3931:    my $uhome=&homeserver($uname,$udomain);
 3932:    if ($regexp) {
 3933:        $regexp=&escape($regexp);
 3934:    } else {
 3935:        $regexp='.';
 3936:    }
 3937:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3938:    my @pairs=split(/\&/,$rep);
 3939:    my %returnhash=();
 3940:    foreach my $item (@pairs) {
 3941:        my ($key,$value)=split(/=/,$item,2);
 3942:        next if ($key =~ /^error: 2 /);
 3943:        $returnhash{$key}=&thaw_unescape($value);
 3944:    }
 3945:    return %returnhash;
 3946: }
 3947: 
 3948: # -------------------------------------------------------------- keys interface
 3949: 
 3950: sub getkeys {
 3951:    my ($namespace,$udomain,$uname)=@_;
 3952:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3953:    if (!$uname) { $uname=$env{'user.name'}; }
 3954:    my $uhome=&homeserver($uname,$udomain);
 3955:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3956:    my @keyarray=();
 3957:    foreach my $key (split(/\&/,$rep)) {
 3958:       next if ($key =~ /^error: 2 /);
 3959:       push(@keyarray,&unescape($key));
 3960:    }
 3961:    return @keyarray;
 3962: }
 3963: 
 3964: # --------------------------------------------------------------- currentdump
 3965: sub currentdump {
 3966:    my ($courseid,$sdom,$sname)=@_;
 3967:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3968:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3969:    $sname    = $env{'user.name'}         if (! defined($sname));
 3970:    my $uhome = &homeserver($sname,$sdom);
 3971:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3972:    return if ($rep =~ /^(error:|no_such_host)/);
 3973:    #
 3974:    my %returnhash=();
 3975:    #
 3976:    if ($rep eq "unknown_cmd") { 
 3977:        # an old lond will not know currentdump
 3978:        # Do a dump and make it look like a currentdump
 3979:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3980:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3981:        my %hash = @tmp;
 3982:        @tmp=();
 3983:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3984:    } else {
 3985:        my @pairs=split(/\&/,$rep);
 3986:        foreach my $pair (@pairs) {
 3987:            my ($key,$value)=split(/=/,$pair,2);
 3988:            my ($symb,$param) = split(/:/,$key);
 3989:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3990:                                                         &thaw_unescape($value);
 3991:        }
 3992:    }
 3993:    return %returnhash;
 3994: }
 3995: 
 3996: sub convert_dump_to_currentdump{
 3997:     my %hash = %{shift()};
 3998:     my %returnhash;
 3999:     # Code ripped from lond, essentially.  The only difference
 4000:     # here is the unescaping done by lonnet::dump().  Conceivably
 4001:     # we might run in to problems with parameter names =~ /^v\./
 4002:     while (my ($key,$value) = each(%hash)) {
 4003:         my ($v,$symb,$param) = split(/:/,$key);
 4004: 	$symb  = &unescape($symb);
 4005: 	$param = &unescape($param);
 4006:         next if ($v eq 'version' || $symb eq 'keys');
 4007:         next if (exists($returnhash{$symb}) &&
 4008:                  exists($returnhash{$symb}->{$param}) &&
 4009:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4010:         $returnhash{$symb}->{$param}=$value;
 4011:         $returnhash{$symb}->{'v.'.$param}=$v;
 4012:     }
 4013:     #
 4014:     # Remove all of the keys in the hashes which keep track of
 4015:     # the version of the parameter.
 4016:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4017:         # use a foreach because we are going to delete from the hash.
 4018:         foreach my $key (keys(%$param_hash)) {
 4019:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4020:         }
 4021:     }
 4022:     return \%returnhash;
 4023: }
 4024: 
 4025: # ------------------------------------------------------ critical inc interface
 4026: 
 4027: sub cinc {
 4028:     return &inc(@_,'critical');
 4029: }
 4030: 
 4031: # --------------------------------------------------------------- inc interface
 4032: 
 4033: sub inc {
 4034:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4035:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4036:     if (!$uname) { $uname=$env{'user.name'}; }
 4037:     my $uhome=&homeserver($uname,$udomain);
 4038:     my $items='';
 4039:     if (! ref($store)) {
 4040:         # got a single value, so use that instead
 4041:         $items = &escape($store).'=&';
 4042:     } elsif (ref($store) eq 'SCALAR') {
 4043:         $items = &escape($$store).'=&';        
 4044:     } elsif (ref($store) eq 'ARRAY') {
 4045:         $items = join('=&',map {&escape($_);} @{$store});
 4046:     } elsif (ref($store) eq 'HASH') {
 4047:         while (my($key,$value) = each(%{$store})) {
 4048:             $items.= &escape($key).'='.&escape($value).'&';
 4049:         }
 4050:     }
 4051:     $items=~s/\&$//;
 4052:     if ($critical) {
 4053: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4054:     } else {
 4055: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4056:     }
 4057: }
 4058: 
 4059: # --------------------------------------------------------------- put interface
 4060: 
 4061: sub put {
 4062:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4063:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4064:    if (!$uname) { $uname=$env{'user.name'}; }
 4065:    my $uhome=&homeserver($uname,$udomain);
 4066:    my $items='';
 4067:    foreach my $item (keys(%$storehash)) {
 4068:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4069:    }
 4070:    $items=~s/\&$//;
 4071:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4072: }
 4073: 
 4074: # ------------------------------------------------------------ newput interface
 4075: 
 4076: sub newput {
 4077:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4078:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4079:    if (!$uname) { $uname=$env{'user.name'}; }
 4080:    my $uhome=&homeserver($uname,$udomain);
 4081:    my $items='';
 4082:    foreach my $key (keys(%$storehash)) {
 4083:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4084:    }
 4085:    $items=~s/\&$//;
 4086:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4087: }
 4088: 
 4089: # ---------------------------------------------------------  putstore interface
 4090: 
 4091: sub putstore {
 4092:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4093:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4094:    if (!$uname) { $uname=$env{'user.name'}; }
 4095:    my $uhome=&homeserver($uname,$udomain);
 4096:    my $items='';
 4097:    foreach my $key (keys(%$storehash)) {
 4098:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4099:    }
 4100:    $items=~s/\&$//;
 4101:    my $esc_symb=&escape($symb);
 4102:    my $esc_v=&escape($version);
 4103:    my $reply =
 4104:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4105: 	      $uhome);
 4106:    if ($reply eq 'unknown_cmd') {
 4107:        # gfall back to way things use to be done
 4108:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4109: 			    $uname);
 4110:    }
 4111:    return $reply;
 4112: }
 4113: 
 4114: sub old_putstore {
 4115:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4116:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4117:     if (!$uname) { $uname=$env{'user.name'}; }
 4118:     my $uhome=&homeserver($uname,$udomain);
 4119:     my %newstorehash;
 4120:     foreach my $item (keys(%$storehash)) {
 4121: 	my $key = $version.':'.&escape($symb).':'.$item;
 4122: 	$newstorehash{$key} = $storehash->{$item};
 4123:     }
 4124:     my $items='';
 4125:     my %allitems = ();
 4126:     foreach my $item (keys(%newstorehash)) {
 4127: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4128: 	    my $key = $1.':keys:'.$2;
 4129: 	    $allitems{$key} .= $3.':';
 4130: 	}
 4131: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4132:     }
 4133:     foreach my $item (keys(%allitems)) {
 4134: 	$allitems{$item} =~ s/\:$//;
 4135: 	$items.= $item.'='.$allitems{$item}.'&';
 4136:     }
 4137:     $items=~s/\&$//;
 4138:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4139: }
 4140: 
 4141: # ------------------------------------------------------ critical put interface
 4142: 
 4143: sub cput {
 4144:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4145:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4146:    if (!$uname) { $uname=$env{'user.name'}; }
 4147:    my $uhome=&homeserver($uname,$udomain);
 4148:    my $items='';
 4149:    foreach my $item (keys(%$storehash)) {
 4150:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4151:    }
 4152:    $items=~s/\&$//;
 4153:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4154: }
 4155: 
 4156: # -------------------------------------------------------------- eget interface
 4157: 
 4158: sub eget {
 4159:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4160:    my $items='';
 4161:    foreach my $item (@$storearr) {
 4162:        $items.=&escape($item).'&';
 4163:    }
 4164:    $items=~s/\&$//;
 4165:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4166:    if (!$uname) { $uname=$env{'user.name'}; }
 4167:    my $uhome=&homeserver($uname,$udomain);
 4168:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4169:    my @pairs=split(/\&/,$rep);
 4170:    my %returnhash=();
 4171:    my $i=0;
 4172:    foreach my $item (@$storearr) {
 4173:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4174:       $i++;
 4175:    }
 4176:    return %returnhash;
 4177: }
 4178: 
 4179: # ------------------------------------------------------------ tmpput interface
 4180: sub tmpput {
 4181:     my ($storehash,$server,$context)=@_;
 4182:     my $items='';
 4183:     foreach my $item (keys(%$storehash)) {
 4184: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4185:     }
 4186:     $items=~s/\&$//;
 4187:     if (defined($context)) {
 4188:         $items .= ':'.&escape($context);
 4189:     }
 4190:     return &reply("tmpput:$items",$server);
 4191: }
 4192: 
 4193: # ------------------------------------------------------------ tmpget interface
 4194: sub tmpget {
 4195:     my ($token,$server)=@_;
 4196:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4197:     my $rep=&reply("tmpget:$token",$server);
 4198:     my %returnhash;
 4199:     foreach my $item (split(/\&/,$rep)) {
 4200: 	my ($key,$value)=split(/=/,$item);
 4201:         next if ($key =~ /^error: 2 /);
 4202: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4203:     }
 4204:     return %returnhash;
 4205: }
 4206: 
 4207: # ------------------------------------------------------------ tmpget interface
 4208: sub tmpdel {
 4209:     my ($token,$server)=@_;
 4210:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4211:     return &reply("tmpdel:$token",$server);
 4212: }
 4213: 
 4214: # -------------------------------------------------- portfolio access checking
 4215: 
 4216: sub portfolio_access {
 4217:     my ($requrl) = @_;
 4218:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4219:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4220:     if ($result) {
 4221:         my %setters;
 4222:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4223:             my ($startblock,$endblock) =
 4224:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4225:             if ($startblock && $endblock) {
 4226:                 return 'B';
 4227:             }
 4228:         } else {
 4229:             my ($startblock,$endblock) =
 4230:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4231:             if ($startblock && $endblock) {
 4232:                 return 'B';
 4233:             }
 4234:         }
 4235:     }
 4236:     if ($result eq 'ok') {
 4237:        return 'F';
 4238:     } elsif ($result =~ /^[^:]+:guest_/) {
 4239:        return 'A';
 4240:     }
 4241:     return '';
 4242: }
 4243: 
 4244: sub get_portfolio_access {
 4245:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4246: 
 4247:     if (!ref($access_hash)) {
 4248: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4249: 	my %access_controls = &get_access_controls($current_perms,$group,
 4250: 						   $file_name);
 4251: 	$access_hash = $access_controls{$file_name};
 4252:     }
 4253: 
 4254:     my ($public,$guest,@domains,@users,@courses,@groups);
 4255:     my $now = time;
 4256:     if (ref($access_hash) eq 'HASH') {
 4257:         foreach my $key (keys(%{$access_hash})) {
 4258:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4259:             if ($start > $now) {
 4260:                 next;
 4261:             }
 4262:             if ($end && $end<$now) {
 4263:                 next;
 4264:             }
 4265:             if ($scope eq 'public') {
 4266:                 $public = $key;
 4267:                 last;
 4268:             } elsif ($scope eq 'guest') {
 4269:                 $guest = $key;
 4270:             } elsif ($scope eq 'domains') {
 4271:                 push(@domains,$key);
 4272:             } elsif ($scope eq 'users') {
 4273:                 push(@users,$key);
 4274:             } elsif ($scope eq 'course') {
 4275:                 push(@courses,$key);
 4276:             } elsif ($scope eq 'group') {
 4277:                 push(@groups,$key);
 4278:             }
 4279:         }
 4280:         if ($public) {
 4281:             return 'ok';
 4282:         }
 4283:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4284:             if ($guest) {
 4285:                 return $guest;
 4286:             }
 4287:         } else {
 4288:             if (@domains > 0) {
 4289:                 foreach my $domkey (@domains) {
 4290:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4291:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4292:                             return 'ok';
 4293:                         }
 4294:                     }
 4295:                 }
 4296:             }
 4297:             if (@users > 0) {
 4298:                 foreach my $userkey (@users) {
 4299:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4300:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4301:                             if (ref($item) eq 'HASH') {
 4302:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4303:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4304:                                     return 'ok';
 4305:                                 }
 4306:                             }
 4307:                         }
 4308:                     } 
 4309:                 }
 4310:             }
 4311:             my %roleshash;
 4312:             my @courses_and_groups = @courses;
 4313:             push(@courses_and_groups,@groups); 
 4314:             if (@courses_and_groups > 0) {
 4315:                 my (%allgroups,%allroles); 
 4316:                 my ($start,$end,$role,$sec,$group);
 4317:                 foreach my $envkey (%env) {
 4318:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4319:                         my $cid = $2.'_'.$3; 
 4320:                         if ($1 eq 'gr') {
 4321:                             $group = $4;
 4322:                             $allgroups{$cid}{$group} = $env{$envkey};
 4323:                         } else {
 4324:                             if ($4 eq '') {
 4325:                                 $sec = 'none';
 4326:                             } else {
 4327:                                 $sec = $4;
 4328:                             }
 4329:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4330:                         }
 4331:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4332:                         my $cid = $2.'_'.$3;
 4333:                         if ($4 eq '') {
 4334:                             $sec = 'none';
 4335:                         } else {
 4336:                             $sec = $4;
 4337:                         }
 4338:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4339:                     }
 4340:                 }
 4341:                 if (keys(%allroles) == 0) {
 4342:                     return;
 4343:                 }
 4344:                 foreach my $key (@courses_and_groups) {
 4345:                     my %content = %{$$access_hash{$key}};
 4346:                     my $cnum = $content{'number'};
 4347:                     my $cdom = $content{'domain'};
 4348:                     my $cid = $cdom.'_'.$cnum;
 4349:                     if (!exists($allroles{$cid})) {
 4350:                         next;
 4351:                     }    
 4352:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4353:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4354:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4355:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4356:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4357:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4358:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4359:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4360:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4361:                                         if (grep/^all$/,@sections) {
 4362:                                             return 'ok';
 4363:                                         } else {
 4364:                                             if (grep/^$sec$/,@sections) {
 4365:                                                 return 'ok';
 4366:                                             }
 4367:                                         }
 4368:                                     }
 4369:                                 }
 4370:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4371:                                     if (grep/^none$/,@groups) {
 4372:                                         return 'ok';
 4373:                                     }
 4374:                                 } else {
 4375:                                     if (grep/^all$/,@groups) {
 4376:                                         return 'ok';
 4377:                                     } 
 4378:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4379:                                         if (grep/^$group$/,@groups) {
 4380:                                             return 'ok';
 4381:                                         }
 4382:                                     }
 4383:                                 } 
 4384:                             }
 4385:                         }
 4386:                     }
 4387:                 }
 4388:             }
 4389:             if ($guest) {
 4390:                 return $guest;
 4391:             }
 4392:         }
 4393:     }
 4394:     return;
 4395: }
 4396: 
 4397: sub course_group_datechecker {
 4398:     my ($dates,$now,$status) = @_;
 4399:     my ($start,$end) = split(/\./,$dates);
 4400:     if (!$start && !$end) {
 4401:         return 'ok';
 4402:     }
 4403:     if (grep/^active$/,@{$status}) {
 4404:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4405:             return 'ok';
 4406:         }
 4407:     }
 4408:     if (grep/^previous$/,@{$status}) {
 4409:         if ($end > $now ) {
 4410:             return 'ok';
 4411:         }
 4412:     }
 4413:     if (grep/^future$/,@{$status}) {
 4414:         if ($start > $now) {
 4415:             return 'ok';
 4416:         }
 4417:     }
 4418:     return; 
 4419: }
 4420: 
 4421: sub parse_portfolio_url {
 4422:     my ($url) = @_;
 4423: 
 4424:     my ($type,$udom,$unum,$group,$file_name);
 4425:     
 4426:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4427: 	$type = 1;
 4428:         $udom = $1;
 4429:         $unum = $2;
 4430:         $file_name = $3;
 4431:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4432: 	$type = 2;
 4433:         $udom = $1;
 4434:         $unum = $2;
 4435:         $group = $3;
 4436:         $file_name = $3.'/'.$4;
 4437:     }
 4438:     if (wantarray) {
 4439: 	return ($type,$udom,$unum,$file_name,$group);
 4440:     }
 4441:     return $type;
 4442: }
 4443: 
 4444: sub is_portfolio_url {
 4445:     my ($url) = @_;
 4446:     return scalar(&parse_portfolio_url($url));
 4447: }
 4448: 
 4449: sub is_portfolio_file {
 4450:     my ($file) = @_;
 4451:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4452:         return 1;
 4453:     }
 4454:     return;
 4455: }
 4456: 
 4457: sub usertools_access {
 4458:     my ($uname,$udom,$tool,$action,$context) = @_;
 4459:     my ($access,%tools);
 4460:     if ($context eq '') {
 4461:         $context = 'tools';
 4462:     }
 4463:     if ($context eq 'requestcourses') {
 4464:         %tools = (
 4465:                       official   => 1,
 4466:                       unofficial => 1,
 4467:                  );
 4468:     } else {
 4469:         %tools = (
 4470:                       aboutme   => 1,
 4471:                       blog      => 1,
 4472:                       portfolio => 1,
 4473:                  );
 4474:     }
 4475:     return if (!defined($tools{$tool}));
 4476: 
 4477:     if ((!defined($udom)) || (!defined($uname))) {
 4478:         $udom = $env{'user.domain'};
 4479:         $uname = $env{'user.name'};
 4480:     }
 4481: 
 4482:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4483:         if ($action ne 'reload') {
 4484:             if ($context eq 'requestcourses') {
 4485:                 return $env{'environment.canrequest.'.$tool};
 4486:             } else {
 4487:                 return $env{'environment.availabletools.'.$tool};
 4488:             }
 4489:         }
 4490:     }
 4491: 
 4492:     my ($toolstatus,$inststatus);
 4493: 
 4494:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4495:          ($action ne 'reload')) {
 4496:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4497:         $inststatus = $env{'environment.inststatus'};
 4498:     } else {
 4499:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4500:         $toolstatus = $userenv{$context.'.'.$tool};
 4501:         $inststatus = $userenv{'inststatus'};
 4502:     }
 4503: 
 4504:     if ($toolstatus ne '') {
 4505:         if ($toolstatus) {
 4506:             $access = 1;
 4507:         } else {
 4508:             $access = 0;
 4509:         }
 4510:         return $access;
 4511:     }
 4512: 
 4513:     my $is_adv = &is_advanced_user($udom,$uname);
 4514:     my %domdef = &get_domain_defaults($udom);
 4515:     if (ref($domdef{$tool}) eq 'HASH') {
 4516:         if ($is_adv) {
 4517:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4518:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4519:                     $access = 1;
 4520:                 } else {
 4521:                     $access = 0;
 4522:                 }
 4523:                 return $access;
 4524:             }
 4525:         }
 4526:         if ($inststatus ne '') {
 4527:             my ($hasaccess,$hasnoaccess);
 4528:             foreach my $affiliation (split(/:/,$inststatus)) {
 4529:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4530:                     if ($domdef{$tool}{$affiliation}) {
 4531:                         $hasaccess = 1;
 4532:                     } else {
 4533:                         $hasnoaccess = 1;
 4534:                     }
 4535:                 }
 4536:             }
 4537:             if ($hasaccess || $hasnoaccess) {
 4538:                 if ($hasaccess) {
 4539:                     $access = 1;
 4540:                 } elsif ($hasnoaccess) {
 4541:                     $access = 0; 
 4542:                 }
 4543:                 return $access;
 4544:             }
 4545:         } else {
 4546:             if ($domdef{$tool}{'default'} ne '') {
 4547:                 if ($domdef{$tool}{'default'}) {
 4548:                     $access = 1;
 4549:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4550:                     $access = 0;
 4551:                 }
 4552:                 return $access;
 4553:             }
 4554:         }
 4555:     } else {
 4556:         if ($context eq 'tools') {
 4557:             $access = 1;
 4558:         } else {
 4559:             $access = 0;
 4560:         }
 4561:         return $access;
 4562:     }
 4563: }
 4564: 
 4565: sub is_advanced_user {
 4566:     my ($udom,$uname) = @_;
 4567:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4568:     my %allroles;
 4569:     my $is_adv;
 4570:     foreach my $role (keys(%roleshash)) {
 4571:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4572:         my $area = '/'.$tdomain.'/'.$trest;
 4573:         if ($sec ne '') {
 4574:             $area .= '/'.$sec;
 4575:         }
 4576:         if (($area ne '') && ($trole ne '')) {
 4577:             my $spec=$trole.'.'.$area;
 4578:             if ($trole =~ /^cr\//) {
 4579:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4580:             } elsif ($trole ne 'gr') {
 4581:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4582:             }
 4583:         }
 4584:     }
 4585:     foreach my $role (keys(%allroles)) {
 4586:         last if ($is_adv);
 4587:         foreach my $item (split(/:/,$allroles{$role})) {
 4588:             if ($item ne '') {
 4589:                 my ($privilege,$restrictions)=split(/&/,$item);
 4590:                 if ($privilege eq 'adv') {
 4591:                     $is_adv = 1;
 4592:                     last;
 4593:                 }
 4594:             }
 4595:         }
 4596:     }
 4597:     return $is_adv;
 4598: }
 4599: 
 4600: # ---------------------------------------------- Custom access rule evaluation
 4601: 
 4602: sub customaccess {
 4603:     my ($priv,$uri)=@_;
 4604:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4605:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4606:     $udom = &LONCAPA::clean_domain($udom);
 4607:     $ucrs = &LONCAPA::clean_username($ucrs);
 4608:     my $access=0;
 4609:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4610: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4611: 	if ($type eq 'user') {
 4612: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4613: 		my ($tdom,$tuname)=split(m{/},$scope);
 4614: 		if ($tdom) {
 4615: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4616: 		}
 4617: 		if ($tuname) {
 4618: 		    if ($tuname ne $env{'user.name'}) { next; }
 4619: 		}
 4620: 		$access=($effect eq 'allow');
 4621: 		last;
 4622: 	    }
 4623: 	} else {
 4624: 	    if ($role) {
 4625: 		if ($role ne $urole) { next; }
 4626: 	    }
 4627: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4628: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4629: 		if ($tdom) {
 4630: 		    if ($tdom ne $udom) { next; }
 4631: 		}
 4632: 		if ($tcrs) {
 4633: 		    if ($tcrs ne $ucrs) { next; }
 4634: 		}
 4635: 		if ($tsec) {
 4636: 		    if ($tsec ne $usec) { next; }
 4637: 		}
 4638: 		$access=($effect eq 'allow');
 4639: 		last;
 4640: 	    }
 4641: 	    if ($realm eq '' && $role eq '') {
 4642: 		$access=($effect eq 'allow');
 4643: 	    }
 4644: 	}
 4645:     }
 4646:     return $access;
 4647: }
 4648: 
 4649: # ------------------------------------------------- Check for a user privilege
 4650: 
 4651: sub allowed {
 4652:     my ($priv,$uri,$symb,$role)=@_;
 4653:     my $ver_orguri=$uri;
 4654:     $uri=&deversion($uri);
 4655:     my $orguri=$uri;
 4656:     $uri=&declutter($uri);
 4657: 
 4658:     if ($priv eq 'evb') {
 4659: # Evade communication block restrictions for specified role in a course
 4660:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4661:             return $1;
 4662:         } else {
 4663:             return;
 4664:         }
 4665:     }
 4666: 
 4667:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4668: # Free bre access to adm and meta resources
 4669:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4670: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4671: 	&& ($priv eq 'bre')) {
 4672: 	return 'F';
 4673:     }
 4674: 
 4675: # Free bre access to user's own portfolio contents
 4676:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4677:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4678: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4679:         my %setters;
 4680:         my ($startblock,$endblock) = 
 4681:             &Apache::loncommon::blockcheck(\%setters,'port');
 4682:         if ($startblock && $endblock) {
 4683:             return 'B';
 4684:         } else {
 4685:             return 'F';
 4686:         }
 4687:     }
 4688: 
 4689: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4690:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4691:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4692:         if (exists($env{'request.course.id'})) {
 4693:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4694:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4695:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4696:                 my $courseprivid=$env{'request.course.id'};
 4697:                 $courseprivid=~s/\_/\//;
 4698:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4699:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4700:                     return $1; 
 4701:                 } else {
 4702:                     if ($env{'request.course.sec'}) {
 4703:                         $courseprivid.='/'.$env{'request.course.sec'};
 4704:                     }
 4705:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4706:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4707:                         return $2;
 4708:                     }
 4709:                 }
 4710:             }
 4711:         }
 4712:     }
 4713: 
 4714: # Free bre to public access
 4715: 
 4716:     if ($priv eq 'bre') {
 4717:         my $copyright=&metadata($uri,'copyright');
 4718: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4719:            return 'F'; 
 4720:         }
 4721:         if ($copyright eq 'priv') {
 4722:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4723: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4724: 		return '';
 4725:             }
 4726:         }
 4727:         if ($copyright eq 'domain') {
 4728:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4729: 	    unless (($env{'user.domain'} eq $1) ||
 4730:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4731: 		return '';
 4732:             }
 4733:         }
 4734:         if ($env{'request.role'}=~ /li\.\//) {
 4735:             # Library role, so allow browsing of resources in this domain.
 4736:             return 'F';
 4737:         }
 4738:         if ($copyright eq 'custom') {
 4739: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4740:         }
 4741:     }
 4742:     # Domain coordinator is trying to create a course
 4743:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4744:         # uri is the requested domain in this case.
 4745:         # comparison to 'request.role.domain' shows if the user has selected
 4746:         # a role of dc for the domain in question.
 4747:         return 'F' if ($uri eq $env{'request.role.domain'});
 4748:     }
 4749: 
 4750:     my $thisallowed='';
 4751:     my $statecond=0;
 4752:     my $courseprivid='';
 4753: 
 4754: # Course
 4755: 
 4756:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4757:        $thisallowed.=$1;
 4758:     }
 4759: 
 4760: # Domain
 4761: 
 4762:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4763:        =~/\Q$priv\E\&([^\:]*)/) {
 4764:        $thisallowed.=$1;
 4765:     }
 4766: 
 4767: # Course: uri itself is a course
 4768:     my $courseuri=$uri;
 4769:     $courseuri=~s/\_(\d)/\/$1/;
 4770:     $courseuri=~s/^([^\/])/\/$1/;
 4771: 
 4772:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4773:        =~/\Q$priv\E\&([^\:]*)/) {
 4774:        $thisallowed.=$1;
 4775:     }
 4776: 
 4777: # URI is an uploaded document for this course, default permissions don't matter
 4778: # not allowing 'edit' access (editupload) to uploaded course docs
 4779:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4780: 	$thisallowed='';
 4781:         my ($match)=&is_on_map($uri);
 4782:         if ($match) {
 4783:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4784:                   =~/\Q$priv\E\&([^\:]*)/) {
 4785:                 $thisallowed.=$1;
 4786:             }
 4787:         } else {
 4788:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4789:             if ($refuri) {
 4790:                 if ($refuri =~ m|^/adm/|) {
 4791:                     $thisallowed='F';
 4792:                 } else {
 4793:                     $refuri=&declutter($refuri);
 4794:                     my ($match) = &is_on_map($refuri);
 4795:                     if ($match) {
 4796:                         $thisallowed='F';
 4797:                     }
 4798:                 }
 4799:             }
 4800:         }
 4801:     }
 4802: 
 4803:     if ($priv eq 'bre'
 4804: 	&& $thisallowed ne 'F' 
 4805: 	&& $thisallowed ne '2'
 4806: 	&& &is_portfolio_url($uri)) {
 4807: 	$thisallowed = &portfolio_access($uri);
 4808:     }
 4809:     
 4810: # Full access at system, domain or course-wide level? Exit.
 4811:     if ($thisallowed=~/F/) {
 4812: 	return 'F';
 4813:     }
 4814: 
 4815: # If this is generating or modifying users, exit with special codes
 4816: 
 4817:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4818: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4819: 	    my ($audom,$auname)=split('/',$uri);
 4820: # no author name given, so this just checks on the general right to make a co-author in this domain
 4821: 	    unless ($auname) { return $thisallowed; }
 4822: # an author name is given, so we are about to actually make a co-author for a certain account
 4823: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4824: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4825: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4826: 	}
 4827: 	return $thisallowed;
 4828:     }
 4829: #
 4830: # Gathered so far: system, domain and course wide privileges
 4831: #
 4832: # Course: See if uri or referer is an individual resource that is part of 
 4833: # the course
 4834: 
 4835:     if ($env{'request.course.id'}) {
 4836: 
 4837:        $courseprivid=$env{'request.course.id'};
 4838:        if ($env{'request.course.sec'}) {
 4839:           $courseprivid.='/'.$env{'request.course.sec'};
 4840:        }
 4841:        $courseprivid=~s/\_/\//;
 4842:        my $checkreferer=1;
 4843:        my ($match,$cond)=&is_on_map($uri);
 4844:        if ($match) {
 4845:            $statecond=$cond;
 4846:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4847:                =~/\Q$priv\E\&([^\:]*)/) {
 4848:                $thisallowed.=$1;
 4849:                $checkreferer=0;
 4850:            }
 4851:        }
 4852:        
 4853:        if ($checkreferer) {
 4854: 	  my $refuri=$env{'httpref.'.$orguri};
 4855:             unless ($refuri) {
 4856:                 foreach my $key (keys(%env)) {
 4857: 		    if ($key=~/^httpref\..*\*/) {
 4858: 			my $pattern=$key;
 4859:                         $pattern=~s/^httpref\.\/res\///;
 4860:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4861:                         $pattern=~s/\//\\\//g;
 4862:                         if ($orguri=~/$pattern/) {
 4863: 			    $refuri=$env{$key};
 4864:                         }
 4865:                     }
 4866:                 }
 4867:             }
 4868: 
 4869:          if ($refuri) { 
 4870: 	  $refuri=&declutter($refuri);
 4871:           my ($match,$cond)=&is_on_map($refuri);
 4872:             if ($match) {
 4873:               my $refstatecond=$cond;
 4874:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4875:                   =~/\Q$priv\E\&([^\:]*)/) {
 4876:                   $thisallowed.=$1;
 4877:                   $uri=$refuri;
 4878:                   $statecond=$refstatecond;
 4879:               }
 4880:           }
 4881:         }
 4882:        }
 4883:    }
 4884: 
 4885: #
 4886: # Gathered now: all privileges that could apply, and condition number
 4887: # 
 4888: #
 4889: # Full or no access?
 4890: #
 4891: 
 4892:     if ($thisallowed=~/F/) {
 4893: 	return 'F';
 4894:     }
 4895: 
 4896:     unless ($thisallowed) {
 4897:         return '';
 4898:     }
 4899: 
 4900: # Restrictions exist, deal with them
 4901: #
 4902: #   C:according to course preferences
 4903: #   R:according to resource settings
 4904: #   L:unless locked
 4905: #   X:according to user session state
 4906: #
 4907: 
 4908: # Possibly locked functionality, check all courses
 4909: # Locks might take effect only after 10 minutes cache expiration for other
 4910: # courses, and 2 minutes for current course
 4911: 
 4912:     my $envkey;
 4913:     if ($thisallowed=~/L/) {
 4914:         foreach $envkey (keys %env) {
 4915:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4916:                my $courseid=$2;
 4917:                my $roleid=$1.'.'.$2;
 4918:                $courseid=~s/^\///;
 4919:                my $expiretime=600;
 4920:                if ($env{'request.role'} eq $roleid) {
 4921: 		  $expiretime=120;
 4922:                }
 4923: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4924:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4925:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4926: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4927:                }
 4928:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4929:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4930: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4931:                        &log($env{'user.domain'},$env{'user.name'},
 4932:                             $env{'user.home'},
 4933:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4934:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4935:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4936: 		       return '';
 4937:                    }
 4938:                }
 4939:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4940:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4941: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4942:                        &log($env{'user.domain'},$env{'user.name'},
 4943:                             $env{'user.home'},
 4944:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4945:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4946:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4947: 		       return '';
 4948:                    }
 4949:                }
 4950: 	   }
 4951:        }
 4952:     }
 4953:    
 4954: #
 4955: # Rest of the restrictions depend on selected course
 4956: #
 4957: 
 4958:     unless ($env{'request.course.id'}) {
 4959: 	if ($thisallowed eq 'A') {
 4960: 	    return 'A';
 4961:         } elsif ($thisallowed eq 'B') {
 4962:             return 'B';
 4963: 	} else {
 4964: 	    return '1';
 4965: 	}
 4966:     }
 4967: 
 4968: #
 4969: # Now user is definitely in a course
 4970: #
 4971: 
 4972: 
 4973: # Course preferences
 4974: 
 4975:    if ($thisallowed=~/C/) {
 4976:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4977:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4978:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4979: 	   =~/\Q$rolecode\E/) {
 4980: 	   if ($priv ne 'pch') { 
 4981: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4982: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4983: 			$env{'request.course.id'});
 4984: 	   }
 4985:            return '';
 4986:        }
 4987: 
 4988:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4989: 	   =~/\Q$unamedom\E/) {
 4990: 	   if ($priv ne 'pch') { 
 4991: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4992: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4993: 			$env{'request.course.id'});
 4994: 	   }
 4995:            return '';
 4996:        }
 4997:    }
 4998: 
 4999: # Resource preferences
 5000: 
 5001:    if ($thisallowed=~/R/) {
 5002:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5003:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5004: 	   if ($priv ne 'pch') { 
 5005: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5006: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5007: 	   }
 5008: 	   return '';
 5009:        }
 5010:    }
 5011: 
 5012: # Restricted by state or randomout?
 5013: 
 5014:    if ($thisallowed=~/X/) {
 5015:       if ($env{'acc.randomout'}) {
 5016: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5017:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5018:             return ''; 
 5019:          }
 5020:       }
 5021:       if (&condval($statecond)) {
 5022: 	 return '2';
 5023:       } else {
 5024:          return '';
 5025:       }
 5026:    }
 5027: 
 5028:     if ($thisallowed eq 'A') {
 5029: 	return 'A';
 5030:     } elsif ($thisallowed eq 'B') {
 5031:         return 'B';
 5032:     }
 5033:    return 'F';
 5034: }
 5035: 
 5036: sub split_uri_for_cond {
 5037:     my $uri=&deversion(&declutter(shift));
 5038:     my @uriparts=split(/\//,$uri);
 5039:     my $filename=pop(@uriparts);
 5040:     my $pathname=join('/',@uriparts);
 5041:     return ($pathname,$filename);
 5042: }
 5043: # --------------------------------------------------- Is a resource on the map?
 5044: 
 5045: sub is_on_map {
 5046:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5047:     #Trying to find the conditional for the file
 5048:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5049: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5050:     if ($match) {
 5051: 	return (1,$1);
 5052:     } else {
 5053: 	return (0,0);
 5054:     }
 5055: }
 5056: 
 5057: # --------------------------------------------------------- Get symb from alias
 5058: 
 5059: sub get_symb_from_alias {
 5060:     my $symb=shift;
 5061:     my ($map,$resid,$url)=&decode_symb($symb);
 5062: # Already is a symb
 5063:     if ($url) { return $symb; }
 5064: # Must be an alias
 5065:     my $aliassymb='';
 5066:     my %bighash;
 5067:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5068:                             &GDBM_READER(),0640)) {
 5069:         my $rid=$bighash{'mapalias_'.$symb};
 5070: 	if ($rid) {
 5071: 	    my ($mapid,$resid)=split(/\./,$rid);
 5072: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5073: 				    $resid,$bighash{'src_'.$rid});
 5074: 	}
 5075:         untie %bighash;
 5076:     }
 5077:     return $aliassymb;
 5078: }
 5079: 
 5080: # ----------------------------------------------------------------- Define Role
 5081: 
 5082: sub definerole {
 5083:   if (allowed('mcr','/')) {
 5084:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5085:     foreach my $role (split(':',$sysrole)) {
 5086: 	my ($crole,$cqual)=split(/\&/,$role);
 5087:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5088:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5089: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5090:                return "refused:s:$crole&$cqual"; 
 5091:             }
 5092:         }
 5093:     }
 5094:     foreach my $role (split(':',$domrole)) {
 5095: 	my ($crole,$cqual)=split(/\&/,$role);
 5096:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5097:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5098: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5099:                return "refused:d:$crole&$cqual"; 
 5100:             }
 5101:         }
 5102:     }
 5103:     foreach my $role (split(':',$courole)) {
 5104: 	my ($crole,$cqual)=split(/\&/,$role);
 5105:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5106:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5107: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5108:                return "refused:c:$crole&$cqual"; 
 5109:             }
 5110:         }
 5111:     }
 5112:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5113:                 "$env{'user.domain'}:$env{'user.name'}:".
 5114: 	        "rolesdef_$rolename=".
 5115:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5116:     return reply($command,$env{'user.home'});
 5117:   } else {
 5118:     return 'refused';
 5119:   }
 5120: }
 5121: 
 5122: # ---------------- Make a metadata query against the network of library servers
 5123: 
 5124: sub metadata_query {
 5125:     my ($query,$custom,$customshow,$server_array)=@_;
 5126:     my %rhash;
 5127:     my %libserv = &all_library();
 5128:     my @server_list = (defined($server_array) ? @$server_array
 5129:                                               : keys(%libserv) );
 5130:     for my $server (@server_list) {
 5131: 	unless ($custom or $customshow) {
 5132: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5133: 	    $rhash{$server}=$reply;
 5134: 	}
 5135: 	else {
 5136: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5137: 			     &escape($custom).':'.&escape($customshow),
 5138: 			     $server);
 5139: 	    $rhash{$server}=$reply;
 5140: 	}
 5141:     }
 5142:     return \%rhash;
 5143: }
 5144: 
 5145: # ----------------------------------------- Send log queries and wait for reply
 5146: 
 5147: sub log_query {
 5148:     my ($uname,$udom,$query,%filters)=@_;
 5149:     my $uhome=&homeserver($uname,$udom);
 5150:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5151:     my $uhost=&hostname($uhome);
 5152:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5153:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5154:                        $uhome);
 5155:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5156:     return get_query_reply($queryid);
 5157: }
 5158: 
 5159: # -------------------------- Update MySQL table for portfolio file
 5160: 
 5161: sub update_portfolio_table {
 5162:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5163:     if ($group ne '') {
 5164:         $file_name =~s /^\Q$group\E//;
 5165:     }
 5166:     my $homeserver = &homeserver($uname,$udom);
 5167:     my $queryid=
 5168:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5169:                ':'.&escape($file_name).':'.$action,$homeserver);
 5170:     my $reply = &get_query_reply($queryid);
 5171:     return $reply;
 5172: }
 5173: 
 5174: # -------------------------- Update MySQL allusers table
 5175: 
 5176: sub update_allusers_table {
 5177:     my ($uname,$udom,$names) = @_;
 5178:     my $homeserver = &homeserver($uname,$udom);
 5179:     my $queryid=
 5180:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5181:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5182:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5183:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5184:                'generation='.&escape($names->{'generation'}).'%%'.
 5185:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5186:                'id='.&escape($names->{'id'}),$homeserver);
 5187:     my $reply = &get_query_reply($queryid);
 5188:     return $reply;
 5189: }
 5190: 
 5191: # ------- Request retrieval of institutional classlists for course(s)
 5192: 
 5193: sub fetch_enrollment_query {
 5194:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5195:     my $homeserver;
 5196:     my $maxtries = 1;
 5197:     if ($context eq 'automated') {
 5198:         $homeserver = $perlvar{'lonHostID'};
 5199:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5200:     } else {
 5201:         $homeserver = &homeserver($cnum,$dom);
 5202:     }
 5203:     my $host=&hostname($homeserver);
 5204:     my $cmd = '';
 5205:     foreach my $affiliate (keys %{$affiliatesref}) {
 5206:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5207:     }
 5208:     $cmd =~ s/%%$//;
 5209:     $cmd = &escape($cmd);
 5210:     my $query = 'fetchenrollment';
 5211:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5212:     unless ($queryid=~/^\Q$host\E\_/) { 
 5213:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5214:         return 'error: '.$queryid;
 5215:     }
 5216:     my $reply = &get_query_reply($queryid);
 5217:     my $tries = 1;
 5218:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5219:         $reply = &get_query_reply($queryid);
 5220:         $tries ++;
 5221:     }
 5222:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5223:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5224:     } else {
 5225:         my @responses = split(/:/,$reply);
 5226:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5227:             foreach my $line (@responses) {
 5228:                 my ($key,$value) = split(/=/,$line,2);
 5229:                 $$replyref{$key} = $value;
 5230:             }
 5231:         } else {
 5232:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5233:             foreach my $line (@responses) {
 5234:                 my ($key,$value) = split(/=/,$line);
 5235:                 $$replyref{$key} = $value;
 5236:                 if ($value > 0) {
 5237:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5238:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5239:                         my $destname = $pathname.'/'.$filename;
 5240:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5241:                         if ($xml_classlist =~ /^error/) {
 5242:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5243:                         } else {
 5244:                             if ( open(FILE,">$destname") ) {
 5245:                                 print FILE &unescape($xml_classlist);
 5246:                                 close(FILE);
 5247:                             } else {
 5248:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5249:                             }
 5250:                         }
 5251:                     }
 5252:                 }
 5253:             }
 5254:         }
 5255:         return 'ok';
 5256:     }
 5257:     return 'error';
 5258: }
 5259: 
 5260: sub get_query_reply {
 5261:     my $queryid=shift;
 5262:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5263:     my $reply='';
 5264:     for (1..100) {
 5265: 	sleep 2;
 5266:         if (-e $replyfile.'.end') {
 5267: 	    if (open(my $fh,$replyfile)) {
 5268: 		$reply = join('',<$fh>);
 5269: 		close($fh);
 5270: 	   } else { return 'error: reply_file_error'; }
 5271:            return &unescape($reply);
 5272: 	}
 5273:     }
 5274:     return 'timeout:'.$queryid;
 5275: }
 5276: 
 5277: sub courselog_query {
 5278: #
 5279: # possible filters:
 5280: # url: url or symb
 5281: # username
 5282: # domain
 5283: # action: view, submit, grade
 5284: # start: timestamp
 5285: # end: timestamp
 5286: #
 5287:     my (%filters)=@_;
 5288:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5289:     if ($filters{'url'}) {
 5290: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5291:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5292:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5293:     }
 5294:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5295:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5296:     return &log_query($cname,$cdom,'courselog',%filters);
 5297: }
 5298: 
 5299: sub userlog_query {
 5300: #
 5301: # possible filters:
 5302: # action: log check role
 5303: # start: timestamp
 5304: # end: timestamp
 5305: #
 5306:     my ($uname,$udom,%filters)=@_;
 5307:     return &log_query($uname,$udom,'userlog',%filters);
 5308: }
 5309: 
 5310: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5311: 
 5312: sub auto_run {
 5313:     my ($cnum,$cdom) = @_;
 5314:     my $response = 0;
 5315:     my $settings;
 5316:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5317:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5318:         $settings = $domconfig{'autoenroll'};
 5319:         if ($settings->{'run'} eq '1') {
 5320:             $response = 1;
 5321:         }
 5322:     } else {
 5323:         my $homeserver;
 5324:         if (&is_course($cdom,$cnum)) {
 5325:             $homeserver = &homeserver($cnum,$cdom);
 5326:         } else {
 5327:             $homeserver = &domain($cdom,'primary');
 5328:         }
 5329:         if ($homeserver ne 'no_host') {
 5330:             $response = &reply('autorun:'.$cdom,$homeserver);
 5331:         }
 5332:     }
 5333:     return $response;
 5334: }
 5335: 
 5336: sub auto_get_sections {
 5337:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5338:     my $homeserver = &homeserver($cnum,$cdom);
 5339:     my @secs = ();
 5340:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5341:     unless ($response eq 'refused') {
 5342:         @secs = split(/:/,$response);
 5343:     }
 5344:     return @secs;
 5345: }
 5346: 
 5347: sub auto_new_course {
 5348:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5349:     my $homeserver = &homeserver($cnum,$cdom);
 5350:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5351:     return $response;
 5352: }
 5353: 
 5354: sub auto_validate_courseID {
 5355:     my ($cnum,$cdom,$inst_course_id) = @_;
 5356:     my $homeserver = &homeserver($cnum,$cdom);
 5357:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5358:     return $response;
 5359: }
 5360: 
 5361: sub auto_create_password {
 5362:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5363:     my ($homeserver,$response);
 5364:     my $create_passwd = 0;
 5365:     my $authchk = '';
 5366:     if ($udom =~ /^$match_domain$/) {
 5367:         $homeserver = &domain($udom,'primary');
 5368:     }
 5369:     if ($homeserver eq '') {
 5370:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5371:             $homeserver = &homeserver($cnum,$cdom);
 5372:         }
 5373:     }
 5374:     if ($homeserver eq '') {
 5375:         $authchk = 'nodomain';
 5376:     } else {
 5377:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5378:         if ($response eq 'refused') {
 5379:             $authchk = 'refused';
 5380:         } else {
 5381:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5382:         }
 5383:     }
 5384:     return ($authparam,$create_passwd,$authchk);
 5385: }
 5386: 
 5387: sub auto_photo_permission {
 5388:     my ($cnum,$cdom,$students) = @_;
 5389:     my $homeserver = &homeserver($cnum,$cdom);
 5390:     my ($outcome,$perm_reqd,$conditions) = 
 5391: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5392:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5393: 	return (undef,undef);
 5394:     }
 5395:     return ($outcome,$perm_reqd,$conditions);
 5396: }
 5397: 
 5398: sub auto_checkphotos {
 5399:     my ($uname,$udom,$pid) = @_;
 5400:     my $homeserver = &homeserver($uname,$udom);
 5401:     my ($result,$resulttype);
 5402:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5403: 				   &escape($uname).':'.&escape($pid),
 5404: 				   $homeserver));
 5405:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5406: 	return (undef,undef);
 5407:     }
 5408:     if ($outcome) {
 5409:         ($result,$resulttype) = split(/:/,$outcome);
 5410:     } 
 5411:     return ($result,$resulttype);
 5412: }
 5413: 
 5414: sub auto_photochoice {
 5415:     my ($cnum,$cdom) = @_;
 5416:     my $homeserver = &homeserver($cnum,$cdom);
 5417:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5418: 						       &escape($cdom),
 5419: 						       $homeserver)));
 5420:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5421: 	return (undef,undef);
 5422:     }
 5423:     return ($update,$comment);
 5424: }
 5425: 
 5426: sub auto_photoupdate {
 5427:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5428:     my $homeserver = &homeserver($cnum,$dom);
 5429:     my $host=&hostname($homeserver);
 5430:     my $cmd = '';
 5431:     my $maxtries = 1;
 5432:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5433:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5434:     }
 5435:     $cmd =~ s/%%$//;
 5436:     $cmd = &escape($cmd);
 5437:     my $query = 'institutionalphotos';
 5438:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5439:     unless ($queryid=~/^\Q$host\E\_/) {
 5440:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5441:         return 'error: '.$queryid;
 5442:     }
 5443:     my $reply = &get_query_reply($queryid);
 5444:     my $tries = 1;
 5445:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5446:         $reply = &get_query_reply($queryid);
 5447:         $tries ++;
 5448:     }
 5449:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5450:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5451:     } else {
 5452:         my @responses = split(/:/,$reply);
 5453:         my $outcome = shift(@responses); 
 5454:         foreach my $item (@responses) {
 5455:             my ($key,$value) = split(/=/,$item);
 5456:             $$photo{$key} = $value;
 5457:         }
 5458:         return $outcome;
 5459:     }
 5460:     return 'error';
 5461: }
 5462: 
 5463: sub auto_instcode_format {
 5464:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5465: 	$cat_order) = @_;
 5466:     my $courses = '';
 5467:     my @homeservers;
 5468:     if ($caller eq 'global') {
 5469: 	my %servers = &get_servers($codedom,'library');
 5470: 	foreach my $tryserver (keys(%servers)) {
 5471: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5472: 		push(@homeservers,$tryserver);
 5473: 	    }
 5474:         }
 5475:     } else {
 5476:         push(@homeservers,&homeserver($caller,$codedom));
 5477:     }
 5478:     foreach my $code (keys(%{$instcodes})) {
 5479:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5480:     }
 5481:     chop($courses);
 5482:     my $ok_response = 0;
 5483:     my $response;
 5484:     while (@homeservers > 0 && $ok_response == 0) {
 5485:         my $server = shift(@homeservers); 
 5486:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5487:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5488:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5489: 		split(/:/,$response);
 5490:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5491:             push(@{$codetitles},&str2array($codetitles_str));
 5492:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5493:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5494:             $ok_response = 1;
 5495:         }
 5496:     }
 5497:     if ($ok_response) {
 5498:         return 'ok';
 5499:     } else {
 5500:         return $response;
 5501:     }
 5502: }
 5503: 
 5504: sub auto_instcode_defaults {
 5505:     my ($domain,$returnhash,$code_order) = @_;
 5506:     my @homeservers;
 5507: 
 5508:     my %servers = &get_servers($domain,'library');
 5509:     foreach my $tryserver (keys(%servers)) {
 5510: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5511: 	    push(@homeservers,$tryserver);
 5512: 	}
 5513:     }
 5514: 
 5515:     my $response;
 5516:     foreach my $server (@homeservers) {
 5517:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5518:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5519: 	
 5520: 	foreach my $pair (split(/\&/,$response)) {
 5521: 	    my ($name,$value)=split(/\=/,$pair);
 5522: 	    if ($name eq 'code_order') {
 5523: 		@{$code_order} = split(/\&/,&unescape($value));
 5524: 	    } else {
 5525: 		$returnhash->{&unescape($name)}=&unescape($value);
 5526: 	    }
 5527: 	}
 5528: 	return 'ok';
 5529:     }
 5530: 
 5531:     return $response;
 5532: } 
 5533: 
 5534: sub auto_validate_class_sec {
 5535:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5536:     my $homeserver = &homeserver($cnum,$cdom);
 5537:     my $ownerlist;
 5538:     if (ref($owners) eq 'ARRAY') {
 5539:         $ownerlist = join(',',@{$owners});
 5540:     } else {
 5541:         $ownerlist = $owners;
 5542:     }
 5543:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5544:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5545:     return $response;
 5546: }
 5547: 
 5548: # ------------------------------------------------------- Course Group routines
 5549: 
 5550: sub get_coursegroups {
 5551:     my ($cdom,$cnum,$group,$namespace) = @_;
 5552:     return(&dump($namespace,$cdom,$cnum,$group));
 5553: }
 5554: 
 5555: sub modify_coursegroup {
 5556:     my ($cdom,$cnum,$groupsettings) = @_;
 5557:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5558: }
 5559: 
 5560: sub toggle_coursegroup_status {
 5561:     my ($cdom,$cnum,$group,$action) = @_;
 5562:     my ($from_namespace,$to_namespace);
 5563:     if ($action eq 'delete') {
 5564:         $from_namespace = 'coursegroups';
 5565:         $to_namespace = 'deleted_groups';
 5566:     } else {
 5567:         $from_namespace = 'deleted_groups';
 5568:         $to_namespace = 'coursegroups';
 5569:     }
 5570:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5571:     if (my $tmp = &error(%curr_group)) {
 5572:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5573:         return ('read error',$tmp);
 5574:     } else {
 5575:         my %savedsettings = %curr_group; 
 5576:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5577:         my $deloutcome;
 5578:         if ($result eq 'ok') {
 5579:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5580:         } else {
 5581:             return ('write error',$result);
 5582:         }
 5583:         if ($deloutcome eq 'ok') {
 5584:             return 'ok';
 5585:         } else {
 5586:             return ('delete error',$deloutcome);
 5587:         }
 5588:     }
 5589: }
 5590: 
 5591: sub modify_group_roles {
 5592:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5593:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5594:     my $role = 'gr/'.&escape($userprivs);
 5595:     my ($uname,$udom) = split(/:/,$user);
 5596:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5597:     if ($result eq 'ok') {
 5598:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5599:     }
 5600:     return $result;
 5601: }
 5602: 
 5603: sub modify_coursegroup_membership {
 5604:     my ($cdom,$cnum,$membership) = @_;
 5605:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5606:     return $result;
 5607: }
 5608: 
 5609: sub get_active_groups {
 5610:     my ($udom,$uname,$cdom,$cnum) = @_;
 5611:     my $now = time;
 5612:     my %groups = ();
 5613:     foreach my $key (keys(%env)) {
 5614:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5615:             my ($start,$end) = split(/\./,$env{$key});
 5616:             if (($end!=0) && ($end<$now)) { next; }
 5617:             if (($start!=0) && ($start>$now)) { next; }
 5618:             if ($1 eq $cdom && $2 eq $cnum) {
 5619:                 $groups{$3} = $env{$key} ;
 5620:             }
 5621:         }
 5622:     }
 5623:     return %groups;
 5624: }
 5625: 
 5626: sub get_group_membership {
 5627:     my ($cdom,$cnum,$group) = @_;
 5628:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5629: }
 5630: 
 5631: sub get_users_groups {
 5632:     my ($udom,$uname,$courseid) = @_;
 5633:     my @usersgroups;
 5634:     my $cachetime=1800;
 5635: 
 5636:     my $hashid="$udom:$uname:$courseid";
 5637:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5638:     if (defined($cached)) {
 5639:         @usersgroups = split(/:/,$grouplist);
 5640:     } else {  
 5641:         $grouplist = '';
 5642:         my $courseurl = &courseid_to_courseurl($courseid);
 5643:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5644:         my $access_end = $env{'course.'.$courseid.
 5645:                               '.default_enrollment_end_date'};
 5646:         my $now = time;
 5647:         foreach my $key (keys(%roleshash)) {
 5648:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5649:                 my $group = $1;
 5650:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5651:                     my $start = $2;
 5652:                     my $end = $1;
 5653:                     if ($start == -1) { next; } # deleted from group
 5654:                     if (($start!=0) && ($start>$now)) { next; }
 5655:                     if (($end!=0) && ($end<$now)) {
 5656:                         if ($access_end && $access_end < $now) {
 5657:                             if ($access_end - $end < 86400) {
 5658:                                 push(@usersgroups,$group);
 5659:                             }
 5660:                         }
 5661:                         next;
 5662:                     }
 5663:                     push(@usersgroups,$group);
 5664:                 }
 5665:             }
 5666:         }
 5667:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5668:         $grouplist = join(':',@usersgroups);
 5669:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5670:     }
 5671:     return @usersgroups;
 5672: }
 5673: 
 5674: sub devalidate_getgroups_cache {
 5675:     my ($udom,$uname,$cdom,$cnum)=@_;
 5676:     my $courseid = $cdom.'_'.$cnum;
 5677: 
 5678:     my $hashid="$udom:$uname:$courseid";
 5679:     &devalidate_cache_new('getgroups',$hashid);
 5680: }
 5681: 
 5682: # ------------------------------------------------------------------ Plain Text
 5683: 
 5684: sub plaintext {
 5685:     my ($short,$type,$cid,$forcedefault) = @_;
 5686:     if ($short =~ /^cr/) {
 5687: 	return (split('/',$short))[-1];
 5688:     }
 5689:     if (!defined($cid)) {
 5690:         $cid = $env{'request.course.id'};
 5691:     }
 5692:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 5693:         unless ($forcedefault) {
 5694:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 5695:             &Apache::lonlocal::mt_escape(\$roletext);
 5696:             return &Apache::lonlocal::mt($roletext);
 5697:         }
 5698:     }
 5699:     my %rolenames = (
 5700:                       Course => 'std',
 5701:                       Group => 'alt1',
 5702:                     );
 5703:     if (defined($type) && 
 5704:          defined($rolenames{$type}) && 
 5705:          defined($prp{$short}{$rolenames{$type}})) {
 5706:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5707:     } else {
 5708:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5709:     }
 5710: }
 5711: 
 5712: # ----------------------------------------------------------------- Assign Role
 5713: 
 5714: sub assignrole {
 5715:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5716:         $context)=@_;
 5717:     my $mrole;
 5718:     if ($role =~ /^cr\//) {
 5719:         my $cwosec=$url;
 5720:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5721: 	unless (&allowed('ccr',$cwosec)) {
 5722:            &logthis('Refused custom assignrole: '.
 5723:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5724: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5725:            return 'refused'; 
 5726:         }
 5727:         $mrole='cr';
 5728:     } elsif ($role =~ /^gr\//) {
 5729:         my $cwogrp=$url;
 5730:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5731:         unless (&allowed('mdg',$cwogrp)) {
 5732:             &logthis('Refused group assignrole: '.
 5733:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5734:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5735:             return 'refused';
 5736:         }
 5737:         $mrole='gr';
 5738:     } else {
 5739:         my $cwosec=$url;
 5740:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5741:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5742:             my $refused;
 5743:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5744:                 if (!(&allowed('c'.$role,$url))) {
 5745:                     $refused = 1;
 5746:                 }
 5747:             } else {
 5748:                 $refused = 1;
 5749:             }
 5750:             if ($refused) {
 5751:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5752:                     $refused = '';
 5753:                 } else {
 5754:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5755:                              ' '.$role.' '.$end.' '.$start.' by '.
 5756: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5757:                     return 'refused';
 5758:                 }
 5759:             }
 5760:         }
 5761:         $mrole=$role;
 5762:     }
 5763:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5764:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5765:     if ($end) { $command.='_'.$end; }
 5766:     if ($start) {
 5767: 	if ($end) { 
 5768:            $command.='_'.$start; 
 5769:         } else {
 5770:            $command.='_0_'.$start;
 5771:         }
 5772:     }
 5773:     my $origstart = $start;
 5774:     my $origend = $end;
 5775:     my $delflag;
 5776: # actually delete
 5777:     if ($deleteflag) {
 5778: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5779: # modify command to delete the role
 5780:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5781:                 "$udom:$uname:$url".'_'."$mrole";
 5782: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5783: # set start and finish to negative values for userrolelog
 5784:            $start=-1;
 5785:            $end=-1;
 5786:            $delflag = 1;
 5787:         }
 5788:     }
 5789: # send command
 5790:     my $answer=&reply($command,&homeserver($uname,$udom));
 5791: # log new user role if status is ok
 5792:     if ($answer eq 'ok') {
 5793: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5794: # for course roles, perform group memberships changes triggered by role change.
 5795:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5796:         unless ($role =~ /^gr/) {
 5797:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5798:                                              $origstart,$selfenroll,$context);
 5799:         }
 5800:     }
 5801:     return $answer;
 5802: }
 5803: 
 5804: # -------------------------------------------------- Modify user authentication
 5805: # Overrides without validation
 5806: 
 5807: sub modifyuserauth {
 5808:     my ($udom,$uname,$umode,$upass)=@_;
 5809:     my $uhome=&homeserver($uname,$udom);
 5810:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5811:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5812:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5813:              ' in domain '.$env{'request.role.domain'});  
 5814:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5815: 		     &escape($upass),$uhome);
 5816:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5817:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5818:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5819:     &log($udom,,$uname,$uhome,
 5820:         'Authentication changed by '.$env{'user.domain'}.', '.
 5821:                                      $env{'user.name'}.', '.$umode.
 5822:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5823:     unless ($reply eq 'ok') {
 5824:         &logthis('Authentication mode error: '.$reply);
 5825: 	return 'error: '.$reply;
 5826:     }   
 5827:     return 'ok';
 5828: }
 5829: 
 5830: # --------------------------------------------------------------- Modify a user
 5831: 
 5832: sub modifyuser {
 5833:     my ($udom,    $uname, $uid,
 5834:         $umode,   $upass, $first,
 5835:         $middle,  $last,  $gene,
 5836:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5837:     $udom= &LONCAPA::clean_domain($udom);
 5838:     $uname=&LONCAPA::clean_username($uname);
 5839:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5840:              $umode.', '.$first.', '.$middle.', '.
 5841: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5842:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5843:                                      ' desiredhome not specified'). 
 5844:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5845:              ' in domain '.$env{'request.role.domain'});
 5846:     my $uhome=&homeserver($uname,$udom,'true');
 5847: # ----------------------------------------------------------------- Create User
 5848:     if (($uhome eq 'no_host') && 
 5849: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5850:         my $unhome='';
 5851:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5852:             $unhome = $desiredhome;
 5853: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5854: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5855:         } else { # load balancing routine for determining $unhome
 5856:             my $loadm=10000000;
 5857: 	    my %servers = &get_servers($udom,'library');
 5858: 	    foreach my $tryserver (keys(%servers)) {
 5859: 		my $answer=reply('load',$tryserver);
 5860: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5861: 		    $loadm=$answer;
 5862: 		    $unhome=$tryserver;
 5863: 		}
 5864: 	    }
 5865:         }
 5866:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5867: 	    return 'error: unable to find a home server for '.$uname.
 5868:                    ' in domain '.$udom;
 5869:         }
 5870:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5871:                          &escape($upass),$unhome);
 5872: 	unless ($reply eq 'ok') {
 5873:             return 'error: '.$reply;
 5874:         }   
 5875:         $uhome=&homeserver($uname,$udom,'true');
 5876:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5877: 	    return 'error: unable verify users home machine.';
 5878:         }
 5879:     }   # End of creation of new user
 5880: # ---------------------------------------------------------------------- Add ID
 5881:     if ($uid) {
 5882:        $uid=~tr/A-Z/a-z/;
 5883:        my %uidhash=&idrget($udom,$uname);
 5884:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5885:          && (!$forceid)) {
 5886: 	  unless ($uid eq $uidhash{$uname}) {
 5887: 	      return 'error: user id "'.$uid.'" does not match '.
 5888:                   'current user id "'.$uidhash{$uname}.'".';
 5889:           }
 5890:        } else {
 5891: 	  &idput($udom,($uname => $uid));
 5892:        }
 5893:     }
 5894: # -------------------------------------------------------------- Add names, etc
 5895:     my @tmp=&get('environment',
 5896: 		   ['firstname','middlename','lastname','generation','id',
 5897:                     'permanentemail','inststatus'],
 5898: 		   $udom,$uname);
 5899:     my %names;
 5900:     if ($tmp[0] =~ m/^error:.*/) { 
 5901:         %names=(); 
 5902:     } else {
 5903:         %names = @tmp;
 5904:     }
 5905: #
 5906: # Make sure to not trash student environment if instructor does not bother
 5907: # to supply name and email information
 5908: #
 5909:     if ($first)  { $names{'firstname'}  = $first; }
 5910:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5911:     if ($last)   { $names{'lastname'}   = $last; }
 5912:     if (defined($gene))   { $names{'generation'} = $gene; }
 5913:     if ($email) {
 5914:        $email=~s/[^\w\@\.\-\,]//gs;
 5915:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5916:     }
 5917:     if ($uid) { $names{'id'}  = $uid; }
 5918:     if (defined($inststatus)) {
 5919:         $names{'inststatus'} = '';
 5920:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 5921:         if (ref($usertypes) eq 'HASH') {
 5922:             my @okstatuses; 
 5923:             foreach my $item (split(/:/,$inststatus)) {
 5924:                 if (defined($usertypes->{$item})) {
 5925:                     push(@okstatuses,$item);  
 5926:                 }
 5927:             }
 5928:             if (@okstatuses) {
 5929:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 5930:             }
 5931:         }
 5932:     }
 5933:     my $reply = &put('environment', \%names, $udom,$uname);
 5934:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5935:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5936:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5937:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5938:                  $umode.', '.$first.', '.$middle.', '.
 5939: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5940:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5941:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5942:     } else {
 5943:         $logmsg .= ' during self creation';
 5944:     }
 5945:     &logthis($logmsg);
 5946:     return 'ok';
 5947: }
 5948: 
 5949: # -------------------------------------------------------------- Modify student
 5950: 
 5951: sub modifystudent {
 5952:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5953:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5954:         $selfenroll,$context,$inststatus)=@_;
 5955:     if (!$cid) {
 5956: 	unless ($cid=$env{'request.course.id'}) {
 5957: 	    return 'not_in_class';
 5958: 	}
 5959:     }
 5960: # --------------------------------------------------------------- Make the user
 5961:     my $reply=&modifyuser
 5962: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5963:          $desiredhome,$email,$inststatus);
 5964:     unless ($reply eq 'ok') { return $reply; }
 5965:     # This will cause &modify_student_enrollment to get the uid from the
 5966:     # students environment
 5967:     $uid = undef if (!$forceid);
 5968:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5969: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5970:     return $reply;
 5971: }
 5972: 
 5973: sub modify_student_enrollment {
 5974:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5975:     my ($cdom,$cnum,$chome);
 5976:     if (!$cid) {
 5977: 	unless ($cid=$env{'request.course.id'}) {
 5978: 	    return 'not_in_class';
 5979: 	}
 5980: 	$cdom=$env{'course.'.$cid.'.domain'};
 5981: 	$cnum=$env{'course.'.$cid.'.num'};
 5982:     } else {
 5983: 	($cdom,$cnum)=split(/_/,$cid);
 5984:     }
 5985:     $chome=$env{'course.'.$cid.'.home'};
 5986:     if (!$chome) {
 5987: 	$chome=&homeserver($cnum,$cdom);
 5988:     }
 5989:     if (!$chome) { return 'unknown_course'; }
 5990:     # Make sure the user exists
 5991:     my $uhome=&homeserver($uname,$udom);
 5992:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5993: 	return 'error: no such user';
 5994:     }
 5995:     # Get student data if we were not given enough information
 5996:     if (!defined($first)  || $first  eq '' || 
 5997:         !defined($last)   || $last   eq '' || 
 5998:         !defined($uid)    || $uid    eq '' || 
 5999:         !defined($middle) || $middle eq '' || 
 6000:         !defined($gene)   || $gene   eq '') {
 6001:         # They did not supply us with enough data to enroll the student, so
 6002:         # we need to pick up more information.
 6003:         my %tmp = &get('environment',
 6004:                        ['firstname','middlename','lastname', 'generation','id']
 6005:                        ,$udom,$uname);
 6006: 
 6007:         #foreach my $key (keys(%tmp)) {
 6008:         #    &logthis("key $key = ".$tmp{$key});
 6009:         #}
 6010:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6011:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6012:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6013:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6014:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6015:     }
 6016:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6017:     my $reply=cput('classlist',
 6018: 		   {"$uname:$udom" => 
 6019: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6020: 		   $cdom,$cnum);
 6021:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6022: 	return 'error: '.$reply;
 6023:     } else {
 6024: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6025:     }
 6026:     # Add student role to user
 6027:     my $uurl='/'.$cid;
 6028:     $uurl=~s/\_/\//g;
 6029:     if ($usec) {
 6030: 	$uurl.='/'.$usec;
 6031:     }
 6032:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6033: }
 6034: 
 6035: sub format_name {
 6036:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6037:     my $name;
 6038:     if ($first ne 'lastname') {
 6039: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6040:     } else {
 6041: 	if ($lastname=~/\S/) {
 6042: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6043: 	    $name=~s/\s+,/,/;
 6044: 	} else {
 6045: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6046: 	}
 6047:     }
 6048:     $name=~s/^\s+//;
 6049:     $name=~s/\s+$//;
 6050:     $name=~s/\s+/ /g;
 6051:     return $name;
 6052: }
 6053: 
 6054: # ------------------------------------------------- Write to course preferences
 6055: 
 6056: sub writecoursepref {
 6057:     my ($courseid,%prefs)=@_;
 6058:     $courseid=~s/^\///;
 6059:     $courseid=~s/\_/\//g;
 6060:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6061:     my $chome=homeserver($cnum,$cdomain);
 6062:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6063: 	return 'error: no such course';
 6064:     }
 6065:     my $cstring='';
 6066:     foreach my $pref (keys(%prefs)) {
 6067: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6068:     }
 6069:     $cstring=~s/\&$//;
 6070:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6071: }
 6072: 
 6073: # ---------------------------------------------------------- Make/modify course
 6074: 
 6075: sub createcourse {
 6076:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6077:         $course_owner,$crstype)=@_;
 6078:     $url=&declutter($url);
 6079:     my $cid='';
 6080:     unless (&allowed('ccc',$udom)) {
 6081:         return 'refused';
 6082:     }
 6083: # ------------------------------------------------------------------- Create ID
 6084:    my $uname=int(1+rand(9)).
 6085:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6086:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6087:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6088: # ----------------------------------------------- Make sure that does not exist
 6089:    my $uhome=&homeserver($uname,$udom,'true');
 6090:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6091:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6092:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6093:        $uhome=&homeserver($uname,$udom,'true');       
 6094:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6095:            return 'error: unable to generate unique course-ID';
 6096:        } 
 6097:    }
 6098: # ------------------------------------------------ Check supplied server name
 6099:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6100:     if (! &is_library($course_server)) {
 6101:         return 'error:bad server name '.$course_server;
 6102:     }
 6103: # ------------------------------------------------------------- Make the course
 6104:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6105:                       $course_server);
 6106:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6107:     $uhome=&homeserver($uname,$udom,'true');
 6108:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6109: 	return 'error: no such course';
 6110:     }
 6111: # ----------------------------------------------------------------- Course made
 6112: # log existence
 6113:     my $newcourse = {
 6114:                     $udom.'_'.$uname => {
 6115:                                      description => $description,
 6116:                                      inst_code   => $inst_code,
 6117:                                      owner       => $course_owner,
 6118:                                      type        => $crstype,
 6119:                                                 },
 6120:                     };
 6121:     &courseidput($udom,$newcourse,$uhome,'notime');
 6122: # set toplevel url
 6123:     my $topurl=$url;
 6124:     unless ($nonstandard) {
 6125: # ------------------------------------------ For standard courses, make top url
 6126:         my $mapurl=&clutter($url);
 6127:         if ($mapurl eq '/res/') { $mapurl=''; }
 6128:         $env{'form.initmap'}=(<<ENDINITMAP);
 6129: <map>
 6130: <resource id="1" type="start"></resource>
 6131: <resource id="2" src="$mapurl"></resource>
 6132: <resource id="3" type="finish"></resource>
 6133: <link index="1" from="1" to="2"></link>
 6134: <link index="2" from="2" to="3"></link>
 6135: </map>
 6136: ENDINITMAP
 6137:         $topurl=&declutter(
 6138:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6139:                           );
 6140:     }
 6141: # ----------------------------------------------------------- Write preferences
 6142:     &writecoursepref($udom.'_'.$uname,
 6143:                      ('description' => $description,
 6144:                       'url'         => $topurl));
 6145:     return '/'.$udom.'/'.$uname;
 6146: }
 6147: 
 6148: sub is_course {
 6149:     my ($cdom,$cnum) = @_;
 6150:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6151: 				undef,'.');
 6152:     if (exists($courses{$cdom.'_'.$cnum})) {
 6153:         return 1;
 6154:     }
 6155:     return 0;
 6156: }
 6157: 
 6158: # ---------------------------------------------------------- Assign Custom Role
 6159: 
 6160: sub assigncustomrole {
 6161:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6162:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6163:                        $end,$start,$deleteflag,$selfenroll,$context);
 6164: }
 6165: 
 6166: # ----------------------------------------------------------------- Revoke Role
 6167: 
 6168: sub revokerole {
 6169:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6170:     my $now=time;
 6171:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6172: }
 6173: 
 6174: # ---------------------------------------------------------- Revoke Custom Role
 6175: 
 6176: sub revokecustomrole {
 6177:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6178:     my $now=time;
 6179:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6180:            $deleteflag,$selfenroll,$context);
 6181: }
 6182: 
 6183: # ------------------------------------------------------------ Disk usage
 6184: sub diskusage {
 6185:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6186:     $directorypath =~ s/\/$//;
 6187:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6188:                        .&escape($getpropath).':'.&escape($uname).':'
 6189:                        .&escape($udom),homeserver($uname,$udom));
 6190:     if ($listing eq 'unknown_cmd') {
 6191:         if ($getpropath) {
 6192:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6193:         }
 6194:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6195:     }
 6196:     return $listing;
 6197: }
 6198: 
 6199: sub is_locked {
 6200:     my ($file_name, $domain, $user) = @_;
 6201:     my @check;
 6202:     my $is_locked;
 6203:     push @check, $file_name;
 6204:     my %locked = &get('file_permissions',\@check,
 6205: 		      $env{'user.domain'},$env{'user.name'});
 6206:     my ($tmp)=keys(%locked);
 6207:     if ($tmp=~/^error:/) { undef(%locked); }
 6208:     
 6209:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6210:         $is_locked = 'false';
 6211:         foreach my $entry (@{$locked{$file_name}}) {
 6212:            if (ref($entry) eq 'ARRAY') { 
 6213:                $is_locked = 'true';
 6214:                last;
 6215:            }
 6216:        }
 6217:     } else {
 6218:         $is_locked = 'false';
 6219:     }
 6220: }
 6221: 
 6222: sub declutter_portfile {
 6223:     my ($file) = @_;
 6224:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6225:     return $file;
 6226: }
 6227: 
 6228: # ------------------------------------------------------------- Mark as Read Only
 6229: 
 6230: sub mark_as_readonly {
 6231:     my ($domain,$user,$files,$what) = @_;
 6232:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6233:     my ($tmp)=keys(%current_permissions);
 6234:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6235:     foreach my $file (@{$files}) {
 6236: 	$file = &declutter_portfile($file);
 6237:         push(@{$current_permissions{$file}},$what);
 6238:     }
 6239:     &put('file_permissions',\%current_permissions,$domain,$user);
 6240:     return;
 6241: }
 6242: 
 6243: # ------------------------------------------------------------Save Selected Files
 6244: 
 6245: sub save_selected_files {
 6246:     my ($user, $path, @files) = @_;
 6247:     my $filename = $user."savedfiles";
 6248:     my @other_files = &files_not_in_path($user, $path);
 6249:     open (OUT, '>'.$tmpdir.$filename);
 6250:     foreach my $file (@files) {
 6251:         print (OUT $env{'form.currentpath'}.$file."\n");
 6252:     }
 6253:     foreach my $file (@other_files) {
 6254:         print (OUT $file."\n");
 6255:     }
 6256:     close (OUT);
 6257:     return 'ok';
 6258: }
 6259: 
 6260: sub clear_selected_files {
 6261:     my ($user) = @_;
 6262:     my $filename = $user."savedfiles";
 6263:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6264:     print (OUT undef);
 6265:     close (OUT);
 6266:     return ("ok");    
 6267: }
 6268: 
 6269: sub files_in_path {
 6270:     my ($user, $path) = @_;
 6271:     my $filename = $user."savedfiles";
 6272:     my %return_files;
 6273:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6274:     while (my $line_in = <IN>) {
 6275:         chomp ($line_in);
 6276:         my @paths_and_file = split (m!/!, $line_in);
 6277:         my $file_part = pop (@paths_and_file);
 6278:         my $path_part = join ('/', @paths_and_file);
 6279:         $path_part.='/';
 6280:         my $path_and_file = $path_part.$file_part;
 6281:         if ($path_part eq $path) {
 6282:             $return_files{$file_part}= 'selected';
 6283:         }
 6284:     }
 6285:     close (IN);
 6286:     return (\%return_files);
 6287: }
 6288: 
 6289: # called in portfolio select mode, to show files selected NOT in current directory
 6290: sub files_not_in_path {
 6291:     my ($user, $path) = @_;
 6292:     my $filename = $user."savedfiles";
 6293:     my @return_files;
 6294:     my $path_part;
 6295:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6296:     while (my $line = <IN>) {
 6297:         #ok, I know it's clunky, but I want it to work
 6298:         my @paths_and_file = split(m|/|, $line);
 6299:         my $file_part = pop(@paths_and_file);
 6300:         chomp($file_part);
 6301:         my $path_part = join('/', @paths_and_file);
 6302:         $path_part .= '/';
 6303:         my $path_and_file = $path_part.$file_part;
 6304:         if ($path_part ne $path) {
 6305:             push(@return_files, ($path_and_file));
 6306:         }
 6307:     }
 6308:     close(OUT);
 6309:     return (@return_files);
 6310: }
 6311: 
 6312: #----------------------------------------------Get portfolio file permissions
 6313: 
 6314: sub get_portfile_permissions {
 6315:     my ($domain,$user) = @_;
 6316:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6317:     my ($tmp)=keys(%current_permissions);
 6318:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6319:     return \%current_permissions;
 6320: }
 6321: 
 6322: #---------------------------------------------Get portfolio file access controls
 6323: 
 6324: sub get_access_controls {
 6325:     my ($current_permissions,$group,$file) = @_;
 6326:     my %access;
 6327:     my $real_file = $file;
 6328:     $file =~ s/\.meta$//;
 6329:     if (defined($file)) {
 6330:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6331:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6332:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6333:             }
 6334:         }
 6335:     } else {
 6336:         foreach my $key (keys(%{$current_permissions})) {
 6337:             if ($key =~ /\0accesscontrol$/) {
 6338:                 if (defined($group)) {
 6339:                     if ($key !~ m-^\Q$group\E/-) {
 6340:                         next;
 6341:                     }
 6342:                 }
 6343:                 my ($fullpath) = split(/\0/,$key);
 6344:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6345:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6346:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6347:                     }
 6348:                 }
 6349:             }
 6350:         }
 6351:     }
 6352:     return %access;
 6353: }
 6354: 
 6355: sub modify_access_controls {
 6356:     my ($file_name,$changes,$domain,$user)=@_;
 6357:     my ($outcome,$deloutcome);
 6358:     my %store_permissions;
 6359:     my %new_values;
 6360:     my %new_control;
 6361:     my %translation;
 6362:     my @deletions = ();
 6363:     my $now = time;
 6364:     if (exists($$changes{'activate'})) {
 6365:         if (ref($$changes{'activate'}) eq 'HASH') {
 6366:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6367:             my $numnew = scalar(@newitems);
 6368:             for (my $i=0; $i<$numnew; $i++) {
 6369:                 my $newkey = $newitems[$i];
 6370:                 my $newid = &Apache::loncommon::get_cgi_id();
 6371:                 if ($newkey =~ /^\d+:/) { 
 6372:                     $newkey =~ s/^(\d+)/$newid/;
 6373:                     $translation{$1} = $newid;
 6374:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6375:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6376:                     $translation{$1} = $newid;
 6377:                 }
 6378:                 $new_values{$file_name."\0".$newkey} = 
 6379:                                           $$changes{'activate'}{$newitems[$i]};
 6380:                 $new_control{$newkey} = $now;
 6381:             }
 6382:         }
 6383:     }
 6384:     my %todelete;
 6385:     my %changed_items;
 6386:     foreach my $action ('delete','update') {
 6387:         if (exists($$changes{$action})) {
 6388:             if (ref($$changes{$action}) eq 'HASH') {
 6389:                 foreach my $key (keys(%{$$changes{$action}})) {
 6390:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6391:                     if ($action eq 'delete') { 
 6392:                         $todelete{$itemnum} = 1;
 6393:                     } else {
 6394:                         $changed_items{$itemnum} = $key;
 6395:                     }
 6396:                 }
 6397:             }
 6398:         }
 6399:     }
 6400:     # get lock on access controls for file.
 6401:     my $lockhash = {
 6402:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6403:                                                        ':'.$env{'user.domain'},
 6404:                    }; 
 6405:     my $tries = 0;
 6406:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6407:    
 6408:     while (($gotlock ne 'ok') && $tries <3) {
 6409:         $tries ++;
 6410:         sleep 1;
 6411:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6412:     }
 6413:     if ($gotlock eq 'ok') {
 6414:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6415:         my ($tmp)=keys(%curr_permissions);
 6416:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6417:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6418:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6419:             if (ref($curr_controls) eq 'HASH') {
 6420:                 foreach my $control_item (keys(%{$curr_controls})) {
 6421:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6422:                     if (defined($todelete{$itemnum})) {
 6423:                         push(@deletions,$file_name."\0".$control_item);
 6424:                     } else {
 6425:                         if (defined($changed_items{$itemnum})) {
 6426:                             $new_control{$changed_items{$itemnum}} = $now;
 6427:                             push(@deletions,$file_name."\0".$control_item);
 6428:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6429:                         } else {
 6430:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6431:                         }
 6432:                     }
 6433:                 }
 6434:             }
 6435:         }
 6436:         my ($group);
 6437:         if (&is_course($domain,$user)) {
 6438:             ($group,my $file) = split(/\//,$file_name,2);
 6439:         }
 6440:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6441:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6442:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6443:         #  remove lock
 6444:         my @del_lock = ($file_name."\0".'locked_access_records');
 6445:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6446:         my $sqlresult =
 6447:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6448:                                     $group);
 6449:     } else {
 6450:         $outcome = "error: could not obtain lockfile\n";  
 6451:     }
 6452:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6453: }
 6454: 
 6455: sub make_public_indefinitely {
 6456:     my ($requrl) = @_;
 6457:     my $now = time;
 6458:     my $action = 'activate';
 6459:     my $aclnum = 0;
 6460:     if (&is_portfolio_url($requrl)) {
 6461:         my (undef,$udom,$unum,$file_name,$group) =
 6462:             &parse_portfolio_url($requrl);
 6463:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6464:         my %access_controls = &get_access_controls($current_perms,
 6465:                                                    $group,$file_name);
 6466:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6467:             my ($num,$scope,$end,$start) = 
 6468:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6469:             if ($scope eq 'public') {
 6470:                 if ($start <= $now && $end == 0) {
 6471:                     $action = 'none';
 6472:                 } else {
 6473:                     $action = 'update';
 6474:                     $aclnum = $num;
 6475:                 }
 6476:                 last;
 6477:             }
 6478:         }
 6479:         if ($action eq 'none') {
 6480:              return 'ok';
 6481:         } else {
 6482:             my %changes;
 6483:             my $newend = 0;
 6484:             my $newstart = $now;
 6485:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6486:             $changes{$action}{$newkey} = {
 6487:                 type => 'public',
 6488:                 time => {
 6489:                     start => $newstart,
 6490:                     end   => $newend,
 6491:                 },
 6492:             };
 6493:             my ($outcome,$deloutcome,$new_values,$translation) =
 6494:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6495:             return $outcome;
 6496:         }
 6497:     } else {
 6498:         return 'invalid';
 6499:     }
 6500: }
 6501: 
 6502: #------------------------------------------------------Get Marked as Read Only
 6503: 
 6504: sub get_marked_as_readonly {
 6505:     my ($domain,$user,$what,$group) = @_;
 6506:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6507:     my @readonly_files;
 6508:     my $cmp1=$what;
 6509:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6510:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6511:         if (defined($group)) {
 6512:             if ($file_name !~ m-^\Q$group\E/-) {
 6513:                 next;
 6514:             }
 6515:         }
 6516:         if (ref($value) eq "ARRAY"){
 6517:             foreach my $stored_what (@{$value}) {
 6518:                 my $cmp2=$stored_what;
 6519:                 if (ref($stored_what) eq 'ARRAY') {
 6520:                     $cmp2=join('',@{$stored_what});
 6521:                 }
 6522:                 if ($cmp1 eq $cmp2) {
 6523:                     push(@readonly_files, $file_name);
 6524:                     last;
 6525:                 } elsif (!defined($what)) {
 6526:                     push(@readonly_files, $file_name);
 6527:                     last;
 6528:                 }
 6529:             }
 6530:         }
 6531:     }
 6532:     return @readonly_files;
 6533: }
 6534: #-----------------------------------------------------------Get Marked as Read Only Hash
 6535: 
 6536: sub get_marked_as_readonly_hash {
 6537:     my ($current_permissions,$group,$what) = @_;
 6538:     my %readonly_files;
 6539:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6540:         if (defined($group)) {
 6541:             if ($file_name !~ m-^\Q$group\E/-) {
 6542:                 next;
 6543:             }
 6544:         }
 6545:         if (ref($value) eq "ARRAY"){
 6546:             foreach my $stored_what (@{$value}) {
 6547:                 if (ref($stored_what) eq 'ARRAY') {
 6548:                     foreach my $lock_descriptor(@{$stored_what}) {
 6549:                         if ($lock_descriptor eq 'graded') {
 6550:                             $readonly_files{$file_name} = 'graded';
 6551:                         } elsif ($lock_descriptor eq 'handback') {
 6552:                             $readonly_files{$file_name} = 'handback';
 6553:                         } else {
 6554:                             if (!exists($readonly_files{$file_name})) {
 6555:                                 $readonly_files{$file_name} = 'locked';
 6556:                             }
 6557:                         }
 6558:                     }
 6559:                 } 
 6560:             }
 6561:         } 
 6562:     }
 6563:     return %readonly_files;
 6564: }
 6565: # ------------------------------------------------------------ Unmark as Read Only
 6566: 
 6567: sub unmark_as_readonly {
 6568:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6569:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6570:     my ($domain,$user,$what,$file_name,$group) = @_;
 6571:     $file_name = &declutter_portfile($file_name);
 6572:     my $symb_crs = $what;
 6573:     if (ref($what)) { $symb_crs=join('',@$what); }
 6574:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6575:     my ($tmp)=keys(%current_permissions);
 6576:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6577:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6578:     foreach my $file (@readonly_files) {
 6579: 	my $clean_file = &declutter_portfile($file);
 6580: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6581: 	my $current_locks = $current_permissions{$file};
 6582:         my @new_locks;
 6583:         my @del_keys;
 6584:         if (ref($current_locks) eq "ARRAY"){
 6585:             foreach my $locker (@{$current_locks}) {
 6586:                 my $compare=$locker;
 6587:                 if (ref($locker) eq 'ARRAY') {
 6588:                     $compare=join('',@{$locker});
 6589:                     if ($compare ne $symb_crs) {
 6590:                         push(@new_locks, $locker);
 6591:                     }
 6592:                 }
 6593:             }
 6594:             if (scalar(@new_locks) > 0) {
 6595:                 $current_permissions{$file} = \@new_locks;
 6596:             } else {
 6597:                 push(@del_keys, $file);
 6598:                 &del('file_permissions',\@del_keys, $domain, $user);
 6599:                 delete($current_permissions{$file});
 6600:             }
 6601:         }
 6602:     }
 6603:     &put('file_permissions',\%current_permissions,$domain,$user);
 6604:     return;
 6605: }
 6606: 
 6607: # ------------------------------------------------------------ Directory lister
 6608: 
 6609: sub dirlist {
 6610:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6611:     $uri=~s/^\///;
 6612:     $uri=~s/\/$//;
 6613:     my ($udom, $uname);
 6614:     if ($getuserdir) {
 6615:         $udom = $userdomain;
 6616:         $uname = $username;
 6617:     } else {
 6618:         (undef,$udom,$uname)=split(/\//,$uri);
 6619:         if(defined($userdomain)) {
 6620:             $udom = $userdomain;
 6621:         }
 6622:         if(defined($username)) {
 6623:             $uname = $username;
 6624:         }
 6625:     }
 6626:     my ($dirRoot,$listing,@listing_results);
 6627: 
 6628:     $dirRoot = $perlvar{'lonDocRoot'};
 6629:     if (defined($getpropath)) {
 6630:         $dirRoot = &propath($udom,$uname);
 6631:         $dirRoot =~ s/\/$//;
 6632:     } elsif (defined($getuserdir)) {
 6633:         my $subdir=$uname.'__';
 6634:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6635:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6636:                    ."/$udom/$subdir/$uname";
 6637:     } elsif (defined($alternateRoot)) {
 6638:         $dirRoot = $alternateRoot;
 6639:     }
 6640: 
 6641:     if($udom) {
 6642:         if($uname) {
 6643:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6644:                               .$getuserdir.':'.&escape($dirRoot)
 6645:                               .':'.&escape($uname).':'.&escape($udom),
 6646:                               &homeserver($uname,$udom));
 6647:             if ($listing eq 'unknown_cmd') {
 6648:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6649:                                   &homeserver($uname,$udom));
 6650:             } else {
 6651:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6652:             }
 6653:             if ($listing eq 'unknown_cmd') {
 6654:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6655: 				  &homeserver($uname,$udom));
 6656:                 @listing_results = split(/:/,$listing);
 6657:             } else {
 6658:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6659:             }
 6660:             return @listing_results;
 6661:         } elsif(!$alternateRoot) {
 6662:             my %allusers;
 6663: 	    my %servers = &get_servers($udom,'library');
 6664:  	    foreach my $tryserver (keys(%servers)) {
 6665:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6666:                                   &escape($udom),$tryserver);
 6667:                 if ($listing eq 'unknown_cmd') {
 6668: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6669: 				      $udom, $tryserver);
 6670:                 } else {
 6671:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6672:                 }
 6673: 		if ($listing eq 'unknown_cmd') {
 6674: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6675: 				      $udom, $tryserver);
 6676: 		    @listing_results = split(/:/,$listing);
 6677: 		} else {
 6678: 		    @listing_results =
 6679: 			map { &unescape($_); } split(/:/,$listing);
 6680: 		}
 6681: 		if ($listing_results[0] ne 'no_such_dir' && 
 6682: 		    $listing_results[0] ne 'empty'       &&
 6683: 		    $listing_results[0] ne 'con_lost') {
 6684: 		    foreach my $line (@listing_results) {
 6685: 			my ($entry) = split(/&/,$line,2);
 6686: 			$allusers{$entry} = 1;
 6687: 		    }
 6688: 		}
 6689:             }
 6690:             my $alluserstr='';
 6691:             foreach my $user (sort(keys(%allusers))) {
 6692:                 $alluserstr.=$user.'&user:';
 6693:             }
 6694:             $alluserstr=~s/:$//;
 6695:             return split(/:/,$alluserstr);
 6696:         } else {
 6697:             return ('missing user name');
 6698:         }
 6699:     } elsif(!defined($getpropath)) {
 6700:         my @all_domains = sort(&all_domains());
 6701:         foreach my $domain (@all_domains) {
 6702:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6703:         }
 6704:         return @all_domains;
 6705:     } else {
 6706:         return ('missing domain');
 6707:     }
 6708: }
 6709: 
 6710: # --------------------------------------------- GetFileTimestamp
 6711: # This function utilizes dirlist and returns the date stamp for
 6712: # when it was last modified.  It will also return an error of -1
 6713: # if an error occurs
 6714: 
 6715: sub GetFileTimestamp {
 6716:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6717:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6718:     $studentName   = &LONCAPA::clean_username($studentName);
 6719:     my ($fileStat) = 
 6720:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6721:                                  undef,$getuserdir);
 6722:     my @stats = split('&', $fileStat);
 6723:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6724:         # @stats contains first the filename, then the stat output
 6725:         return $stats[10]; # so this is 10 instead of 9.
 6726:     } else {
 6727:         return -1;
 6728:     }
 6729: }
 6730: 
 6731: sub stat_file {
 6732:     my ($uri) = @_;
 6733:     $uri = &clutter_with_no_wrapper($uri);
 6734: 
 6735:     my ($udom,$uname,$file);
 6736:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6737: 	($udom,$uname,$file) =
 6738: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6739: 	$file = 'userfiles/'.$file;
 6740:     }
 6741:     if ($uri =~ m-^/res/-) {
 6742: 	($udom,$uname) = 
 6743: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6744: 	$file = $uri;
 6745:     }
 6746: 
 6747:     if (!$udom || !$uname || !$file) {
 6748: 	# unable to handle the uri
 6749: 	return ();
 6750:     }
 6751:     my $getpropath;
 6752:     if ($file =~ /^userfiles\//) {
 6753:         $getpropath = 1;
 6754:     }
 6755:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6756:     my @stats = split('&', $result);
 6757:     
 6758:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6759: 	shift(@stats); #filename is first
 6760: 	return @stats;
 6761:     }
 6762:     return ();
 6763: }
 6764: 
 6765: # -------------------------------------------------------- Value of a Condition
 6766: 
 6767: # gets the value of a specific preevaluated condition
 6768: #    stored in the string  $env{user.state.<cid>}
 6769: # or looks up a condition reference in the bighash and if if hasn't
 6770: # already been evaluated recurses into docondval to get the value of
 6771: # the condition, then memoizing it to 
 6772: #   $env{user.state.<cid>.<condition>}
 6773: sub directcondval {
 6774:     my $number=shift;
 6775:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6776: 	&Apache::lonuserstate::evalstate();
 6777:     }
 6778:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6779: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6780:     } elsif ($number =~ /^_/) {
 6781: 	my $sub_condition;
 6782: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6783: 		&GDBM_READER(),0640)) {
 6784: 	    $sub_condition=$bighash{'conditions'.$number};
 6785: 	    untie(%bighash);
 6786: 	}
 6787: 	my $value = &docondval($sub_condition);
 6788: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6789: 	return $value;
 6790:     }
 6791:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6792:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6793:     } else {
 6794:        return 2;
 6795:     }
 6796: }
 6797: 
 6798: # get the collection of conditions for this resource
 6799: sub condval {
 6800:     my $condidx=shift;
 6801:     my $allpathcond='';
 6802:     foreach my $cond (split(/\|/,$condidx)) {
 6803: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6804: 	    $allpathcond.=
 6805: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6806: 	}
 6807:     }
 6808:     $allpathcond=~s/\|$//;
 6809:     return &docondval($allpathcond);
 6810: }
 6811: 
 6812: #evaluates an expression of conditions
 6813: sub docondval {
 6814:     my ($allpathcond) = @_;
 6815:     my $result=0;
 6816:     if ($env{'request.course.id'}
 6817: 	&& defined($allpathcond)) {
 6818: 	my $operand='|';
 6819: 	my @stack;
 6820: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6821: 	    if ($chunk eq '(') {
 6822: 		push @stack,($operand,$result);
 6823: 	    } elsif ($chunk eq ')') {
 6824: 		my $before=pop @stack;
 6825: 		if (pop @stack eq '&') {
 6826: 		    $result=$result>$before?$before:$result;
 6827: 		} else {
 6828: 		    $result=$result>$before?$result:$before;
 6829: 		}
 6830: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6831: 		$operand=$chunk;
 6832: 	    } else {
 6833: 		my $new=directcondval($chunk);
 6834: 		if ($operand eq '&') {
 6835: 		    $result=$result>$new?$new:$result;
 6836: 		} else {
 6837: 		    $result=$result>$new?$result:$new;
 6838: 		}
 6839: 	    }
 6840: 	}
 6841:     }
 6842:     return $result;
 6843: }
 6844: 
 6845: # ---------------------------------------------------- Devalidate courseresdata
 6846: 
 6847: sub devalidatecourseresdata {
 6848:     my ($coursenum,$coursedomain)=@_;
 6849:     my $hashid=$coursenum.':'.$coursedomain;
 6850:     &devalidate_cache_new('courseres',$hashid);
 6851: }
 6852: 
 6853: 
 6854: # --------------------------------------------------- Course Resourcedata Query
 6855: #
 6856: #  Parameters:
 6857: #      $coursenum    - Number of the course.
 6858: #      $coursedomain - Domain at which the course was created.
 6859: #  Returns:
 6860: #     A hash of the course parameters along (I think) with timestamps
 6861: #     and version info.
 6862: 
 6863: sub get_courseresdata {
 6864:     my ($coursenum,$coursedomain)=@_;
 6865:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6866:     my $hashid=$coursenum.':'.$coursedomain;
 6867:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6868:     my %dumpreply;
 6869:     unless (defined($cached)) {
 6870: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6871: 	$result=\%dumpreply;
 6872: 	my ($tmp) = keys(%dumpreply);
 6873: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6874: 	    &do_cache_new('courseres',$hashid,$result,600);
 6875: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6876: 	    return $tmp;
 6877: 	} elsif ($tmp =~ /^(error)/) {
 6878: 	    $result=undef;
 6879: 	    &do_cache_new('courseres',$hashid,$result,600);
 6880: 	}
 6881:     }
 6882:     return $result;
 6883: }
 6884: 
 6885: sub devalidateuserresdata {
 6886:     my ($uname,$udom)=@_;
 6887:     my $hashid="$udom:$uname";
 6888:     &devalidate_cache_new('userres',$hashid);
 6889: }
 6890: 
 6891: sub get_userresdata {
 6892:     my ($uname,$udom)=@_;
 6893:     #most student don\'t have any data set, check if there is some data
 6894:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6895: 
 6896:     my $hashid="$udom:$uname";
 6897:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6898:     if (!defined($cached)) {
 6899: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6900: 	$result=\%resourcedata;
 6901: 	&do_cache_new('userres',$hashid,$result,600);
 6902:     }
 6903:     my ($tmp)=keys(%$result);
 6904:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6905: 	return $result;
 6906:     }
 6907:     #error 2 occurs when the .db doesn't exist
 6908:     if ($tmp!~/error: 2 /) {
 6909: 	&logthis("<font color=\"blue\">WARNING:".
 6910: 		 " Trying to get resource data for ".
 6911: 		 $uname." at ".$udom.": ".
 6912: 		 $tmp."</font>");
 6913:     } elsif ($tmp=~/error: 2 /) {
 6914: 	#&EXT_cache_set($udom,$uname);
 6915: 	&do_cache_new('userres',$hashid,undef,600);
 6916: 	undef($tmp); # not really an error so don't send it back
 6917:     }
 6918:     return $tmp;
 6919: }
 6920: #----------------------------------------------- resdata - return resource data
 6921: #  Purpose:
 6922: #    Return resource data for either users or for a course.
 6923: #  Parameters:
 6924: #     $name      - Course/user name.
 6925: #     $domain    - Name of the domain the user/course is registered on.
 6926: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6927: #     @which     - Array of names of resources desired.
 6928: #  Returns:
 6929: #     The value of the first reasource in @which that is found in the
 6930: #     resource hash.
 6931: #  Exceptional Conditions:
 6932: #     If the $type passed in is not valid (not the string 'course' or 
 6933: #     'user', an undefined  reference is returned.
 6934: #     If none of the resources are found, an undef is returned
 6935: sub resdata {
 6936:     my ($name,$domain,$type,@which)=@_;
 6937:     my $result;
 6938:     if ($type eq 'course') {
 6939: 	$result=&get_courseresdata($name,$domain);
 6940:     } elsif ($type eq 'user') {
 6941: 	$result=&get_userresdata($name,$domain);
 6942:     }
 6943:     if (!ref($result)) { return $result; }    
 6944:     foreach my $item (@which) {
 6945: 	if (defined($result->{$item->[0]})) {
 6946: 	    return [$result->{$item->[0]},$item->[1]];
 6947: 	}
 6948:     }
 6949:     return undef;
 6950: }
 6951: 
 6952: #
 6953: # EXT resource caching routines
 6954: #
 6955: 
 6956: sub clear_EXT_cache_status {
 6957:     &delenv('cache.EXT.');
 6958: }
 6959: 
 6960: sub EXT_cache_status {
 6961:     my ($target_domain,$target_user) = @_;
 6962:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6963:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6964:         # We know already the user has no data
 6965:         return 1;
 6966:     } else {
 6967:         return 0;
 6968:     }
 6969: }
 6970: 
 6971: sub EXT_cache_set {
 6972:     my ($target_domain,$target_user) = @_;
 6973:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6974:     #&appenv({$cachename => time});
 6975: }
 6976: 
 6977: # --------------------------------------------------------- Value of a Variable
 6978: sub EXT {
 6979: 
 6980:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6981:     unless ($varname) { return ''; }
 6982:     #get real user name/domain, courseid and symb
 6983:     my $courseid;
 6984:     my $publicuser;
 6985:     if ($symbparm) {
 6986: 	$symbparm=&get_symb_from_alias($symbparm);
 6987:     }
 6988:     if (!($uname && $udom)) {
 6989:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6990:       if (!$symbparm) {	$symbparm=$cursymb; }
 6991:     } else {
 6992: 	$courseid=$env{'request.course.id'};
 6993:     }
 6994:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6995:     my $rest;
 6996:     if (defined($therest[0])) {
 6997:        $rest=join('.',@therest);
 6998:     } else {
 6999:        $rest='';
 7000:     }
 7001: 
 7002:     my $qualifierrest=$qualifier;
 7003:     if ($rest) { $qualifierrest.='.'.$rest; }
 7004:     my $spacequalifierrest=$space;
 7005:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7006:     if ($realm eq 'user') {
 7007: # --------------------------------------------------------------- user.resource
 7008: 	if ($space eq 'resource') {
 7009: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7010: 		  || defined($Apache::lonhomework::parsing_a_task))
 7011: 		 &&
 7012: 		 ($symbparm eq &symbread()) ) {	
 7013: 		# if we are in the middle of processing the resource the
 7014: 		# get the value we are planning on committing
 7015:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7016:                     return $Apache::lonhomework::results{$qualifierrest};
 7017:                 } else {
 7018:                     return $Apache::lonhomework::history{$qualifierrest};
 7019:                 }
 7020: 	    } else {
 7021: 		my %restored;
 7022: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7023: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7024: 		} else {
 7025: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7026: 		}
 7027: 		return $restored{$qualifierrest};
 7028: 	    }
 7029: # ----------------------------------------------------------------- user.access
 7030:         } elsif ($space eq 'access') {
 7031: 	    # FIXME - not supporting calls for a specific user
 7032:             return &allowed($qualifier,$rest);
 7033: # ------------------------------------------ user.preferences, user.environment
 7034:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7035: 	    if (($uname eq $env{'user.name'}) &&
 7036: 		($udom eq $env{'user.domain'})) {
 7037: 		return $env{join('.',('environment',$qualifierrest))};
 7038: 	    } else {
 7039: 		my %returnhash;
 7040: 		if (!$publicuser) {
 7041: 		    %returnhash=&userenvironment($udom,$uname,
 7042: 						 $qualifierrest);
 7043: 		}
 7044: 		return $returnhash{$qualifierrest};
 7045: 	    }
 7046: # ----------------------------------------------------------------- user.course
 7047:         } elsif ($space eq 'course') {
 7048: 	    # FIXME - not supporting calls for a specific user
 7049:             return $env{join('.',('request.course',$qualifier))};
 7050: # ------------------------------------------------------------------- user.role
 7051:         } elsif ($space eq 'role') {
 7052: 	    # FIXME - not supporting calls for a specific user
 7053:             my ($role,$where)=split(/\./,$env{'request.role'});
 7054:             if ($qualifier eq 'value') {
 7055: 		return $role;
 7056:             } elsif ($qualifier eq 'extent') {
 7057:                 return $where;
 7058:             }
 7059: # ----------------------------------------------------------------- user.domain
 7060:         } elsif ($space eq 'domain') {
 7061:             return $udom;
 7062: # ------------------------------------------------------------------- user.name
 7063:         } elsif ($space eq 'name') {
 7064:             return $uname;
 7065: # ---------------------------------------------------- Any other user namespace
 7066:         } else {
 7067: 	    my %reply;
 7068: 	    if (!$publicuser) {
 7069: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7070: 	    }
 7071: 	    return $reply{$qualifierrest};
 7072:         }
 7073:     } elsif ($realm eq 'query') {
 7074: # ---------------------------------------------- pull stuff out of query string
 7075:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7076: 						[$spacequalifierrest]);
 7077: 	return $env{'form.'.$spacequalifierrest}; 
 7078:    } elsif ($realm eq 'request') {
 7079: # ------------------------------------------------------------- request.browser
 7080:         if ($space eq 'browser') {
 7081: 	    if ($qualifier eq 'textremote') {
 7082: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7083: 		    return 1;
 7084: 		} else {
 7085: 		    return 0;
 7086: 		}
 7087: 	    } else {
 7088: 		return $env{'browser.'.$qualifier};
 7089: 	    }
 7090: # ------------------------------------------------------------ request.filename
 7091:         } else {
 7092:             return $env{'request.'.$spacequalifierrest};
 7093:         }
 7094:     } elsif ($realm eq 'course') {
 7095: # ---------------------------------------------------------- course.description
 7096:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7097:     } elsif ($realm eq 'resource') {
 7098: 
 7099: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7100: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7101: 	}
 7102: 
 7103: 	if ($space eq 'title') {
 7104: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7105: 	    return &gettitle($symbparm);
 7106: 	}
 7107: 	
 7108: 	if ($space eq 'map') {
 7109: 	    my ($map) = &decode_symb($symbparm);
 7110: 	    return &symbread($map);
 7111: 	}
 7112: 	if ($space eq 'filename') {
 7113: 	    if ($symbparm) {
 7114: 		return &clutter((&decode_symb($symbparm))[2]);
 7115: 	    }
 7116: 	    return &hreflocation('',$env{'request.filename'});
 7117: 	}
 7118: 
 7119: 	my ($section, $group, @groups);
 7120: 	my ($courselevelm,$courselevel);
 7121: 	if ($symbparm && defined($courseid) && 
 7122: 	    $courseid eq $env{'request.course.id'}) {
 7123: 
 7124: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7125: 
 7126: # ----------------------------------------------------- Cascading lookup scheme
 7127: 	    my $symbp=$symbparm;
 7128: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7129: 
 7130: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7131: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7132: 
 7133: 	    if (($env{'user.name'} eq $uname) &&
 7134: 		($env{'user.domain'} eq $udom)) {
 7135: 		$section=$env{'request.course.sec'};
 7136:                 @groups = split(/:/,$env{'request.course.groups'});  
 7137:                 @groups=&sort_course_groups($courseid,@groups); 
 7138: 	    } else {
 7139: 		if (! defined($usection)) {
 7140: 		    $section=&getsection($udom,$uname,$courseid);
 7141: 		} else {
 7142: 		    $section = $usection;
 7143: 		}
 7144:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7145: 	    }
 7146: 
 7147: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7148: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7149: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7150: 
 7151: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7152: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7153: 	    $courselevelm=$courseid.'.'.$mapparm;
 7154: 
 7155: # ----------------------------------------------------------- first, check user
 7156: 
 7157: 	    my $userreply=&resdata($uname,$udom,'user',
 7158: 				       ([$courselevelr,'resource'],
 7159: 					[$courselevelm,'map'     ],
 7160: 					[$courselevel, 'course'  ]));
 7161: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7162: 
 7163: # ------------------------------------------------ second, check some of course
 7164:             my $coursereply;
 7165:             if (@groups > 0) {
 7166:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7167:                                        $mapparm,$spacequalifierrest);
 7168:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7169:             }
 7170: 
 7171: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7172: 				  $env{'course.'.$courseid.'.domain'},
 7173: 				  'course',
 7174: 				  ([$seclevelr,   'resource'],
 7175: 				   [$seclevelm,   'map'     ],
 7176: 				   [$seclevel,    'course'  ],
 7177: 				   [$courselevelr,'resource']));
 7178: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7179: 
 7180: # ------------------------------------------------------ third, check map parms
 7181: 	    my %parmhash=();
 7182: 	    my $thisparm='';
 7183: 	    if (tie(%parmhash,'GDBM_File',
 7184: 		    $env{'request.course.fn'}.'_parms.db',
 7185: 		    &GDBM_READER(),0640)) {
 7186: 		$thisparm=$parmhash{$symbparm};
 7187: 		untie(%parmhash);
 7188: 	    }
 7189: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7190: 	}
 7191: # ------------------------------------------ fourth, look in resource metadata
 7192: 
 7193: 	$spacequalifierrest=~s/\./\_/;
 7194: 	my $filename;
 7195: 	if (!$symbparm) { $symbparm=&symbread(); }
 7196: 	if ($symbparm) {
 7197: 	    $filename=(&decode_symb($symbparm))[2];
 7198: 	} else {
 7199: 	    $filename=$env{'request.filename'};
 7200: 	}
 7201: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7202: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7203: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7204: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7205: 
 7206: # ---------------------------------------------- fourth, look in rest of course
 7207: 	if ($symbparm && defined($courseid) && 
 7208: 	    $courseid eq $env{'request.course.id'}) {
 7209: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7210: 				     $env{'course.'.$courseid.'.domain'},
 7211: 				     'course',
 7212: 				     ([$courselevelm,'map'   ],
 7213: 				      [$courselevel, 'course']));
 7214: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7215: 	}
 7216: # ------------------------------------------------------------------ Cascade up
 7217: 	unless ($space eq '0') {
 7218: 	    my @parts=split(/_/,$space);
 7219: 	    my $id=pop(@parts);
 7220: 	    my $part=join('_',@parts);
 7221: 	    if ($part eq '') { $part='0'; }
 7222: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7223: 				 $symbparm,$udom,$uname,$section,1);
 7224: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7225: 	}
 7226: 	if ($recurse) { return undef; }
 7227: 	my $pack_def=&packages_tab_default($filename,$varname);
 7228: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7229: # ---------------------------------------------------- Any other user namespace
 7230:     } elsif ($realm eq 'environment') {
 7231: # ----------------------------------------------------------------- environment
 7232: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7233: 	    return $env{'environment.'.$spacequalifierrest};
 7234: 	} else {
 7235: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7236: 		return '';
 7237: 	    }
 7238: 	    my %returnhash=&userenvironment($udom,$uname,
 7239: 					    $spacequalifierrest);
 7240: 	    return $returnhash{$spacequalifierrest};
 7241: 	}
 7242:     } elsif ($realm eq 'system') {
 7243: # ----------------------------------------------------------------- system.time
 7244: 	if ($space eq 'time') {
 7245: 	    return time;
 7246:         }
 7247:     } elsif ($realm eq 'server') {
 7248: # ----------------------------------------------------------------- system.time
 7249: 	if ($space eq 'name') {
 7250: 	    return $ENV{'SERVER_NAME'};
 7251:         }
 7252:     }
 7253:     return '';
 7254: }
 7255: 
 7256: sub get_reply {
 7257:     my ($reply_value) = @_;
 7258:     if (ref($reply_value) eq 'ARRAY') {
 7259:         if (wantarray) {
 7260: 	    return @$reply_value;
 7261:         }
 7262:         return $reply_value->[0];
 7263:     } else {
 7264:         return $reply_value;
 7265:     }
 7266: }
 7267: 
 7268: sub check_group_parms {
 7269:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7270:     my @groupitems = ();
 7271:     my $resultitem;
 7272:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7273:     foreach my $group (@{$groups}) {
 7274:         foreach my $level (@levels) {
 7275:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7276:              push(@groupitems,[$item,$level->[1]]);
 7277:         }
 7278:     }
 7279:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7280:                             $env{'course.'.$courseid.'.domain'},
 7281:                                      'course',@groupitems);
 7282:     return $coursereply;
 7283: }
 7284: 
 7285: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7286:     my ($courseid,@groups) = @_;
 7287:     @groups = sort(@groups);
 7288:     return @groups;
 7289: }
 7290: 
 7291: sub packages_tab_default {
 7292:     my ($uri,$varname)=@_;
 7293:     my (undef,$part,$name)=split(/\./,$varname);
 7294: 
 7295:     my (@extension,@specifics,$do_default);
 7296:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7297: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7298: 	if ($pack_type eq 'default') {
 7299: 	    $do_default=1;
 7300: 	} elsif ($pack_type eq 'extension') {
 7301: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7302: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7303: 	    # only look at packages defaults for packages that this id is
 7304: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7305: 	}
 7306:     }
 7307:     # first look for a package that matches the requested part id
 7308:     foreach my $package (@specifics) {
 7309: 	my (undef,$pack_type,$pack_part)=@{$package};
 7310: 	next if ($pack_part ne $part);
 7311: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7312: 	    return $packagetab{"$pack_type&$name&default"};
 7313: 	}
 7314:     }
 7315:     # look for any possible matching non extension_ package
 7316:     foreach my $package (@specifics) {
 7317: 	my (undef,$pack_type,$pack_part)=@{$package};
 7318: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7319: 	    return $packagetab{"$pack_type&$name&default"};
 7320: 	}
 7321: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7322: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7323: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7324: 	}
 7325:     }
 7326:     # look for any posible extension_ match
 7327:     foreach my $package (@extension) {
 7328: 	my ($package,$pack_type)=@{$package};
 7329: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7330: 	    return $packagetab{"$pack_type&$name&default"};
 7331: 	}
 7332: 	if (defined($packagetab{$package."&$name&default"})) {
 7333: 	    return $packagetab{$package."&$name&default"};
 7334: 	}
 7335:     }
 7336:     # look for a global default setting
 7337:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7338: 	return $packagetab{"default&$name&default"};
 7339:     }
 7340:     return undef;
 7341: }
 7342: 
 7343: sub add_prefix_and_part {
 7344:     my ($prefix,$part)=@_;
 7345:     my $keyroot;
 7346:     if (defined($prefix) && $prefix !~ /^__/) {
 7347: 	# prefix that has a part already
 7348: 	$keyroot=$prefix;
 7349:     } elsif (defined($prefix)) {
 7350: 	# prefix that is missing a part
 7351: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7352:     } else {
 7353: 	# no prefix at all
 7354: 	if (defined($part)) { $keyroot='_'.$part; }
 7355:     }
 7356:     return $keyroot;
 7357: }
 7358: 
 7359: # ---------------------------------------------------------------- Get metadata
 7360: 
 7361: my %metaentry;
 7362: sub metadata {
 7363:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7364:     $uri=&declutter($uri);
 7365:     # if it is a non metadata possible uri return quickly
 7366:     if (($uri eq '') || 
 7367: 	(($uri =~ m|^/*adm/|) && 
 7368: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7369:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7370: 	return undef;
 7371:     }
 7372:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7373: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7374: 	return undef;
 7375:     }
 7376:     my $filename=$uri;
 7377:     $uri=~s/\.meta$//;
 7378: #
 7379: # Is the metadata already cached?
 7380: # Look at timestamp of caching
 7381: # Everything is cached by the main uri, libraries are never directly cached
 7382: #
 7383:     if (!defined($liburi)) {
 7384: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7385: 	if (defined($cached)) { return $result->{':'.$what}; }
 7386:     }
 7387:     {
 7388: #
 7389: # Is this a recursive call for a library?
 7390: #
 7391: #	if (! exists($metacache{$uri})) {
 7392: #	    $metacache{$uri}={};
 7393: #	}
 7394: 	my $cachetime = 60*60;
 7395:         if ($liburi) {
 7396: 	    $liburi=&declutter($liburi);
 7397:             $filename=$liburi;
 7398:         } else {
 7399: 	    &devalidate_cache_new('meta',$uri);
 7400: 	    undef(%metaentry);
 7401: 	}
 7402:         my %metathesekeys=();
 7403:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7404: 	my $metastring;
 7405: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7406: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7407: 	    $metastring = 
 7408: 		&Apache::lonnet::ssi_body($which,
 7409: 					  ('grade_target' => 'meta'));
 7410: 	    $cachetime = 1; # only want this cached in the child not long term
 7411: 	} elsif ($uri !~ m -^(editupload)/-) {
 7412: 	    my $file=&filelocation('',&clutter($filename));
 7413: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7414: 	    $metastring=&getfile($file);
 7415: 	}
 7416:         my $parser=HTML::LCParser->new(\$metastring);
 7417:         my $token;
 7418:         undef %metathesekeys;
 7419:         while ($token=$parser->get_token) {
 7420: 	    if ($token->[0] eq 'S') {
 7421: 		if (defined($token->[2]->{'package'})) {
 7422: #
 7423: # This is a package - get package info
 7424: #
 7425: 		    my $package=$token->[2]->{'package'};
 7426: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7427: 		    if (defined($token->[2]->{'id'})) { 
 7428: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7429: 		    }
 7430: 		    if ($metaentry{':packages'}) {
 7431: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7432: 		    } else {
 7433: 			$metaentry{':packages'}=$package.$keyroot;
 7434: 		    }
 7435: 		    foreach my $pack_entry (keys(%packagetab)) {
 7436: 			my $part=$keyroot;
 7437: 			$part=~s/^\_//;
 7438: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7439: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7440: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7441: 			    # ignore package.tab specified default values
 7442:                             # here &package_tab_default() will fetch those
 7443: 			    if ($subp eq 'default') { next; }
 7444: 			    my $value=$packagetab{$pack_entry};
 7445: 			    my $unikey;
 7446: 			    if ($pack =~ /_0$/) {
 7447: 				$unikey='parameter_0_'.$name;
 7448: 				$part=0;
 7449: 			    } else {
 7450: 				$unikey='parameter'.$keyroot.'_'.$name;
 7451: 			    }
 7452: 			    if ($subp eq 'display') {
 7453: 				$value.=' [Part: '.$part.']';
 7454: 			    }
 7455: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7456: 			    $metathesekeys{$unikey}=1;
 7457: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7458: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7459: 			    }
 7460: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7461: 				$metaentry{':'.$unikey}=
 7462: 				    $metaentry{':'.$unikey.'.default'};
 7463: 			    }
 7464: 			}
 7465: 		    }
 7466: 		} else {
 7467: #
 7468: # This is not a package - some other kind of start tag
 7469: #
 7470: 		    my $entry=$token->[1];
 7471: 		    my $unikey;
 7472: 		    if ($entry eq 'import') {
 7473: 			$unikey='';
 7474: 		    } else {
 7475: 			$unikey=$entry;
 7476: 		    }
 7477: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7478: 
 7479: 		    if (defined($token->[2]->{'id'})) { 
 7480: 			$unikey.='_'.$token->[2]->{'id'}; 
 7481: 		    }
 7482: 
 7483: 		    if ($entry eq 'import') {
 7484: #
 7485: # Importing a library here
 7486: #
 7487: 			if ($depthcount<20) {
 7488: 			    my $location=$parser->get_text('/import');
 7489: 			    my $dir=$filename;
 7490: 			    $dir=~s|[^/]*$||;
 7491: 			    $location=&filelocation($dir,$location);
 7492: 			    my $metadata = 
 7493: 				&metadata($uri,'keys', $location,$unikey,
 7494: 					  $depthcount+1);
 7495: 			    foreach my $meta (split(',',$metadata)) {
 7496: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7497: 				$metathesekeys{$meta}=1;
 7498: 			    }
 7499: 			}
 7500: 		    } else { 
 7501: 			
 7502: 			if (defined($token->[2]->{'name'})) { 
 7503: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7504: 			}
 7505: 			$metathesekeys{$unikey}=1;
 7506: 			foreach my $param (@{$token->[3]}) {
 7507: 			    $metaentry{':'.$unikey.'.'.$param} =
 7508: 				$token->[2]->{$param};
 7509: 			}
 7510: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7511: 			my $default=$metaentry{':'.$unikey.'.default'};
 7512: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7513: 		 # only ws inside the tag, and not in default, so use default
 7514: 		 # as value
 7515: 			    $metaentry{':'.$unikey}=$default;
 7516: 			} elsif ( $internaltext =~ /\S/ ) {
 7517: 		  # something interesting inside the tag
 7518: 			    $metaentry{':'.$unikey}=$internaltext;
 7519: 			} else {
 7520: 		  # no interesting values, don't set a default
 7521: 			}
 7522: # end of not-a-package not-a-library import
 7523: 		    }
 7524: # end of not-a-package start tag
 7525: 		}
 7526: # the next is the end of "start tag"
 7527: 	    }
 7528: 	}
 7529: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7530: 	$extension = lc($extension);
 7531: 	if ($extension eq 'htm') { $extension='html'; }
 7532: 
 7533: 	foreach my $key (keys(%packagetab)) {
 7534: 	    #no specific packages #how's our extension
 7535: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7536: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7537: 					 \%metathesekeys);
 7538: 	}
 7539: 
 7540: 	if (!exists($metaentry{':packages'})
 7541: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7542: 	    foreach my $key (keys(%packagetab)) {
 7543: 		#no specific packages well let's get default then
 7544: 		if ($key!~/^default&/) { next; }
 7545: 		&metadata_create_package_def($uri,$key,'default',
 7546: 					     \%metathesekeys);
 7547: 	    }
 7548: 	}
 7549: # are there custom rights to evaluate
 7550: 	if ($metaentry{':copyright'} eq 'custom') {
 7551: 
 7552:     #
 7553:     # Importing a rights file here
 7554:     #
 7555: 	    unless ($depthcount) {
 7556: 		my $location=$metaentry{':customdistributionfile'};
 7557: 		my $dir=$filename;
 7558: 		$dir=~s|[^/]*$||;
 7559: 		$location=&filelocation($dir,$location);
 7560: 		my $rights_metadata =
 7561: 		    &metadata($uri,'keys',$location,'_rights',
 7562: 			      $depthcount+1);
 7563: 		foreach my $rights (split(',',$rights_metadata)) {
 7564: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7565: 		    $metathesekeys{$rights}=1;
 7566: 		}
 7567: 	    }
 7568: 	}
 7569: 	# uniqifiy package listing
 7570: 	my %seen;
 7571: 	my @uniq_packages =
 7572: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7573: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7574: 
 7575: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7576: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7577: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7578: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7579: # this is the end of "was not already recently cached
 7580:     }
 7581:     return $metaentry{':'.$what};
 7582: }
 7583: 
 7584: sub metadata_create_package_def {
 7585:     my ($uri,$key,$package,$metathesekeys)=@_;
 7586:     my ($pack,$name,$subp)=split(/\&/,$key);
 7587:     if ($subp eq 'default') { next; }
 7588:     
 7589:     if (defined($metaentry{':packages'})) {
 7590: 	$metaentry{':packages'}.=','.$package;
 7591:     } else {
 7592: 	$metaentry{':packages'}=$package;
 7593:     }
 7594:     my $value=$packagetab{$key};
 7595:     my $unikey;
 7596:     $unikey='parameter_0_'.$name;
 7597:     $metaentry{':'.$unikey.'.part'}=0;
 7598:     $$metathesekeys{$unikey}=1;
 7599:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7600: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7601:     }
 7602:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7603: 	$metaentry{':'.$unikey}=
 7604: 	    $metaentry{':'.$unikey.'.default'};
 7605:     }
 7606: }
 7607: 
 7608: sub metadata_generate_part0 {
 7609:     my ($metadata,$metacache,$uri) = @_;
 7610:     my %allnames;
 7611:     foreach my $metakey (keys(%$metadata)) {
 7612: 	if ($metakey=~/^parameter\_(.*)/) {
 7613: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7614: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7615: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7616: 	    $allnames{$name}=$part;
 7617: 	  }
 7618: 	}
 7619:     }
 7620:     foreach my $name (keys(%allnames)) {
 7621:       $$metadata{"parameter_0_$name"}=1;
 7622:       my $key=":parameter_0_$name";
 7623:       $$metacache{"$key.part"}='0';
 7624:       $$metacache{"$key.name"}=$name;
 7625:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7626: 					   $allnames{$name}.'_'.$name.
 7627: 					   '.type'};
 7628:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7629: 			     '.display'};
 7630:       my $expr='[Part: '.$allnames{$name}.']';
 7631:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7632:       $$metacache{"$key.display"}=$olddis;
 7633:     }
 7634: }
 7635: 
 7636: # ------------------------------------------------------ Devalidate title cache
 7637: 
 7638: sub devalidate_title_cache {
 7639:     my ($url)=@_;
 7640:     if (!$env{'request.course.id'}) { return; }
 7641:     my $symb=&symbread($url);
 7642:     if (!$symb) { return; }
 7643:     my $key=$env{'request.course.id'}."\0".$symb;
 7644:     &devalidate_cache_new('title',$key);
 7645: }
 7646: 
 7647: # ------------------------------------------------- Get the title of a resource
 7648: 
 7649: sub gettitle {
 7650:     my $urlsymb=shift;
 7651:     my $symb=&symbread($urlsymb);
 7652:     if ($symb) {
 7653: 	my $key=$env{'request.course.id'}."\0".$symb;
 7654: 	my ($result,$cached)=&is_cached_new('title',$key);
 7655: 	if (defined($cached)) { 
 7656: 	    return $result;
 7657: 	}
 7658: 	my ($map,$resid,$url)=&decode_symb($symb);
 7659: 	my $title='';
 7660: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7661: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7662: 	} else {
 7663: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7664: 		    &GDBM_READER(),0640)) {
 7665: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7666: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7667: 		untie(%bighash);
 7668: 	    }
 7669: 	}
 7670: 	$title=~s/\&colon\;/\:/gs;
 7671: 	if ($title) {
 7672: 	    return &do_cache_new('title',$key,$title,600);
 7673: 	}
 7674: 	$urlsymb=$url;
 7675:     }
 7676:     my $title=&metadata($urlsymb,'title');
 7677:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7678:     return $title;
 7679: }
 7680: 
 7681: sub get_slot {
 7682:     my ($which,$cnum,$cdom)=@_;
 7683:     if (!$cnum || !$cdom) {
 7684: 	(undef,my $courseid)=&whichuser();
 7685: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7686: 	$cnum=$env{'course.'.$courseid.'.num'};
 7687:     }
 7688:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7689:     my %slotinfo;
 7690:     if (exists($remembered{$key})) {
 7691: 	$slotinfo{$which} = $remembered{$key};
 7692:     } else {
 7693: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7694: 	&Apache::lonhomework::showhash(%slotinfo);
 7695: 	my ($tmp)=keys(%slotinfo);
 7696: 	if ($tmp=~/^error:/) { return (); }
 7697: 	$remembered{$key} = $slotinfo{$which};
 7698:     }
 7699:     if (ref($slotinfo{$which}) eq 'HASH') {
 7700: 	return %{$slotinfo{$which}};
 7701:     }
 7702:     return $slotinfo{$which};
 7703: }
 7704: # ------------------------------------------------- Update symbolic store links
 7705: 
 7706: sub symblist {
 7707:     my ($mapname,%newhash)=@_;
 7708:     $mapname=&deversion(&declutter($mapname));
 7709:     my %hash;
 7710:     if (($env{'request.course.fn'}) && (%newhash)) {
 7711:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7712:                       &GDBM_WRCREAT(),0640)) {
 7713: 	    foreach my $url (keys %newhash) {
 7714: 		next if ($url eq 'last_known'
 7715: 			 && $env{'form.no_update_last_known'});
 7716: 		$hash{declutter($url)}=&encode_symb($mapname,
 7717: 						    $newhash{$url}->[1],
 7718: 						    $newhash{$url}->[0]);
 7719:             }
 7720:             if (untie(%hash)) {
 7721: 		return 'ok';
 7722:             }
 7723:         }
 7724:     }
 7725:     return 'error';
 7726: }
 7727: 
 7728: # --------------------------------------------------------------- Verify a symb
 7729: 
 7730: sub symbverify {
 7731:     my ($symb,$thisurl)=@_;
 7732:     my $thisfn=$thisurl;
 7733:     $thisfn=&declutter($thisfn);
 7734: # direct jump to resource in page or to a sequence - will construct own symbs
 7735:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7736: # check URL part
 7737:     my ($map,$resid,$url)=&decode_symb($symb);
 7738: 
 7739:     unless ($url eq $thisfn) { return 0; }
 7740: 
 7741:     $symb=&symbclean($symb);
 7742:     $thisurl=&deversion($thisurl);
 7743:     $thisfn=&deversion($thisfn);
 7744: 
 7745:     my %bighash;
 7746:     my $okay=0;
 7747: 
 7748:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7749:                             &GDBM_READER(),0640)) {
 7750:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7751:         unless ($ids) { 
 7752:            $ids=$bighash{'ids_/'.$thisurl};
 7753:         }
 7754:         if ($ids) {
 7755: # ------------------------------------------------------------------- Has ID(s)
 7756: 	    foreach my $id (split(/\,/,$ids)) {
 7757: 	       my ($mapid,$resid)=split(/\./,$id);
 7758:                if (
 7759:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7760:    eq $symb) { 
 7761: 		   if (($env{'request.role.adv'}) ||
 7762: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7763: 		       $okay=1; 
 7764: 		   }
 7765: 	       }
 7766: 	   }
 7767:         }
 7768: 	untie(%bighash);
 7769:     }
 7770:     return $okay;
 7771: }
 7772: 
 7773: # --------------------------------------------------------------- Clean-up symb
 7774: 
 7775: sub symbclean {
 7776:     my $symb=shift;
 7777:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7778: # remove version from map
 7779:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7780: 
 7781: # remove version from URL
 7782:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7783: 
 7784: # remove wrapper
 7785: 
 7786:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7787:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7788:     return $symb;
 7789: }
 7790: 
 7791: # ---------------------------------------------- Split symb to find map and url
 7792: 
 7793: sub encode_symb {
 7794:     my ($map,$resid,$url)=@_;
 7795:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7796: }
 7797: 
 7798: sub decode_symb {
 7799:     my $symb=shift;
 7800:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7801:     my ($map,$resid,$url)=split(/___/,$symb);
 7802:     return (&fixversion($map),$resid,&fixversion($url));
 7803: }
 7804: 
 7805: sub fixversion {
 7806:     my $fn=shift;
 7807:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7808:     my %bighash;
 7809:     my $uri=&clutter($fn);
 7810:     my $key=$env{'request.course.id'}.'_'.$uri;
 7811: # is this cached?
 7812:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7813:     if (defined($cached)) { return $result; }
 7814: # unfortunately not cached, or expired
 7815:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7816: 	    &GDBM_READER(),0640)) {
 7817:  	if ($bighash{'version_'.$uri}) {
 7818:  	    my $version=$bighash{'version_'.$uri};
 7819:  	    unless (($version eq 'mostrecent') || 
 7820: 		    ($version==&getversion($uri))) {
 7821:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7822:  	    }
 7823:  	}
 7824:  	untie %bighash;
 7825:     }
 7826:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7827: }
 7828: 
 7829: sub deversion {
 7830:     my $url=shift;
 7831:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7832:     return $url;
 7833: }
 7834: 
 7835: # ------------------------------------------------------ Return symb list entry
 7836: 
 7837: sub symbread {
 7838:     my ($thisfn,$donotrecurse)=@_;
 7839:     my $cache_str='request.symbread.cached.'.$thisfn;
 7840:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7841: # no filename provided? try from environment
 7842:     unless ($thisfn) {
 7843:         if ($env{'request.symb'}) {
 7844: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7845: 	}
 7846: 	$thisfn=$env{'request.filename'};
 7847:     }
 7848:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7849: # is that filename actually a symb? Verify, clean, and return
 7850:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7851: 	if (&symbverify($thisfn,$1)) {
 7852: 	    return $env{$cache_str}=&symbclean($thisfn);
 7853: 	}
 7854:     }
 7855:     $thisfn=declutter($thisfn);
 7856:     my %hash;
 7857:     my %bighash;
 7858:     my $syval='';
 7859:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7860:         my $targetfn = $thisfn;
 7861:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7862:             $targetfn = 'adm/wrapper/'.$thisfn;
 7863:         }
 7864: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7865: 	    $targetfn=$1;
 7866: 	}
 7867:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7868:                       &GDBM_READER(),0640)) {
 7869: 	    $syval=$hash{$targetfn};
 7870:             untie(%hash);
 7871:         }
 7872: # ---------------------------------------------------------- There was an entry
 7873:         if ($syval) {
 7874: 	    #unless ($syval=~/\_\d+$/) {
 7875: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7876: 		    #&appenv({'request.ambiguous' => $thisfn});
 7877: 		    #return $env{$cache_str}='';
 7878: 		#}    
 7879: 		#$syval.=$1;
 7880: 	    #}
 7881:         } else {
 7882: # ------------------------------------------------------- Was not in symb table
 7883:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7884:                             &GDBM_READER(),0640)) {
 7885: # ---------------------------------------------- Get ID(s) for current resource
 7886:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7887:               unless ($ids) { 
 7888:                  $ids=$bighash{'ids_/'.$thisfn};
 7889:               }
 7890:               unless ($ids) {
 7891: # alias?
 7892: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7893:               }
 7894:               if ($ids) {
 7895: # ------------------------------------------------------------------- Has ID(s)
 7896:                  my @possibilities=split(/\,/,$ids);
 7897:                  if ($#possibilities==0) {
 7898: # ----------------------------------------------- There is only one possibility
 7899: 		     my ($mapid,$resid)=split(/\./,$ids);
 7900: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7901: 						    $resid,$thisfn);
 7902:                  } elsif (!$donotrecurse) {
 7903: # ------------------------------------------ There is more than one possibility
 7904:                      my $realpossible=0;
 7905:                      foreach my $id (@possibilities) {
 7906: 			 my $file=$bighash{'src_'.$id};
 7907:                          if (&allowed('bre',$file)) {
 7908:          		    my ($mapid,$resid)=split(/\./,$id);
 7909:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7910: 				$realpossible++;
 7911:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7912: 						    $resid,$thisfn);
 7913:                             }
 7914: 			 }
 7915:                      }
 7916: 		     if ($realpossible!=1) { $syval=''; }
 7917:                  } else {
 7918:                      $syval='';
 7919:                  }
 7920: 	      }
 7921:               untie(%bighash)
 7922:            }
 7923:         }
 7924:         if ($syval) {
 7925: 	    return $env{$cache_str}=$syval;
 7926:         }
 7927:     }
 7928:     &appenv({'request.ambiguous' => $thisfn});
 7929:     return $env{$cache_str}='';
 7930: }
 7931: 
 7932: # ---------------------------------------------------------- Return random seed
 7933: 
 7934: sub numval {
 7935:     my $txt=shift;
 7936:     $txt=~tr/A-J/0-9/;
 7937:     $txt=~tr/a-j/0-9/;
 7938:     $txt=~tr/K-T/0-9/;
 7939:     $txt=~tr/k-t/0-9/;
 7940:     $txt=~tr/U-Z/0-5/;
 7941:     $txt=~tr/u-z/0-5/;
 7942:     $txt=~s/\D//g;
 7943:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7944:     return int($txt);
 7945: }
 7946: 
 7947: sub numval2 {
 7948:     my $txt=shift;
 7949:     $txt=~tr/A-J/0-9/;
 7950:     $txt=~tr/a-j/0-9/;
 7951:     $txt=~tr/K-T/0-9/;
 7952:     $txt=~tr/k-t/0-9/;
 7953:     $txt=~tr/U-Z/0-5/;
 7954:     $txt=~tr/u-z/0-5/;
 7955:     $txt=~s/\D//g;
 7956:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7957:     my $total;
 7958:     foreach my $val (@txts) { $total+=$val; }
 7959:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7960:     return int($total);
 7961: }
 7962: 
 7963: sub numval3 {
 7964:     use integer;
 7965:     my $txt=shift;
 7966:     $txt=~tr/A-J/0-9/;
 7967:     $txt=~tr/a-j/0-9/;
 7968:     $txt=~tr/K-T/0-9/;
 7969:     $txt=~tr/k-t/0-9/;
 7970:     $txt=~tr/U-Z/0-5/;
 7971:     $txt=~tr/u-z/0-5/;
 7972:     $txt=~s/\D//g;
 7973:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7974:     my $total;
 7975:     foreach my $val (@txts) { $total+=$val; }
 7976:     if ($_64bit) { $total=(($total<<32)>>32); }
 7977:     return $total;
 7978: }
 7979: 
 7980: sub digest {
 7981:     my ($data)=@_;
 7982:     my $digest=&Digest::MD5::md5($data);
 7983:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7984:     my ($e,$f);
 7985:     {
 7986:         use integer;
 7987:         $e=($a+$b);
 7988:         $f=($c+$d);
 7989:         if ($_64bit) {
 7990:             $e=(($e<<32)>>32);
 7991:             $f=(($f<<32)>>32);
 7992:         }
 7993:     }
 7994:     if (wantarray) {
 7995: 	return ($e,$f);
 7996:     } else {
 7997: 	my $g;
 7998: 	{
 7999: 	    use integer;
 8000: 	    $g=($e+$f);
 8001: 	    if ($_64bit) {
 8002: 		$g=(($g<<32)>>32);
 8003: 	    }
 8004: 	}
 8005: 	return $g;
 8006:     }
 8007: }
 8008: 
 8009: sub latest_rnd_algorithm_id {
 8010:     return '64bit5';
 8011: }
 8012: 
 8013: sub get_rand_alg {
 8014:     my ($courseid)=@_;
 8015:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8016:     if ($courseid) {
 8017: 	return $env{"course.$courseid.rndseed"};
 8018:     }
 8019:     return &latest_rnd_algorithm_id();
 8020: }
 8021: 
 8022: sub validCODE {
 8023:     my ($CODE)=@_;
 8024:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8025:     return 0;
 8026: }
 8027: 
 8028: sub getCODE {
 8029:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8030:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8031: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8032: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8033: 	return $Apache::lonhomework::history{'resource.CODE'};
 8034:     }
 8035:     return undef;
 8036: }
 8037: 
 8038: sub rndseed {
 8039:     my ($symb,$courseid,$domain,$username)=@_;
 8040:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8041:     if (!defined($symb)) {
 8042: 	unless ($symb=$wsymb) { return time; }
 8043:     }
 8044:     if (!$courseid) { $courseid=$wcourseid; }
 8045:     if (!$domain) { $domain=$wdomain; }
 8046:     if (!$username) { $username=$wusername }
 8047:     my $which=&get_rand_alg();
 8048: 
 8049:     if (defined(&getCODE())) {
 8050: 	if ($which eq '64bit5') {
 8051: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8052: 	} elsif ($which eq '64bit4') {
 8053: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8054: 	} else {
 8055: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8056: 	}
 8057:     } elsif ($which eq '64bit5') {
 8058: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8059:     } elsif ($which eq '64bit4') {
 8060: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8061:     } elsif ($which eq '64bit3') {
 8062: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8063:     } elsif ($which eq '64bit2') {
 8064: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8065:     } elsif ($which eq '64bit') {
 8066: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8067:     }
 8068:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8069: }
 8070: 
 8071: sub rndseed_32bit {
 8072:     my ($symb,$courseid,$domain,$username)=@_;
 8073:     {
 8074: 	use integer;
 8075: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8076: 	my $symbseed=numval($symb) << 22;
 8077: 	my $namechck=unpack("%32C*",$username) << 17;
 8078: 	my $nameseed=numval($username) << 12;
 8079: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8080: 	my $courseseed=unpack("%32C*",$courseid);
 8081: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8082: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8083: 	#&logthis("rndseed :$num:$symb");
 8084: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8085: 	return $num;
 8086:     }
 8087: }
 8088: 
 8089: sub rndseed_64bit {
 8090:     my ($symb,$courseid,$domain,$username)=@_;
 8091:     {
 8092: 	use integer;
 8093: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8094: 	my $symbseed=numval($symb) << 10;
 8095: 	my $namechck=unpack("%32S*",$username);
 8096: 	
 8097: 	my $nameseed=numval($username) << 21;
 8098: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8099: 	my $courseseed=unpack("%32S*",$courseid);
 8100: 	
 8101: 	my $num1=$symbchck+$symbseed+$namechck;
 8102: 	my $num2=$nameseed+$domainseed+$courseseed;
 8103: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8104: 	#&logthis("rndseed :$num:$symb");
 8105: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8106: 	return "$num1,$num2";
 8107:     }
 8108: }
 8109: 
 8110: sub rndseed_64bit2 {
 8111:     my ($symb,$courseid,$domain,$username)=@_;
 8112:     {
 8113: 	use integer;
 8114: 	# strings need to be an even # of cahracters long, it it is odd the
 8115:         # last characters gets thrown away
 8116: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8117: 	my $symbseed=numval($symb) << 10;
 8118: 	my $namechck=unpack("%32S*",$username.' ');
 8119: 	
 8120: 	my $nameseed=numval($username) << 21;
 8121: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8122: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8123: 	
 8124: 	my $num1=$symbchck+$symbseed+$namechck;
 8125: 	my $num2=$nameseed+$domainseed+$courseseed;
 8126: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8127: 	#&logthis("rndseed :$num:$symb");
 8128: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8129: 	return "$num1,$num2";
 8130:     }
 8131: }
 8132: 
 8133: sub rndseed_64bit3 {
 8134:     my ($symb,$courseid,$domain,$username)=@_;
 8135:     {
 8136: 	use integer;
 8137: 	# strings need to be an even # of cahracters long, it it is odd the
 8138:         # last characters gets thrown away
 8139: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8140: 	my $symbseed=numval2($symb) << 10;
 8141: 	my $namechck=unpack("%32S*",$username.' ');
 8142: 	
 8143: 	my $nameseed=numval2($username) << 21;
 8144: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8145: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8146: 	
 8147: 	my $num1=$symbchck+$symbseed+$namechck;
 8148: 	my $num2=$nameseed+$domainseed+$courseseed;
 8149: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8150: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8151: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8152: 	
 8153: 	return "$num1:$num2";
 8154:     }
 8155: }
 8156: 
 8157: sub rndseed_64bit4 {
 8158:     my ($symb,$courseid,$domain,$username)=@_;
 8159:     {
 8160: 	use integer;
 8161: 	# strings need to be an even # of cahracters long, it it is odd the
 8162:         # last characters gets thrown away
 8163: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8164: 	my $symbseed=numval3($symb) << 10;
 8165: 	my $namechck=unpack("%32S*",$username.' ');
 8166: 	
 8167: 	my $nameseed=numval3($username) << 21;
 8168: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8169: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8170: 	
 8171: 	my $num1=$symbchck+$symbseed+$namechck;
 8172: 	my $num2=$nameseed+$domainseed+$courseseed;
 8173: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8174: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8175: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8176: 	
 8177: 	return "$num1:$num2";
 8178:     }
 8179: }
 8180: 
 8181: sub rndseed_64bit5 {
 8182:     my ($symb,$courseid,$domain,$username)=@_;
 8183:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8184:     return "$num1:$num2";
 8185: }
 8186: 
 8187: sub rndseed_CODE_64bit {
 8188:     my ($symb,$courseid,$domain,$username)=@_;
 8189:     {
 8190: 	use integer;
 8191: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8192: 	my $symbseed=numval2($symb);
 8193: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8194: 	my $CODEseed=numval(&getCODE());
 8195: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8196: 	my $num1=$symbseed+$CODEchck;
 8197: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8198: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8199: 	#&logthis("rndseed :$num1:$num2:$symb");
 8200: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8201: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8202: 	return "$num1:$num2";
 8203:     }
 8204: }
 8205: 
 8206: sub rndseed_CODE_64bit4 {
 8207:     my ($symb,$courseid,$domain,$username)=@_;
 8208:     {
 8209: 	use integer;
 8210: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8211: 	my $symbseed=numval3($symb);
 8212: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8213: 	my $CODEseed=numval3(&getCODE());
 8214: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8215: 	my $num1=$symbseed+$CODEchck;
 8216: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8217: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8218: 	#&logthis("rndseed :$num1:$num2:$symb");
 8219: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8220: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8221: 	return "$num1:$num2";
 8222:     }
 8223: }
 8224: 
 8225: sub rndseed_CODE_64bit5 {
 8226:     my ($symb,$courseid,$domain,$username)=@_;
 8227:     my $code = &getCODE();
 8228:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8229:     return "$num1:$num2";
 8230: }
 8231: 
 8232: sub setup_random_from_rndseed {
 8233:     my ($rndseed)=@_;
 8234:     if ($rndseed =~/([,:])/) {
 8235: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8236: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8237:     } else {
 8238: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8239:     }
 8240: }
 8241: 
 8242: sub latest_receipt_algorithm_id {
 8243:     return 'receipt3';
 8244: }
 8245: 
 8246: sub recunique {
 8247:     my $fucourseid=shift;
 8248:     my $unique;
 8249:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8250: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8251: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8252:     } else {
 8253: 	$unique=$perlvar{'lonReceipt'};
 8254:     }
 8255:     return unpack("%32C*",$unique);
 8256: }
 8257: 
 8258: sub recprefix {
 8259:     my $fucourseid=shift;
 8260:     my $prefix;
 8261:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8262: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8263: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8264:     } else {
 8265: 	$prefix=$perlvar{'lonHostID'};
 8266:     }
 8267:     return unpack("%32C*",$prefix);
 8268: }
 8269: 
 8270: sub ireceipt {
 8271:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8272: 
 8273:     my $return =&recprefix($fucourseid).'-';
 8274: 
 8275:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8276: 	$env{'request.state'} eq 'construct') {
 8277: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8278: 	return $return;
 8279:     }
 8280: 
 8281:     my $cuname=unpack("%32C*",$funame);
 8282:     my $cudom=unpack("%32C*",$fudom);
 8283:     my $cucourseid=unpack("%32C*",$fucourseid);
 8284:     my $cusymb=unpack("%32C*",$fusymb);
 8285:     my $cunique=&recunique($fucourseid);
 8286:     my $cpart=unpack("%32S*",$part);
 8287:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8288: 
 8289: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8290: 			       
 8291: 	$return.= ($cunique%$cuname+
 8292: 		   $cunique%$cudom+
 8293: 		   $cusymb%$cuname+
 8294: 		   $cusymb%$cudom+
 8295: 		   $cucourseid%$cuname+
 8296: 		   $cucourseid%$cudom+
 8297: 		   $cpart%$cuname+
 8298: 		   $cpart%$cudom);
 8299:     } else {
 8300: 	$return.= ($cunique%$cuname+
 8301: 		   $cunique%$cudom+
 8302: 		   $cusymb%$cuname+
 8303: 		   $cusymb%$cudom+
 8304: 		   $cucourseid%$cuname+
 8305: 		   $cucourseid%$cudom);
 8306:     }
 8307:     return $return;
 8308: }
 8309: 
 8310: sub receipt {
 8311:     my ($part)=@_;
 8312:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8313:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8314: }
 8315: 
 8316: sub whichuser {
 8317:     my ($passedsymb)=@_;
 8318:     my ($symb,$courseid,$domain,$name,$publicuser);
 8319:     if (defined($env{'form.grade_symb'})) {
 8320: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8321: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8322: 	if (!$allowed &&
 8323: 	    exists($env{'request.course.sec'}) &&
 8324: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8325: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8326: 			      '/'.$env{'request.course.sec'});
 8327: 	}
 8328: 	if ($allowed) {
 8329: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8330: 	    $courseid=$tmp_courseid;
 8331: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8332: 	    ($name)=&get_env_multiple('form.grade_username');
 8333: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8334: 	}
 8335:     }
 8336:     if (!$passedsymb) {
 8337: 	$symb=&symbread();
 8338:     } else {
 8339: 	$symb=$passedsymb;
 8340:     }
 8341:     $courseid=$env{'request.course.id'};
 8342:     $domain=$env{'user.domain'};
 8343:     $name=$env{'user.name'};
 8344:     if ($name eq 'public' && $domain eq 'public') {
 8345: 	if (!defined($env{'form.username'})) {
 8346: 	    $env{'form.username'}.=time.rand(10000000);
 8347: 	}
 8348: 	$name.=$env{'form.username'};
 8349:     }
 8350:     return ($symb,$courseid,$domain,$name,$publicuser);
 8351: 
 8352: }
 8353: 
 8354: # ------------------------------------------------------------ Serves up a file
 8355: # returns either the contents of the file or 
 8356: # -1 if the file doesn't exist
 8357: #
 8358: # if the target is a file that was uploaded via DOCS, 
 8359: # a check will be made to see if a current copy exists on the local server,
 8360: # if it does this will be served, otherwise a copy will be retrieved from
 8361: # the home server for the course and stored in /home/httpd/html/userfiles on
 8362: # the local server.   
 8363: 
 8364: sub getfile {
 8365:     my ($file) = @_;
 8366:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8367:     &repcopy($file);
 8368:     return &readfile($file);
 8369: }
 8370: 
 8371: sub repcopy_userfile {
 8372:     my ($file)=@_;
 8373:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8374:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8375:     my ($cdom,$cnum,$filename) = 
 8376: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8377:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8378:     if (-e "$file") {
 8379: # we already have a local copy, check it out
 8380: 	my @fileinfo = stat($file);
 8381: 	my $rtncode;
 8382: 	my $info;
 8383: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8384: 	if ($lwpresp ne 'ok') {
 8385: # there is no such file anymore, even though we had a local copy
 8386: 	    if ($rtncode eq '404') {
 8387: 		unlink($file);
 8388: 	    }
 8389: 	    return -1;
 8390: 	}
 8391: 	if ($info < $fileinfo[9]) {
 8392: # nice, the file we have is up-to-date, just say okay
 8393: 	    return 'ok';
 8394: 	} else {
 8395: # the file is outdated, get rid of it
 8396: 	    unlink($file);
 8397: 	}
 8398:     }
 8399: # one way or the other, at this point, we don't have the file
 8400: # construct the correct path for the file
 8401:     my @parts = ($cdom,$cnum); 
 8402:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8403: 	push @parts, split(/\//,$1);
 8404:     }
 8405:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8406:     foreach my $part (@parts) {
 8407: 	$path .= '/'.$part;
 8408: 	if (!-e $path) {
 8409: 	    mkdir($path,0770);
 8410: 	}
 8411:     }
 8412: # now the path exists for sure
 8413: # get a user agent
 8414:     my $ua=new LWP::UserAgent;
 8415:     my $transferfile=$file.'.in.transfer';
 8416: # FIXME: this should flock
 8417:     if (-e $transferfile) { return 'ok'; }
 8418:     my $request;
 8419:     $uri=~s/^\///;
 8420:     my $homeserver = &homeserver($cnum,$cdom);
 8421:     my $protocol = $protocol{$homeserver};
 8422:     $protocol = 'http' if ($protocol ne 'https');
 8423:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8424:     my $response=$ua->request($request,$transferfile);
 8425: # did it work?
 8426:     if ($response->is_error()) {
 8427: 	unlink($transferfile);
 8428: 	&logthis("Userfile repcopy failed for $uri");
 8429: 	return -1;
 8430:     }
 8431: # worked, rename the transfer file
 8432:     rename($transferfile,$file);
 8433:     return 'ok';
 8434: }
 8435: 
 8436: sub tokenwrapper {
 8437:     my $uri=shift;
 8438:     $uri=~s|^https?\://([^/]+)||;
 8439:     $uri=~s|^/||;
 8440:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8441:     my $token=$1;
 8442:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8443:     if ($udom && $uname && $file) {
 8444: 	$file=~s|(\?\.*)*$||;
 8445:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8446:         my $homeserver = &homeserver($uname,$udom);
 8447:         my $protocol = $protocol{$homeserver};
 8448:         $protocol = 'http' if ($protocol ne 'https');
 8449:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8450:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8451:                                '&tokenissued='.$perlvar{'lonHostID'};
 8452:     } else {
 8453:         return '/adm/notfound.html';
 8454:     }
 8455: }
 8456: 
 8457: # call with reqtype HEAD: get last modification time
 8458: # call with reqtype GET: get the file contents
 8459: # Do not call this with reqtype GET for large files! It loads everything into memory
 8460: #
 8461: sub getuploaded {
 8462:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8463:     $uri=~s/^\///;
 8464:     my $homeserver = &homeserver($cnum,$cdom);
 8465:     my $protocol = $protocol{$homeserver};
 8466:     $protocol = 'http' if ($protocol ne 'https');
 8467:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8468:     my $ua=new LWP::UserAgent;
 8469:     my $request=new HTTP::Request($reqtype,$uri);
 8470:     my $response=$ua->request($request);
 8471:     $$rtncode = $response->code;
 8472:     if (! $response->is_success()) {
 8473: 	return 'failed';
 8474:     }      
 8475:     if ($reqtype eq 'HEAD') {
 8476: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8477:     } elsif ($reqtype eq 'GET') {
 8478: 	$$info = $response->content;
 8479:     }
 8480:     return 'ok';
 8481: }
 8482: 
 8483: sub readfile {
 8484:     my $file = shift;
 8485:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8486:     my $fh;
 8487:     open($fh,"<$file");
 8488:     my $a='';
 8489:     while (my $line = <$fh>) { $a .= $line; }
 8490:     return $a;
 8491: }
 8492: 
 8493: sub filelocation {
 8494:     my ($dir,$file) = @_;
 8495:     my $location;
 8496:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8497: 
 8498:     if ($file =~ m-^/adm/-) {
 8499: 	$file=~s-^/adm/wrapper/-/-;
 8500: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8501:     }
 8502: 
 8503:     if ($file=~m:^/~:) { # is a contruction space reference
 8504:         $location = $file;
 8505:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8506:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8507: 	# is a correct contruction space reference
 8508:         $location = $file;
 8509:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8510:         $location = $file;
 8511:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8512:         my ($udom,$uname,$filename)=
 8513:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8514:         my $home=&homeserver($uname,$udom);
 8515:         my $is_me=0;
 8516:         my @ids=&current_machine_ids();
 8517:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8518:         if ($is_me) {
 8519:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8520:         } else {
 8521:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8522:   	      $udom.'/'.$uname.'/'.$filename;
 8523:         }
 8524:     } elsif ($file =~ m-^/adm/-) {
 8525: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8526:     } else {
 8527:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8528:         $file=~s:^/res/:/:;
 8529:         if ( !( $file =~ m:^/:) ) {
 8530:             $location = $dir. '/'.$file;
 8531:         } else {
 8532:             $location = '/home/httpd/html/res'.$file;
 8533:         }
 8534:     }
 8535:     $location=~s://+:/:g; # remove duplicate /
 8536:     while ($location=~m{/\.\./}) {
 8537: 	if ($location =~ m{/[^/]+/\.\./}) {
 8538: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8539: 	} else {
 8540: 	    $location=~ s{/\.\./}{/}g;
 8541: 	}
 8542:     } #remove dir/..
 8543:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8544:     return $location;
 8545: }
 8546: 
 8547: sub hreflocation {
 8548:     my ($dir,$file)=@_;
 8549:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8550: 	$file=filelocation($dir,$file);
 8551:     } elsif ($file=~m-^/adm/-) {
 8552: 	$file=~s-^/adm/wrapper/-/-;
 8553: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8554:     }
 8555:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8556: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8557:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8558: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8559:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8560: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8561: 	    -/uploaded/$1/$2/-x;
 8562:     }
 8563:     if ($file=~ m{^/userfiles/}) {
 8564: 	$file =~ s{^/userfiles/}{/uploaded/};
 8565:     }
 8566:     return $file;
 8567: }
 8568: 
 8569: sub current_machine_domains {
 8570:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8571: }
 8572: 
 8573: sub machine_domains {
 8574:     my ($hostname) = @_;
 8575:     my @domains;
 8576:     my %hostname = &all_hostnames();
 8577:     while( my($id, $name) = each(%hostname)) {
 8578: #	&logthis("-$id-$name-$hostname-");
 8579: 	if ($hostname eq $name) {
 8580: 	    push(@domains,&host_domain($id));
 8581: 	}
 8582:     }
 8583:     return @domains;
 8584: }
 8585: 
 8586: sub current_machine_ids {
 8587:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8588: }
 8589: 
 8590: sub machine_ids {
 8591:     my ($hostname) = @_;
 8592:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8593:     my @ids;
 8594:     my %name_to_host = &all_names();
 8595:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8596: 	return @{ $name_to_host{$hostname} };
 8597:     }
 8598:     return;
 8599: }
 8600: 
 8601: sub additional_machine_domains {
 8602:     my @domains;
 8603:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8604:     while( my $line = <$fh>) {
 8605:         $line =~ s/\s//g;
 8606:         push(@domains,$line);
 8607:     }
 8608:     return @domains;
 8609: }
 8610: 
 8611: sub default_login_domain {
 8612:     my $domain = $perlvar{'lonDefDomain'};
 8613:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8614:     foreach my $posdom (&current_machine_domains(),
 8615:                         &additional_machine_domains()) {
 8616:         if (lc($posdom) eq lc($testdomain)) {
 8617:             $domain=$posdom;
 8618:             last;
 8619:         }
 8620:     }
 8621:     return $domain;
 8622: }
 8623: 
 8624: # ------------------------------------------------------------- Declutters URLs
 8625: 
 8626: sub declutter {
 8627:     my $thisfn=shift;
 8628:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8629:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8630:     $thisfn=~s/^\///;
 8631:     $thisfn=~s|^adm/wrapper/||;
 8632:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8633:     $thisfn=~s/^res\///;
 8634:     $thisfn=~s/\?.+$//;
 8635:     return $thisfn;
 8636: }
 8637: 
 8638: # ------------------------------------------------------------- Clutter up URLs
 8639: 
 8640: sub clutter {
 8641:     my $thisfn='/'.&declutter(shift);
 8642:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8643: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8644:        $thisfn='/res'.$thisfn; 
 8645:     }
 8646:     if ($thisfn !~m|/adm|) {
 8647: 	if ($thisfn =~ m|/ext/|) {
 8648: 	    $thisfn='/adm/wrapper'.$thisfn;
 8649: 	} else {
 8650: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8651: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8652: 	    if ($embstyle eq 'ssi'
 8653: 		|| ($embstyle eq 'hdn')
 8654: 		|| ($embstyle eq 'rat')
 8655: 		|| ($embstyle eq 'prv')
 8656: 		|| ($embstyle eq 'ign')) {
 8657: 		#do nothing with these
 8658: 	    } elsif (($embstyle eq 'img') 
 8659: 		|| ($embstyle eq 'emb')
 8660: 		|| ($embstyle eq 'wrp')) {
 8661: 		$thisfn='/adm/wrapper'.$thisfn;
 8662: 	    } elsif ($embstyle eq 'unk'
 8663: 		     && $thisfn!~/\.(sequence|page)$/) {
 8664: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8665: 	    } else {
 8666: #		&logthis("Got a blank emb style");
 8667: 	    }
 8668: 	}
 8669:     }
 8670:     return $thisfn;
 8671: }
 8672: 
 8673: sub clutter_with_no_wrapper {
 8674:     my $uri = &clutter(shift);
 8675:     if ($uri =~ m-^/adm/-) {
 8676: 	$uri =~ s-^/adm/wrapper/-/-;
 8677: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8678:     }
 8679:     return $uri;
 8680: }
 8681: 
 8682: sub freeze_escape {
 8683:     my ($value)=@_;
 8684:     if (ref($value)) {
 8685: 	$value=&nfreeze($value);
 8686: 	return '__FROZEN__'.&escape($value);
 8687:     }
 8688:     return &escape($value);
 8689: }
 8690: 
 8691: 
 8692: sub thaw_unescape {
 8693:     my ($value)=@_;
 8694:     if ($value =~ /^__FROZEN__/) {
 8695: 	substr($value,0,10,undef);
 8696: 	$value=&unescape($value);
 8697: 	return &thaw($value);
 8698:     }
 8699:     return &unescape($value);
 8700: }
 8701: 
 8702: sub correct_line_ends {
 8703:     my ($result)=@_;
 8704:     $$result =~s/\r\n/\n/mg;
 8705:     $$result =~s/\r/\n/mg;
 8706: }
 8707: # ================================================================ Main Program
 8708: 
 8709: sub goodbye {
 8710:    &logthis("Starting Shut down");
 8711: #not converted to using infrastruture and probably shouldn't be
 8712:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8713: #converted
 8714: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8715:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8716: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8717: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8718: #1.1 only
 8719: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8720: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8721: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8722: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8723:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8724:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8725:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8726:    &flushcourselogs();
 8727:    &logthis("Shutting down");
 8728: }
 8729: 
 8730: sub get_dns {
 8731:     my ($url,$func,$ignore_cache) = @_;
 8732:     if (!$ignore_cache) {
 8733: 	my ($content,$cached)=
 8734: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8735: 	if ($cached) {
 8736: 	    &$func($content);
 8737: 	    return;
 8738: 	}
 8739:     }
 8740: 
 8741:     my %alldns;
 8742:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8743:     foreach my $dns (<$config>) {
 8744: 	next if ($dns !~ /^\^(\S*)/x);
 8745:         my $line = $1;
 8746:         my ($host,$protocol) = split(/:/,$line);
 8747:         if ($protocol ne 'https') {
 8748:             $protocol = 'http';
 8749:         }
 8750: 	$alldns{$host} = $protocol;
 8751:     }
 8752:     while (%alldns) {
 8753: 	my ($dns) = keys(%alldns);
 8754: 	my $ua=new LWP::UserAgent;
 8755: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8756: 	my $response=$ua->request($request);
 8757:         delete($alldns{$dns});
 8758: 	next if ($response->is_error());
 8759: 	my @content = split("\n",$response->content);
 8760: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8761: 	&$func(\@content);
 8762: 	return;
 8763:     }
 8764:     close($config);
 8765:     my $which = (split('/',$url))[3];
 8766:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8767:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8768:     my @content = <$config>;
 8769:     &$func(\@content);
 8770:     return;
 8771: }
 8772: # ------------------------------------------------------------ Read domain file
 8773: {
 8774:     my $loaded;
 8775:     my %domain;
 8776: 
 8777:     sub parse_domain_tab {
 8778: 	my ($lines) = @_;
 8779: 	foreach my $line (@$lines) {
 8780: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8781: 
 8782: 	    chomp($line);
 8783: 	    my ($name,@elements) = split(/:/,$line,9);
 8784: 	    my %this_domain;
 8785: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8786: 			       'lang_def', 'city', 'longi', 'lati',
 8787: 			       'primary') {
 8788: 		$this_domain{$field} = shift(@elements);
 8789: 	    }
 8790: 	    $domain{$name} = \%this_domain;
 8791: 	}
 8792:     }
 8793: 
 8794:     sub reset_domain_info {
 8795: 	undef($loaded);
 8796: 	undef(%domain);
 8797:     }
 8798: 
 8799:     sub load_domain_tab {
 8800: 	my ($ignore_cache) = @_;
 8801: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8802: 	my $fh;
 8803: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8804: 	    my @lines = <$fh>;
 8805: 	    &parse_domain_tab(\@lines);
 8806: 	}
 8807: 	close($fh);
 8808: 	$loaded = 1;
 8809:     }
 8810: 
 8811:     sub domain {
 8812: 	&load_domain_tab() if (!$loaded);
 8813: 
 8814: 	my ($name,$what) = @_;
 8815: 	return if ( !exists($domain{$name}) );
 8816: 
 8817: 	if (!$what) {
 8818: 	    return $domain{$name}{'description'};
 8819: 	}
 8820: 	return $domain{$name}{$what};
 8821:     }
 8822: 
 8823:     sub domain_info {
 8824:         &load_domain_tab() if (!$loaded);
 8825:         return %domain;
 8826:     }
 8827: 
 8828: }
 8829: 
 8830: 
 8831: # ------------------------------------------------------------- Read hosts file
 8832: {
 8833:     my %hostname;
 8834:     my %hostdom;
 8835:     my %libserv;
 8836:     my $loaded;
 8837:     my %name_to_host;
 8838: 
 8839:     sub parse_hosts_tab {
 8840: 	my ($file) = @_;
 8841: 	foreach my $configline (@$file) {
 8842: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8843: 	    next if ($configline =~ /^\^/);
 8844: 	    chomp($configline);
 8845: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8846: 	    $name=~s/\s//g;
 8847: 	    if ($id && $domain && $role && $name) {
 8848: 		$hostname{$id}=$name;
 8849: 		push(@{$name_to_host{$name}}, $id);
 8850: 		$hostdom{$id}=$domain;
 8851: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8852:                 if (defined($protocol)) {
 8853:                     if ($protocol eq 'https') {
 8854:                         $protocol{$id} = $protocol;
 8855:                     } else {
 8856:                         $protocol{$id} = 'http'; 
 8857:                     }
 8858:                 } else {
 8859:                     $protocol{$id} = 'http';
 8860:                 }
 8861: 	    }
 8862: 	}
 8863:     }
 8864:     
 8865:     sub reset_hosts_info {
 8866: 	&purge_remembered();
 8867: 	&reset_domain_info();
 8868: 	&reset_hosts_ip_info();
 8869: 	undef(%name_to_host);
 8870: 	undef(%hostname);
 8871: 	undef(%hostdom);
 8872: 	undef(%libserv);
 8873: 	undef($loaded);
 8874:     }
 8875: 
 8876:     sub load_hosts_tab {
 8877: 	my ($ignore_cache) = @_;
 8878: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8879: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8880: 	my @config = <$config>;
 8881: 	&parse_hosts_tab(\@config);
 8882: 	close($config);
 8883: 	$loaded=1;
 8884:     }
 8885: 
 8886:     sub hostname {
 8887: 	&load_hosts_tab() if (!$loaded);
 8888: 
 8889: 	my ($lonid) = @_;
 8890: 	return $hostname{$lonid};
 8891:     }
 8892: 
 8893:     sub all_hostnames {
 8894: 	&load_hosts_tab() if (!$loaded);
 8895: 
 8896: 	return %hostname;
 8897:     }
 8898: 
 8899:     sub all_names {
 8900: 	&load_hosts_tab() if (!$loaded);
 8901: 
 8902: 	return %name_to_host;
 8903:     }
 8904: 
 8905:     sub all_host_domain {
 8906:         &load_hosts_tab() if (!$loaded);
 8907:         return %hostdom;
 8908:     }
 8909: 
 8910:     sub is_library {
 8911: 	&load_hosts_tab() if (!$loaded);
 8912: 
 8913: 	return exists($libserv{$_[0]});
 8914:     }
 8915: 
 8916:     sub all_library {
 8917: 	&load_hosts_tab() if (!$loaded);
 8918: 
 8919: 	return %libserv;
 8920:     }
 8921: 
 8922:     sub get_servers {
 8923: 	&load_hosts_tab() if (!$loaded);
 8924: 
 8925: 	my ($domain,$type) = @_;
 8926: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8927: 	                                          : %hostname;
 8928: 	my %result;
 8929: 	if (ref($domain) eq 'ARRAY') {
 8930: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8931: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8932: 		    $result{$host} = $hostname;
 8933: 		}
 8934: 	    }
 8935: 	} else {
 8936: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8937: 		if ($hostdom{$host} eq $domain) {
 8938: 		    $result{$host} = $hostname;
 8939: 		}
 8940: 	    }
 8941: 	}
 8942: 	return %result;
 8943:     }
 8944: 
 8945:     sub host_domain {
 8946: 	&load_hosts_tab() if (!$loaded);
 8947: 
 8948: 	my ($lonid) = @_;
 8949: 	return $hostdom{$lonid};
 8950:     }
 8951: 
 8952:     sub all_domains {
 8953: 	&load_hosts_tab() if (!$loaded);
 8954: 
 8955: 	my %seen;
 8956: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8957: 	return @uniq;
 8958:     }
 8959: }
 8960: 
 8961: { 
 8962:     my %iphost;
 8963:     my %name_to_ip;
 8964:     my %lonid_to_ip;
 8965: 
 8966:     sub get_hosts_from_ip {
 8967: 	my ($ip) = @_;
 8968: 	my %iphosts = &get_iphost();
 8969: 	if (ref($iphosts{$ip})) {
 8970: 	    return @{$iphosts{$ip}};
 8971: 	}
 8972: 	return;
 8973:     }
 8974:     
 8975:     sub reset_hosts_ip_info {
 8976: 	undef(%iphost);
 8977: 	undef(%name_to_ip);
 8978: 	undef(%lonid_to_ip);
 8979:     }
 8980: 
 8981:     sub get_host_ip {
 8982: 	my ($lonid) = @_;
 8983: 	if (exists($lonid_to_ip{$lonid})) {
 8984: 	    return $lonid_to_ip{$lonid};
 8985: 	}
 8986: 	my $name=&hostname($lonid);
 8987:    	my $ip = gethostbyname($name);
 8988: 	return if (!$ip || length($ip) ne 4);
 8989: 	$ip=inet_ntoa($ip);
 8990: 	$name_to_ip{$name}   = $ip;
 8991: 	$lonid_to_ip{$lonid} = $ip;
 8992: 	return $ip;
 8993:     }
 8994:     
 8995:     sub get_iphost {
 8996: 	my ($ignore_cache) = @_;
 8997: 
 8998: 	if (!$ignore_cache) {
 8999: 	    if (%iphost) {
 9000: 		return %iphost;
 9001: 	    }
 9002: 	    my ($ip_info,$cached)=
 9003: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9004: 	    if ($cached) {
 9005: 		%iphost      = %{$ip_info->[0]};
 9006: 		%name_to_ip  = %{$ip_info->[1]};
 9007: 		%lonid_to_ip = %{$ip_info->[2]};
 9008: 		return %iphost;
 9009: 	    }
 9010: 	}
 9011: 
 9012: 	# get yesterday's info for fallback
 9013: 	my %old_name_to_ip;
 9014: 	my ($ip_info,$cached)=
 9015: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9016: 	if ($cached) {
 9017: 	    %old_name_to_ip = %{$ip_info->[1]};
 9018: 	}
 9019: 
 9020: 	my %name_to_host = &all_names();
 9021: 	foreach my $name (keys(%name_to_host)) {
 9022: 	    my $ip;
 9023: 	    if (!exists($name_to_ip{$name})) {
 9024: 		$ip = gethostbyname($name);
 9025: 		if (!$ip || length($ip) ne 4) {
 9026: 		    if (defined($old_name_to_ip{$name})) {
 9027: 			$ip = $old_name_to_ip{$name};
 9028: 			&logthis("Can't find $name defaulting to old $ip");
 9029: 		    } else {
 9030: 			&logthis("Name $name no IP found");
 9031: 			next;
 9032: 		    }
 9033: 		} else {
 9034: 		    $ip=inet_ntoa($ip);
 9035: 		}
 9036: 		$name_to_ip{$name} = $ip;
 9037: 	    } else {
 9038: 		$ip = $name_to_ip{$name};
 9039: 	    }
 9040: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9041: 		$lonid_to_ip{$id} = $ip;
 9042: 	    }
 9043: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9044: 	}
 9045: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9046: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9047: 				      48*60*60);
 9048: 
 9049: 	return %iphost;
 9050:     }
 9051: }
 9052: 
 9053: #
 9054: #  Given a DNS returns the loncapa host name for that DNS 
 9055: # 
 9056: sub host_from_dns {
 9057:     my ($dns) = @_;
 9058:     my @hosts;
 9059:     my $ip;
 9060: 
 9061:     $ip = gethostbyname($dns);	# Initial translation to IP is in net order.
 9062:     if (length($ip) == 4) { 
 9063: 	$ip   = &IO::Socket::inet_ntoa($ip);
 9064: 	@hosts = get_hosts_from_ip($ip);
 9065: 	return $hosts[0];
 9066:     }
 9067:     return undef;
 9068: }
 9069: 
 9070: BEGIN {
 9071: 
 9072: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9073:     unless ($readit) {
 9074: {
 9075:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9076:     %perlvar = (%perlvar,%{$configvars});
 9077: }
 9078: 
 9079: 
 9080: # ------------------------------------------------------ Read spare server file
 9081: {
 9082:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9083: 
 9084:     while (my $configline=<$config>) {
 9085:        chomp($configline);
 9086:        if ($configline) {
 9087: 	   my ($host,$type) = split(':',$configline,2);
 9088: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9089: 	   push(@{ $spareid{$type} }, $host);
 9090:        }
 9091:     }
 9092:     close($config);
 9093: }
 9094: # ------------------------------------------------------------ Read permissions
 9095: {
 9096:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9097: 
 9098:     while (my $configline=<$config>) {
 9099: 	chomp($configline);
 9100: 	if ($configline) {
 9101: 	    my ($role,$perm)=split(/ /,$configline);
 9102: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9103: 	}
 9104:     }
 9105:     close($config);
 9106: }
 9107: 
 9108: # -------------------------------------------- Read plain texts for permissions
 9109: {
 9110:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9111: 
 9112:     while (my $configline=<$config>) {
 9113: 	chomp($configline);
 9114: 	if ($configline) {
 9115: 	    my ($short,@plain)=split(/:/,$configline);
 9116:             %{$prp{$short}} = ();
 9117: 	    if (@plain > 0) {
 9118:                 $prp{$short}{'std'} = $plain[0];
 9119:                 for (my $i=1; $i<@plain; $i++) {
 9120:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9121:                 }
 9122:             }
 9123: 	}
 9124:     }
 9125:     close($config);
 9126: }
 9127: 
 9128: # ---------------------------------------------------------- Read package table
 9129: {
 9130:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9131: 
 9132:     while (my $configline=<$config>) {
 9133: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9134: 	chomp($configline);
 9135: 	my ($short,$plain)=split(/:/,$configline);
 9136: 	my ($pack,$name)=split(/\&/,$short);
 9137: 	if ($plain ne '') {
 9138: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9139: 	    $packagetab{$short}=$plain; 
 9140: 	}
 9141:     }
 9142:     close($config);
 9143: }
 9144: 
 9145: # ------------- set up temporary directory
 9146: {
 9147:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9148: 
 9149: }
 9150: 
 9151: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9152: 				'compress_threshold'=> 20_000,
 9153:  			        });
 9154: 
 9155: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9156: $dumpcount=0;
 9157: $locknum=0;
 9158: 
 9159: &logtouch();
 9160: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9161: $readit=1;
 9162:     {
 9163: 	use integer;
 9164: 	my $test=(2**32)+1;
 9165: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9166: 	&logthis(" Detected 64bit platform ($_64bit)");
 9167:     }
 9168: }
 9169: }
 9170: 
 9171: 1;
 9172: __END__
 9173: 
 9174: =pod
 9175: 
 9176: =head1 NAME
 9177: 
 9178: Apache::lonnet - Subroutines to ask questions about things in the network.
 9179: 
 9180: =head1 SYNOPSIS
 9181: 
 9182: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9183: 
 9184:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9185: 
 9186: Common parameters:
 9187: 
 9188: =over 4
 9189: 
 9190: =item *
 9191: 
 9192: $uname : an internal username (if $cname expecting a course Id specifically)
 9193: 
 9194: =item *
 9195: 
 9196: $udom : a domain (if $cdom expecting a course's domain specifically)
 9197: 
 9198: =item *
 9199: 
 9200: $symb : a resource instance identifier
 9201: 
 9202: =item *
 9203: 
 9204: $namespace : the name of a .db file that contains the data needed or
 9205: being set.
 9206: 
 9207: =back
 9208: 
 9209: =head1 OVERVIEW
 9210: 
 9211: lonnet provides subroutines which interact with the
 9212: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9213: about classes, users, and resources.
 9214: 
 9215: For many of these objects you can also use this to store data about
 9216: them or modify them in various ways.
 9217: 
 9218: =head2 Symbs
 9219: 
 9220: To identify a specific instance of a resource, LON-CAPA uses symbols
 9221: or "symbs"X<symb>. These identifiers are built from the URL of the
 9222: map, the resource number of the resource in the map, and the URL of
 9223: the resource itself. The latter is somewhat redundant, but might help
 9224: if maps change.
 9225: 
 9226: An example is
 9227: 
 9228:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9229: 
 9230: The respective map entry is
 9231: 
 9232:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9233:   title="Problem 2">
 9234:  </resource>
 9235: 
 9236: Symbs are used by the random number generator, as well as to store and
 9237: restore data specific to a certain instance of for example a problem.
 9238: 
 9239: =head2 Storing And Retrieving Data
 9240: 
 9241: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9242: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9243: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9244: is is the non-critical message twin of cstore. These functions are for
 9245: handlers to store a perl hash to a user's permanent data space in an
 9246: easy manner, and to retrieve it again on another call. It is expected
 9247: that a handler would use this once at the beginning to retrieve data,
 9248: and then again once at the end to send only the new data back.
 9249: 
 9250: The data is stored in the user's data directory on the user's
 9251: homeserver under the ID of the course.
 9252: 
 9253: The hash that is returned by restore will have all of the previous
 9254: value for all of the elements of the hash.
 9255: 
 9256: Example:
 9257: 
 9258:  #creating a hash
 9259:  my %hash;
 9260:  $hash{'foo'}='bar';
 9261: 
 9262:  #storing it
 9263:  &Apache::lonnet::cstore(\%hash);
 9264: 
 9265:  #changing a value
 9266:  $hash{'foo'}='notbar';
 9267: 
 9268:  #adding a new value
 9269:  $hash{'bar'}='foo';
 9270:  &Apache::lonnet::cstore(\%hash);
 9271: 
 9272:  #retrieving the hash
 9273:  my %history=&Apache::lonnet::restore();
 9274: 
 9275:  #print the hash
 9276:  foreach my $key (sort(keys(%history))) {
 9277:    print("\%history{$key} = $history{$key}");
 9278:  }
 9279: 
 9280: Will print out:
 9281: 
 9282:  %history{1:foo} = bar
 9283:  %history{1:keys} = foo:timestamp
 9284:  %history{1:timestamp} = 990455579
 9285:  %history{2:bar} = foo
 9286:  %history{2:foo} = notbar
 9287:  %history{2:keys} = foo:bar:timestamp
 9288:  %history{2:timestamp} = 990455580
 9289:  %history{bar} = foo
 9290:  %history{foo} = notbar
 9291:  %history{timestamp} = 990455580
 9292:  %history{version} = 2
 9293: 
 9294: Note that the special hash entries C<keys>, C<version> and
 9295: C<timestamp> were added to the hash. C<version> will be equal to the
 9296: total number of versions of the data that have been stored. The
 9297: C<timestamp> attribute will be the UNIX time the hash was
 9298: stored. C<keys> is available in every historical section to list which
 9299: keys were added or changed at a specific historical revision of a
 9300: hash.
 9301: 
 9302: B<Warning>: do not store the hash that restore returns directly. This
 9303: will cause a mess since it will restore the historical keys as if the
 9304: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9305: 
 9306: Calling convention:
 9307: 
 9308:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9309:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9310: 
 9311: For more detailed information, see lonnet specific documentation.
 9312: 
 9313: =head1 RETURN MESSAGES
 9314: 
 9315: =over 4
 9316: 
 9317: =item * B<con_lost>: unable to contact remote host
 9318: 
 9319: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9320: when the connection is brought back up
 9321: 
 9322: =item * B<con_failed>: unable to contact remote host and unable to save message
 9323: for later delivery
 9324: 
 9325: =item * B<error:>: an error a occurred, a description of the error follows the :
 9326: 
 9327: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9328: that was requested
 9329: 
 9330: =back
 9331: 
 9332: =head1 PUBLIC SUBROUTINES
 9333: 
 9334: =head2 Session Environment Functions
 9335: 
 9336: =over 4
 9337: 
 9338: =item * 
 9339: X<appenv()>
 9340: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9341: the user envirnoment file, and will be restored for each access this
 9342: user makes during this session, also modifies the %env for the current
 9343: process. Optional rolesarrayref - if defined contains a reference to an array
 9344: of roles which are exempt from the restriction on modifying user.role entries 
 9345: in the user's environment.db and in %env.    
 9346: 
 9347: =item *
 9348: X<delenv()>
 9349: B<delenv($delthis,$regexp)>: removes all items from the session
 9350: environment file that begin with $delthis. If the 
 9351: optional second arg - $regexp - is true, $delthis is treated as a 
 9352: regular expression, otherwise \Q$delthis\E is used. 
 9353: The values are also deleted from the current processes %env.
 9354: 
 9355: =item * get_env_multiple($name) 
 9356: 
 9357: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9358: values may be defined and end up as an array ref.
 9359: 
 9360: returns an array of values
 9361: 
 9362: =back
 9363: 
 9364: =head2 User Information
 9365: 
 9366: =over 4
 9367: 
 9368: =item *
 9369: X<queryauthenticate()>
 9370: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9371: authentication scheme
 9372: 
 9373: =item *
 9374: X<authenticate()>
 9375: B<authenticate($uname,$upass,$udom)>: try to
 9376: authenticate user from domain's lib servers (first use the current
 9377: one). C<$upass> should be the users password.
 9378: 
 9379: =item *
 9380: X<homeserver()>
 9381: B<homeserver($uname,$udom)>: find the server which has
 9382: the user's directory and files (there must be only one), this caches
 9383: the answer, and also caches if there is a borken connection.
 9384: 
 9385: =item *
 9386: X<idget()>
 9387: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9388: (IDs are a unique resource in a domain, there must be only 1 ID per
 9389: username, and only 1 username per ID in a specific domain) (returns
 9390: hash: id=>name,id=>name)
 9391: 
 9392: =item *
 9393: X<idrget()>
 9394: B<idrget($udom,@unames)>: find the IDs behind a list of
 9395: usernames (returns hash: name=>id,name=>id)
 9396: 
 9397: =item *
 9398: X<idput()>
 9399: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9400: 
 9401: =item *
 9402: X<rolesinit()>
 9403: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9404: 
 9405: =item *
 9406: X<getsection()>
 9407: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9408: course $cname, return section name/number or '' for "not in course"
 9409: and '-1' for "no section"
 9410: 
 9411: =item *
 9412: X<userenvironment()>
 9413: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9414: passed in @what from the requested user's environment, returns a hash
 9415: 
 9416: =item * 
 9417: X<userlog_query()>
 9418: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9419: activity.log file. %filters defines filters applied when parsing the
 9420: log file. These can be start or end timestamps, or the type of action
 9421: - log to look for Login or Logout events, check for Checkin or
 9422: Checkout, role for role selection. The response is in the form
 9423: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9424: escaped strings of the action recorded in the activity.log file.
 9425: 
 9426: =back
 9427: 
 9428: =head2 User Roles
 9429: 
 9430: =over 4
 9431: 
 9432: =item *
 9433: 
 9434: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9435:  F: full access
 9436:  U,I,K: authentication modes (cxx only)
 9437:  '': forbidden
 9438:  1: user needs to choose course
 9439:  2: browse allowed
 9440:  A: passphrase authentication needed
 9441: 
 9442: =item *
 9443: 
 9444: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9445: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9446: and course level
 9447: 
 9448: =item *
 9449: 
 9450: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9451: (rolesplain.tab); plain text explanation of a user role term.
 9452: $type is Course (default) or Group.
 9453: If $forcedefault evaluates to true, text returned will be default 
 9454: text for $type. Otherwise, if this is a course, the text returned 
 9455: will be a custom name for the role (if defined in the course's 
 9456: environment).  If no custom name is defined the default is returned.
 9457:    
 9458: =item *
 9459: 
 9460: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9461: All arguments are optional. Returns a hash of a roles, either for
 9462: co-author/assistant author roles for a user's Construction Space
 9463: (default), or if $context is 'userroles', roles for the user himself,
 9464: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9465: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9466: For each key, value is set to colon-separated start and end times for
 9467: the role.  If no username and domain are specified, will default to
 9468: current user/domain. Types, roles, and roledoms are references to arrays
 9469: of role statuses (active, future or previous), roles 
 9470: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9471: to restrict the list of roles reported. If no array ref is 
 9472: provided for types, will default to return only active roles.
 9473: 
 9474: =back
 9475: 
 9476: =head2 User Modification
 9477: 
 9478: =over 4
 9479: 
 9480: =item *
 9481: 
 9482: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9483: user for the level given by URL.  Optional start and end dates (leave empty
 9484: string or zero for "no date")
 9485: 
 9486: =item *
 9487: 
 9488: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9489: change a users, password, possible return values are: ok,
 9490: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9491: refused
 9492: 
 9493: =item *
 9494: 
 9495: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9496: 
 9497: =item *
 9498: 
 9499: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9500:            $forceid,$desiredhome,$email,$inststatus) : 
 9501: modify user
 9502: 
 9503: =item *
 9504: 
 9505: modifystudent
 9506: 
 9507: modify a student's enrollment and identification information.
 9508: The course id is resolved based on the current users environment.  
 9509: This means the envoking user must be a course coordinator or otherwise
 9510: associated with a course.
 9511: 
 9512: This call is essentially a wrapper for lonnet::modifyuser and
 9513: lonnet::modify_student_enrollment
 9514: 
 9515: Inputs: 
 9516: 
 9517: =over 4
 9518: 
 9519: =item B<$udom> Student's loncapa domain
 9520: 
 9521: =item B<$uname> Student's loncapa login name
 9522: 
 9523: =item B<$uid> Student/Employee ID
 9524: 
 9525: =item B<$umode> Student's authentication mode
 9526: 
 9527: =item B<$upass> Student's password
 9528: 
 9529: =item B<$first> Student's first name
 9530: 
 9531: =item B<$middle> Student's middle name
 9532: 
 9533: =item B<$last> Student's last name
 9534: 
 9535: =item B<$gene> Student's generation
 9536: 
 9537: =item B<$usec> Student's section in course
 9538: 
 9539: =item B<$end> Unix time of the roles expiration
 9540: 
 9541: =item B<$start> Unix time of the roles start date
 9542: 
 9543: =item B<$forceid> If defined, allow $uid to be changed
 9544: 
 9545: =item B<$desiredhome> server to use as home server for student
 9546: 
 9547: =item B<$email> Student's permanent e-mail address
 9548: 
 9549: =item B<$type> Type of enrollment (auto or manual)
 9550: 
 9551: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9552: 
 9553: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9554: 
 9555: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9556: 
 9557: =item B<$context> role change context (shown in User Management Logs display in a course)
 9558: 
 9559: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9560: 
 9561: =back
 9562: 
 9563: =item *
 9564: 
 9565: modify_student_enrollment
 9566: 
 9567: Change a students enrollment status in a class.  The environment variable
 9568: 'role.request.course' must be defined for this function to proceed.
 9569: 
 9570: Inputs:
 9571: 
 9572: =over 4
 9573: 
 9574: =item $udom, students domain
 9575: 
 9576: =item $uname, students name
 9577: 
 9578: =item $uid, students user id
 9579: 
 9580: =item $first, students first name
 9581: 
 9582: =item $middle
 9583: 
 9584: =item $last
 9585: 
 9586: =item $gene
 9587: 
 9588: =item $usec
 9589: 
 9590: =item $end
 9591: 
 9592: =item $start
 9593: 
 9594: =item $type
 9595: 
 9596: =item $locktype
 9597: 
 9598: =item $cid
 9599: 
 9600: =item $selfenroll
 9601: 
 9602: =item $context
 9603: 
 9604: =back
 9605: 
 9606: 
 9607: =item *
 9608: 
 9609: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9610: custom role; give a custom role to a user for the level given by URL.  Specify
 9611: name and domain of role author, and role name
 9612: 
 9613: =item *
 9614: 
 9615: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9616: 
 9617: =item *
 9618: 
 9619: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9620: 
 9621: =back
 9622: 
 9623: =head2 Course Infomation
 9624: 
 9625: =over 4
 9626: 
 9627: =item *
 9628: 
 9629: coursedescription($courseid) : returns a hash of information about the
 9630: specified course id, including all environment settings for the
 9631: course, the description of the course will be in the hash under the
 9632: key 'description'
 9633: 
 9634: =item *
 9635: 
 9636: resdata($name,$domain,$type,@which) : request for current parameter
 9637: setting for a specific $type, where $type is either 'course' or 'user',
 9638: @what should be a list of parameters to ask about. This routine caches
 9639: answers for 5 minutes.
 9640: 
 9641: =item *
 9642: 
 9643: get_courseresdata($courseid, $domain) : dump the entire course resource
 9644: data base, returning a hash that is keyed by the resource name and has
 9645: values that are the resource value.  I believe that the timestamps and
 9646: versions are also returned.
 9647: 
 9648: 
 9649: =back
 9650: 
 9651: =head2 Course Modification
 9652: 
 9653: =over 4
 9654: 
 9655: =item *
 9656: 
 9657: writecoursepref($courseid,%prefs) : write preferences (environment
 9658: database) for a course
 9659: 
 9660: =item *
 9661: 
 9662: createcourse($udom,$description,$url) : make/modify course
 9663: 
 9664: =back
 9665: 
 9666: =head2 Resource Subroutines
 9667: 
 9668: =over 4
 9669: 
 9670: =item *
 9671: 
 9672: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9673: 
 9674: =item *
 9675: 
 9676: repcopy($filename) : subscribes to the requested file, and attempts to
 9677: replicate from the owning library server, Might return
 9678: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9679: 'bad_request', also attempts to grab the metadata for the
 9680: resource. Expects the local filesystem pathname
 9681: (/home/httpd/html/res/....)
 9682: 
 9683: =back
 9684: 
 9685: =head2 Resource Information
 9686: 
 9687: =over 4
 9688: 
 9689: =item *
 9690: 
 9691: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9692: a vairety of different possible values, $varname should be a request
 9693: string, and the other parameters can be used to specify who and what
 9694: one is asking about.
 9695: 
 9696: Possible values for $varname are environment.lastname (or other item
 9697: from the envirnment hash), user.name (or someother aspect about the
 9698: user), resource.0.maxtries (or some other part and parameter of a
 9699: resource)
 9700: 
 9701: =item *
 9702: 
 9703: directcondval($number) : get current value of a condition; reads from a state
 9704: string
 9705: 
 9706: =item *
 9707: 
 9708: condval($condidx) : value of condition index based on state
 9709: 
 9710: =item *
 9711: 
 9712: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9713: resource's metadata, $what should be either a specific key, or either
 9714: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9715: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9716: 
 9717: this function automatically caches all requests
 9718: 
 9719: =item *
 9720: 
 9721: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9722: network of library servers; returns file handle of where SQL and regex results
 9723: will be stored for query
 9724: 
 9725: =item *
 9726: 
 9727: symbread($filename) : return symbolic list entry (filename argument optional);
 9728: returns the data handle
 9729: 
 9730: =item *
 9731: 
 9732: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9733: a possible symb for the URL in $thisfn, and if is an encryypted
 9734: resource that the user accessed using /enc/ returns a 1 on success, 0
 9735: on failure, user must be in a course, as it assumes the existance of
 9736: the course initial hash, and uses $env('request.course.id'}
 9737: 
 9738: 
 9739: =item *
 9740: 
 9741: symbclean($symb) : removes versions numbers from a symb, returns the
 9742: cleaned symb
 9743: 
 9744: =item *
 9745: 
 9746: is_on_map($uri) : checks if the $uri is somewhere on the current
 9747: course map, user must be in a course for it to work.
 9748: 
 9749: =item *
 9750: 
 9751: numval($salt) : return random seed value (addend for rndseed)
 9752: 
 9753: =item *
 9754: 
 9755: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9756: a random seed, all arguments are optional, if they aren't sent it uses the
 9757: environment to derive them. Note: if symb isn't sent and it can't get one
 9758: from &symbread it will use the current time as its return value
 9759: 
 9760: =item *
 9761: 
 9762: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9763: unfakeable, receipt
 9764: 
 9765: =item *
 9766: 
 9767: receipt() : API to ireceipt working off of env values; given out to users
 9768: 
 9769: =item *
 9770: 
 9771: countacc($url) : count the number of accesses to a given URL
 9772: 
 9773: =item *
 9774: 
 9775: 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
 9776: 
 9777: =item *
 9778: 
 9779: 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)
 9780: 
 9781: =item *
 9782: 
 9783: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9784: 
 9785: =item *
 9786: 
 9787: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9788: forcing spreadsheet to reevaluate the resource scores next time.
 9789: 
 9790: =back
 9791: 
 9792: =head2 Storing/Retreiving Data
 9793: 
 9794: =over 4
 9795: 
 9796: =item *
 9797: 
 9798: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9799: for this url; hashref needs to be given and should be a \%hashname; the
 9800: remaining args aren't required and if they aren't passed or are '' they will
 9801: be derived from the env
 9802: 
 9803: =item *
 9804: 
 9805: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9806: uses critical subroutine
 9807: 
 9808: =item *
 9809: 
 9810: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9811: all args are optional
 9812: 
 9813: =item *
 9814: 
 9815: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9816: dumps the complete (or key matching regexp) namespace into a hash
 9817: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9818: normally &store()ed into
 9819: 
 9820: $range should be either an integer '100' (give me the first 100
 9821:                                            matching records)
 9822:               or be  two integers sperated by a - with no spaces
 9823:                  '30-50' (give me the 30th through the 50th matching
 9824:                           records)
 9825: 
 9826: 
 9827: =item *
 9828: 
 9829: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9830: replaces a &store() version of data with a replacement set of data
 9831: for a particular resource in a namespace passed in the $storehash hash 
 9832: reference
 9833: 
 9834: =item *
 9835: 
 9836: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9837: works very similar to store/cstore, but all data is stored in a
 9838: temporary location and can be reset using tmpreset, $storehash should
 9839: be a hash reference, returns nothing on success
 9840: 
 9841: =item *
 9842: 
 9843: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9844: similar to restore, but all data is stored in a temporary location and
 9845: can be reset using tmpreset. Returns a hash of values on success,
 9846: error string otherwise.
 9847: 
 9848: =item *
 9849: 
 9850: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9851: deltes all keys for $symb form the temporary storage hash.
 9852: 
 9853: =item *
 9854: 
 9855: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9856: reference filled in from namesp ($udom and $uname are optional)
 9857: 
 9858: =item *
 9859: 
 9860: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9861: namesp ($udom and $uname are optional)
 9862: 
 9863: =item *
 9864: 
 9865: dump($namespace,$udom,$uname,$regexp,$range) : 
 9866: dumps the complete (or key matching regexp) namespace into a hash
 9867: ($udom, $uname, $regexp, $range are optional)
 9868: 
 9869: $range should be either an integer '100' (give me the first 100
 9870:                                            matching records)
 9871:               or be  two integers sperated by a - with no spaces
 9872:                  '30-50' (give me the 30th through the 50th matching
 9873:                           records)
 9874: =item *
 9875: 
 9876: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9877: $store can be a scalar, an array reference, or if the amount to be 
 9878: incremented is > 1, a hash reference.
 9879: 
 9880: ($udom and $uname are optional)
 9881: 
 9882: =item *
 9883: 
 9884: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9885: ($udom and $uname are optional)
 9886: 
 9887: =item *
 9888: 
 9889: cput($namespace,$storehash,$udom,$uname) : critical put
 9890: ($udom and $uname are optional)
 9891: 
 9892: =item *
 9893: 
 9894: newput($namespace,$storehash,$udom,$uname) :
 9895: 
 9896: Attempts to store the items in the $storehash, but only if they don't
 9897: currently exist, if this succeeds you can be certain that you have 
 9898: successfully created a new key value pair in the $namespace db.
 9899: 
 9900: 
 9901: Args:
 9902:  $namespace: name of database to store values to
 9903:  $storehash: hashref to store to the db
 9904:  $udom: (optional) domain of user containing the db
 9905:  $uname: (optional) name of user caontaining the db
 9906: 
 9907: Returns:
 9908:  'ok' -> succeeded in storing all keys of $storehash
 9909:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9910:                         least <key> already existed in the db (other
 9911:                         requested keys may also already exist)
 9912:  'error: <msg>' -> unable to tie the DB or other error occurred
 9913:  'con_lost' -> unable to contact request server
 9914:  'refused' -> action was not allowed by remote machine
 9915: 
 9916: 
 9917: =item *
 9918: 
 9919: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9920: reference filled in from namesp (encrypts the return communication)
 9921: ($udom and $uname are optional)
 9922: 
 9923: =item *
 9924: 
 9925: log($udom,$name,$home,$message) : write to permanent log for user; use
 9926: critical subroutine
 9927: 
 9928: =item *
 9929: 
 9930: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9931: array reference filled in from namespace found in domain level on either
 9932: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9933: 
 9934: =item *
 9935: 
 9936: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9937: domain level either on specified domain server ($uhome) or primary domain 
 9938: server ($udom and $uhome are optional)
 9939: 
 9940: =item * 
 9941: 
 9942: get_domain_defaults($target_domain) : returns hash with defaults for
 9943: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9944: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9945: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9946: Values are retrieved from cache (if current), or from domain's configuration.db
 9947: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9948: or lonTabs/domain.tab. 
 9949: 
 9950: %domdefaults = &get_auth_defaults($target_domain);
 9951: 
 9952: =back
 9953: 
 9954: =head2 Network Status Functions
 9955: 
 9956: =over 4
 9957: 
 9958: =item *
 9959: 
 9960: dirlist($uri) : return directory list based on URI
 9961: 
 9962: =item *
 9963: 
 9964: spareserver() : find server with least workload from spare.tab
 9965: 
 9966: 
 9967: =item *
 9968: 
 9969: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
 9970: if there is no corresponding loncapa host.
 9971: 
 9972: =back
 9973: 
 9974: 
 9975: =head2 Apache Request
 9976: 
 9977: =over 4
 9978: 
 9979: =item *
 9980: 
 9981: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9982: localhost, posts hash
 9983: 
 9984: =back
 9985: 
 9986: =head2 Data to String to Data
 9987: 
 9988: =over 4
 9989: 
 9990: =item *
 9991: 
 9992: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9993: and '&' separators, supports elements that are arrayrefs and hashrefs
 9994: 
 9995: =item *
 9996: 
 9997: hashref2str($hashref) : convert a hashref into a string complete with
 9998: escaping and '=' and '&' separators, supports elements that are
 9999: arrayrefs and hashrefs
10000: 
10001: =item *
10002: 
10003: arrayref2str($arrayref) : convert an arrayref into a string complete
10004: with escaping and '&' separators, supports elements that are arrayrefs
10005: and hashrefs
10006: 
10007: =item *
10008: 
10009: str2hash($string) : convert string to hash using unescaping and
10010: splitting on '=' and '&', supports elements that are arrayrefs and
10011: hashrefs
10012: 
10013: =item *
10014: 
10015: str2array($string) : convert string to hash using unescaping and
10016: splitting on '&', supports elements that are arrayrefs and hashrefs
10017: 
10018: =back
10019: 
10020: =head2 Logging Routines
10021: 
10022: =over 4
10023: 
10024: These routines allow one to make log messages in the lonnet.log and
10025: lonnet.perm logfiles.
10026: 
10027: =item *
10028: 
10029: logtouch() : make sure the logfile, lonnet.log, exists
10030: 
10031: =item *
10032: 
10033: logthis() : append message to the normal lonnet.log file, it gets
10034: preiodically rolled over and deleted.
10035: 
10036: =item *
10037: 
10038: logperm() : append a permanent message to lonnet.perm.log, this log
10039: file never gets deleted by any automated portion of the system, only
10040: messages of critical importance should go in here.
10041: 
10042: =back
10043: 
10044: =head2 General File Helper Routines
10045: 
10046: =over 4
10047: 
10048: =item *
10049: 
10050: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10051: (a) files in /uploaded
10052:   (i) If a local copy of the file exists - 
10053:       compares modification date of local copy with last-modified date for 
10054:       definitive version stored on home server for course. If local copy is 
10055:       stale, requests a new version from the home server and stores it. 
10056:       If the original has been removed from the home server, then local copy 
10057:       is unlinked.
10058:   (ii) If local copy does not exist -
10059:       requests the file from the home server and stores it. 
10060:   
10061:   If $caller is 'uploadrep':  
10062:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10063:     for request for files originally uploaded via DOCS. 
10064:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10065:   
10066:   Otherwise:
10067:      This indicates a call from the content generation phase of the request.
10068:      -  returns the entire contents of the file or -1.
10069:      
10070: (b) files in /res
10071:    - returns the entire contents of a file or -1; 
10072:    it properly subscribes to and replicates the file if neccessary.
10073: 
10074: 
10075: =item *
10076: 
10077: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10078:                   reference
10079: 
10080: returns either a stat() list of data about the file or an empty list
10081: if the file doesn't exist or couldn't find out about it (connection
10082: problems or user unknown)
10083: 
10084: =item *
10085: 
10086: filelocation($dir,$file) : returns file system location of a file
10087: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10088: directory that relative $file lookups are to looked in ($dir of /a/dir
10089: and a file of ../bob will become /a/bob)
10090: 
10091: =item *
10092: 
10093: hreflocation($dir,$file) : returns file system location or a URL; same as
10094: filelocation except for hrefs
10095: 
10096: =item *
10097: 
10098: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10099: 
10100: =back
10101: 
10102: =head2 Usererfile file routines (/uploaded*)
10103: 
10104: =over 4
10105: 
10106: =item *
10107: 
10108: userfileupload(): main rotine for putting a file in a user or course's
10109:                   filespace, arguments are,
10110: 
10111:  formname - required - this is the name of the element in $env where the
10112:            filename, and the contents of the file to create/modifed exist
10113:            the filename is in $env{'form.'.$formname.'.filename'} and the
10114:            contents of the file is located in $env{'form.'.$formname}
10115:  coursedoc - if true, store the file in the course of the active role
10116:              of the current user
10117:  subdir - required - subdirectory to put the file in under ../userfiles/
10118:          if undefined, it will be placed in "unknown"
10119: 
10120:  (This routine calls clean_filename() to remove any dangerous
10121:  characters from the filename, and then calls finuserfileupload() to
10122:  complete the transaction)
10123: 
10124:  returns either the url of the uploaded file (/uploaded/....) if successful
10125:  and /adm/notfound.html if unsuccessful
10126: 
10127: =item *
10128: 
10129: clean_filename(): routine for cleaing a filename up for storage in
10130:                  userfile space, argument is:
10131: 
10132:  filename - proposed filename
10133: 
10134: returns: the new clean filename
10135: 
10136: =item *
10137: 
10138: finishuserfileupload(): routine that creaes and sends the file to
10139: userspace, probably shouldn't be called directly
10140: 
10141:   docuname: username or courseid of destination for the file
10142:   docudom: domain of user/course of destination for the file
10143:   formname: same as for userfileupload()
10144:   fname: filename (inculding subdirectories) for the file
10145: 
10146:  returns either the url of the uploaded file (/uploaded/....) if successful
10147:  and /adm/notfound.html if unsuccessful
10148: 
10149: =item *
10150: 
10151: renameuserfile(): renames an existing userfile to a new name
10152: 
10153:   Args:
10154:    docuname: username or courseid of destination for the file
10155:    docudom: domain of user/course of destination for the file
10156:    old: current file name (including any subdirs under userfiles)
10157:    new: desired file name (including any subdirs under userfiles)
10158: 
10159: =item *
10160: 
10161: mkdiruserfile(): creates a directory is a userfiles dir
10162: 
10163:   Args:
10164:    docuname: username or courseid of destination for the file
10165:    docudom: domain of user/course of destination for the file
10166:    dir: dir to create (including any subdirs under userfiles)
10167: 
10168: =item *
10169: 
10170: removeuserfile(): removes a file that exists in userfiles
10171: 
10172:   Args:
10173:    docuname: username or courseid of destination for the file
10174:    docudom: domain of user/course of destination for the file
10175:    fname: filname to delete (including any subdirs under userfiles)
10176: 
10177: =item *
10178: 
10179: removeuploadedurl(): convience function for removeuserfile()
10180: 
10181:   Args:
10182:    url:  a full /uploaded/... url to delete
10183: 
10184: =item * 
10185: 
10186: get_portfile_permissions():
10187:   Args:
10188:     domain: domain of user or course contain the portfolio files
10189:     user: name of user or num of course contain the portfolio files
10190:   Returns:
10191:     hashref of a dump of the proper file_permissions.db
10192:    
10193: 
10194: =item * 
10195: 
10196: get_access_controls():
10197: 
10198: Args:
10199:   current_permissions: the hash ref returned from get_portfile_permissions()
10200:   group: (optional) the group you want the files associated with
10201:   file: (optional) the file you want access info on
10202: 
10203: Returns:
10204:     a hash (keys are file names) of hashes containing
10205:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10206:         values are XML containing access control settings (see below) 
10207: 
10208: Internal notes:
10209: 
10210:  access controls are stored in file_permissions.db as key=value pairs.
10211:     key -> path to file/file_name\0uniqueID:scope_end_start
10212:         where scope -> public,guest,course,group,domains or users.
10213:               end -> UNIX time for end of access (0 -> no end date)
10214:               start -> UNIX time for start of access
10215: 
10216:     value -> XML description of access control
10217:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10218:             <start></start>
10219:             <end></end>
10220: 
10221:             <password></password>  for scope type = guest
10222: 
10223:             <domain></domain>     for scope type = course or group
10224:             <number></number>
10225:             <roles id="">
10226:              <role></role>
10227:              <access></access>
10228:              <section></section>
10229:              <group></group>
10230:             </roles>
10231: 
10232:             <dom></dom>         for scope type = domains
10233: 
10234:             <users>             for scope type = users
10235:              <user>
10236:               <uname></uname>
10237:               <udom></udom>
10238:              </user>
10239:             </users>
10240:            </scope> 
10241:               
10242:  Access data is also aggregated for each file in an additional key=value pair:
10243:  key -> path to file/file_name\0accesscontrol 
10244:  value -> reference to hash
10245:           hash contains key = value pairs
10246:           where key = uniqueID:scope_end_start
10247:                 value = UNIX time record was last updated
10248: 
10249:           Used to improve speed of look-ups of access controls for each file.  
10250:  
10251:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10252: 
10253: modify_access_controls():
10254: 
10255: Modifies access controls for a portfolio file
10256: Args
10257: 1. file name
10258: 2. reference to hash of required changes,
10259: 3. domain
10260: 4. username
10261:   where domain,username are the domain of the portfolio owner 
10262:   (either a user or a course) 
10263: 
10264: Returns:
10265: 1. result of additions or updates ('ok' or 'error', with error message). 
10266: 2. result of deletions ('ok' or 'error', with error message).
10267: 3. reference to hash of any new or updated access controls.
10268: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10269:    key = integer (inbound ID)
10270:    value = uniqueID  
10271: 
10272: =back
10273: 
10274: =head2 HTTP Helper Routines
10275: 
10276: =over 4
10277: 
10278: =item *
10279: 
10280: escape() : unpack non-word characters into CGI-compatible hex codes
10281: 
10282: =item *
10283: 
10284: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10285: 
10286: =back
10287: 
10288: =head1 PRIVATE SUBROUTINES
10289: 
10290: =head2 Underlying communication routines (Shouldn't call)
10291: 
10292: =over 4
10293: 
10294: =item *
10295: 
10296: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10297: 
10298: =item *
10299: 
10300: reply() : uses subreply to send a message to remote machine, logs all failures
10301: 
10302: =item *
10303: 
10304: critical() : passes a critical message to another server; if cannot
10305: get through then place message in connection buffer directory and
10306: returns con_delayed, if incapable of saving message, returns
10307: con_failed
10308: 
10309: =item *
10310: 
10311: reconlonc() : tries to reconnect lonc client processes.
10312: 
10313: =back
10314: 
10315: =head2 Resource Access Logging
10316: 
10317: =over 4
10318: 
10319: =item *
10320: 
10321: flushcourselogs() : flush (save) buffer logs and access logs
10322: 
10323: =item *
10324: 
10325: courselog($what) : save message for course in hash
10326: 
10327: =item *
10328: 
10329: courseacclog($what) : save message for course using &courselog().  Perform
10330: special processing for specific resource types (problems, exams, quizzes, etc).
10331: 
10332: =item *
10333: 
10334: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10335: as a PerlChildExitHandler
10336: 
10337: =back
10338: 
10339: =head2 Other
10340: 
10341: =over 4
10342: 
10343: =item *
10344: 
10345: symblist($mapname,%newhash) : update symbolic storage links
10346: 
10347: =back
10348: 
10349: =cut
10350: 

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