File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.728: download - view: text, annotated - select for diffs
Fri Apr 7 22:42:32 2006 UTC (18 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- moving hadnler routines out of lonnet into lonacc

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.728 2006/04/07 22:42:32 albertel 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: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
   39:    %libserv %pr %prp $memcache %packagetab 
   40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
   43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
   44:    $tmpdir $_64bit %env);
   45: 
   46: use IO::Socket;
   47: use GDBM_File;
   48: use HTML::LCParser;
   49: use HTML::Parser;
   50: use Fcntl qw(:flock);
   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   52: use Time::HiRes qw( gettimeofday tv_interval );
   53: use Cache::Memcached;
   54: use Digest::MD5;
   55: 
   56: my $readit;
   57: my $max_connection_retries = 10;     # Or some such value.
   58: 
   59: require Exporter;
   60: 
   61: our @ISA = qw (Exporter);
   62: our @EXPORT = qw(%env);
   63: 
   64: =pod
   65: 
   66: =head1 Package Variables
   67: 
   68: These are largely undocumented, so if you decipher one please note it here.
   69: 
   70: =over 4
   71: 
   72: =item $processmarker
   73: 
   74: Contains the time this process was started and this servers host id.
   75: 
   76: =item $dumpcount
   77: 
   78: Counts the number of times a message log flush has been attempted (regardless
   79: of success) by this process.  Used as part of the filename when messages are
   80: delayed.
   81: 
   82: =back
   83: 
   84: =cut
   85: 
   86: 
   87: # --------------------------------------------------------------------- Logging
   88: 
   89: sub logtouch {
   90:     my $execdir=$perlvar{'lonDaemons'};
   91:     unless (-e "$execdir/logs/lonnet.log") {	
   92: 	open(my $fh,">>$execdir/logs/lonnet.log");
   93: 	close $fh;
   94:     }
   95:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
   96:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
   97: }
   98: 
   99: sub logthis {
  100:     my $message=shift;
  101:     my $execdir=$perlvar{'lonDaemons'};
  102:     my $now=time;
  103:     my $local=localtime($now);
  104:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  105: 	print $fh "$local ($$): $message\n";
  106: 	close($fh);
  107:     }
  108:     return 1;
  109: }
  110: 
  111: sub logperm {
  112:     my $message=shift;
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     my $now=time;
  115:     my $local=localtime($now);
  116:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  117: 	print $fh "$now:$message:$local\n";
  118: 	close($fh);
  119:     }
  120:     return 1;
  121: }
  122: 
  123: # -------------------------------------------------- Non-critical communication
  124: sub subreply {
  125:     my ($cmd,$server)=@_;
  126:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
  127:     #
  128:     #  With loncnew process trimming, there's a timing hole between lonc server
  129:     #  process exit and the master server picking up the listen on the AF_UNIX
  130:     #  socket.  In that time interval, a lock file will exist:
  131: 
  132:     my $lockfile=$peerfile.".lock";
  133:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  134: 	sleep(1);
  135:     }
  136:     # At this point, either a loncnew parent is listening or an old lonc
  137:     # or loncnew child is listening so we can connect or everything's dead.
  138:     #
  139:     #   We'll give the connection a few tries before abandoning it.  If
  140:     #   connection is not possible, we'll con_lost back to the client.
  141:     #   
  142:     my $client;
  143:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  144: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  145: 				      Type    => SOCK_STREAM,
  146: 				      Timeout => 10);
  147: 	if($client) {
  148: 	    last;		# Connected!
  149: 	}
  150: 	sleep(1);		# Try again later if failed connection.
  151:     }
  152:     my $answer;
  153:     if ($client) {
  154: 	print $client "sethost:$server:$cmd\n";
  155: 	$answer=<$client>;
  156: 	if (!$answer) { $answer="con_lost"; }
  157: 	chomp($answer);
  158:     } else {
  159: 	$answer = 'con_lost';	# Failed connection.
  160:     }
  161:     return $answer;
  162: }
  163: 
  164: sub reply {
  165:     my ($cmd,$server)=@_;
  166:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  167:     my $answer=subreply($cmd,$server);
  168:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  169:        &logthis("<font color=\"blue\">WARNING:".
  170:                 " $cmd to $server returned $answer</font>");
  171:     }
  172:     return $answer;
  173: }
  174: 
  175: # ----------------------------------------------------------- Send USR1 to lonc
  176: 
  177: sub reconlonc {
  178:     my $peerfile=shift;
  179:     &logthis("Trying to reconnect for $peerfile");
  180:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  181:     if (open(my $fh,"<$loncfile")) {
  182: 	my $loncpid=<$fh>;
  183:         chomp($loncpid);
  184:         if (kill 0 => $loncpid) {
  185: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  186:             kill USR1 => $loncpid;
  187:             sleep 1;
  188:             if (-e "$peerfile") { return; }
  189:             &logthis("$peerfile still not there, give it another try");
  190:             sleep 5;
  191:             if (-e "$peerfile") { return; }
  192:             &logthis(
  193:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
  194:         } else {
  195: 	    &logthis(
  196:                "<font color=\"blue\">WARNING:".
  197:                " lonc at pid $loncpid not responding, giving up</font>");
  198:         }
  199:     } else {
  200:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  201:     }
  202: }
  203: 
  204: # ------------------------------------------------------ Critical communication
  205: 
  206: sub critical {
  207:     my ($cmd,$server)=@_;
  208:     unless ($hostname{$server}) {
  209:         &logthis("<font color=\"blue\">WARNING:".
  210:                " Critical message to unknown server ($server)</font>");
  211:         return 'no_such_host';
  212:     }
  213:     my $answer=reply($cmd,$server);
  214:     if ($answer eq 'con_lost') {
  215: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  216: 	my $answer=reply($cmd,$server);
  217:         if ($answer eq 'con_lost') {
  218:             my $now=time;
  219:             my $middlename=$cmd;
  220:             $middlename=substr($middlename,0,16);
  221:             $middlename=~s/\W//g;
  222:             my $dfilename=
  223:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  224:             $dumpcount++;
  225:             {
  226: 		my $dfh;
  227: 		if (open($dfh,">$dfilename")) {
  228: 		    print $dfh "$cmd\n"; 
  229: 		    close($dfh);
  230: 		}
  231:             }
  232:             sleep 2;
  233:             my $wcmd='';
  234:             {
  235: 		my $dfh;
  236: 		if (open($dfh,"<$dfilename")) {
  237: 		    $wcmd=<$dfh>; 
  238: 		    close($dfh);
  239: 		}
  240:             }
  241:             chomp($wcmd);
  242:             if ($wcmd eq $cmd) {
  243: 		&logthis("<font color=\"blue\">WARNING: ".
  244:                          "Connection buffer $dfilename: $cmd</font>");
  245:                 &logperm("D:$server:$cmd");
  246: 	        return 'con_delayed';
  247:             } else {
  248:                 &logthis("<font color=\"red\">CRITICAL:"
  249:                         ." Critical connection failed: $server $cmd</font>");
  250:                 &logperm("F:$server:$cmd");
  251:                 return 'con_failed';
  252:             }
  253:         }
  254:     }
  255:     return $answer;
  256: }
  257: 
  258: # ------------------------------------------- Transfer profile into environment
  259: 
  260: sub transfer_profile_to_env {
  261:     my ($lonidsdir,$handle)=@_;
  262:     if (!defined($lonidsdir)) {
  263: 	$lonidsdir = $perlvar{'lonIDsDir'};
  264:     }
  265:     if (!defined($handle)) {
  266:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  267:     }
  268: 
  269:     my @profile;
  270:     {
  271: 	open(my $idf,"$lonidsdir/$handle.id");
  272: 	flock($idf,LOCK_SH);
  273: 	@profile=<$idf>;
  274: 	close($idf);
  275:     }
  276:     my $envi;
  277:     my %Remove;
  278:     for ($envi=0;$envi<=$#profile;$envi++) {
  279: 	chomp($profile[$envi]);
  280: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
  281: 	$envname=&unescape($envname);
  282: 	$envvalue=&unescape($envvalue);
  283: 	$env{$envname} = $envvalue;
  284:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  285:             if ($time < time-300) {
  286:                 $Remove{$key}++;
  287:             }
  288:         }
  289:     }
  290:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  291:     foreach my $expired_key (keys(%Remove)) {
  292:         &delenv($expired_key);
  293:     }
  294: }
  295: 
  296: # ---------------------------------------------------------- Append Environment
  297: 
  298: sub appenv {
  299:     my %newenv=@_;
  300:     foreach my $key (keys(%newenv)) {
  301: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  302:             &logthis("<font color=\"blue\">WARNING: ".
  303:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  304:                 .'</font>');
  305: 	    delete($newenv{$key});
  306:         } else {
  307:             $env{$key}=$newenv{$key};
  308:         }
  309:     }
  310: 
  311:     my $lockfh;
  312:     unless (open($lockfh,"$env{'user.environment'}")) {
  313: 	return 'error: '.$!;
  314:     }
  315:     unless (flock($lockfh,LOCK_EX)) {
  316:          &logthis("<font color=\"blue\">WARNING: ".
  317:                   'Could not obtain exclusive lock in appenv: '.$!);
  318:          close($lockfh);
  319:          return 'error: '.$!;
  320:     }
  321: 
  322:     my @oldenv;
  323:     {
  324: 	my $fh;
  325: 	unless (open($fh,"$env{'user.environment'}")) {
  326: 	    return 'error: '.$!;
  327: 	}
  328: 	@oldenv=<$fh>;
  329: 	close($fh);
  330:     }
  331:     for (my $i=0; $i<=$#oldenv; $i++) {
  332:         chomp($oldenv[$i]);
  333:         if ($oldenv[$i] ne '') {
  334: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
  335: 	    $name=&unescape($name);
  336: 	    $value=&unescape($value);
  337: 	    unless (defined($newenv{$name})) {
  338: 		$newenv{$name}=$value;
  339: 	    }
  340:         }
  341:     }
  342:     {
  343: 	my $fh;
  344: 	unless (open($fh,">$env{'user.environment'}")) {
  345: 	    return 'error';
  346: 	}
  347: 	my $newname;
  348: 	foreach $newname (keys %newenv) {
  349: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
  350: 	}
  351: 	close($fh);
  352:     }
  353: 	
  354:     close($lockfh);
  355:     return 'ok';
  356: }
  357: # ----------------------------------------------------- Delete from Environment
  358: 
  359: sub delenv {
  360:     my $delthis=shift;
  361:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  362:         &logthis("<font color=\"blue\">WARNING: ".
  363:                 "Attempt to delete from environment ".$delthis);
  364:         return 'error';
  365:     }
  366:     my @oldenv;
  367:     {
  368: 	my $fh;
  369: 	unless (open($fh,"$env{'user.environment'}")) {
  370: 	    return 'error';
  371: 	}
  372: 	unless (flock($fh,LOCK_SH)) {
  373: 	    &logthis("<font color=\"blue\">WARNING: ".
  374: 		     'Could not obtain shared lock in delenv: '.$!);
  375: 	    close($fh);
  376: 	    return 'error: '.$!;
  377: 	}
  378: 	@oldenv=<$fh>;
  379: 	close($fh);
  380:     }
  381:     {
  382: 	my $fh;
  383: 	unless (open($fh,">$env{'user.environment'}")) {
  384: 	    return 'error';
  385: 	}
  386: 	unless (flock($fh,LOCK_EX)) {
  387: 	    &logthis("<font color=\"blue\">WARNING: ".
  388: 		     'Could not obtain exclusive lock in delenv: '.$!);
  389: 	    close($fh);
  390: 	    return 'error: '.$!;
  391: 	}
  392: 	foreach my $cur_key (@oldenv) {
  393: 	    my $unescaped_cur_key = &unescape($cur_key);
  394: 	    if ($unescaped_cur_key=~/^$delthis/) { 
  395:                 my ($key) = split('=',$cur_key,2);
  396: 		$key = &unescape($key);
  397:                 delete($env{$key});
  398:             } else {
  399:                 print $fh $cur_key; 
  400:             }
  401: 	}
  402: 	close($fh);
  403:     }
  404:     return 'ok';
  405: }
  406: 
  407: # ------------------------------------------ Find out current server userload
  408: # there is a copy in lond
  409: sub userload {
  410:     my $numusers=0;
  411:     {
  412: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  413: 	my $filename;
  414: 	my $curtime=time;
  415: 	while ($filename=readdir(LONIDS)) {
  416: 	    if ($filename eq '.' || $filename eq '..') {next;}
  417: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  418: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  419: 	}
  420: 	closedir(LONIDS);
  421:     }
  422:     my $userloadpercent=0;
  423:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  424:     if ($maxuserload) {
  425: 	$userloadpercent=100*$numusers/$maxuserload;
  426:     }
  427:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  428:     return $userloadpercent;
  429: }
  430: 
  431: # ------------------------------------------ Fight off request when overloaded
  432: 
  433: sub overloaderror {
  434:     my ($r,$checkserver)=@_;
  435:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  436:     my $loadavg;
  437:     if ($checkserver eq $perlvar{'lonHostID'}) {
  438:        open(my $loadfile,'/proc/loadavg');
  439:        $loadavg=<$loadfile>;
  440:        $loadavg =~ s/\s.*//g;
  441:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  442:        close($loadfile);
  443:     } else {
  444:        $loadavg=&reply('load',$checkserver);
  445:     }
  446:     my $overload=$loadavg-100;
  447:     if ($overload>0) {
  448: 	$r->err_headers_out->{'Retry-After'}=$overload;
  449:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  450:         return 413;
  451:     }    
  452:     return '';
  453: }
  454: 
  455: # ------------------------------ Find server with least workload from spare.tab
  456: 
  457: sub spareserver {
  458:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  459:     my $tryserver;
  460:     my $spareserver='';
  461:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  462:     my $lowestserver=$loadpercent > $userloadpercent?
  463: 	             $loadpercent :  $userloadpercent;
  464:     foreach $tryserver (keys(%spareid)) {
  465: 	my $loadans=&reply('load',$tryserver);
  466: 	my $userloadans=&reply('userload',$tryserver);
  467: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  468: 	    next; #didn't get a number from the server
  469: 	}
  470: 	my $answer;
  471: 	if ($loadans =~ /\d/) {
  472: 	    if ($userloadans =~ /\d/) {
  473: 		#both are numbers, pick the bigger one
  474: 		$answer=$loadans > $userloadans?
  475: 		    $loadans :  $userloadans;
  476: 	    } else {
  477: 		$answer = $loadans;
  478: 	    }
  479: 	} else {
  480: 	    $answer = $userloadans;
  481: 	}
  482: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  483: 	    if ($want_server_name) {
  484: 		$spareserver=$tryserver;
  485: 	    } else {
  486: 		$spareserver="http://$hostname{$tryserver}";
  487: 	    }
  488: 	    $lowestserver=$answer;
  489: 	}
  490:     }
  491:     return $spareserver;
  492: }
  493: 
  494: # --------------------------------------------- Try to change a user's password
  495: 
  496: sub changepass {
  497:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  498:     $currentpass = &escape($currentpass);
  499:     $newpass     = &escape($newpass);
  500:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  501: 		       $server);
  502:     if (! $answer) {
  503: 	&logthis("No reply on password change request to $server ".
  504: 		 "by $uname in domain $udom.");
  505:     } elsif ($answer =~ "^ok") {
  506:         &logthis("$uname in $udom successfully changed their password ".
  507: 		 "on $server.");
  508:     } elsif ($answer =~ "^pwchange_failure") {
  509: 	&logthis("$uname in $udom was unable to change their password ".
  510: 		 "on $server.  The action was blocked by either lcpasswd ".
  511: 		 "or pwchange");
  512:     } elsif ($answer =~ "^non_authorized") {
  513:         &logthis("$uname in $udom did not get their password correct when ".
  514: 		 "attempting to change it on $server.");
  515:     } elsif ($answer =~ "^auth_mode_error") {
  516:         &logthis("$uname in $udom attempted to change their password despite ".
  517: 		 "not being locally or internally authenticated on $server.");
  518:     } elsif ($answer =~ "^unknown_user") {
  519:         &logthis("$uname in $udom attempted to change their password ".
  520: 		 "on $server but were unable to because $server is not ".
  521: 		 "their home server.");
  522:     } elsif ($answer =~ "^refused") {
  523: 	&logthis("$server refused to change $uname in $udom password because ".
  524: 		 "it was sent an unencrypted request to change the password.");
  525:     }
  526:     return $answer;
  527: }
  528: 
  529: # ----------------------- Try to determine user's current authentication scheme
  530: 
  531: sub queryauthenticate {
  532:     my ($uname,$udom)=@_;
  533:     my $uhome=&homeserver($uname,$udom);
  534:     if (!$uhome) {
  535: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  536: 	return 'no_host';
  537:     }
  538:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  539:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  540: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  541:     }
  542:     return $answer;
  543: }
  544: 
  545: # --------- Try to authenticate user from domain's lib servers (first this one)
  546: 
  547: sub authenticate {
  548:     my ($uname,$upass,$udom)=@_;
  549:     $upass=escape($upass);
  550:     $uname=~s/\W//g;
  551:     my $uhome=&homeserver($uname,$udom);
  552:     if (!$uhome) {
  553: 	&logthis("User $uname at $udom is unknown in authenticate");
  554: 	return 'no_host';
  555:     }
  556:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  557:     if ($answer eq 'authorized') {
  558: 	&logthis("User $uname at $udom authorized by $uhome"); 
  559: 	return $uhome; 
  560:     }
  561:     if ($answer eq 'non_authorized') {
  562: 	&logthis("User $uname at $udom rejected by $uhome");
  563: 	return 'no_host'; 
  564:     }
  565:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  566:     return 'no_host';
  567: }
  568: 
  569: # ---------------------- Find the homebase for a user from domain's lib servers
  570: 
  571: my %homecache;
  572: sub homeserver {
  573:     my ($uname,$udom,$ignoreBadCache)=@_;
  574:     my $index="$uname:$udom";
  575: 
  576:     if (exists($homecache{$index})) { return $homecache{$index}; }
  577:     my $tryserver;
  578:     foreach $tryserver (keys %libserv) {
  579:         next if ($ignoreBadCache ne 'true' && 
  580: 		 exists($badServerCache{$tryserver}));
  581: 	if ($hostdom{$tryserver} eq $udom) {
  582:            my $answer=reply("home:$udom:$uname",$tryserver);
  583:            if ($answer eq 'found') { 
  584: 	       return $homecache{$index}=$tryserver;
  585:            } elsif ($answer eq 'no_host') {
  586: 	       $badServerCache{$tryserver}=1;
  587:            }
  588:        }
  589:     }    
  590:     return 'no_host';
  591: }
  592: 
  593: # ------------------------------------- Find the usernames behind a list of IDs
  594: 
  595: sub idget {
  596:     my ($udom,@ids)=@_;
  597:     my %returnhash=();
  598:     
  599:     my $tryserver;
  600:     foreach $tryserver (keys %libserv) {
  601:        if ($hostdom{$tryserver} eq $udom) {
  602: 	  my $idlist=join('&',@ids);
  603:           $idlist=~tr/A-Z/a-z/; 
  604: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  605:           my @answer=();
  606:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  607: 	      @answer=split(/\&/,$reply);
  608:           }                    ;
  609:           my $i;
  610:           for ($i=0;$i<=$#ids;$i++) {
  611:               if ($answer[$i]) {
  612: 		  $returnhash{$ids[$i]}=$answer[$i];
  613:               } 
  614:           }
  615:        }
  616:     }    
  617:     return %returnhash;
  618: }
  619: 
  620: # ------------------------------------- Find the IDs behind a list of usernames
  621: 
  622: sub idrget {
  623:     my ($udom,@unames)=@_;
  624:     my %returnhash=();
  625:     foreach (@unames) {
  626:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  627:     }
  628:     return %returnhash;
  629: }
  630: 
  631: # ------------------------------- Store away a list of names and associated IDs
  632: 
  633: sub idput {
  634:     my ($udom,%ids)=@_;
  635:     my %servers=();
  636:     foreach (keys %ids) {
  637: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
  638:         my $uhom=&homeserver($_,$udom);
  639:         if ($uhom ne 'no_host') {
  640:             my $id=&escape($ids{$_});
  641:             $id=~tr/A-Z/a-z/;
  642:             my $unam=&escape($_);
  643: 	    if ($servers{$uhom}) {
  644: 		$servers{$uhom}.='&'.$id.'='.$unam;
  645:             } else {
  646:                 $servers{$uhom}=$id.'='.$unam;
  647:             }
  648:         }
  649:     }
  650:     foreach (keys %servers) {
  651:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  652:     }
  653: }
  654: 
  655: # --------------------------------------------------- Assign a key to a student
  656: 
  657: sub assign_access_key {
  658: #
  659: # a valid key looks like uname:udom#comments
  660: # comments are being appended
  661: #
  662:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  663:     $kdom=
  664:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  665:     $knum=
  666:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  667:     $cdom=
  668:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  669:     $cnum=
  670:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  671:     $udom=$env{'user.name'} unless (defined($udom));
  672:     $uname=$env{'user.domain'} unless (defined($uname));
  673:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  674:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  675:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  676:                                                   # assigned to this person
  677:                                                   # - this should not happen,
  678:                                                   # unless something went wrong
  679:                                                   # the first time around
  680: # ready to assign
  681:         $logentry=$1.'; '.$logentry;
  682:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  683:                                                  $kdom,$knum) eq 'ok') {
  684: # key now belongs to user
  685: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  686:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  687:                 &appenv('environment.'.$envkey => $ckey);
  688:                 return 'ok';
  689:             } else {
  690:                 return 
  691:   'error: Count not permanently assign key, will need to be re-entered later.';
  692: 	    }
  693:         } else {
  694:             return 'error: Could not assign key, try again later.';
  695:         }
  696:     } elsif (!$existing{$ckey}) {
  697: # the key does not exist
  698: 	return 'error: The key does not exist';
  699:     } else {
  700: # the key is somebody else's
  701: 	return 'error: The key is already in use';
  702:     }
  703: }
  704: 
  705: # ------------------------------------------ put an additional comment on a key
  706: 
  707: sub comment_access_key {
  708: #
  709: # a valid key looks like uname:udom#comments
  710: # comments are being appended
  711: #
  712:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  713:     $cdom=
  714:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  715:     $cnum=
  716:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  717:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  718:     if ($existing{$ckey}) {
  719:         $existing{$ckey}.='; '.$logentry;
  720: # ready to assign
  721:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  722:                                                  $cdom,$cnum) eq 'ok') {
  723: 	    return 'ok';
  724:         } else {
  725: 	    return 'error: Count not store comment.';
  726:         }
  727:     } else {
  728: # the key does not exist
  729: 	return 'error: The key does not exist';
  730:     }
  731: }
  732: 
  733: # ------------------------------------------------------ Generate a set of keys
  734: 
  735: sub generate_access_keys {
  736:     my ($number,$cdom,$cnum,$logentry)=@_;
  737:     $cdom=
  738:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  739:     $cnum=
  740:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  741:     unless (&allowed('mky',$cdom)) { return 0; }
  742:     unless (($cdom) && ($cnum)) { return 0; }
  743:     if ($number>10000) { return 0; }
  744:     sleep(2); # make sure don't get same seed twice
  745:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  746:     my $total=0;
  747:     for (my $i=1;$i<=$number;$i++) {
  748:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  749:                   sprintf("%lx",int(100000*rand)).'-'.
  750:                   sprintf("%lx",int(100000*rand));
  751:        $newkey=~s/1/g/g; # folks mix up 1 and l
  752:        $newkey=~s/0/h/g; # and also 0 and O
  753:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  754:        if ($existing{$newkey}) {
  755:            $i--;
  756:        } else {
  757: 	  if (&put('accesskeys',
  758:               { $newkey => '# generated '.localtime().
  759:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  760:                            '; '.$logentry },
  761: 		   $cdom,$cnum) eq 'ok') {
  762:               $total++;
  763: 	  }
  764:        }
  765:     }
  766:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  767:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  768:     return $total;
  769: }
  770: 
  771: # ------------------------------------------------------- Validate an accesskey
  772: 
  773: sub validate_access_key {
  774:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  775:     $cdom=
  776:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  777:     $cnum=
  778:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  779:     $udom=$env{'user.domain'} unless (defined($udom));
  780:     $uname=$env{'user.name'} unless (defined($uname));
  781:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  782:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  783: }
  784: 
  785: # ------------------------------------- Find the section of student in a course
  786: sub devalidate_getsection_cache {
  787:     my ($udom,$unam,$courseid)=@_;
  788:     $courseid=~s/\_/\//g;
  789:     $courseid=~s/^(\w)/\/$1/;
  790:     my $hashid="$udom:$unam:$courseid";
  791:     &devalidate_cache_new('getsection',$hashid);
  792: }
  793: 
  794: sub getsection {
  795:     my ($udom,$unam,$courseid)=@_;
  796:     my $cachetime=1800;
  797:     $courseid=~s/\_/\//g;
  798:     $courseid=~s/^(\w)/\/$1/;
  799: 
  800:     my $hashid="$udom:$unam:$courseid";
  801:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  802:     if (defined($cached)) { return $result; }
  803: 
  804:     my %Pending; 
  805:     my %Expired;
  806:     #
  807:     # Each role can either have not started yet (pending), be active, 
  808:     #    or have expired.
  809:     #
  810:     # If there is an active role, we are done.
  811:     #
  812:     # If there is more than one role which has not started yet, 
  813:     #     choose the one which will start sooner
  814:     # If there is one role which has not started yet, return it.
  815:     #
  816:     # If there is more than one expired role, choose the one which ended last.
  817:     # If there is a role which has expired, return it.
  818:     #
  819:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  820:                         &homeserver($unam,$udom)))) {
  821:         my ($key,$value)=split(/\=/,$_);
  822:         $key=&unescape($key);
  823:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  824:         my $section=$1;
  825:         if ($key eq $courseid.'_st') { $section=''; }
  826:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  827:         my $now=time;
  828:         if (defined($end) && $end && ($now > $end)) {
  829:             $Expired{$end}=$section;
  830:             next;
  831:         }
  832:         if (defined($start) && $start && ($now < $start)) {
  833:             $Pending{$start}=$section;
  834:             next;
  835:         }
  836:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  837:     }
  838:     #
  839:     # Presumedly there will be few matching roles from the above
  840:     # loop and the sorting time will be negligible.
  841:     if (scalar(keys(%Pending))) {
  842:         my ($time) = sort {$a <=> $b} keys(%Pending);
  843:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  844:     } 
  845:     if (scalar(keys(%Expired))) {
  846:         my @sorted = sort {$a <=> $b} keys(%Expired);
  847:         my $time = pop(@sorted);
  848:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  849:     }
  850:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  851: }
  852: 
  853: sub save_cache {
  854:     &purge_remembered();
  855:     #&Apache::loncommon::validate_page();
  856:     undef(%env);
  857: }
  858: 
  859: my $to_remember=-1;
  860: my %remembered;
  861: my %accessed;
  862: my $kicks=0;
  863: my $hits=0;
  864: sub devalidate_cache_new {
  865:     my ($name,$id,$debug) = @_;
  866:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  867:     $id=&escape($name.':'.$id);
  868:     $memcache->delete($id);
  869:     delete($remembered{$id});
  870:     delete($accessed{$id});
  871: }
  872: 
  873: sub is_cached_new {
  874:     my ($name,$id,$debug) = @_;
  875:     $id=&escape($name.':'.$id);
  876:     if (exists($remembered{$id})) {
  877: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  878: 	$accessed{$id}=[&gettimeofday()];
  879: 	$hits++;
  880: 	return ($remembered{$id},1);
  881:     }
  882:     my $value = $memcache->get($id);
  883:     if (!(defined($value))) {
  884: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  885: 	return (undef,undef);
  886:     }
  887:     if ($value eq '__undef__') {
  888: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  889: 	$value=undef;
  890:     }
  891:     &make_room($id,$value,$debug);
  892:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  893:     return ($value,1);
  894: }
  895: 
  896: sub do_cache_new {
  897:     my ($name,$id,$value,$time,$debug) = @_;
  898:     $id=&escape($name.':'.$id);
  899:     my $setvalue=$value;
  900:     if (!defined($setvalue)) {
  901: 	$setvalue='__undef__';
  902:     }
  903:     if (!defined($time) ) {
  904: 	$time=600;
  905:     }
  906:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  907:     $memcache->set($id,$setvalue,$time);
  908:     # need to make a copy of $value
  909:     #&make_room($id,$value,$debug);
  910:     return $value;
  911: }
  912: 
  913: sub make_room {
  914:     my ($id,$value,$debug)=@_;
  915:     $remembered{$id}=$value;
  916:     if ($to_remember<0) { return; }
  917:     $accessed{$id}=[&gettimeofday()];
  918:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
  919:     my $to_kick;
  920:     my $max_time=0;
  921:     foreach my $other (keys(%accessed)) {
  922: 	if (&tv_interval($accessed{$other}) > $max_time) {
  923: 	    $to_kick=$other;
  924: 	    $max_time=&tv_interval($accessed{$other});
  925: 	}
  926:     }
  927:     delete($remembered{$to_kick});
  928:     delete($accessed{$to_kick});
  929:     $kicks++;
  930:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
  931:     return;
  932: }
  933: 
  934: sub purge_remembered {
  935:     #&logthis("Tossing ".scalar(keys(%remembered)));
  936:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
  937:     undef(%remembered);
  938:     undef(%accessed);
  939: }
  940: # ------------------------------------- Read an entry from a user's environment
  941: 
  942: sub userenvironment {
  943:     my ($udom,$unam,@what)=@_;
  944:     my %returnhash=();
  945:     my @answer=split(/\&/,
  946:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  947:                       &homeserver($unam,$udom)));
  948:     my $i;
  949:     for ($i=0;$i<=$#what;$i++) {
  950: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  951:     }
  952:     return %returnhash;
  953: }
  954: 
  955: # ---------------------------------------------------------- Get a studentphoto
  956: sub studentphoto {
  957:     my ($udom,$unam,$ext) = @_;
  958:     my $home=&Apache::lonnet::homeserver($unam,$udom);
  959:     if (defined($env{'request.course.id'})) {
  960:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
  961:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
  962:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
  963:             } else {
  964:                 my ($result,$perm_reqd)=
  965: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
  966:                 if ($result eq 'ok') {
  967:                     if (!($perm_reqd eq 'yes')) {
  968:                         return(&retrievestudentphoto($udom,$unam,$ext));
  969:                     }
  970:                 }
  971:             }
  972:         }
  973:     } else {
  974:         my ($result,$perm_reqd) = 
  975: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
  976:         if ($result eq 'ok') {
  977:             if (!($perm_reqd eq 'yes')) {
  978:                 return(&retrievestudentphoto($udom,$unam,$ext));
  979:             }
  980:         }
  981:     }
  982:     return '/adm/lonKaputt/lonlogo_broken.gif';
  983: }
  984: 
  985: sub retrievestudentphoto {
  986:     my ($udom,$unam,$ext,$type) = @_;
  987:     my $home=&Apache::lonnet::homeserver($unam,$udom);
  988:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
  989:     if ($ret eq 'ok') {
  990:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
  991:         if ($type eq 'thumbnail') {
  992:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
  993:         }
  994:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
  995:         return $tokenurl;
  996:     } else {
  997:         if ($type eq 'thumbnail') {
  998:             return '/adm/lonKaputt/genericstudent_tn.gif';
  999:         } else { 
 1000:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1001:         }
 1002:     }
 1003: }
 1004: 
 1005: # -------------------------------------------------------------------- New chat
 1006: 
 1007: sub chatsend {
 1008:     my ($newentry,$anon,$group)=@_;
 1009:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1010:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1011:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1012:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1013: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1014: 		   &escape($newentry)).':'.$group,$chome);
 1015: }
 1016: 
 1017: # ------------------------------------------ Find current version of a resource
 1018: 
 1019: sub getversion {
 1020:     my $fname=&clutter(shift);
 1021:     unless ($fname=~/^\/res\//) { return -1; }
 1022:     return &currentversion(&filelocation('',$fname));
 1023: }
 1024: 
 1025: sub currentversion {
 1026:     my $fname=shift;
 1027:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1028:     if (defined($cached)) { return $result; }
 1029:     my $author=$fname;
 1030:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1031:     my ($udom,$uname)=split(/\//,$author);
 1032:     my $home=homeserver($uname,$udom);
 1033:     if ($home eq 'no_host') { 
 1034:         return -1; 
 1035:     }
 1036:     my $answer=reply("currentversion:$fname",$home);
 1037:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1038: 	return -1;
 1039:     }
 1040:     return &do_cache_new('resversion',$fname,$answer,600);
 1041: }
 1042: 
 1043: # ----------------------------- Subscribe to a resource, return URL if possible
 1044: 
 1045: sub subscribe {
 1046:     my $fname=shift;
 1047:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1048:     $fname=~s/[\n\r]//g;
 1049:     my $author=$fname;
 1050:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1051:     my ($udom,$uname)=split(/\//,$author);
 1052:     my $home=homeserver($uname,$udom);
 1053:     if ($home eq 'no_host') {
 1054:         return 'not_found';
 1055:     }
 1056:     my $answer=reply("sub:$fname",$home);
 1057:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1058: 	$answer.=' by '.$home;
 1059:     }
 1060:     return $answer;
 1061: }
 1062:     
 1063: # -------------------------------------------------------------- Replicate file
 1064: 
 1065: sub repcopy {
 1066:     my $filename=shift;
 1067:     $filename=~s/\/+/\//g;
 1068:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1069:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1070:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1071: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1072: 	return &repcopy_userfile($filename);
 1073:     }
 1074:     $filename=~s/[\n\r]//g;
 1075:     my $transname="$filename.in.transfer";
 1076:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1077:     my $remoteurl=subscribe($filename);
 1078:     if ($remoteurl =~ /^con_lost by/) {
 1079: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1080:            return 'unavailable';
 1081:     } elsif ($remoteurl eq 'not_found') {
 1082: 	   #&logthis("Subscribe returned not_found: $filename");
 1083: 	   return 'not_found';
 1084:     } elsif ($remoteurl =~ /^rejected by/) {
 1085: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1086:            return 'forbidden';
 1087:     } elsif ($remoteurl eq 'directory') {
 1088:            return 'ok';
 1089:     } else {
 1090:         my $author=$filename;
 1091:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1092:         my ($udom,$uname)=split(/\//,$author);
 1093:         my $home=homeserver($uname,$udom);
 1094:         unless ($home eq $perlvar{'lonHostID'}) {
 1095:            my @parts=split(/\//,$filename);
 1096:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1097:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1098:                &logthis("Malconfiguration for replication: $filename");
 1099: 	       return 'bad_request';
 1100:            }
 1101:            my $count;
 1102:            for ($count=5;$count<$#parts;$count++) {
 1103:                $path.="/$parts[$count]";
 1104:                if ((-e $path)!=1) {
 1105: 		   mkdir($path,0777);
 1106:                }
 1107:            }
 1108:            my $ua=new LWP::UserAgent;
 1109:            my $request=new HTTP::Request('GET',"$remoteurl");
 1110:            my $response=$ua->request($request,$transname);
 1111:            if ($response->is_error()) {
 1112: 	       unlink($transname);
 1113:                my $message=$response->status_line;
 1114:                &logthis("<font color=\"blue\">WARNING:"
 1115:                        ." LWP get: $message: $filename</font>");
 1116:                return 'unavailable';
 1117:            } else {
 1118: 	       if ($remoteurl!~/\.meta$/) {
 1119:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1120:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1121:                   if ($mresponse->is_error()) {
 1122: 		      unlink($filename.'.meta');
 1123:                       &logthis(
 1124:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1125:                   }
 1126: 	       }
 1127:                rename($transname,$filename);
 1128:                return 'ok';
 1129:            }
 1130:        }
 1131:     }
 1132: }
 1133: 
 1134: # ------------------------------------------------ Get server side include body
 1135: sub ssi_body {
 1136:     my ($filelink,%form)=@_;
 1137:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1138:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1139:     }
 1140:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1141:                                      &ssi($filelink,%form));
 1142:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
 1143:     $output=~s/^.*?\<body[^\>]*\>//si;
 1144:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1145:     return $output;
 1146: }
 1147: 
 1148: # --------------------------------------------------------- Server Side Include
 1149: 
 1150: sub ssi {
 1151: 
 1152:     my ($fn,%form)=@_;
 1153: 
 1154:     my $ua=new LWP::UserAgent;
 1155:     
 1156:     my $request;
 1157: 
 1158:     $form{'no_update_last_known'}=1;
 1159: 
 1160:     if (%form) {
 1161:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
 1162:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1163:     } else {
 1164:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
 1165:     }
 1166: 
 1167:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1168:     my $response=$ua->request($request);
 1169: 
 1170:     return $response->content;
 1171: }
 1172: 
 1173: sub externalssi {
 1174:     my ($url)=@_;
 1175:     my $ua=new LWP::UserAgent;
 1176:     my $request=new HTTP::Request('GET',$url);
 1177:     my $response=$ua->request($request);
 1178:     return $response->content;
 1179: }
 1180: 
 1181: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1182: 
 1183: sub allowuploaded {
 1184:     my ($srcurl,$url)=@_;
 1185:     $url=&clutter(&declutter($url));
 1186:     my $dir=$url;
 1187:     $dir=~s/\/[^\/]+$//;
 1188:     my %httpref=();
 1189:     my $httpurl=&hreflocation('',$url);
 1190:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1191:     &Apache::lonnet::appenv(%httpref);
 1192: }
 1193: 
 1194: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1195: # input: action, courseID, current domain, intended
 1196: #        path to file, source of file, instruction to parse file for objects,
 1197: #        ref to hash for embedded objects,
 1198: #        ref to hash for codebase of java objects.
 1199: #
 1200: # output: url to file (if action was uploaddoc), 
 1201: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1202: #
 1203: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1204: # course.
 1205: #
 1206: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1207: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1208: #          course's home server.
 1209: #
 1210: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1211: #          be copied from $source (current location) to 
 1212: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1213: #         and will then be copied to
 1214: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1215: #         course's home server.
 1216: #
 1217: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1218: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1219: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1220: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1221: #         in course's home server.
 1222: #
 1223: 
 1224: sub process_coursefile {
 1225:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1226:     my $fetchresult;
 1227:     my $home=&homeserver($docuname,$docudom);
 1228:     if ($action eq 'propagate') {
 1229:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1230: 			     $home);
 1231:     } else {
 1232:         my $fpath = '';
 1233:         my $fname = $file;
 1234:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1235:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1236:         my $filepath = &build_filepath($fpath);
 1237:         if ($action eq 'copy') {
 1238:             if ($source eq '') {
 1239:                 $fetchresult = 'no source file';
 1240:                 return $fetchresult;
 1241:             } else {
 1242:                 my $destination = $filepath.'/'.$fname;
 1243:                 rename($source,$destination);
 1244:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1245:                                  $home);
 1246:             }
 1247:         } elsif ($action eq 'uploaddoc') {
 1248:             open(my $fh,'>'.$filepath.'/'.$fname);
 1249:             print $fh $env{'form.'.$source};
 1250:             close($fh);
 1251:             if ($parser eq 'parse') {
 1252:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1253:                 unless ($parse_result eq 'ok') {
 1254:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1255:                 }
 1256:             }
 1257:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1258:                                  $home);
 1259:             if ($fetchresult eq 'ok') {
 1260:                 return '/uploaded/'.$fpath.'/'.$fname;
 1261:             } else {
 1262:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1263:                         ' to host '.$home.': '.$fetchresult);
 1264:                 return '/adm/notfound.html';
 1265:             }
 1266:         }
 1267:     }
 1268:     unless ( $fetchresult eq 'ok') {
 1269:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1270:              ' to host '.$home.': '.$fetchresult);
 1271:     }
 1272:     return $fetchresult;
 1273: }
 1274: 
 1275: sub build_filepath {
 1276:     my ($fpath) = @_;
 1277:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1278:     unless ($fpath eq '') {
 1279:         my @parts=split('/',$fpath);
 1280:         foreach my $part (@parts) {
 1281:             $filepath.= '/'.$part;
 1282:             if ((-e $filepath)!=1) {
 1283:                 mkdir($filepath,0777);
 1284:             }
 1285:         }
 1286:     }
 1287:     return $filepath;
 1288: }
 1289: 
 1290: sub store_edited_file {
 1291:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1292:     my $file = $primary_url;
 1293:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1294:     my $fpath = '';
 1295:     my $fname = $file;
 1296:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1297:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1298:     my $filepath = &build_filepath($fpath);
 1299:     open(my $fh,'>'.$filepath.'/'.$fname);
 1300:     print $fh $content;
 1301:     close($fh);
 1302:     my $home=&homeserver($docuname,$docudom);
 1303:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1304: 			  $home);
 1305:     if ($$fetchresult eq 'ok') {
 1306:         return '/uploaded/'.$fpath.'/'.$fname;
 1307:     } else {
 1308:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1309: 		 ' to host '.$home.': '.$$fetchresult);
 1310:         return '/adm/notfound.html';
 1311:     }
 1312: }
 1313: 
 1314: sub clean_filename {
 1315:     my ($fname)=@_;
 1316: # Replace Windows backslashes by forward slashes
 1317:     $fname=~s/\\/\//g;
 1318: # Get rid of everything but the actual filename
 1319:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1320: # Replace spaces by underscores
 1321:     $fname=~s/\s+/\_/g;
 1322: # Replace all other weird characters by nothing
 1323:     $fname=~s/[^\w\.\-]//g;
 1324: # Replace all .\d. sequences with _\d. so they no longer look like version
 1325: # numbers
 1326:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1327:     return $fname;
 1328: }
 1329: 
 1330: # --------------- Take an uploaded file and put it into the userfiles directory
 1331: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1332: #                    the desired filenam is in $env{"form.$formname.filename"}
 1333: #        $coursedoc - if true up to the current course
 1334: #                     if false
 1335: #        $subdir - directory in userfile to store the file into
 1336: #        $parser, $allfiles, $codebase - unknown
 1337: #
 1338: # output: url of file in userspace, or error: <message> 
 1339: #             or /adm/notfound.html if failure to upload occurse
 1340: 
 1341: 
 1342: sub userfileupload {
 1343:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1344:     if (!defined($subdir)) { $subdir='unknown'; }
 1345:     my $fname=$env{'form.'.$formname.'.filename'};
 1346:     $fname=&clean_filename($fname);
 1347: # See if there is anything left
 1348:     unless ($fname) { return 'error: no uploaded file'; }
 1349:     chop($env{'form.'.$formname});
 1350:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1351:         my $now = time;
 1352:         my $filepath = 'tmp/helprequests/'.$now;
 1353:         my @parts=split(/\//,$filepath);
 1354:         my $fullpath = $perlvar{'lonDaemons'};
 1355:         for (my $i=0;$i<@parts;$i++) {
 1356:             $fullpath .= '/'.$parts[$i];
 1357:             if ((-e $fullpath)!=1) {
 1358:                 mkdir($fullpath,0777);
 1359:             }
 1360:         }
 1361:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1362:         print $fh $env{'form.'.$formname};
 1363:         close($fh);
 1364:         return $fullpath.'/'.$fname; 
 1365:     }
 1366:     
 1367: # Create the directory if not present
 1368:     $fname="$subdir/$fname";
 1369:     if ($coursedoc) {
 1370: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1371: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1372:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1373:             return &finishuserfileupload($docuname,$docudom,
 1374: 					 $formname,$fname,$parser,$allfiles,
 1375: 					 $codebase);
 1376:         } else {
 1377:             $fname=$env{'form.folder'}.'/'.$fname;
 1378:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1379: 				       $fname,$formname,$parser,
 1380: 				       $allfiles,$codebase);
 1381:         }
 1382:     } elsif (defined($destuname)) {
 1383:         my $docuname=$destuname;
 1384:         my $docudom=$destudom;
 1385: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1386: 				     $fname,$parser,$allfiles,$codebase);
 1387:         
 1388:     } else {
 1389:         my $docuname=$env{'user.name'};
 1390:         my $docudom=$env{'user.domain'};
 1391:         if (exists($env{'form.group'})) {
 1392:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1393:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1394:         }
 1395: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1396: 				     $fname,$parser,$allfiles,$codebase);
 1397:     }
 1398: }
 1399: 
 1400: sub finishuserfileupload {
 1401:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1402:     my $path=$docudom.'/'.$docuname.'/';
 1403:     my $filepath=$perlvar{'lonDocRoot'};
 1404:     my ($fnamepath,$file);
 1405:     $file=$fname;
 1406:     if ($fname=~m|/|) {
 1407:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1408: 	$path.=$fnamepath.'/';
 1409:     }
 1410:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1411:     my $count;
 1412:     for ($count=4;$count<=$#parts;$count++) {
 1413:         $filepath.="/$parts[$count]";
 1414:         if ((-e $filepath)!=1) {
 1415: 	    mkdir($filepath,0777);
 1416:         }
 1417:     }
 1418: # Save the file
 1419:     {
 1420: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1421: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1422: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1423: 	    return '/adm/notfound.html';
 1424: 	}
 1425: 	if (!print FH ($env{'form.'.$formname})) {
 1426: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1427: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1428: 	    return '/adm/notfound.html';
 1429: 	}
 1430: 	close(FH);
 1431:     }
 1432:     if ($parser eq 'parse') {
 1433:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1434: 						   $codebase);
 1435:         unless ($parse_result eq 'ok') {
 1436:             &logthis('Failed to parse '.$filepath.$file.
 1437: 		     ' for embedded media: '.$parse_result); 
 1438:         }
 1439:     }
 1440: # Notify homeserver to grep it
 1441: #
 1442:     my $docuhome=&homeserver($docuname,$docudom);
 1443:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1444:     if ($fetchresult eq 'ok') {
 1445: #
 1446: # Return the URL to it
 1447:         return '/uploaded/'.$path.$file;
 1448:     } else {
 1449:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1450: 		 ': '.$fetchresult);
 1451:         return '/adm/notfound.html';
 1452:     }    
 1453: }
 1454: 
 1455: sub extract_embedded_items {
 1456:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1457:     my @state = ();
 1458:     my %javafiles = (
 1459:                       codebase => '',
 1460:                       code => '',
 1461:                       archive => ''
 1462:                     );
 1463:     my %mediafiles = (
 1464:                       src => '',
 1465:                       movie => '',
 1466:                      );
 1467:     my $p;
 1468:     if ($content) {
 1469:         $p = HTML::LCParser->new($content);
 1470:     } else {
 1471:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1472:     }
 1473:     while (my $t=$p->get_token()) {
 1474: 	if ($t->[0] eq 'S') {
 1475: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1476: 	    push (@state, $tagname);
 1477:             if (lc($tagname) eq 'allow') {
 1478:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1479:             }
 1480: 	    if (lc($tagname) eq 'img') {
 1481: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1482: 	    }
 1483:             if (lc($tagname) eq 'script') {
 1484:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1485:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1486:                 } else {
 1487:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1488:                 }
 1489:             }
 1490:             if (lc($tagname) eq 'link') {
 1491:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1492:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1493:                 }
 1494:             }
 1495: 	    if (lc($tagname) eq 'object' ||
 1496: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1497: 		foreach my $item (keys(%javafiles)) {
 1498: 		    $javafiles{$item} = '';
 1499: 		}
 1500: 	    }
 1501: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1502: 		my $name = lc($attr->{'name'});
 1503: 		foreach my $item (keys(%javafiles)) {
 1504: 		    if ($name eq $item) {
 1505: 			$javafiles{$item} = $attr->{'value'};
 1506: 			last;
 1507: 		    }
 1508: 		}
 1509: 		foreach my $item (keys(%mediafiles)) {
 1510: 		    if ($name eq $item) {
 1511: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1512: 			last;
 1513: 		    }
 1514: 		}
 1515: 	    }
 1516: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1517: 		foreach my $item (keys(%javafiles)) {
 1518: 		    if ($attr->{$item}) {
 1519: 			$javafiles{$item} = $attr->{$item};
 1520: 			last;
 1521: 		    }
 1522: 		}
 1523: 		foreach my $item (keys(%mediafiles)) {
 1524: 		    if ($attr->{$item}) {
 1525: 			&add_filetype($allfiles,$attr->{$item},$item);
 1526: 			last;
 1527: 		    }
 1528: 		}
 1529: 	    }
 1530: 	} elsif ($t->[0] eq 'E') {
 1531: 	    my ($tagname) = ($t->[1]);
 1532: 	    if ($javafiles{'codebase'} ne '') {
 1533: 		$javafiles{'codebase'} .= '/';
 1534: 	    }  
 1535: 	    if (lc($tagname) eq 'applet' ||
 1536: 		lc($tagname) eq 'object' ||
 1537: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1538: 		) {
 1539: 		foreach my $item (keys(%javafiles)) {
 1540: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1541: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1542: 			&add_filetype($allfiles,$file,$item);
 1543: 		    }
 1544: 		}
 1545: 	    } 
 1546: 	    pop @state;
 1547: 	}
 1548:     }
 1549:     return 'ok';
 1550: }
 1551: 
 1552: sub add_filetype {
 1553:     my ($allfiles,$file,$type)=@_;
 1554:     if (exists($allfiles->{$file})) {
 1555: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1556: 	    push(@{$allfiles->{$file}}, &escape($type));
 1557: 	}
 1558:     } else {
 1559: 	@{$allfiles->{$file}} = (&escape($type));
 1560:     }
 1561: }
 1562: 
 1563: sub removeuploadedurl {
 1564:     my ($url)=@_;
 1565:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1566:     return &removeuserfile($uname,$udom,$fname);
 1567: }
 1568: 
 1569: sub removeuserfile {
 1570:     my ($docuname,$docudom,$fname)=@_;
 1571:     my $home=&homeserver($docuname,$docudom);
 1572:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1573: }
 1574: 
 1575: sub mkdiruserfile {
 1576:     my ($docuname,$docudom,$dir)=@_;
 1577:     my $home=&homeserver($docuname,$docudom);
 1578:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1579: }
 1580: 
 1581: sub renameuserfile {
 1582:     my ($docuname,$docudom,$old,$new)=@_;
 1583:     my $home=&homeserver($docuname,$docudom);
 1584:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
 1585: 		  &escape("$new"),$home);
 1586: }
 1587: 
 1588: # ------------------------------------------------------------------------- Log
 1589: 
 1590: sub log {
 1591:     my ($dom,$nam,$hom,$what)=@_;
 1592:     return critical("log:$dom:$nam:$what",$hom);
 1593: }
 1594: 
 1595: # ------------------------------------------------------------------ Course Log
 1596: #
 1597: # This routine flushes several buffers of non-mission-critical nature
 1598: #
 1599: 
 1600: sub flushcourselogs {
 1601:     &logthis('Flushing log buffers');
 1602: #
 1603: # course logs
 1604: # This is a log of all transactions in a course, which can be used
 1605: # for data mining purposes
 1606: #
 1607: # It also collects the courseid database, which lists last transaction
 1608: # times and course titles for all courseids
 1609: #
 1610:     my %courseidbuffer=();
 1611:     foreach (keys %courselogs) {
 1612:         my $crsid=$_;
 1613:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1614: 		          &escape($courselogs{$crsid}),
 1615: 		          $coursehombuf{$crsid}) eq 'ok') {
 1616: 	    delete $courselogs{$crsid};
 1617:         } else {
 1618:             &logthis('Failed to flush log buffer for '.$crsid);
 1619:             if (length($courselogs{$crsid})>40000) {
 1620:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1621:                         " exceeded maximum size, deleting.</font>");
 1622:                delete $courselogs{$crsid};
 1623:             }
 1624:         }
 1625:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1626:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1627: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1628:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
 1629:         } else {
 1630:            $courseidbuffer{$coursehombuf{$crsid}}=
 1631: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1632:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
 1633:         }
 1634:     }
 1635: #
 1636: # Write course id database (reverse lookup) to homeserver of courses 
 1637: # Is used in pickcourse
 1638: #
 1639:     foreach (keys %courseidbuffer) {
 1640:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1641:     }
 1642: #
 1643: # File accesses
 1644: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1645: #
 1646:     foreach my $entry (keys(%accesshash)) {
 1647:         if ($entry =~ /___count$/) {
 1648:             my ($dom,$name);
 1649:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1650:             if (! defined($dom) || $dom eq '' || 
 1651:                 ! defined($name) || $name eq '') {
 1652:                 my $cid = $env{'request.course.id'};
 1653:                 $dom  = $env{'request.'.$cid.'.domain'};
 1654:                 $name = $env{'request.'.$cid.'.num'};
 1655:             }
 1656:             my $value = $accesshash{$entry};
 1657:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1658:             my %temphash=($url => $value);
 1659:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1660:             if ($result eq 'ok') {
 1661:                 delete $accesshash{$entry};
 1662:             } elsif ($result eq 'unknown_cmd') {
 1663:                 # Target server has old code running on it.
 1664:                 my %temphash=($entry => $value);
 1665:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1666:                     delete $accesshash{$entry};
 1667:                 }
 1668:             }
 1669:         } else {
 1670:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1671:             my %temphash=($entry => $accesshash{$entry});
 1672:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1673:                 delete $accesshash{$entry};
 1674:             }
 1675:         }
 1676:     }
 1677: #
 1678: # Roles
 1679: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1680: #
 1681:     foreach (keys %userrolehash) {
 1682:         my $entry=$_;
 1683:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1684: 	    split(/\:/,$entry);
 1685:         if (&Apache::lonnet::put('nohist_userroles',
 1686:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1687:                 $rudom,$runame) eq 'ok') {
 1688: 	    delete $userrolehash{$entry};
 1689:         }
 1690:     }
 1691: #
 1692: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1693: #
 1694:     my %domrolebuffer = ();
 1695:     foreach my $entry (keys %domainrolehash) {
 1696:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1697:         if ($domrolebuffer{$rudom}) {
 1698:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1699:                       '='.&escape($domainrolehash{$entry});
 1700:         } else {
 1701:             $domrolebuffer{$rudom}.=&escape($entry).
 1702:                       '='.&escape($domainrolehash{$entry});
 1703:         }
 1704:         delete $domainrolehash{$entry};
 1705:     }
 1706:     foreach my $dom (keys(%domrolebuffer)) {
 1707:         foreach my $tryserver (keys %libserv) {
 1708:             if ($hostdom{$tryserver} eq $dom) {
 1709:                 unless (&reply('domroleput:'.$dom.':'.
 1710:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1711:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1712:                 }
 1713:             }
 1714:         }
 1715:     }
 1716:     $dumpcount++;
 1717: }
 1718: 
 1719: sub courselog {
 1720:     my $what=shift;
 1721:     $what=time.':'.$what;
 1722:     unless ($env{'request.course.id'}) { return ''; }
 1723:     $coursedombuf{$env{'request.course.id'}}=
 1724:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1725:     $coursenumbuf{$env{'request.course.id'}}=
 1726:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1727:     $coursehombuf{$env{'request.course.id'}}=
 1728:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1729:     $coursedescrbuf{$env{'request.course.id'}}=
 1730:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1731:     $courseinstcodebuf{$env{'request.course.id'}}=
 1732:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1733:     $courseownerbuf{$env{'request.course.id'}}=
 1734:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1735:     if (defined $courselogs{$env{'request.course.id'}}) {
 1736: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1737:     } else {
 1738: 	$courselogs{$env{'request.course.id'}}.=$what;
 1739:     }
 1740:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1741: 	&flushcourselogs();
 1742:     }
 1743: }
 1744: 
 1745: sub courseacclog {
 1746:     my $fnsymb=shift;
 1747:     unless ($env{'request.course.id'}) { return ''; }
 1748:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1749:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1750:         $what.=':POST';
 1751:         # FIXME: Probably ought to escape things....
 1752: 	foreach (keys %env) {
 1753:             if ($_=~/^form\.(.*)/) {
 1754: 		$what.=':'.$1.'='.$env{$_};
 1755:             }
 1756:         }
 1757:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1758:         # FIXME: We should not be depending on a form parameter that someone
 1759:         # editing lonsearchcat.pm might change in the future.
 1760:         if ($env{'form.phase'} eq 'course_search') {
 1761:             $what.= ':POST';
 1762:             # FIXME: Probably ought to escape things....
 1763:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1764:                                  'crsdiscuss') {
 1765:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1766:             }
 1767:         }
 1768:     }
 1769:     &courselog($what);
 1770: }
 1771: 
 1772: sub countacc {
 1773:     my $url=&declutter(shift);
 1774:     return if (! defined($url) || $url eq '');
 1775:     unless ($env{'request.course.id'}) { return ''; }
 1776:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1777:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1778:     $accesshash{$key}++;
 1779: }
 1780: 
 1781: sub linklog {
 1782:     my ($from,$to)=@_;
 1783:     $from=&declutter($from);
 1784:     $to=&declutter($to);
 1785:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1786:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1787: }
 1788:   
 1789: sub userrolelog {
 1790:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1791:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1792:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1793:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1794:         ($trole=~/^ta/)) {
 1795:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1796:        $userrolehash
 1797:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1798:                     =$tend.':'.$tstart;
 1799:     }
 1800:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1801:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1802:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1803:         ($trole=~/^sc/)) {
 1804:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1805:        $domainrolehash
 1806:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1807:                     = $tend.':'.$tstart;
 1808:     }
 1809: }
 1810: 
 1811: sub get_course_adv_roles {
 1812:     my $cid=shift;
 1813:     $cid=$env{'request.course.id'} unless (defined($cid));
 1814:     my %coursehash=&coursedescription($cid);
 1815:     my %nothide=();
 1816:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1817: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
 1818:     }
 1819:     my %returnhash=();
 1820:     my %dumphash=
 1821:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1822:     my $now=time;
 1823:     foreach (keys %dumphash) {
 1824: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1825:         if (($tstart) && ($tstart<0)) { next; }
 1826:         if (($tend) && ($tend<$now)) { next; }
 1827:         if (($tstart) && ($now<$tstart)) { next; }
 1828:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1829: 	if ($username eq '' || $domain eq '') { next; }
 1830: 	if ((&privileged($username,$domain)) && 
 1831: 	    (!$nothide{$username.':'.$domain})) { next; }
 1832: 	if ($role eq 'cr') { next; }
 1833:         my $key=&plaintext($role);
 1834: 	if ($role =~ /^cr/) {
 1835: 	    $key=(split('/',$role))[3];
 1836: 	}
 1837:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1838:         if ($returnhash{$key}) {
 1839: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1840:         } else {
 1841:             $returnhash{$key}=$username.':'.$domain;
 1842:         }
 1843:      }
 1844:     return %returnhash;
 1845: }
 1846: 
 1847: sub get_my_roles {
 1848:     my ($uname,$udom)=@_;
 1849:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1850:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1851:     my %dumphash=
 1852:             &dump('nohist_userroles',$udom,$uname);
 1853:     my %returnhash=();
 1854:     my $now=time;
 1855:     foreach (keys %dumphash) {
 1856: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1857:         if (($tstart) && ($tstart<0)) { next; }
 1858:         if (($tend) && ($tend<$now)) { next; }
 1859:         if (($tstart) && ($now<$tstart)) { next; }
 1860:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1861: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1862:      }
 1863:     return %returnhash;
 1864: }
 1865: 
 1866: # ----------------------------------------------------- Frontpage Announcements
 1867: #
 1868: #
 1869: 
 1870: sub postannounce {
 1871:     my ($server,$text)=@_;
 1872:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1873:     unless ($text=~/\w/) { $text=''; }
 1874:     return &reply('setannounce:'.&escape($text),$server);
 1875: }
 1876: 
 1877: sub getannounce {
 1878: 
 1879:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1880: 	my $announcement='';
 1881: 	while (<$fh>) { $announcement .=$_; }
 1882: 	close($fh);
 1883: 	if ($announcement=~/\w/) { 
 1884: 	    return 
 1885:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1886:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1887: 	} else {
 1888: 	    return '';
 1889: 	}
 1890:     } else {
 1891: 	return '';
 1892:     }
 1893: }
 1894: 
 1895: # ---------------------------------------------------------- Course ID routines
 1896: # Deal with domain's nohist_courseid.db files
 1897: #
 1898: 
 1899: sub courseidput {
 1900:     my ($domain,$what,$coursehome)=@_;
 1901:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1902: }
 1903: 
 1904: sub courseiddump {
 1905:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
 1906:     my %returnhash=();
 1907:     unless ($domfilter) { $domfilter=''; }
 1908:     foreach my $tryserver (keys %libserv) {
 1909:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1910: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1911: 	        foreach (
 1912:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1913: 			       $sincefilter.':'.&escape($descfilter).':'.
 1914:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
 1915:                                $tryserver))) {
 1916: 		    my ($key,$value)=split(/\=/,$_);
 1917:                     if (($key) && ($value)) {
 1918: 		        $returnhash{&unescape($key)}=$value;
 1919:                     }
 1920:                 }
 1921:             }
 1922:         }
 1923:     }
 1924:     return %returnhash;
 1925: }
 1926: 
 1927: # ---------------------------------------------------------- DC e-mail
 1928: 
 1929: sub dcmailput {
 1930:     my ($domain,$msgid,$message,$server)=@_;
 1931:     my $status = &Apache::lonnet::critical(
 1932:        'dcmailput:'.$domain.':'.&Apache::lonnet::escape($msgid).'='.
 1933:        &Apache::lonnet::escape($message),$server);
 1934:     return $status;
 1935: }
 1936: 
 1937: sub dcmaildump {
 1938:     my ($dom,$startdate,$enddate,$senders) = @_;
 1939:     my %returnhash=();
 1940:     if (exists($domain_primary{$dom})) {
 1941:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 1942:                                                          &escape($enddate).':';
 1943: 	my @esc_senders=map { &escape($_)} @$senders;
 1944: 	$cmd.=&escape(join('&',@esc_senders));
 1945: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 1946:             my ($key,$value) = split(/\=/,$_);
 1947:             if (($key) && ($value)) {
 1948:                 $returnhash{&unescape($key)} = &unescape($value);
 1949:             }
 1950:         }
 1951:     }
 1952:     return %returnhash;
 1953: }
 1954: # ---------------------------------------------------------- Domain roles
 1955: 
 1956: sub get_domain_roles {
 1957:     my ($dom,$roles,$startdate,$enddate)=@_;
 1958:     if (undef($startdate) || $startdate eq '') {
 1959:         $startdate = '.';
 1960:     }
 1961:     if (undef($enddate) || $enddate eq '') {
 1962:         $enddate = '.';
 1963:     }
 1964:     my $rolelist = join(':',@{$roles});
 1965:     my %personnel = ();
 1966:     foreach my $tryserver (keys(%libserv)) {
 1967:         if ($hostdom{$tryserver} eq $dom) {
 1968:             %{$personnel{$tryserver}}=();
 1969:             foreach (
 1970:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 1971:                    &escape($startdate).':'.&escape($enddate).':'.
 1972:                    &escape($rolelist), $tryserver))) {
 1973:                 my($key,$value) = split(/\=/,$_);
 1974:                 if (($key) && ($value)) {
 1975:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 1976:                 }
 1977:             }
 1978:         }
 1979:     }
 1980:     return %personnel;
 1981: }
 1982: 
 1983: # ----------------------------------------------------------- Check out an item
 1984: 
 1985: sub get_first_access {
 1986:     my ($type,$argsymb)=@_;
 1987:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 1988:     if ($argsymb) { $symb=$argsymb; }
 1989:     my ($map,$id,$res)=&decode_symb($symb);
 1990:     if ($type eq 'map') {
 1991: 	$res=&symbread($map);
 1992:     } else {
 1993: 	$res=$symb;
 1994:     }
 1995:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 1996:     return $times{"$courseid\0$res"};
 1997: }
 1998: 
 1999: sub set_first_access {
 2000:     my ($type)=@_;
 2001:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2002:     my ($map,$id,$res)=&decode_symb($symb);
 2003:     if ($type eq 'map') {
 2004: 	$res=&symbread($map);
 2005:     } else {
 2006: 	$res=$symb;
 2007:     }
 2008:     my $firstaccess=&get_first_access($type,$symb);
 2009:     if (!$firstaccess) {
 2010: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2011:     }
 2012:     return 'already_set';
 2013: }
 2014: 
 2015: sub checkout {
 2016:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2017:     my $now=time;
 2018:     my $lonhost=$perlvar{'lonHostID'};
 2019:     my $infostr=&escape(
 2020:                  'CHECKOUTTOKEN&'.
 2021:                  $tuname.'&'.
 2022:                  $tudom.'&'.
 2023:                  $tcrsid.'&'.
 2024:                  $symb.'&'.
 2025: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2026:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2027:     if ($token=~/^error\:/) { 
 2028:         &logthis("<font color=\"blue\">WARNING: ".
 2029:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2030:                  "</font>");
 2031:         return ''; 
 2032:     }
 2033: 
 2034:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2035:     $token=~tr/a-z/A-Z/;
 2036: 
 2037:     my %infohash=('resource.0.outtoken' => $token,
 2038:                   'resource.0.checkouttime' => $now,
 2039:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2040: 
 2041:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2042:        return '';
 2043:     } else {
 2044:         &logthis("<font color=\"blue\">WARNING: ".
 2045:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2046:                  "</font>");
 2047:     }    
 2048: 
 2049:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2050:                          &escape('Checkout '.$infostr.' - '.
 2051:                                                  $token)) ne 'ok') {
 2052: 	return '';
 2053:     } else {
 2054:         &logthis("<font color=\"blue\">WARNING: ".
 2055:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2056:                  "</font>");
 2057:     }
 2058:     return $token;
 2059: }
 2060: 
 2061: # ------------------------------------------------------------ Check in an item
 2062: 
 2063: sub checkin {
 2064:     my $token=shift;
 2065:     my $now=time;
 2066:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2067:     $lonhost=~tr/A-Z/a-z/;
 2068:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2069:     $dtoken=~s/\W/\_/g;
 2070:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2071:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2072: 
 2073:     unless (($tuname) && ($tudom)) {
 2074:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2075:         return '';
 2076:     }
 2077:     
 2078:     unless (&allowed('mgr',$tcrsid)) {
 2079:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2080:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2081:         return '';
 2082:     }
 2083: 
 2084:     my %infohash=('resource.0.intoken' => $token,
 2085:                   'resource.0.checkintime' => $now,
 2086:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2087: 
 2088:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2089:        return '';
 2090:     }    
 2091: 
 2092:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2093:                          &escape('Checkin - '.$token)) ne 'ok') {
 2094: 	return '';
 2095:     }
 2096: 
 2097:     return ($symb,$tuname,$tudom,$tcrsid);    
 2098: }
 2099: 
 2100: # --------------------------------------------- Set Expire Date for Spreadsheet
 2101: 
 2102: sub expirespread {
 2103:     my ($uname,$udom,$stype,$usymb)=@_;
 2104:     my $cid=$env{'request.course.id'}; 
 2105:     if ($cid) {
 2106:        my $now=time;
 2107:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2108:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2109:                             $env{'course.'.$cid.'.num'}.
 2110: 	        	    ':nohist_expirationdates:'.
 2111:                             &escape($key).'='.$now,
 2112:                             $env{'course.'.$cid.'.home'})
 2113:     }
 2114:     return 'ok';
 2115: }
 2116: 
 2117: # ----------------------------------------------------- Devalidate Spreadsheets
 2118: 
 2119: sub devalidate {
 2120:     my ($symb,$uname,$udom)=@_;
 2121:     my $cid=$env{'request.course.id'}; 
 2122:     if ($cid) {
 2123:         # delete the stored spreadsheets for
 2124:         # - the student level sheet of this user in course's homespace
 2125:         # - the assessment level sheet for this resource 
 2126:         #   for this user in user's homespace
 2127: 	# - current conditional state info
 2128: 	my $key=$uname.':'.$udom.':';
 2129:         my $status=
 2130: 	    &del('nohist_calculatedsheets',
 2131: 		 [$key.'studentcalc:'],
 2132: 		 $env{'course.'.$cid.'.domain'},
 2133: 		 $env{'course.'.$cid.'.num'})
 2134: 		.' '.
 2135: 	    &del('nohist_calculatedsheets_'.$cid,
 2136: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2137:         unless ($status eq 'ok ok') {
 2138:            &logthis('Could not devalidate spreadsheet '.
 2139:                     $uname.' at '.$udom.' for '.
 2140: 		    $symb.': '.$status);
 2141:         }
 2142: 	&delenv('user.state.'.$cid);
 2143:     }
 2144: }
 2145: 
 2146: sub get_scalar {
 2147:     my ($string,$end) = @_;
 2148:     my $value;
 2149:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2150: 	$value = $1;
 2151:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2152: 	$value = $1;
 2153:     }
 2154:     return &unescape($value);
 2155: }
 2156: 
 2157: sub array2str {
 2158:   my (@array) = @_;
 2159:   my $result=&arrayref2str(\@array);
 2160:   $result=~s/^__ARRAY_REF__//;
 2161:   $result=~s/__END_ARRAY_REF__$//;
 2162:   return $result;
 2163: }
 2164: 
 2165: sub arrayref2str {
 2166:   my ($arrayref) = @_;
 2167:   my $result='__ARRAY_REF__';
 2168:   foreach my $elem (@$arrayref) {
 2169:     if(ref($elem) eq 'ARRAY') {
 2170:       $result.=&arrayref2str($elem).'&';
 2171:     } elsif(ref($elem) eq 'HASH') {
 2172:       $result.=&hashref2str($elem).'&';
 2173:     } elsif(ref($elem)) {
 2174:       #print("Got a ref of ".(ref($elem))." skipping.");
 2175:     } else {
 2176:       $result.=&escape($elem).'&';
 2177:     }
 2178:   }
 2179:   $result=~s/\&$//;
 2180:   $result .= '__END_ARRAY_REF__';
 2181:   return $result;
 2182: }
 2183: 
 2184: sub hash2str {
 2185:   my (%hash) = @_;
 2186:   my $result=&hashref2str(\%hash);
 2187:   $result=~s/^__HASH_REF__//;
 2188:   $result=~s/__END_HASH_REF__$//;
 2189:   return $result;
 2190: }
 2191: 
 2192: sub hashref2str {
 2193:   my ($hashref)=@_;
 2194:   my $result='__HASH_REF__';
 2195:   foreach (sort(keys(%$hashref))) {
 2196:     if (ref($_) eq 'ARRAY') {
 2197:       $result.=&arrayref2str($_).'=';
 2198:     } elsif (ref($_) eq 'HASH') {
 2199:       $result.=&hashref2str($_).'=';
 2200:     } elsif (ref($_)) {
 2201:       $result.='=';
 2202:       #print("Got a ref of ".(ref($_))." skipping.");
 2203:     } else {
 2204: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 2205:     }
 2206: 
 2207:     if(ref($hashref->{$_}) eq 'ARRAY') {
 2208:       $result.=&arrayref2str($hashref->{$_}).'&';
 2209:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 2210:       $result.=&hashref2str($hashref->{$_}).'&';
 2211:     } elsif(ref($hashref->{$_})) {
 2212:        $result.='&';
 2213:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 2214:     } else {
 2215:       $result.=&escape($hashref->{$_}).'&';
 2216:     }
 2217:   }
 2218:   $result=~s/\&$//;
 2219:   $result .= '__END_HASH_REF__';
 2220:   return $result;
 2221: }
 2222: 
 2223: sub str2hash {
 2224:     my ($string)=@_;
 2225:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2226:     return %$hash;
 2227: }
 2228: 
 2229: sub str2hashref {
 2230:   my ($string) = @_;
 2231: 
 2232:   my %hash;
 2233: 
 2234:   if($string !~ /^__HASH_REF__/) {
 2235:       if (! ($string eq '' || !defined($string))) {
 2236: 	  $hash{'error'}='Not hash reference';
 2237:       }
 2238:       return (\%hash, $string);
 2239:   }
 2240: 
 2241:   $string =~ s/^__HASH_REF__//;
 2242: 
 2243:   while($string !~ /^__END_HASH_REF__/) {
 2244:       #key
 2245:       my $key='';
 2246:       if($string =~ /^__HASH_REF__/) {
 2247:           ($key, $string)=&str2hashref($string);
 2248:           if(defined($key->{'error'})) {
 2249:               $hash{'error'}='Bad data';
 2250:               return (\%hash, $string);
 2251:           }
 2252:       } elsif($string =~ /^__ARRAY_REF__/) {
 2253:           ($key, $string)=&str2arrayref($string);
 2254:           if($key->[0] eq 'Array reference error') {
 2255:               $hash{'error'}='Bad data';
 2256:               return (\%hash, $string);
 2257:           }
 2258:       } else {
 2259:           $string =~ s/^(.*?)=//;
 2260: 	  $key=&unescape($1);
 2261:       }
 2262:       $string =~ s/^=//;
 2263: 
 2264:       #value
 2265:       my $value='';
 2266:       if($string =~ /^__HASH_REF__/) {
 2267:           ($value, $string)=&str2hashref($string);
 2268:           if(defined($value->{'error'})) {
 2269:               $hash{'error'}='Bad data';
 2270:               return (\%hash, $string);
 2271:           }
 2272:       } elsif($string =~ /^__ARRAY_REF__/) {
 2273:           ($value, $string)=&str2arrayref($string);
 2274:           if($value->[0] eq 'Array reference error') {
 2275:               $hash{'error'}='Bad data';
 2276:               return (\%hash, $string);
 2277:           }
 2278:       } else {
 2279: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2280:       }
 2281:       $string =~ s/^&//;
 2282: 
 2283:       $hash{$key}=$value;
 2284:   }
 2285: 
 2286:   $string =~ s/^__END_HASH_REF__//;
 2287: 
 2288:   return (\%hash, $string);
 2289: }
 2290: 
 2291: sub str2array {
 2292:     my ($string)=@_;
 2293:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2294:     return @$array;
 2295: }
 2296: 
 2297: sub str2arrayref {
 2298:   my ($string) = @_;
 2299:   my @array;
 2300: 
 2301:   if($string !~ /^__ARRAY_REF__/) {
 2302:       if (! ($string eq '' || !defined($string))) {
 2303: 	  $array[0]='Array reference error';
 2304:       }
 2305:       return (\@array, $string);
 2306:   }
 2307: 
 2308:   $string =~ s/^__ARRAY_REF__//;
 2309: 
 2310:   while($string !~ /^__END_ARRAY_REF__/) {
 2311:       my $value='';
 2312:       if($string =~ /^__HASH_REF__/) {
 2313:           ($value, $string)=&str2hashref($string);
 2314:           if(defined($value->{'error'})) {
 2315:               $array[0] ='Array reference error';
 2316:               return (\@array, $string);
 2317:           }
 2318:       } elsif($string =~ /^__ARRAY_REF__/) {
 2319:           ($value, $string)=&str2arrayref($string);
 2320:           if($value->[0] eq 'Array reference error') {
 2321:               $array[0] ='Array reference error';
 2322:               return (\@array, $string);
 2323:           }
 2324:       } else {
 2325: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2326:       }
 2327:       $string =~ s/^&//;
 2328: 
 2329:       push(@array, $value);
 2330:   }
 2331: 
 2332:   $string =~ s/^__END_ARRAY_REF__//;
 2333: 
 2334:   return (\@array, $string);
 2335: }
 2336: 
 2337: # -------------------------------------------------------------------Temp Store
 2338: 
 2339: sub tmpreset {
 2340:   my ($symb,$namespace,$domain,$stuname) = @_;
 2341:   if (!$symb) {
 2342:     $symb=&symbread();
 2343:     if (!$symb) { $symb= $env{'request.url'}; }
 2344:   }
 2345:   $symb=escape($symb);
 2346: 
 2347:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2348:   $namespace=~s/\//\_/g;
 2349:   $namespace=~s/\W//g;
 2350: 
 2351:   if (!$domain) { $domain=$env{'user.domain'}; }
 2352:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2353:   if ($domain eq 'public' && $stuname eq 'public') {
 2354:       $stuname=$ENV{'REMOTE_ADDR'};
 2355:   }
 2356:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2357:   my %hash;
 2358:   if (tie(%hash,'GDBM_File',
 2359: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2360: 	  &GDBM_WRCREAT(),0640)) {
 2361:     foreach my $key (keys %hash) {
 2362:       if ($key=~ /:$symb/) {
 2363: 	delete($hash{$key});
 2364:       }
 2365:     }
 2366:   }
 2367: }
 2368: 
 2369: sub tmpstore {
 2370:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2371: 
 2372:   if (!$symb) {
 2373:     $symb=&symbread();
 2374:     if (!$symb) { $symb= $env{'request.url'}; }
 2375:   }
 2376:   $symb=escape($symb);
 2377: 
 2378:   if (!$namespace) {
 2379:     # I don't think we would ever want to store this for a course.
 2380:     # it seems this will only be used if we don't have a course.
 2381:     #$namespace=$env{'request.course.id'};
 2382:     #if (!$namespace) {
 2383:       $namespace=$env{'request.state'};
 2384:     #}
 2385:   }
 2386:   $namespace=~s/\//\_/g;
 2387:   $namespace=~s/\W//g;
 2388:   if (!$domain) { $domain=$env{'user.domain'}; }
 2389:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2390:   if ($domain eq 'public' && $stuname eq 'public') {
 2391:       $stuname=$ENV{'REMOTE_ADDR'};
 2392:   }
 2393:   my $now=time;
 2394:   my %hash;
 2395:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2396:   if (tie(%hash,'GDBM_File',
 2397: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2398: 	  &GDBM_WRCREAT(),0640)) {
 2399:     $hash{"version:$symb"}++;
 2400:     my $version=$hash{"version:$symb"};
 2401:     my $allkeys=''; 
 2402:     foreach my $key (keys(%$storehash)) {
 2403:       $allkeys.=$key.':';
 2404:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2405:     }
 2406:     $hash{"$version:$symb:timestamp"}=$now;
 2407:     $allkeys.='timestamp';
 2408:     $hash{"$version:keys:$symb"}=$allkeys;
 2409:     if (untie(%hash)) {
 2410:       return 'ok';
 2411:     } else {
 2412:       return "error:$!";
 2413:     }
 2414:   } else {
 2415:     return "error:$!";
 2416:   }
 2417: }
 2418: 
 2419: # -----------------------------------------------------------------Temp Restore
 2420: 
 2421: sub tmprestore {
 2422:   my ($symb,$namespace,$domain,$stuname) = @_;
 2423: 
 2424:   if (!$symb) {
 2425:     $symb=&symbread();
 2426:     if (!$symb) { $symb= $env{'request.url'}; }
 2427:   }
 2428:   $symb=escape($symb);
 2429: 
 2430:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2431: 
 2432:   if (!$domain) { $domain=$env{'user.domain'}; }
 2433:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2434:   if ($domain eq 'public' && $stuname eq 'public') {
 2435:       $stuname=$ENV{'REMOTE_ADDR'};
 2436:   }
 2437:   my %returnhash;
 2438:   $namespace=~s/\//\_/g;
 2439:   $namespace=~s/\W//g;
 2440:   my %hash;
 2441:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2442:   if (tie(%hash,'GDBM_File',
 2443: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2444: 	  &GDBM_READER(),0640)) {
 2445:     my $version=$hash{"version:$symb"};
 2446:     $returnhash{'version'}=$version;
 2447:     my $scope;
 2448:     for ($scope=1;$scope<=$version;$scope++) {
 2449:       my $vkeys=$hash{"$scope:keys:$symb"};
 2450:       my @keys=split(/:/,$vkeys);
 2451:       my $key;
 2452:       $returnhash{"$scope:keys"}=$vkeys;
 2453:       foreach $key (@keys) {
 2454: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2455: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2456:       }
 2457:     }
 2458:     if (!(untie(%hash))) {
 2459:       return "error:$!";
 2460:     }
 2461:   } else {
 2462:     return "error:$!";
 2463:   }
 2464:   return %returnhash;
 2465: }
 2466: 
 2467: # ----------------------------------------------------------------------- Store
 2468: 
 2469: sub store {
 2470:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2471:     my $home='';
 2472: 
 2473:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2474: 
 2475:     $symb=&symbclean($symb);
 2476:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2477: 
 2478:     if (!$domain) { $domain=$env{'user.domain'}; }
 2479:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2480: 
 2481:     &devalidate($symb,$stuname,$domain);
 2482: 
 2483:     $symb=escape($symb);
 2484:     if (!$namespace) { 
 2485:        unless ($namespace=$env{'request.course.id'}) { 
 2486:           return ''; 
 2487:        } 
 2488:     }
 2489:     if (!$home) { $home=$env{'user.home'}; }
 2490: 
 2491:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2492:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2493: 
 2494:     my $namevalue='';
 2495:     foreach (keys %$storehash) {
 2496:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2497:     }
 2498:     $namevalue=~s/\&$//;
 2499:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2500:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2501: }
 2502: 
 2503: # -------------------------------------------------------------- Critical Store
 2504: 
 2505: sub cstore {
 2506:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2507:     my $home='';
 2508: 
 2509:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2510: 
 2511:     $symb=&symbclean($symb);
 2512:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2513: 
 2514:     if (!$domain) { $domain=$env{'user.domain'}; }
 2515:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2516: 
 2517:     &devalidate($symb,$stuname,$domain);
 2518: 
 2519:     $symb=escape($symb);
 2520:     if (!$namespace) { 
 2521:        unless ($namespace=$env{'request.course.id'}) { 
 2522:           return ''; 
 2523:        } 
 2524:     }
 2525:     if (!$home) { $home=$env{'user.home'}; }
 2526: 
 2527:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2528:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2529: 
 2530:     my $namevalue='';
 2531:     foreach (keys %$storehash) {
 2532:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2533:     }
 2534:     $namevalue=~s/\&$//;
 2535:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2536:     return critical
 2537:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2538: }
 2539: 
 2540: # --------------------------------------------------------------------- Restore
 2541: 
 2542: sub restore {
 2543:     my ($symb,$namespace,$domain,$stuname) = @_;
 2544:     my $home='';
 2545: 
 2546:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2547: 
 2548:     if (!$symb) {
 2549:       unless ($symb=escape(&symbread())) { return ''; }
 2550:     } else {
 2551:       $symb=&escape(&symbclean($symb));
 2552:     }
 2553:     if (!$namespace) { 
 2554:        unless ($namespace=$env{'request.course.id'}) { 
 2555:           return ''; 
 2556:        } 
 2557:     }
 2558:     if (!$domain) { $domain=$env{'user.domain'}; }
 2559:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2560:     if (!$home) { $home=$env{'user.home'}; }
 2561:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2562: 
 2563:     my %returnhash=();
 2564:     foreach (split(/\&/,$answer)) {
 2565: 	my ($name,$value)=split(/\=/,$_);
 2566:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2567:     }
 2568:     my $version;
 2569:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2570:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2571:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2572:        }
 2573:     }
 2574:     return %returnhash;
 2575: }
 2576: 
 2577: # ---------------------------------------------------------- Course Description
 2578: 
 2579: sub coursedescription {
 2580:     my $courseid=shift;
 2581:     $courseid=~s/^\///;
 2582:     $courseid=~s/\_/\//g;
 2583:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2584:     my $chome=&homeserver($cnum,$cdomain);
 2585:     my $normalid=$cdomain.'_'.$cnum;
 2586:     # need to always cache even if we get errors otherwise we keep 
 2587:     # trying and trying and trying to get the course description.
 2588:     my %envhash=();
 2589:     my %returnhash=();
 2590:     $envhash{'course.'.$normalid.'.last_cache'}=time;
 2591:     if ($chome ne 'no_host') {
 2592:        %returnhash=&dump('environment',$cdomain,$cnum);
 2593:        if (!exists($returnhash{'con_lost'})) {
 2594:            $returnhash{'home'}= $chome;
 2595: 	   $returnhash{'domain'} = $cdomain;
 2596: 	   $returnhash{'num'} = $cnum;
 2597:            while (my ($name,$value) = each %returnhash) {
 2598:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2599:            }
 2600:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2601:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2602: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2603:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2604:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2605:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2606:        }
 2607:     }
 2608:     &appenv(%envhash);
 2609:     return %returnhash;
 2610: }
 2611: 
 2612: # -------------------------------------------------See if a user is privileged
 2613: 
 2614: sub privileged {
 2615:     my ($username,$domain)=@_;
 2616:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2617: 			&homeserver($username,$domain));
 2618:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2619:     my $now=time;
 2620:     if ($rolesdump ne '') {
 2621:         foreach (split(/&/,$rolesdump)) {
 2622: 	    if ($_!~/^rolesdef_/) {
 2623: 		my ($area,$role)=split(/=/,$_);
 2624: 		$area=~s/\_\w\w$//;
 2625: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2626: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2627: 		    my $active=1;
 2628: 		    if ($tend) {
 2629: 			if ($tend<$now) { $active=0; }
 2630: 		    }
 2631: 		    if ($tstart) {
 2632: 			if ($tstart>$now) { $active=0; }
 2633: 		    }
 2634: 		    if ($active) { return 1; }
 2635: 		}
 2636: 	    }
 2637: 	}
 2638:     }
 2639:     return 0;
 2640: }
 2641: 
 2642: # -------------------------------------------------------- Get user privileges
 2643: 
 2644: sub rolesinit {
 2645:     my ($domain,$username,$authhost)=@_;
 2646:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2647:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2648:     my %allroles=();
 2649:     my %allgroups=();   
 2650:     my $now=time;
 2651:     my $userroles="user.login.time=$now\n";
 2652:     my $group_privs;
 2653: 
 2654:     if ($rolesdump ne '') {
 2655:         foreach (split(/&/,$rolesdump)) {
 2656: 	  if ($_!~/^rolesdef_/) {
 2657:             my ($area,$role)=split(/=/,$_);
 2658: 	    $area=~s/\_\w\w$//;
 2659:             my ($trole,$tend,$tstart,$group_privs);
 2660: 	    if ($role=~/^cr/) { 
 2661: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2662: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2663: 		    ($tend,$tstart)=split('_',$trest);
 2664: 		} else {
 2665: 		    $trole=$role;
 2666: 		}
 2667:             } elsif ($role =~ m|^gr/|) {
 2668:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2669:                 ($trole,$group_privs) = split(/\//,$trole);
 2670:                 $group_privs = &unescape($group_privs);
 2671: 	    } else {
 2672: 		($trole,$tend,$tstart)=split(/_/,$role);
 2673: 	    }
 2674:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
 2675:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2676:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2677:             if (($area ne '') && ($trole ne '')) {
 2678: 		my $spec=$trole.'.'.$area;
 2679: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2680: 		if ($trole =~ /^cr\//) {
 2681:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2682:                 } elsif ($trole eq 'gr') {
 2683:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2684: 		} else {
 2685:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2686: 		}
 2687:             }
 2688:           }
 2689:         }
 2690:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles,\%allgroups);
 2691:         $userroles.='user.adv='.$adv."\n".
 2692: 	            'user.author='.$author."\n";
 2693:         $env{'user.adv'}=$adv;
 2694:     }
 2695:     return $userroles;  
 2696: }
 2697: 
 2698: sub set_arearole {
 2699:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2700: # log the associated role with the area
 2701:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2702:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
 2703: }
 2704: 
 2705: sub custom_roleprivs {
 2706:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2707:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2708:     my $homsvr=homeserver($rauthor,$rdomain);
 2709:     if ($hostname{$homsvr} ne '') {
 2710:         my ($rdummy,$roledef)=
 2711:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2712:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2713:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2714:             if (defined($syspriv)) {
 2715:                 $$allroles{'cm./'}.=':'.$syspriv;
 2716:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2717:             }
 2718:             if ($tdomain ne '') {
 2719:                 if (defined($dompriv)) {
 2720:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2721:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2722:                 }
 2723:                 if (($trest ne '') && (defined($coursepriv))) {
 2724:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2725:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2726:                 }
 2727:             }
 2728:         }
 2729:     }
 2730: }
 2731: 
 2732: sub group_roleprivs {
 2733:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2734:     my $access = 1;
 2735:     my $now = time;
 2736:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2737:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2738:     if ($access) {
 2739:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
 2740:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2741:     }
 2742: }
 2743: 
 2744: sub standard_roleprivs {
 2745:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2746:     if (defined($pr{$trole.':s'})) {
 2747:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2748:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2749:     }
 2750:     if ($tdomain ne '') {
 2751:         if (defined($pr{$trole.':d'})) {
 2752:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2753:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2754:         }
 2755:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2756:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2757:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2758:         }
 2759:     }
 2760: }
 2761: 
 2762: sub set_userprivs {
 2763:     my ($userroles,$allroles,$allgroups) = @_; 
 2764:     my $author=0;
 2765:     my $adv=0;
 2766:     my %grouproles = ();
 2767:     if (keys(%{$allgroups}) > 0) {
 2768:         foreach my $role (keys %{$allroles}) {
 2769:             my ($trole,$area,$sec,$extendedarea);
 2770:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
 2771:                 $trole = $1;
 2772:                 $area = $2;
 2773:                 $sec = $3;
 2774:                 $extendedarea = $area.$sec;
 2775:                 if (exists($$allgroups{$area})) {
 2776:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2777:                         my $spec = $trole.'.'.$extendedarea;
 2778:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2779:                                                 $$allgroups{$area}{$group};
 2780:                     }
 2781:                 }
 2782:             }
 2783:         }
 2784:     }
 2785:     foreach (keys(%grouproles)) {
 2786:         $$allroles{$_} = $grouproles{$_};
 2787:     }
 2788:     foreach (keys %{$allroles}) {
 2789:         my %thesepriv=();
 2790:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2791:         foreach (split(/:/,$$allroles{$_})) {
 2792:             if ($_ ne '') {
 2793:                 my ($privilege,$restrictions)=split(/&/,$_);
 2794:                 if ($restrictions eq '') {
 2795:                     $thesepriv{$privilege}='F';
 2796:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2797:                     $thesepriv{$privilege}.=$restrictions;
 2798:                 }
 2799:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2800:             }
 2801:         }
 2802:         my $thesestr='';
 2803:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2804:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
 2805:     }
 2806:     return ($author,$adv);
 2807: }
 2808: 
 2809: # --------------------------------------------------------------- get interface
 2810: 
 2811: sub get {
 2812:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2813:    my $items='';
 2814:    foreach (@$storearr) {
 2815:        $items.=escape($_).'&';
 2816:    }
 2817:    $items=~s/\&$//;
 2818:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2819:    if (!$uname) { $uname=$env{'user.name'}; }
 2820:    my $uhome=&homeserver($uname,$udomain);
 2821: 
 2822:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2823:    my @pairs=split(/\&/,$rep);
 2824:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2825:      return @pairs;
 2826:    }
 2827:    my %returnhash=();
 2828:    my $i=0;
 2829:    foreach (@$storearr) {
 2830:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2831:       $i++;
 2832:    }
 2833:    return %returnhash;
 2834: }
 2835: 
 2836: # --------------------------------------------------------------- del interface
 2837: 
 2838: sub del {
 2839:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2840:    my $items='';
 2841:    foreach (@$storearr) {
 2842:        $items.=escape($_).'&';
 2843:    }
 2844:    $items=~s/\&$//;
 2845:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2846:    if (!$uname) { $uname=$env{'user.name'}; }
 2847:    my $uhome=&homeserver($uname,$udomain);
 2848: 
 2849:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2850: }
 2851: 
 2852: # -------------------------------------------------------------- dump interface
 2853: 
 2854: sub dump {
 2855:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2856:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2857:    if (!$uname) { $uname=$env{'user.name'}; }
 2858:    my $uhome=&homeserver($uname,$udomain);
 2859:    if ($regexp) {
 2860:        $regexp=&escape($regexp);
 2861:    } else {
 2862:        $regexp='.';
 2863:    }
 2864:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 2865:    my @pairs=split(/\&/,$rep);
 2866:    my %returnhash=();
 2867:    foreach (@pairs) {
 2868:       my ($key,$value)=split(/=/,$_,2);
 2869:       $returnhash{unescape($key)}=&thaw_unescape($value);
 2870:    }
 2871:    return %returnhash;
 2872: }
 2873: 
 2874: # --------------------------------------------------------- dumpstore interface
 2875: 
 2876: sub dumpstore {
 2877:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2878:    return &dump($namespace,$udomain,$uname,$regexp,$range);
 2879: }
 2880: 
 2881: # -------------------------------------------------------------- keys interface
 2882: 
 2883: sub getkeys {
 2884:    my ($namespace,$udomain,$uname)=@_;
 2885:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2886:    if (!$uname) { $uname=$env{'user.name'}; }
 2887:    my $uhome=&homeserver($uname,$udomain);
 2888:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2889:    my @keyarray=();
 2890:    foreach (split(/\&/,$rep)) {
 2891:       push (@keyarray,&unescape($_));
 2892:    }
 2893:    return @keyarray;
 2894: }
 2895: 
 2896: # --------------------------------------------------------------- currentdump
 2897: sub currentdump {
 2898:    my ($courseid,$sdom,$sname)=@_;
 2899:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 2900:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 2901:    $sname    = $env{'user.name'}         if (! defined($sname));
 2902:    my $uhome = &homeserver($sname,$sdom);
 2903:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2904:    return if ($rep =~ /^(error:|no_such_host)/);
 2905:    #
 2906:    my %returnhash=();
 2907:    #
 2908:    if ($rep eq "unknown_cmd") { 
 2909:        # an old lond will not know currentdump
 2910:        # Do a dump and make it look like a currentdump
 2911:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2912:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2913:        my %hash = @tmp;
 2914:        @tmp=();
 2915:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 2916:    } else {
 2917:        my @pairs=split(/\&/,$rep);
 2918:        foreach (@pairs) {
 2919:            my ($key,$value)=split(/=/,$_);
 2920:            my ($symb,$param) = split(/:/,$key);
 2921:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2922:                                                         &thaw_unescape($value);
 2923:        }
 2924:    }
 2925:    return %returnhash;
 2926: }
 2927: 
 2928: sub convert_dump_to_currentdump{
 2929:     my %hash = %{shift()};
 2930:     my %returnhash;
 2931:     # Code ripped from lond, essentially.  The only difference
 2932:     # here is the unescaping done by lonnet::dump().  Conceivably
 2933:     # we might run in to problems with parameter names =~ /^v\./
 2934:     while (my ($key,$value) = each(%hash)) {
 2935:         my ($v,$symb,$param) = split(/:/,$key);
 2936:         next if ($v eq 'version' || $symb eq 'keys');
 2937:         next if (exists($returnhash{$symb}) &&
 2938:                  exists($returnhash{$symb}->{$param}) &&
 2939:                  $returnhash{$symb}->{'v.'.$param} > $v);
 2940:         $returnhash{$symb}->{$param}=$value;
 2941:         $returnhash{$symb}->{'v.'.$param}=$v;
 2942:     }
 2943:     #
 2944:     # Remove all of the keys in the hashes which keep track of
 2945:     # the version of the parameter.
 2946:     while (my ($symb,$param_hash) = each(%returnhash)) {
 2947:         # use a foreach because we are going to delete from the hash.
 2948:         foreach my $key (keys(%$param_hash)) {
 2949:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 2950:         }
 2951:     }
 2952:     return \%returnhash;
 2953: }
 2954: 
 2955: # ------------------------------------------------------ critical inc interface
 2956: 
 2957: sub cinc {
 2958:     return &inc(@_,'critical');
 2959: }
 2960: 
 2961: # --------------------------------------------------------------- inc interface
 2962: 
 2963: sub inc {
 2964:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 2965:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 2966:     if (!$uname) { $uname=$env{'user.name'}; }
 2967:     my $uhome=&homeserver($uname,$udomain);
 2968:     my $items='';
 2969:     if (! ref($store)) {
 2970:         # got a single value, so use that instead
 2971:         $items = &escape($store).'=&';
 2972:     } elsif (ref($store) eq 'SCALAR') {
 2973:         $items = &escape($$store).'=&';        
 2974:     } elsif (ref($store) eq 'ARRAY') {
 2975:         $items = join('=&',map {&escape($_);} @{$store});
 2976:     } elsif (ref($store) eq 'HASH') {
 2977:         while (my($key,$value) = each(%{$store})) {
 2978:             $items.= &escape($key).'='.&escape($value).'&';
 2979:         }
 2980:     }
 2981:     $items=~s/\&$//;
 2982:     if ($critical) {
 2983: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 2984:     } else {
 2985: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 2986:     }
 2987: }
 2988: 
 2989: # --------------------------------------------------------------- put interface
 2990: 
 2991: sub put {
 2992:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2993:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2994:    if (!$uname) { $uname=$env{'user.name'}; }
 2995:    my $uhome=&homeserver($uname,$udomain);
 2996:    my $items='';
 2997:    foreach (keys %$storehash) {
 2998:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2999:    }
 3000:    $items=~s/\&$//;
 3001:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3002: }
 3003: 
 3004: # ------------------------------------------------------------ newput interface
 3005: 
 3006: sub newput {
 3007:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3008:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3009:    if (!$uname) { $uname=$env{'user.name'}; }
 3010:    my $uhome=&homeserver($uname,$udomain);
 3011:    my $items='';
 3012:    foreach my $key (keys(%$storehash)) {
 3013:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3014:    }
 3015:    $items=~s/\&$//;
 3016:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3017: }
 3018: 
 3019: # ---------------------------------------------------------  putstore interface
 3020: 
 3021: sub putstore {
 3022:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3023:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3024:    if (!$uname) { $uname=$env{'user.name'}; }
 3025:    my $uhome=&homeserver($uname,$udomain);
 3026:    my $items='';
 3027:    foreach my $key (keys(%$storehash)) {
 3028:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3029:    }
 3030:    $items=~s/\&$//;
 3031:    my $esc_symb=&escape($symb);
 3032:    my $esc_v=&escape($version);
 3033:    my $reply =
 3034:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3035: 	      $uhome);
 3036:    if ($reply eq 'unknown_cmd') {
 3037:        # gfall back to way things use to be done
 3038:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3039: 			    $uname);
 3040:    }
 3041:    return $reply;
 3042: }
 3043: 
 3044: sub old_putstore {
 3045:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3046:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3047:     if (!$uname) { $uname=$env{'user.name'}; }
 3048:     my $uhome=&homeserver($uname,$udomain);
 3049:     my %newstorehash;
 3050:     foreach (keys %$storehash) {
 3051: 	my $key = $version.':'.&escape($symb).':'.$_;
 3052: 	$newstorehash{$key} = $storehash->{$_};
 3053:     }
 3054:     my $items='';
 3055:     my %allitems = ();
 3056:     foreach (keys %newstorehash) {
 3057: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3058: 	    my $key = $1.':keys:'.$2;
 3059: 	    $allitems{$key} .= $3.':';
 3060: 	}
 3061: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
 3062:     }
 3063:     foreach (keys %allitems) {
 3064: 	$allitems{$_} =~ s/\:$//;
 3065: 	$items.= $_.'='.$allitems{$_}.'&';
 3066:     }
 3067:     $items=~s/\&$//;
 3068:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3069: }
 3070: 
 3071: # ------------------------------------------------------ critical put interface
 3072: 
 3073: sub cput {
 3074:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3075:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3076:    if (!$uname) { $uname=$env{'user.name'}; }
 3077:    my $uhome=&homeserver($uname,$udomain);
 3078:    my $items='';
 3079:    foreach (keys %$storehash) {
 3080:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3081:    }
 3082:    $items=~s/\&$//;
 3083:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3084: }
 3085: 
 3086: # -------------------------------------------------------------- eget interface
 3087: 
 3088: sub eget {
 3089:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3090:    my $items='';
 3091:    foreach (@$storearr) {
 3092:        $items.=escape($_).'&';
 3093:    }
 3094:    $items=~s/\&$//;
 3095:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3096:    if (!$uname) { $uname=$env{'user.name'}; }
 3097:    my $uhome=&homeserver($uname,$udomain);
 3098:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3099:    my @pairs=split(/\&/,$rep);
 3100:    my %returnhash=();
 3101:    my $i=0;
 3102:    foreach (@$storearr) {
 3103:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 3104:       $i++;
 3105:    }
 3106:    return %returnhash;
 3107: }
 3108: 
 3109: # ------------------------------------------------------------ tmpput interface
 3110: sub tmpput {
 3111:     my ($storehash,$server)=@_;
 3112:     my $items='';
 3113:     foreach (keys(%$storehash)) {
 3114: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3115:     }
 3116:     $items=~s/\&$//;
 3117:     return &reply("tmpput:$items",$server);
 3118: }
 3119: 
 3120: # ------------------------------------------------------------ tmpget interface
 3121: sub tmpget {
 3122:     my ($token,$server)=@_;
 3123:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3124:     my $rep=&reply("tmpget:$token",$server);
 3125:     my %returnhash;
 3126:     foreach my $item (split(/\&/,$rep)) {
 3127: 	my ($key,$value)=split(/=/,$item);
 3128: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3129:     }
 3130:     return %returnhash;
 3131: }
 3132: 
 3133: # ------------------------------------------------------------ tmpget interface
 3134: sub tmpdel {
 3135:     my ($token,$server)=@_;
 3136:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3137:     return &reply("tmpdel:$token",$server);
 3138: }
 3139: 
 3140: # ---------------------------------------------- Custom access rule evaluation
 3141: 
 3142: sub customaccess {
 3143:     my ($priv,$uri)=@_;
 3144:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 3145:     $urealm=~s/^\W//;
 3146:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 3147:     my $access=0;
 3148:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3149: 	my ($effect,$realm,$role)=split(/\:/,$_);
 3150:         if ($role) {
 3151: 	   if ($role ne $urole) { next; }
 3152:         }
 3153:         foreach (split(/\s*\,\s*/,$realm)) {
 3154:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 3155:             if ($tdom) {
 3156: 		if ($tdom ne $udom) { next; }
 3157:             }
 3158:             if ($tcrs) {
 3159: 		if ($tcrs ne $ucrs) { next; }
 3160:             }
 3161:             if ($tsec) {
 3162: 		if ($tsec ne $usec) { next; }
 3163:             }
 3164:             $access=($effect eq 'allow');
 3165:             last;
 3166:         }
 3167: 	if ($realm eq '' && $role eq '') {
 3168:             $access=($effect eq 'allow');
 3169: 	}
 3170:     }
 3171:     return $access;
 3172: }
 3173: 
 3174: # ------------------------------------------------- Check for a user privilege
 3175: 
 3176: sub allowed {
 3177:     my ($priv,$uri,$symb)=@_;
 3178:     my $ver_orguri=$uri;
 3179:     $uri=&deversion($uri);
 3180:     my $orguri=$uri;
 3181:     $uri=&declutter($uri);
 3182:     
 3183:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3184: # Free bre access to adm and meta resources
 3185:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
 3186: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 3187: 	return 'F';
 3188:     }
 3189: 
 3190: # Free bre access to user's own portfolio contents
 3191:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3192:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3193: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3194:         return 'F';
 3195:     }
 3196: 
 3197: # bre access to group if user has rgf priv for this group and course.
 3198:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3199:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3200:         if (exists($env{'request.course.id'})) {
 3201:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3202:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3203:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3204:                 my $courseprivid=$env{'request.course.id'};
 3205:                 $courseprivid=~s/\_/\//;
 3206:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3207:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3208:                     return $1; 
 3209:                 }
 3210:             }
 3211:         }
 3212:     }
 3213: 
 3214: # Free bre to public access
 3215: 
 3216:     if ($priv eq 'bre') {
 3217:         my $copyright=&metadata($uri,'copyright');
 3218: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3219:            return 'F'; 
 3220:         }
 3221:         if ($copyright eq 'priv') {
 3222:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3223: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3224: 		return '';
 3225:             }
 3226:         }
 3227:         if ($copyright eq 'domain') {
 3228:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3229: 	    unless (($env{'user.domain'} eq $1) ||
 3230:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3231: 		return '';
 3232:             }
 3233:         }
 3234:         if ($env{'request.role'}=~ /li\.\//) {
 3235:             # Library role, so allow browsing of resources in this domain.
 3236:             return 'F';
 3237:         }
 3238:         if ($copyright eq 'custom') {
 3239: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3240:         }
 3241:     }
 3242:     # Domain coordinator is trying to create a course
 3243:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3244:         # uri is the requested domain in this case.
 3245:         # comparison to 'request.role.domain' shows if the user has selected
 3246:         # a role of dc for the domain in question.
 3247:         return 'F' if ($uri eq $env{'request.role.domain'});
 3248:     }
 3249: 
 3250:     my $thisallowed='';
 3251:     my $statecond=0;
 3252:     my $courseprivid='';
 3253: 
 3254: # Course
 3255: 
 3256:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3257:        $thisallowed.=$1;
 3258:     }
 3259: 
 3260: # Domain
 3261: 
 3262:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3263:        =~/\Q$priv\E\&([^\:]*)/) {
 3264:        $thisallowed.=$1;
 3265:     }
 3266: 
 3267: # Course: uri itself is a course
 3268:     my $courseuri=$uri;
 3269:     $courseuri=~s/\_(\d)/\/$1/;
 3270:     $courseuri=~s/^([^\/])/\/$1/;
 3271: 
 3272:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3273:        =~/\Q$priv\E\&([^\:]*)/) {
 3274:        $thisallowed.=$1;
 3275:     }
 3276: 
 3277: # Group: uri itself is a group
 3278:     my $groupuri=$uri;
 3279:     $groupuri=~s/^([^\/])/\/$1/;
 3280:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
 3281:        =~/\Q$priv\E\&([^\:]*)/) {
 3282:        $thisallowed.=$1;
 3283:     }
 3284: 
 3285: # URI is an uploaded document for this course, default permissions don't matter
 3286: # not allowing 'edit' access (editupload) to uploaded course docs
 3287:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3288: 	$thisallowed='';
 3289:         my ($match)=&is_on_map($uri);
 3290:         if ($match) {
 3291:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3292:                   =~/\Q$priv\E\&([^\:]*)/) {
 3293:                 $thisallowed.=$1;
 3294:             }
 3295:         } else {
 3296:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3297:             if ($refuri) {
 3298:                 if ($refuri =~ m|^/adm/|) {
 3299:                     $thisallowed='F';
 3300:                 } else {
 3301:                     $refuri=&declutter($refuri);
 3302:                     my ($match) = &is_on_map($refuri);
 3303:                     if ($match) {
 3304:                         $thisallowed='F';
 3305:                     }
 3306:                 }
 3307:             }
 3308:         }
 3309:     }
 3310: 
 3311: # Full access at system, domain or course-wide level? Exit.
 3312: 
 3313:     if ($thisallowed=~/F/) {
 3314: 	return 'F';
 3315:     }
 3316: 
 3317: # If this is generating or modifying users, exit with special codes
 3318: 
 3319:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3320: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3321: 	    my ($audom,$auname)=split('/',$uri);
 3322: # no author name given, so this just checks on the general right to make a co-author in this domain
 3323: 	    unless ($auname) { return $thisallowed; }
 3324: # an author name is given, so we are about to actually make a co-author for a certain account
 3325: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3326: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3327: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3328: 	}
 3329: 	return $thisallowed;
 3330:     }
 3331: #
 3332: # Gathered so far: system, domain and course wide privileges
 3333: #
 3334: # Course: See if uri or referer is an individual resource that is part of 
 3335: # the course
 3336: 
 3337:     if ($env{'request.course.id'}) {
 3338: 
 3339:        $courseprivid=$env{'request.course.id'};
 3340:        if ($env{'request.course.sec'}) {
 3341:           $courseprivid.='/'.$env{'request.course.sec'};
 3342:        }
 3343:        $courseprivid=~s/\_/\//;
 3344:        my $checkreferer=1;
 3345:        my ($match,$cond)=&is_on_map($uri);
 3346:        if ($match) {
 3347:            $statecond=$cond;
 3348:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3349:                =~/\Q$priv\E\&([^\:]*)/) {
 3350:                $thisallowed.=$1;
 3351:                $checkreferer=0;
 3352:            }
 3353:        }
 3354:        
 3355:        if ($checkreferer) {
 3356: 	  my $refuri=$env{'httpref.'.$orguri};
 3357:             unless ($refuri) {
 3358:                 foreach (keys %env) {
 3359: 		    if ($_=~/^httpref\..*\*/) {
 3360: 			my $pattern=$_;
 3361:                         $pattern=~s/^httpref\.\/res\///;
 3362:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3363:                         $pattern=~s/\//\\\//g;
 3364:                         if ($orguri=~/$pattern/) {
 3365: 			    $refuri=$env{$_};
 3366:                         }
 3367:                     }
 3368:                 }
 3369:             }
 3370: 
 3371:          if ($refuri) { 
 3372: 	  $refuri=&declutter($refuri);
 3373:           my ($match,$cond)=&is_on_map($refuri);
 3374:             if ($match) {
 3375:               my $refstatecond=$cond;
 3376:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3377:                   =~/\Q$priv\E\&([^\:]*)/) {
 3378:                   $thisallowed.=$1;
 3379:                   $uri=$refuri;
 3380:                   $statecond=$refstatecond;
 3381:               }
 3382:           }
 3383:         }
 3384:        }
 3385:    }
 3386: 
 3387: #
 3388: # Gathered now: all privileges that could apply, and condition number
 3389: # 
 3390: #
 3391: # Full or no access?
 3392: #
 3393: 
 3394:     if ($thisallowed=~/F/) {
 3395: 	return 'F';
 3396:     }
 3397: 
 3398:     unless ($thisallowed) {
 3399:         return '';
 3400:     }
 3401: 
 3402: # Restrictions exist, deal with them
 3403: #
 3404: #   C:according to course preferences
 3405: #   R:according to resource settings
 3406: #   L:unless locked
 3407: #   X:according to user session state
 3408: #
 3409: 
 3410: # Possibly locked functionality, check all courses
 3411: # Locks might take effect only after 10 minutes cache expiration for other
 3412: # courses, and 2 minutes for current course
 3413: 
 3414:     my $envkey;
 3415:     if ($thisallowed=~/L/) {
 3416:         foreach $envkey (keys %env) {
 3417:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3418:                my $courseid=$2;
 3419:                my $roleid=$1.'.'.$2;
 3420:                $courseid=~s/^\///;
 3421:                my $expiretime=600;
 3422:                if ($env{'request.role'} eq $roleid) {
 3423: 		  $expiretime=120;
 3424:                }
 3425: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3426:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3427:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3428: 		   &coursedescription($courseid);
 3429:                }
 3430:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3431:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3432: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3433:                        &log($env{'user.domain'},$env{'user.name'},
 3434:                             $env{'user.home'},
 3435:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3436:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3437:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3438: 		       return '';
 3439:                    }
 3440:                }
 3441:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3442:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3443: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3444:                        &log($env{'user.domain'},$env{'user.name'},
 3445:                             $env{'user.home'},
 3446:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3447:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3448:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3449: 		       return '';
 3450:                    }
 3451:                }
 3452: 	   }
 3453:        }
 3454:     }
 3455:    
 3456: #
 3457: # Rest of the restrictions depend on selected course
 3458: #
 3459: 
 3460:     unless ($env{'request.course.id'}) {
 3461:        return '1';
 3462:     }
 3463: 
 3464: #
 3465: # Now user is definitely in a course
 3466: #
 3467: 
 3468: 
 3469: # Course preferences
 3470: 
 3471:    if ($thisallowed=~/C/) {
 3472:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3473:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3474:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3475: 	   =~/\Q$rolecode\E/) {
 3476: 	   if ($priv ne 'pch') { 
 3477: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3478: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3479: 			$env{'request.course.id'});
 3480: 	   }
 3481:            return '';
 3482:        }
 3483: 
 3484:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3485: 	   =~/\Q$unamedom\E/) {
 3486: 	   if ($priv ne 'pch') { 
 3487: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 3488: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3489: 			$env{'request.course.id'});
 3490: 	   }
 3491:            return '';
 3492:        }
 3493:    }
 3494: 
 3495: # Resource preferences
 3496: 
 3497:    if ($thisallowed=~/R/) {
 3498:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3499:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3500: 	   if ($priv ne 'pch') { 
 3501: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3502: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3503: 	   }
 3504: 	   return '';
 3505:        }
 3506:    }
 3507: 
 3508: # Restricted by state or randomout?
 3509: 
 3510:    if ($thisallowed=~/X/) {
 3511:       if ($env{'acc.randomout'}) {
 3512: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3513:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3514:             return ''; 
 3515:          }
 3516:       }
 3517:       if (&condval($statecond)) {
 3518: 	 return '2';
 3519:       } else {
 3520:          return '';
 3521:       }
 3522:    }
 3523: 
 3524:    return 'F';
 3525: }
 3526: 
 3527: sub split_uri_for_cond {
 3528:     my $uri=&deversion(&declutter(shift));
 3529:     my @uriparts=split(/\//,$uri);
 3530:     my $filename=pop(@uriparts);
 3531:     my $pathname=join('/',@uriparts);
 3532:     return ($pathname,$filename);
 3533: }
 3534: # --------------------------------------------------- Is a resource on the map?
 3535: 
 3536: sub is_on_map {
 3537:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 3538:     #Trying to find the conditional for the file
 3539:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3540: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3541:     if ($match) {
 3542: 	return (1,$1);
 3543:     } else {
 3544: 	return (0,0);
 3545:     }
 3546: }
 3547: 
 3548: # --------------------------------------------------------- Get symb from alias
 3549: 
 3550: sub get_symb_from_alias {
 3551:     my $symb=shift;
 3552:     my ($map,$resid,$url)=&decode_symb($symb);
 3553: # Already is a symb
 3554:     if ($url) { return $symb; }
 3555: # Must be an alias
 3556:     my $aliassymb='';
 3557:     my %bighash;
 3558:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3559:                             &GDBM_READER(),0640)) {
 3560:         my $rid=$bighash{'mapalias_'.$symb};
 3561: 	if ($rid) {
 3562: 	    my ($mapid,$resid)=split(/\./,$rid);
 3563: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3564: 				    $resid,$bighash{'src_'.$rid});
 3565: 	}
 3566:         untie %bighash;
 3567:     }
 3568:     return $aliassymb;
 3569: }
 3570: 
 3571: # ----------------------------------------------------------------- Define Role
 3572: 
 3573: sub definerole {
 3574:   if (allowed('mcr','/')) {
 3575:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3576:     foreach (split(':',$sysrole)) {
 3577: 	my ($crole,$cqual)=split(/\&/,$_);
 3578:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3579:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3580: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3581:                return "refused:s:$crole&$cqual"; 
 3582:             }
 3583:         }
 3584:     }
 3585:     foreach (split(':',$domrole)) {
 3586: 	my ($crole,$cqual)=split(/\&/,$_);
 3587:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3588:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3589: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3590:                return "refused:d:$crole&$cqual"; 
 3591:             }
 3592:         }
 3593:     }
 3594:     foreach (split(':',$courole)) {
 3595: 	my ($crole,$cqual)=split(/\&/,$_);
 3596:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3597:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3598: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3599:                return "refused:c:$crole&$cqual"; 
 3600:             }
 3601:         }
 3602:     }
 3603:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3604:                 "$env{'user.domain'}:$env{'user.name'}:".
 3605: 	        "rolesdef_$rolename=".
 3606:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3607:     return reply($command,$env{'user.home'});
 3608:   } else {
 3609:     return 'refused';
 3610:   }
 3611: }
 3612: 
 3613: # ---------------- Make a metadata query against the network of library servers
 3614: 
 3615: sub metadata_query {
 3616:     my ($query,$custom,$customshow,$server_array)=@_;
 3617:     my %rhash;
 3618:     my @server_list = (defined($server_array) ? @$server_array
 3619:                                               : keys(%libserv) );
 3620:     for my $server (@server_list) {
 3621: 	unless ($custom or $customshow) {
 3622: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3623: 	    $rhash{$server}=$reply;
 3624: 	}
 3625: 	else {
 3626: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3627: 			     &escape($custom).':'.&escape($customshow),
 3628: 			     $server);
 3629: 	    $rhash{$server}=$reply;
 3630: 	}
 3631:     }
 3632:     return \%rhash;
 3633: }
 3634: 
 3635: # ----------------------------------------- Send log queries and wait for reply
 3636: 
 3637: sub log_query {
 3638:     my ($uname,$udom,$query,%filters)=@_;
 3639:     my $uhome=&homeserver($uname,$udom);
 3640:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3641:     my $uhost=$hostname{$uhome};
 3642:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3643:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3644:                        $uhome);
 3645:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3646:     return get_query_reply($queryid);
 3647: }
 3648: 
 3649: # ------- Request retrieval of institutional classlists for course(s)
 3650: 
 3651: sub fetch_enrollment_query {
 3652:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3653:     my $homeserver;
 3654:     my $maxtries = 1;
 3655:     if ($context eq 'automated') {
 3656:         $homeserver = $perlvar{'lonHostID'};
 3657:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3658:     } else {
 3659:         $homeserver = &homeserver($cnum,$dom);
 3660:     }
 3661:     my $host=$hostname{$homeserver};
 3662:     my $cmd = '';
 3663:     foreach (keys %{$affiliatesref}) {
 3664:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3665:     }
 3666:     $cmd =~ s/%%$//;
 3667:     $cmd = &escape($cmd);
 3668:     my $query = 'fetchenrollment';
 3669:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 3670:     unless ($queryid=~/^\Q$host\E\_/) { 
 3671:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3672:         return 'error: '.$queryid;
 3673:     }
 3674:     my $reply = &get_query_reply($queryid);
 3675:     my $tries = 1;
 3676:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3677:         $reply = &get_query_reply($queryid);
 3678:         $tries ++;
 3679:     }
 3680:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3681:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3682:     } else {
 3683:         my @responses = split/:/,$reply;
 3684:         if ($homeserver eq $perlvar{'lonHostID'}) {
 3685:             foreach (@responses) {
 3686:                 my ($key,$value) = split/=/,$_;
 3687:                 $$replyref{$key} = $value;
 3688:             }
 3689:         } else {
 3690:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 3691:             foreach (@responses) {
 3692:                 my ($key,$value) = split/=/,$_;
 3693:                 $$replyref{$key} = $value;
 3694:                 if ($value > 0) {
 3695:                     foreach (@{$$affiliatesref{$key}}) {
 3696:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 3697:                         my $destname = $pathname.'/'.$filename;
 3698:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 3699:                         if ($xml_classlist =~ /^error/) {
 3700:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 3701:                         } else {
 3702:                             if ( open(FILE,">$destname") ) {
 3703:                                 print FILE &unescape($xml_classlist);
 3704:                                 close(FILE);
 3705:                             } else {
 3706:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 3707:                             }
 3708:                         }
 3709:                     }
 3710:                 }
 3711:             }
 3712:         }
 3713:         return 'ok';
 3714:     }
 3715:     return 'error';
 3716: }
 3717: 
 3718: sub get_query_reply {
 3719:     my $queryid=shift;
 3720:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 3721:     my $reply='';
 3722:     for (1..100) {
 3723: 	sleep 2;
 3724:         if (-e $replyfile.'.end') {
 3725: 	    if (open(my $fh,$replyfile)) {
 3726:                $reply.=<$fh>;
 3727:                close($fh);
 3728: 	   } else { return 'error: reply_file_error'; }
 3729:            return &unescape($reply);
 3730: 	}
 3731:     }
 3732:     return 'timeout:'.$queryid;
 3733: }
 3734: 
 3735: sub courselog_query {
 3736: #
 3737: # possible filters:
 3738: # url: url or symb
 3739: # username
 3740: # domain
 3741: # action: view, submit, grade
 3742: # start: timestamp
 3743: # end: timestamp
 3744: #
 3745:     my (%filters)=@_;
 3746:     unless ($env{'request.course.id'}) { return 'no_course'; }
 3747:     if ($filters{'url'}) {
 3748: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 3749:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 3750:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 3751:     }
 3752:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3753:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3754:     return &log_query($cname,$cdom,'courselog',%filters);
 3755: }
 3756: 
 3757: sub userlog_query {
 3758:     my ($uname,$udom,%filters)=@_;
 3759:     return &log_query($uname,$udom,'userlog',%filters);
 3760: }
 3761: 
 3762: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 3763: 
 3764: sub auto_run {
 3765:     my ($cnum,$cdom) = @_;
 3766:     my $homeserver = &homeserver($cnum,$cdom);
 3767:     my $response = &reply('autorun:'.$cdom,$homeserver);
 3768:     return $response;
 3769: }
 3770:                                                                                    
 3771: sub auto_get_sections {
 3772:     my ($cnum,$cdom,$inst_coursecode) = @_;
 3773:     my $homeserver = &homeserver($cnum,$cdom);
 3774:     my @secs = ();
 3775:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 3776:     unless ($response eq 'refused') {
 3777:         @secs = split/:/,$response;
 3778:     }
 3779:     return @secs;
 3780: }
 3781:                                                                                    
 3782: sub auto_new_course {
 3783:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 3784:     my $homeserver = &homeserver($cnum,$cdom);
 3785:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 3786:     return $response;
 3787: }
 3788:                                                                                    
 3789: sub auto_validate_courseID {
 3790:     my ($cnum,$cdom,$inst_course_id) = @_;
 3791:     my $homeserver = &homeserver($cnum,$cdom);
 3792:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 3793:     return $response;
 3794: }
 3795:                                                                                    
 3796: sub auto_create_password {
 3797:     my ($cnum,$cdom,$authparam) = @_;
 3798:     my $homeserver = &homeserver($cnum,$cdom); 
 3799:     my $create_passwd = 0;
 3800:     my $authchk = '';
 3801:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 3802:     if ($response eq 'refused') {
 3803:         $authchk = 'refused';
 3804:     } else {
 3805:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 3806:     }
 3807:     return ($authparam,$create_passwd,$authchk);
 3808: }
 3809: 
 3810: sub auto_photo_permission {
 3811:     my ($cnum,$cdom,$students) = @_;
 3812:     my $homeserver = &homeserver($cnum,$cdom);
 3813:     my ($outcome,$perm_reqd,$conditions) = 
 3814: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 3815:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3816: 	return (undef,undef);
 3817:     }
 3818:     return ($outcome,$perm_reqd,$conditions);
 3819: }
 3820: 
 3821: sub auto_checkphotos {
 3822:     my ($uname,$udom,$pid) = @_;
 3823:     my $homeserver = &homeserver($uname,$udom);
 3824:     my ($result,$resulttype);
 3825:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 3826: 				   &escape($uname).':'.&escape($pid),
 3827: 				   $homeserver));
 3828:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3829: 	return (undef,undef);
 3830:     }
 3831:     if ($outcome) {
 3832:         ($result,$resulttype) = split(/:/,$outcome);
 3833:     } 
 3834:     return ($result,$resulttype);
 3835: }
 3836: 
 3837: sub auto_photochoice {
 3838:     my ($cnum,$cdom) = @_;
 3839:     my $homeserver = &homeserver($cnum,$cdom);
 3840:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 3841: 						       &escape($cdom),
 3842: 						       $homeserver)));
 3843:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3844: 	return (undef,undef);
 3845:     }
 3846:     return ($update,$comment);
 3847: }
 3848: 
 3849: sub auto_photoupdate {
 3850:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 3851:     my $homeserver = &homeserver($cnum,$dom);
 3852:     my $host=$hostname{$homeserver};
 3853:     my $cmd = '';
 3854:     my $maxtries = 1;
 3855:     foreach (keys %{$affiliatesref}) {
 3856:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3857:     }
 3858:     $cmd =~ s/%%$//;
 3859:     $cmd = &escape($cmd);
 3860:     my $query = 'institutionalphotos';
 3861:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 3862:     unless ($queryid=~/^\Q$host\E\_/) {
 3863:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 3864:         return 'error: '.$queryid;
 3865:     }
 3866:     my $reply = &get_query_reply($queryid);
 3867:     my $tries = 1;
 3868:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3869:         $reply = &get_query_reply($queryid);
 3870:         $tries ++;
 3871:     }
 3872:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3873:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3874:     } else {
 3875:         my @responses = split(/:/,$reply);
 3876:         my $outcome = shift(@responses); 
 3877:         foreach my $item (@responses) {
 3878:             my ($key,$value) = split(/=/,$item);
 3879:             $$photo{$key} = $value;
 3880:         }
 3881:         return $outcome;
 3882:     }
 3883:     return 'error';
 3884: }
 3885: 
 3886: sub auto_instcode_format {
 3887:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 3888:     my $courses = '';
 3889:     my $homeserver;
 3890:     if ($caller eq 'global') {
 3891:         foreach my $tryserver (keys %libserv) {
 3892:             if ($hostdom{$tryserver} eq $codedom) {
 3893:                 $homeserver = $tryserver;
 3894:                 last;
 3895:             }
 3896:         }
 3897:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
 3898:             $homeserver = &homeserver($env{'user.name'},$codedom);
 3899:         }
 3900:     } else {
 3901:         $homeserver = &homeserver($caller,$codedom);
 3902:     }
 3903:     foreach (keys %{$instcodes}) {
 3904:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 3905:     }
 3906:     chop($courses);
 3907:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
 3908:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 3909:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
 3910:         %{$codes} = &str2hash($codes_str);
 3911:         @{$codetitles} = &str2array($codetitles_str);
 3912:         %{$cat_titles} = &str2hash($cat_titles_str);
 3913:         %{$cat_order} = &str2hash($cat_order_str);
 3914:         return 'ok';
 3915:     }
 3916:     return $response;
 3917: }
 3918: 
 3919: # ------------------------------------------------------- Course Group routines
 3920: 
 3921: sub get_coursegroups {
 3922:     my ($cdom,$cnum,$group) = @_;
 3923:     return(&dump('coursegroups',$cdom,$cnum,$group));
 3924: }
 3925: 
 3926: sub modify_coursegroup {
 3927:     my ($cdom,$cnum,$groupsettings) = @_;
 3928:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 3929: }
 3930: 
 3931: sub modify_group_roles {
 3932:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 3933:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 3934:     my $role = 'gr/'.&escape($userprivs);
 3935:     my ($uname,$udom) = split(/:/,$user);
 3936:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 3937:     if ($result eq 'ok') {
 3938:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 3939:     }
 3940: 
 3941:     return $result;
 3942: }
 3943: 
 3944: sub modify_coursegroup_membership {
 3945:     my ($cdom,$cnum,$membership) = @_;
 3946:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 3947:     return $result;
 3948: }
 3949: 
 3950: sub get_active_groups {
 3951:     my ($udom,$uname,$cdom,$cnum) = @_;
 3952:     my $now = time;
 3953:     my %groups = ();
 3954:     foreach my $key (keys(%env)) {
 3955:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
 3956:             my ($start,$end) = split(/\./,$env{$key});
 3957:             if (($end!=0) && ($end<$now)) { next; }
 3958:             if (($start!=0) && ($start>$now)) { next; }
 3959:             if ($1 eq $cdom && $2 eq $cnum) {
 3960:                 $groups{$3} = $env{$key} ;
 3961:             }
 3962:         }
 3963:     }
 3964:     return %groups;
 3965: }
 3966: 
 3967: sub get_group_membership {
 3968:     my ($cdom,$cnum,$group) = @_;
 3969:     return(&dump('groupmembership',$cdom,$cnum,$group));
 3970: }
 3971: 
 3972: sub get_users_groups {
 3973:     my ($udom,$uname,$courseid) = @_;
 3974:     my $cachetime=1800;
 3975:     $courseid=~s/\_/\//g;
 3976:     $courseid=~s/^(\w)/\/$1/;
 3977: 
 3978:     my $hashid="$udom:$uname:$courseid";
 3979:     my ($result,$cached)=&is_cached_new('getgroups',$hashid);
 3980:     if (defined($cached)) { return $result; }
 3981: 
 3982:     my %roleshash = &dump('roles',$udom,$uname,$courseid);
 3983:     my ($tmp) = keys(%roleshash);
 3984:     if ($tmp=~/^error:/) {
 3985:         &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
 3986:         return '';
 3987:     } else {
 3988:         my $grouplist;
 3989:         foreach my $key (keys %roleshash) {
 3990:             if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
 3991:                 unless ($roleshash{$key} =~ /_\d+_\-1$/) {   # deleted membership
 3992:                     $grouplist .= $1.':';
 3993:                 }
 3994:             }
 3995:         }
 3996:         $grouplist =~ s/:$//;
 3997:         return &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 3998:     }
 3999: }
 4000: 
 4001: sub devalidate_getgroups_cache {
 4002:     my ($udom,$uname,$cdom,$cnum)=@_;
 4003:     my $courseid = $cdom.'_'.$cnum;
 4004:     $courseid=~s/\_/\//g;
 4005:     $courseid=~s/^(\w)/\/$1/;
 4006:     my $hashid="$udom:$uname:$courseid";
 4007:     &devalidate_cache_new('getgroups',$hashid);
 4008: }
 4009: 
 4010: # ------------------------------------------------------------------ Plain Text
 4011: 
 4012: sub plaintext {
 4013:     my $short=shift;
 4014:     return &Apache::lonlocal::mt($prp{$short});
 4015: }
 4016: 
 4017: # ----------------------------------------------------------------- Assign Role
 4018: 
 4019: sub assignrole {
 4020:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4021:     my $mrole;
 4022:     if ($role =~ /^cr\//) {
 4023:         my $cwosec=$url;
 4024:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4025: 	unless (&allowed('ccr',$cwosec)) {
 4026:            &logthis('Refused custom assignrole: '.
 4027:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4028: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4029:            return 'refused'; 
 4030:         }
 4031:         $mrole='cr';
 4032:     } elsif ($role =~ /^gr\//) {
 4033:         my $cwogrp=$url;
 4034:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4035:         unless (&allowed('mdg',$cwogrp)) {
 4036:             &logthis('Refused group assignrole: '.
 4037:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4038:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4039:             return 'refused';
 4040:         }
 4041:         $mrole='gr';
 4042:     } else {
 4043:         my $cwosec=$url;
 4044:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4045:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4046:            &logthis('Refused assignrole: '.
 4047:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4048: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4049:            return 'refused'; 
 4050:         }
 4051:         $mrole=$role;
 4052:     }
 4053:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4054:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4055:     if ($end) { $command.='_'.$end; }
 4056:     if ($start) {
 4057: 	if ($end) { 
 4058:            $command.='_'.$start; 
 4059:         } else {
 4060:            $command.='_0_'.$start;
 4061:         }
 4062:     }
 4063: # actually delete
 4064:     if ($deleteflag) {
 4065: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4066: # modify command to delete the role
 4067:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4068:                 "$udom:$uname:$url".'_'."$mrole";
 4069: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4070: # set start and finish to negative values for userrolelog
 4071:            $start=-1;
 4072:            $end=-1;
 4073:         }
 4074:     }
 4075: # send command
 4076:     my $answer=&reply($command,&homeserver($uname,$udom));
 4077: # log new user role if status is ok
 4078:     if ($answer eq 'ok') {
 4079: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4080:     }
 4081:     return $answer;
 4082: }
 4083: 
 4084: # -------------------------------------------------- Modify user authentication
 4085: # Overrides without validation
 4086: 
 4087: sub modifyuserauth {
 4088:     my ($udom,$uname,$umode,$upass)=@_;
 4089:     my $uhome=&homeserver($uname,$udom);
 4090:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4091:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4092:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4093:              ' in domain '.$env{'request.role.domain'});  
 4094:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4095: 		     &escape($upass),$uhome);
 4096:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4097:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4098:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4099:     &log($udom,,$uname,$uhome,
 4100:         'Authentication changed by '.$env{'user.domain'}.', '.
 4101:                                      $env{'user.name'}.', '.$umode.
 4102:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4103:     unless ($reply eq 'ok') {
 4104:         &logthis('Authentication mode error: '.$reply);
 4105: 	return 'error: '.$reply;
 4106:     }   
 4107:     return 'ok';
 4108: }
 4109: 
 4110: # --------------------------------------------------------------- Modify a user
 4111: 
 4112: sub modifyuser {
 4113:     my ($udom,    $uname, $uid,
 4114:         $umode,   $upass, $first,
 4115:         $middle,  $last,  $gene,
 4116:         $forceid, $desiredhome, $email)=@_;
 4117:     $udom=~s/\W//g;
 4118:     $uname=~s/\W//g;
 4119:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4120:              $umode.', '.$first.', '.$middle.', '.
 4121: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4122:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4123:                                      ' desiredhome not specified'). 
 4124:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4125:              ' in domain '.$env{'request.role.domain'});
 4126:     my $uhome=&homeserver($uname,$udom,'true');
 4127: # ----------------------------------------------------------------- Create User
 4128:     if (($uhome eq 'no_host') && 
 4129: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4130:         my $unhome='';
 4131:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4132:             $unhome = $desiredhome;
 4133: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4134: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4135:         } else { # load balancing routine for determining $unhome
 4136:             my $tryserver;
 4137:             my $loadm=10000000;
 4138:             foreach $tryserver (keys %libserv) {
 4139: 	       if ($hostdom{$tryserver} eq $udom) {
 4140:                   my $answer=reply('load',$tryserver);
 4141:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4142: 		      $loadm=$answer;
 4143:                       $unhome=$tryserver;
 4144:                   }
 4145: 	       }
 4146: 	    }
 4147:         }
 4148:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4149: 	    return 'error: unable to find a home server for '.$uname.
 4150:                    ' in domain '.$udom;
 4151:         }
 4152:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4153:                          &escape($upass),$unhome);
 4154: 	unless ($reply eq 'ok') {
 4155:             return 'error: '.$reply;
 4156:         }   
 4157:         $uhome=&homeserver($uname,$udom,'true');
 4158:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4159: 	    return 'error: unable verify users home machine.';
 4160:         }
 4161:     }   # End of creation of new user
 4162: # ---------------------------------------------------------------------- Add ID
 4163:     if ($uid) {
 4164:        $uid=~tr/A-Z/a-z/;
 4165:        my %uidhash=&idrget($udom,$uname);
 4166:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4167:          && (!$forceid)) {
 4168: 	  unless ($uid eq $uidhash{$uname}) {
 4169: 	      return 'error: user id "'.$uid.'" does not match '.
 4170:                   'current user id "'.$uidhash{$uname}.'".';
 4171:           }
 4172:        } else {
 4173: 	  &idput($udom,($uname => $uid));
 4174:        }
 4175:     }
 4176: # -------------------------------------------------------------- Add names, etc
 4177:     my @tmp=&get('environment',
 4178: 		   ['firstname','middlename','lastname','generation'],
 4179: 		   $udom,$uname);
 4180:     my %names;
 4181:     if ($tmp[0] =~ m/^error:.*/) { 
 4182:         %names=(); 
 4183:     } else {
 4184:         %names = @tmp;
 4185:     }
 4186: #
 4187: # Make sure to not trash student environment if instructor does not bother
 4188: # to supply name and email information
 4189: #
 4190:     if ($first)  { $names{'firstname'}  = $first; }
 4191:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4192:     if ($last)   { $names{'lastname'}   = $last; }
 4193:     if (defined($gene))   { $names{'generation'} = $gene; }
 4194:     if ($email) {
 4195:        $email=~s/[^\w\@\.\-\,]//gs;
 4196:        if ($email=~/\@/) { $names{'notification'} = $email;
 4197: 			   $names{'critnotification'} = $email;
 4198: 			   $names{'permanentemail'} = $email; }
 4199:     }
 4200:     my $reply = &put('environment', \%names, $udom,$uname);
 4201:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4202:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4203:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4204:              $umode.', '.$first.', '.$middle.', '.
 4205: 	     $last.', '.$gene.' by '.
 4206:              $env{'user.name'}.' at '.$env{'user.domain'});
 4207:     return 'ok';
 4208: }
 4209: 
 4210: # -------------------------------------------------------------- Modify student
 4211: 
 4212: sub modifystudent {
 4213:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4214:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4215:     if (!$cid) {
 4216: 	unless ($cid=$env{'request.course.id'}) {
 4217: 	    return 'not_in_class';
 4218: 	}
 4219:     }
 4220: # --------------------------------------------------------------- Make the user
 4221:     my $reply=&modifyuser
 4222: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4223:          $desiredhome,$email);
 4224:     unless ($reply eq 'ok') { return $reply; }
 4225:     # This will cause &modify_student_enrollment to get the uid from the
 4226:     # students environment
 4227:     $uid = undef if (!$forceid);
 4228:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4229: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4230:     return $reply;
 4231: }
 4232: 
 4233: sub modify_student_enrollment {
 4234:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4235:     my ($cdom,$cnum,$chome);
 4236:     if (!$cid) {
 4237: 	unless ($cid=$env{'request.course.id'}) {
 4238: 	    return 'not_in_class';
 4239: 	}
 4240: 	$cdom=$env{'course.'.$cid.'.domain'};
 4241: 	$cnum=$env{'course.'.$cid.'.num'};
 4242:     } else {
 4243: 	($cdom,$cnum)=split(/_/,$cid);
 4244:     }
 4245:     $chome=$env{'course.'.$cid.'.home'};
 4246:     if (!$chome) {
 4247: 	$chome=&homeserver($cnum,$cdom);
 4248:     }
 4249:     if (!$chome) { return 'unknown_course'; }
 4250:     # Make sure the user exists
 4251:     my $uhome=&homeserver($uname,$udom);
 4252:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4253: 	return 'error: no such user';
 4254:     }
 4255:     # Get student data if we were not given enough information
 4256:     if (!defined($first)  || $first  eq '' || 
 4257:         !defined($last)   || $last   eq '' || 
 4258:         !defined($uid)    || $uid    eq '' || 
 4259:         !defined($middle) || $middle eq '' || 
 4260:         !defined($gene)   || $gene   eq '') {
 4261:         # They did not supply us with enough data to enroll the student, so
 4262:         # we need to pick up more information.
 4263:         my %tmp = &get('environment',
 4264:                        ['firstname','middlename','lastname', 'generation','id']
 4265:                        ,$udom,$uname);
 4266: 
 4267:         #foreach (keys(%tmp)) {
 4268:         #    &logthis("key $_ = ".$tmp{$_});
 4269:         #}
 4270:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4271:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4272:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4273:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4274:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4275:     }
 4276:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4277:     my $reply=cput('classlist',
 4278: 		   {"$uname:$udom" => 
 4279: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4280: 		   $cdom,$cnum);
 4281:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4282: 	return 'error: '.$reply;
 4283:     } else {
 4284: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4285:     }
 4286:     # Add student role to user
 4287:     my $uurl='/'.$cid;
 4288:     $uurl=~s/\_/\//g;
 4289:     if ($usec) {
 4290: 	$uurl.='/'.$usec;
 4291:     }
 4292:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4293: }
 4294: 
 4295: sub format_name {
 4296:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4297:     my $name;
 4298:     if ($first ne 'lastname') {
 4299: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4300:     } else {
 4301: 	if ($lastname=~/\S/) {
 4302: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4303: 	    $name=~s/\s+,/,/;
 4304: 	} else {
 4305: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4306: 	}
 4307:     }
 4308:     $name=~s/^\s+//;
 4309:     $name=~s/\s+$//;
 4310:     $name=~s/\s+/ /g;
 4311:     return $name;
 4312: }
 4313: 
 4314: # ------------------------------------------------- Write to course preferences
 4315: 
 4316: sub writecoursepref {
 4317:     my ($courseid,%prefs)=@_;
 4318:     $courseid=~s/^\///;
 4319:     $courseid=~s/\_/\//g;
 4320:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4321:     my $chome=homeserver($cnum,$cdomain);
 4322:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4323: 	return 'error: no such course';
 4324:     }
 4325:     my $cstring='';
 4326:     foreach (keys %prefs) {
 4327: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 4328:     }
 4329:     $cstring=~s/\&$//;
 4330:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4331: }
 4332: 
 4333: # ---------------------------------------------------------- Make/modify course
 4334: 
 4335: sub createcourse {
 4336:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
 4337:     $url=&declutter($url);
 4338:     my $cid='';
 4339:     unless (&allowed('ccc',$udom)) {
 4340:         return 'refused';
 4341:     }
 4342: # ------------------------------------------------------------------- Create ID
 4343:    my $uname=int(1+rand(9)).
 4344:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 4345:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4346:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4347: # ----------------------------------------------- Make sure that does not exist
 4348:    my $uhome=&homeserver($uname,$udom,'true');
 4349:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4350:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4351:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4352:        $uhome=&homeserver($uname,$udom,'true');       
 4353:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4354:            return 'error: unable to generate unique course-ID';
 4355:        } 
 4356:    }
 4357: # ------------------------------------------------ Check supplied server name
 4358:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 4359:     if (! exists($libserv{$course_server})) {
 4360:         return 'error:bad server name '.$course_server;
 4361:     }
 4362: # ------------------------------------------------------------- Make the course
 4363:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 4364:                       $course_server);
 4365:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 4366:     $uhome=&homeserver($uname,$udom,'true');
 4367:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4368: 	return 'error: no such course';
 4369:     }
 4370: # ----------------------------------------------------------------- Course made
 4371: # log existence
 4372:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 4373:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
 4374:     &flushcourselogs();
 4375: # set toplevel url
 4376:     my $topurl=$url;
 4377:     unless ($nonstandard) {
 4378: # ------------------------------------------ For standard courses, make top url
 4379:         my $mapurl=&clutter($url);
 4380:         if ($mapurl eq '/res/') { $mapurl=''; }
 4381:         $env{'form.initmap'}=(<<ENDINITMAP);
 4382: <map>
 4383: <resource id="1" type="start"></resource>
 4384: <resource id="2" src="$mapurl"></resource>
 4385: <resource id="3" type="finish"></resource>
 4386: <link index="1" from="1" to="2"></link>
 4387: <link index="2" from="2" to="3"></link>
 4388: </map>
 4389: ENDINITMAP
 4390:         $topurl=&declutter(
 4391:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 4392:                           );
 4393:     }
 4394: # ----------------------------------------------------------- Write preferences
 4395:     &writecoursepref($udom.'_'.$uname,
 4396:                      ('description' => $description,
 4397:                       'url'         => $topurl));
 4398:     return '/'.$udom.'/'.$uname;
 4399: }
 4400: 
 4401: # ---------------------------------------------------------- Assign Custom Role
 4402: 
 4403: sub assigncustomrole {
 4404:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 4405:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 4406:                        $end,$start,$deleteflag);
 4407: }
 4408: 
 4409: # ----------------------------------------------------------------- Revoke Role
 4410: 
 4411: sub revokerole {
 4412:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4413:     my $now=time;
 4414:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4415: }
 4416: 
 4417: # ---------------------------------------------------------- Revoke Custom Role
 4418: 
 4419: sub revokecustomrole {
 4420:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4421:     my $now=time;
 4422:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4423:            $deleteflag);
 4424: }
 4425: 
 4426: # ------------------------------------------------------------ Disk usage
 4427: sub diskusage {
 4428:     my ($udom,$uname,$directoryRoot)=@_;
 4429:     $directoryRoot =~ s/\/$//;
 4430:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4431:     return $listing;
 4432: }
 4433: 
 4434: sub is_locked {
 4435:     my ($file_name, $domain, $user) = @_;
 4436:     my @check;
 4437:     my $is_locked;
 4438:     push @check, $file_name;
 4439:     my %locked = &get('file_permissions',\@check,
 4440: 		      $env{'user.domain'},$env{'user.name'});
 4441:     my ($tmp)=keys(%locked);
 4442:     if ($tmp=~/^error:/) { undef(%locked); }
 4443: 
 4444:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4445:         $is_locked = 'true';
 4446:     } else {
 4447:         $is_locked = 'false';
 4448:     }
 4449: }
 4450: 
 4451: # ------------------------------------------------------------- Mark as Read Only
 4452: 
 4453: sub mark_as_readonly {
 4454:     my ($domain,$user,$files,$what) = @_;
 4455:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4456:     my ($tmp)=keys(%current_permissions);
 4457:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4458:     foreach my $file (@{$files}) {
 4459:         push(@{$current_permissions{$file}},$what);
 4460:     }
 4461:     &put('file_permissions',\%current_permissions,$domain,$user);
 4462:     return;
 4463: }
 4464: 
 4465: # ------------------------------------------------------------Save Selected Files
 4466: 
 4467: sub save_selected_files {
 4468:     my ($user, $path, @files) = @_;
 4469:     my $filename = $user."savedfiles";
 4470:     my @other_files = &files_not_in_path($user, $path);
 4471:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4472:     foreach my $file (@files) {
 4473:         print (OUT $env{'form.currentpath'}.$file."\n");
 4474:     }
 4475:     foreach my $file (@other_files) {
 4476:         print (OUT $file."\n");
 4477:     }
 4478:     close (OUT);
 4479:     return 'ok';
 4480: }
 4481: 
 4482: sub clear_selected_files {
 4483:     my ($user) = @_;
 4484:     my $filename = $user."savedfiles";
 4485:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4486:     print (OUT undef);
 4487:     close (OUT);
 4488:     return ("ok");    
 4489: }
 4490: 
 4491: sub files_in_path {
 4492:     my ($user, $path) = @_;
 4493:     my $filename = $user."savedfiles";
 4494:     my %return_files;
 4495:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4496:     while (my $line_in = <IN>) {
 4497:         chomp ($line_in);
 4498:         my @paths_and_file = split (m!/!, $line_in);
 4499:         my $file_part = pop (@paths_and_file);
 4500:         my $path_part = join ('/', @paths_and_file);
 4501:         $path_part.='/';
 4502:         my $path_and_file = $path_part.$file_part;
 4503:         if ($path_part eq $path) {
 4504:             $return_files{$file_part}= 'selected';
 4505:         }
 4506:     }
 4507:     close (IN);
 4508:     return (\%return_files);
 4509: }
 4510: 
 4511: # called in portfolio select mode, to show files selected NOT in current directory
 4512: sub files_not_in_path {
 4513:     my ($user, $path) = @_;
 4514:     my $filename = $user."savedfiles";
 4515:     my @return_files;
 4516:     my $path_part;
 4517:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4518:     while (<IN>) {
 4519:         #ok, I know it's clunky, but I want it to work
 4520:         my @paths_and_file = split m!/!, $_;
 4521:         my $file_part = pop (@paths_and_file);
 4522:         chomp ($file_part);
 4523:         my $path_part = join ('/', @paths_and_file);
 4524:         $path_part .= '/';
 4525:         my $path_and_file = $path_part.$file_part;
 4526:         if ($path_part ne $path) {
 4527:             push (@return_files, ($path_and_file));
 4528:         }
 4529:     }
 4530:     close (OUT);
 4531:     return (@return_files);
 4532: }
 4533: 
 4534: #--------------------------------------------------------------Get Marked as Read Only
 4535: 
 4536: 
 4537: sub get_marked_as_readonly {
 4538:     my ($domain,$user,$what) = @_;
 4539:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4540:     my ($tmp)=keys(%current_permissions);
 4541:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4542:     my @readonly_files;
 4543:     my $cmp1=$what;
 4544:     if (ref($what)) { $cmp1=join('',@{$what}) };
 4545:     while (my ($file_name,$value) = each(%current_permissions)) {
 4546:         if (ref($value) eq "ARRAY"){
 4547:             foreach my $stored_what (@{$value}) {
 4548:                 my $cmp2=$stored_what;
 4549:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
 4550:                 if ($cmp1 eq $cmp2) {
 4551:                     push(@readonly_files, $file_name);
 4552:                 } elsif (!defined($what)) {
 4553:                     push(@readonly_files, $file_name);
 4554:                 }
 4555:             }
 4556:         } 
 4557:     }
 4558:     return @readonly_files;
 4559: }
 4560: #-----------------------------------------------------------Get Marked as Read Only Hash
 4561: 
 4562: sub get_marked_as_readonly_hash {
 4563:     my ($domain,$user,$what) = @_;
 4564:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4565:     my ($tmp)=keys(%current_permissions);
 4566:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4567: 
 4568:     my %readonly_files;
 4569:     while (my ($file_name,$value) = each(%current_permissions)) {
 4570:         if (ref($value) eq "ARRAY"){
 4571:             foreach my $stored_what (@{$value}) {
 4572:                 if ($stored_what eq $what) {
 4573:                     $readonly_files{$file_name} = 'locked';
 4574:                 } elsif (!defined($what)) {
 4575:                     $readonly_files{$file_name} = 'locked';
 4576:                 }
 4577:             }
 4578:         } 
 4579:     }
 4580:     return %readonly_files;
 4581: }
 4582: # ------------------------------------------------------------ Unmark as Read Only
 4583: 
 4584: sub unmark_as_readonly {
 4585:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 4586:     # for portfolio submissions, $what contains [$symb,$crsid] 
 4587:     my ($domain,$user,$what,$file_name) = @_;
 4588:     my $symb_crs = $what;
 4589:     if (ref($what)) { $symb_crs=join('',@$what); }
 4590:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4591:     my ($tmp)=keys(%current_permissions);
 4592:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4593:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
 4594:     foreach my $file (@readonly_files) {
 4595: 	if (defined($file_name) && ($file_name ne $file)) { next; }
 4596: 	my $current_locks = $current_permissions{$file};
 4597:         my @new_locks;
 4598:         my @del_keys;
 4599:         if (ref($current_locks) eq "ARRAY"){
 4600:             foreach my $locker (@{$current_locks}) {
 4601:                 my $compare=$locker;
 4602:                 if (ref($locker)) { $compare=join('',@{$locker}) };
 4603:                 if ($compare ne $symb_crs) {
 4604:                     push(@new_locks, $locker);
 4605:                 }
 4606:             }
 4607:             if (scalar(@new_locks) > 0) {
 4608:                 $current_permissions{$file} = \@new_locks;
 4609:             } else {
 4610:                 push(@del_keys, $file);
 4611:                 &del('file_permissions',\@del_keys, $domain, $user);
 4612:                 delete($current_permissions{$file});
 4613:             }
 4614:         }
 4615:     }
 4616:     &put('file_permissions',\%current_permissions,$domain,$user);
 4617:     return;
 4618: }
 4619: 
 4620: # ------------------------------------------------------------ Directory lister
 4621: 
 4622: sub dirlist {
 4623:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 4624: 
 4625:     $uri=~s/^\///;
 4626:     $uri=~s/\/$//;
 4627:     my ($udom, $uname);
 4628:     (undef,$udom,$uname)=split(/\//,$uri);
 4629:     if(defined($userdomain)) {
 4630:         $udom = $userdomain;
 4631:     }
 4632:     if(defined($username)) {
 4633:         $uname = $username;
 4634:     }
 4635: 
 4636:     my $dirRoot = $perlvar{'lonDocRoot'};
 4637:     if(defined($alternateDirectoryRoot)) {
 4638:         $dirRoot = $alternateDirectoryRoot;
 4639:         $dirRoot =~ s/\/$//;
 4640:     }
 4641: 
 4642:     if($udom) {
 4643:         if($uname) {
 4644:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
 4645:                               homeserver($uname,$udom));
 4646:             my @listing_results;
 4647:             if ($listing eq 'unknown_cmd') {
 4648:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
 4649:                                homeserver($uname,$udom));
 4650:                 @listing_results = split(/:/,$listing);
 4651:             } else {
 4652:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 4653:             }
 4654:             return @listing_results;
 4655:         } elsif(!defined($alternateDirectoryRoot)) {
 4656:             my $tryserver;
 4657:             my %allusers=();
 4658:             foreach $tryserver (keys %libserv) {
 4659:                 if($hostdom{$tryserver} eq $udom) {
 4660:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 4661:                                       $udom, $tryserver);
 4662:                     my @listing_results;
 4663:                     if ($listing eq 'unknown_cmd') {
 4664:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 4665:                                        $udom, $tryserver);
 4666:                         @listing_results = split(/:/,$listing);
 4667:                     } else {
 4668:                         @listing_results =
 4669:                             map { &unescape($_); } split(/:/,$listing);
 4670:                     }
 4671:                     if ($listing_results[0] ne 'no_such_dir' && 
 4672:                         $listing_results[0] ne 'empty'       &&
 4673:                         $listing_results[0] ne 'con_lost') {
 4674:                         foreach (@listing_results) {
 4675:                             my ($entry,@stat)=split(/&/,$_);
 4676:                             $allusers{$entry}=1;
 4677:                         }
 4678:                     }
 4679:                 }
 4680:             }
 4681:             my $alluserstr='';
 4682:             foreach (sort keys %allusers) {
 4683:                 $alluserstr.=$_.'&user:';
 4684:             }
 4685:             $alluserstr=~s/:$//;
 4686:             return split(/:/,$alluserstr);
 4687:         } else {
 4688:             my @emptyResults = ();
 4689:             push(@emptyResults, 'missing user name');
 4690:             return split(':',@emptyResults);
 4691:         }
 4692:     } elsif(!defined($alternateDirectoryRoot)) {
 4693:         my $tryserver;
 4694:         my %alldom=();
 4695:         foreach $tryserver (keys %libserv) {
 4696:             $alldom{$hostdom{$tryserver}}=1;
 4697:         }
 4698:         my $alldomstr='';
 4699:         foreach (sort keys %alldom) {
 4700:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 4701:         }
 4702:         $alldomstr=~s/:$//;
 4703:         return split(/:/,$alldomstr);       
 4704:     } else {
 4705:         my @emptyResults = ();
 4706:         push(@emptyResults, 'missing domain');
 4707:         return split(':',@emptyResults);
 4708:     }
 4709: }
 4710: 
 4711: # --------------------------------------------- GetFileTimestamp
 4712: # This function utilizes dirlist and returns the date stamp for
 4713: # when it was last modified.  It will also return an error of -1
 4714: # if an error occurs
 4715: 
 4716: ##
 4717: ## FIXME: This subroutine assumes its caller knows something about the
 4718: ## directory structure of the home server for the student ($root).
 4719: ## Not a good assumption to make.  Since this is for looking up files
 4720: ## in user directories, the full path should be constructed by lond, not
 4721: ## whatever machine we request data from.
 4722: ##
 4723: sub GetFileTimestamp {
 4724:     my ($studentDomain,$studentName,$filename,$root)=@_;
 4725:     $studentDomain=~s/\W//g;
 4726:     $studentName=~s/\W//g;
 4727:     my $subdir=$studentName.'__';
 4728:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 4729:     my $proname="$studentDomain/$subdir/$studentName";
 4730:     $proname .= '/'.$filename;
 4731:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 4732:                                               $studentName, $root);
 4733:     my @stats = split('&', $fileStat);
 4734:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 4735:         # @stats contains first the filename, then the stat output
 4736:         return $stats[10]; # so this is 10 instead of 9.
 4737:     } else {
 4738:         return -1;
 4739:     }
 4740: }
 4741: 
 4742: sub stat_file {
 4743:     my ($uri) = @_;
 4744:     $uri = &clutter($uri);
 4745: 
 4746:     # we want just the url part without the unneeded accessor url bits
 4747:     if ($uri =~ m-^/adm/-) {
 4748: 	$uri=~s-^/adm/wrapper/-/-;
 4749: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
 4750:     }
 4751:     my ($udom,$uname,$file,$dir);
 4752:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 4753: 	($udom,$uname,$file) =
 4754: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
 4755: 	$file = 'userfiles/'.$file;
 4756: 	$dir = &Apache::loncommon::propath($udom,$uname);
 4757:     }
 4758:     if ($uri =~ m-^/res/-) {
 4759: 	($udom,$uname) = 
 4760: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
 4761: 	$file = $uri;
 4762:     }
 4763: 
 4764:     if (!$udom || !$uname || !$file) {
 4765: 	# unable to handle the uri
 4766: 	return ();
 4767:     }
 4768: 
 4769:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 4770:     my @stats = split('&', $result);
 4771:     
 4772:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 4773: 	shift(@stats); #filename is first
 4774: 	return @stats;
 4775:     }
 4776:     return ();
 4777: }
 4778: 
 4779: # -------------------------------------------------------- Value of a Condition
 4780: 
 4781: # gets the value of a specific preevaluated condition
 4782: #    stored in the string  $env{user.state.<cid>}
 4783: # or looks up a condition reference in the bighash and if if hasn't
 4784: # already been evaluated recurses into docondval to get the value of
 4785: # the condition, then memoizing it to 
 4786: #   $env{user.state.<cid>.<condition>}
 4787: sub directcondval {
 4788:     my $number=shift;
 4789:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 4790: 	&Apache::lonuserstate::evalstate();
 4791:     }
 4792:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 4793: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 4794:     } elsif ($number =~ /^_/) {
 4795: 	my $sub_condition;
 4796: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4797: 		&GDBM_READER(),0640)) {
 4798: 	    $sub_condition=$bighash{'conditions'.$number};
 4799: 	    untie(%bighash);
 4800: 	}
 4801: 	my $value = &docondval($sub_condition);
 4802: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 4803: 	return $value;
 4804:     }
 4805:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 4806:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 4807:     } else {
 4808:        return 2;
 4809:     }
 4810: }
 4811: 
 4812: # get the collection of conditions for this resource
 4813: sub condval {
 4814:     my $condidx=shift;
 4815:     my $allpathcond='';
 4816:     foreach my $cond (split(/\|/,$condidx)) {
 4817: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 4818: 	    $allpathcond.=
 4819: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 4820: 	}
 4821:     }
 4822:     $allpathcond=~s/\|$//;
 4823:     return &docondval($allpathcond);
 4824: }
 4825: 
 4826: #evaluates an expression of conditions
 4827: sub docondval {
 4828:     my ($allpathcond) = @_;
 4829:     my $result=0;
 4830:     if ($env{'request.course.id'}
 4831: 	&& defined($allpathcond)) {
 4832: 	my $operand='|';
 4833: 	my @stack;
 4834: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 4835: 	    if ($chunk eq '(') {
 4836: 		push @stack,($operand,$result);
 4837: 	    } elsif ($chunk eq ')') {
 4838: 		my $before=pop @stack;
 4839: 		if (pop @stack eq '&') {
 4840: 		    $result=$result>$before?$before:$result;
 4841: 		} else {
 4842: 		    $result=$result>$before?$result:$before;
 4843: 		}
 4844: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 4845: 		$operand=$chunk;
 4846: 	    } else {
 4847: 		my $new=directcondval($chunk);
 4848: 		if ($operand eq '&') {
 4849: 		    $result=$result>$new?$new:$result;
 4850: 		} else {
 4851: 		    $result=$result>$new?$result:$new;
 4852: 		}
 4853: 	    }
 4854: 	}
 4855:     }
 4856:     return $result;
 4857: }
 4858: 
 4859: # ---------------------------------------------------- Devalidate courseresdata
 4860: 
 4861: sub devalidatecourseresdata {
 4862:     my ($coursenum,$coursedomain)=@_;
 4863:     my $hashid=$coursenum.':'.$coursedomain;
 4864:     &devalidate_cache_new('courseres',$hashid);
 4865: }
 4866: 
 4867: # --------------------------------------------------- Course Resourcedata Query
 4868: 
 4869: sub get_courseresdata {
 4870:     my ($coursenum,$coursedomain)=@_;
 4871:     my $coursehom=&homeserver($coursenum,$coursedomain);
 4872:     my $hashid=$coursenum.':'.$coursedomain;
 4873:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 4874:     my %dumpreply;
 4875:     unless (defined($cached)) {
 4876: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 4877: 	$result=\%dumpreply;
 4878: 	my ($tmp) = keys(%dumpreply);
 4879: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 4880: 	    &do_cache_new('courseres',$hashid,$result,600);
 4881: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 4882: 	    return $tmp;
 4883: 	} elsif ($tmp =~ /^(error)/) {
 4884: 	    $result=undef;
 4885: 	    &do_cache_new('courseres',$hashid,$result,600);
 4886: 	}
 4887:     }
 4888:     return $result;
 4889: }
 4890: 
 4891: sub devalidateuserresdata {
 4892:     my ($uname,$udom)=@_;
 4893:     my $hashid="$udom:$uname";
 4894:     &devalidate_cache_new('userres',$hashid);
 4895: }
 4896: 
 4897: sub get_userresdata {
 4898:     my ($uname,$udom)=@_;
 4899:     #most student don\'t have any data set, check if there is some data
 4900:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 4901: 
 4902:     my $hashid="$udom:$uname";
 4903:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 4904:     if (!defined($cached)) {
 4905: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 4906: 	$result=\%resourcedata;
 4907: 	&do_cache_new('userres',$hashid,$result,600);
 4908:     }
 4909:     my ($tmp)=keys(%$result);
 4910:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 4911: 	return $result;
 4912:     }
 4913:     #error 2 occurs when the .db doesn't exist
 4914:     if ($tmp!~/error: 2 /) {
 4915: 	&logthis("<font color=\"blue\">WARNING:".
 4916: 		 " Trying to get resource data for ".
 4917: 		 $uname." at ".$udom.": ".
 4918: 		 $tmp."</font>");
 4919:     } elsif ($tmp=~/error: 2 /) {
 4920: 	#&EXT_cache_set($udom,$uname);
 4921: 	&do_cache_new('userres',$hashid,undef,600);
 4922: 	undef($tmp); # not really an error so don't send it back
 4923:     }
 4924:     return $tmp;
 4925: }
 4926: 
 4927: sub resdata {
 4928:     my ($name,$domain,$type,@which)=@_;
 4929:     my $result;
 4930:     if ($type eq 'course') {
 4931: 	$result=&get_courseresdata($name,$domain);
 4932:     } elsif ($type eq 'user') {
 4933: 	$result=&get_userresdata($name,$domain);
 4934:     }
 4935:     if (!ref($result)) { return $result; }    
 4936:     foreach my $item (@which) {
 4937: 	if (defined($result->{$item})) {
 4938: 	    return $result->{$item};
 4939: 	}
 4940:     }
 4941:     return undef;
 4942: }
 4943: 
 4944: #
 4945: # EXT resource caching routines
 4946: #
 4947: 
 4948: sub clear_EXT_cache_status {
 4949:     &delenv('cache.EXT.');
 4950: }
 4951: 
 4952: sub EXT_cache_status {
 4953:     my ($target_domain,$target_user) = @_;
 4954:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 4955:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 4956:         # We know already the user has no data
 4957:         return 1;
 4958:     } else {
 4959:         return 0;
 4960:     }
 4961: }
 4962: 
 4963: sub EXT_cache_set {
 4964:     my ($target_domain,$target_user) = @_;
 4965:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 4966:     #&appenv($cachename => time);
 4967: }
 4968: 
 4969: # --------------------------------------------------------- Value of a Variable
 4970: sub EXT {
 4971: 
 4972:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 4973:     unless ($varname) { return ''; }
 4974:     #get real user name/domain, courseid and symb
 4975:     my $courseid;
 4976:     my $publicuser;
 4977:     if ($symbparm) {
 4978: 	$symbparm=&get_symb_from_alias($symbparm);
 4979:     }
 4980:     if (!($uname && $udom)) {
 4981:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 4982: 	  &Apache::lonxml::whichuser($symbparm);
 4983:       if (!$symbparm) {	$symbparm=$cursymb; }
 4984:     } else {
 4985: 	$courseid=$env{'request.course.id'};
 4986:     }
 4987:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 4988:     my $rest;
 4989:     if (defined($therest[0])) {
 4990:        $rest=join('.',@therest);
 4991:     } else {
 4992:        $rest='';
 4993:     }
 4994: 
 4995:     my $qualifierrest=$qualifier;
 4996:     if ($rest) { $qualifierrest.='.'.$rest; }
 4997:     my $spacequalifierrest=$space;
 4998:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 4999:     if ($realm eq 'user') {
 5000: # --------------------------------------------------------------- user.resource
 5001: 	if ($space eq 'resource') {
 5002: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5003: 		  || defined($Apache::lonhomework::parsing_a_task))
 5004: 		 &&
 5005: 		 ($symbparm eq &symbread()) ) {
 5006: 		return $Apache::lonhomework::history{$qualifierrest};
 5007: 	    } else {
 5008: 		my %restored;
 5009: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5010: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5011: 		} else {
 5012: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5013: 		}
 5014: 		return $restored{$qualifierrest};
 5015: 	    }
 5016: # ----------------------------------------------------------------- user.access
 5017:         } elsif ($space eq 'access') {
 5018: 	    # FIXME - not supporting calls for a specific user
 5019:             return &allowed($qualifier,$rest);
 5020: # ------------------------------------------ user.preferences, user.environment
 5021:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5022: 	    if (($uname eq $env{'user.name'}) &&
 5023: 		($udom eq $env{'user.domain'})) {
 5024: 		return $env{join('.',('environment',$qualifierrest))};
 5025: 	    } else {
 5026: 		my %returnhash;
 5027: 		if (!$publicuser) {
 5028: 		    %returnhash=&userenvironment($udom,$uname,
 5029: 						 $qualifierrest);
 5030: 		}
 5031: 		return $returnhash{$qualifierrest};
 5032: 	    }
 5033: # ----------------------------------------------------------------- user.course
 5034:         } elsif ($space eq 'course') {
 5035: 	    # FIXME - not supporting calls for a specific user
 5036:             return $env{join('.',('request.course',$qualifier))};
 5037: # ------------------------------------------------------------------- user.role
 5038:         } elsif ($space eq 'role') {
 5039: 	    # FIXME - not supporting calls for a specific user
 5040:             my ($role,$where)=split(/\./,$env{'request.role'});
 5041:             if ($qualifier eq 'value') {
 5042: 		return $role;
 5043:             } elsif ($qualifier eq 'extent') {
 5044:                 return $where;
 5045:             }
 5046: # ----------------------------------------------------------------- user.domain
 5047:         } elsif ($space eq 'domain') {
 5048:             return $udom;
 5049: # ------------------------------------------------------------------- user.name
 5050:         } elsif ($space eq 'name') {
 5051:             return $uname;
 5052: # ---------------------------------------------------- Any other user namespace
 5053:         } else {
 5054: 	    my %reply;
 5055: 	    if (!$publicuser) {
 5056: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5057: 	    }
 5058: 	    return $reply{$qualifierrest};
 5059:         }
 5060:     } elsif ($realm eq 'query') {
 5061: # ---------------------------------------------- pull stuff out of query string
 5062:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5063: 						[$spacequalifierrest]);
 5064: 	return $env{'form.'.$spacequalifierrest}; 
 5065:    } elsif ($realm eq 'request') {
 5066: # ------------------------------------------------------------- request.browser
 5067:         if ($space eq 'browser') {
 5068: 	    if ($qualifier eq 'textremote') {
 5069: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5070: 		    return 1;
 5071: 		} else {
 5072: 		    return 0;
 5073: 		}
 5074: 	    } else {
 5075: 		return $env{'browser.'.$qualifier};
 5076: 	    }
 5077: # ------------------------------------------------------------ request.filename
 5078:         } else {
 5079:             return $env{'request.'.$spacequalifierrest};
 5080:         }
 5081:     } elsif ($realm eq 'course') {
 5082: # ---------------------------------------------------------- course.description
 5083:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5084:     } elsif ($realm eq 'resource') {
 5085: 
 5086: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5087: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5088: 	}
 5089: 
 5090: 	if ($space eq 'title') {
 5091: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5092: 	    return &gettitle($symbparm);
 5093: 	}
 5094: 	
 5095: 	if ($space eq 'map') {
 5096: 	    my ($map) = &decode_symb($symbparm);
 5097: 	    return &symbread($map);
 5098: 	}
 5099: 
 5100: 	my ($section, $group, @groups);
 5101: 	my ($courselevelm,$courselevel);
 5102: 	if ($symbparm && defined($courseid) && 
 5103: 	    $courseid eq $env{'request.course.id'}) {
 5104: 
 5105: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5106: 
 5107: # ----------------------------------------------------- Cascading lookup scheme
 5108: 	    my $symbp=$symbparm;
 5109: 	    my $mapp=(&decode_symb($symbp))[0];
 5110: 
 5111: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5112: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5113: 
 5114: 	    if (($env{'user.name'} eq $uname) &&
 5115: 		($env{'user.domain'} eq $udom)) {
 5116: 		$section=$env{'request.course.sec'};
 5117:                 @groups=&sort_course_groups($env{'request.course.groups'},$courseid); 
 5118: 	    } else {
 5119: 		if (! defined($usection)) {
 5120: 		    $section=&getsection($udom,$uname,$courseid);
 5121: 		} else {
 5122: 		    $section = $usection;
 5123: 		}
 5124:                 my $grouplist = &get_users_groups($udom,$uname,$courseid);
 5125:                 if ($grouplist) {
 5126:                     @groups=&sort_course_groups($grouplist,$courseid);
 5127:                 }
 5128: 	    }
 5129: 
 5130: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5131: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5132: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5133: 
 5134: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5135: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5136: 	    $courselevelm=$courseid.'.'.$mapparm;
 5137: 
 5138: # ----------------------------------------------------------- first, check user
 5139: 
 5140: 	    my $userreply=&resdata($uname,$udom,'user',
 5141: 				       ($courselevelr,$courselevelm,
 5142: 					$courselevel));
 5143: 	    if (defined($userreply)) { return $userreply; }
 5144: 
 5145: # ------------------------------------------------ second, check some of course
 5146:             my $coursereply;
 5147:             if (@groups > 0) {
 5148:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5149:                                        $mapparm,$spacequalifierrest);
 5150:                 if (defined($coursereply)) { return $coursereply; }
 5151:             }
 5152: 
 5153: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5154: 				     $env{'course.'.$courseid.'.domain'},
 5155: 				     'course',
 5156: 				     ($seclevelr,$seclevelm,$seclevel,
 5157: 				      $courselevelr));
 5158: 	    if (defined($coursereply)) { return $coursereply; }
 5159: 
 5160: # ------------------------------------------------------ third, check map parms
 5161: 	    my %parmhash=();
 5162: 	    my $thisparm='';
 5163: 	    if (tie(%parmhash,'GDBM_File',
 5164: 		    $env{'request.course.fn'}.'_parms.db',
 5165: 		    &GDBM_READER(),0640)) {
 5166: 		$thisparm=$parmhash{$symbparm};
 5167: 		untie(%parmhash);
 5168: 	    }
 5169: 	    if ($thisparm) { return $thisparm; }
 5170: 	}
 5171: # ------------------------------------------ fourth, look in resource metadata
 5172: 
 5173: 	$spacequalifierrest=~s/\./\_/;
 5174: 	my $filename;
 5175: 	if (!$symbparm) { $symbparm=&symbread(); }
 5176: 	if ($symbparm) {
 5177: 	    $filename=(&decode_symb($symbparm))[2];
 5178: 	} else {
 5179: 	    $filename=$env{'request.filename'};
 5180: 	}
 5181: 	my $metadata=&metadata($filename,$spacequalifierrest);
 5182: 	if (defined($metadata)) { return $metadata; }
 5183: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 5184: 	if (defined($metadata)) { return $metadata; }
 5185: 
 5186: # ---------------------------------------------- fourth, look in rest pf course
 5187: 	if ($symbparm && defined($courseid) && 
 5188: 	    $courseid eq $env{'request.course.id'}) {
 5189: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5190: 				     $env{'course.'.$courseid.'.domain'},
 5191: 				     'course',
 5192: 				     ($courselevelm,$courselevel));
 5193: 	    if (defined($coursereply)) { return $coursereply; }
 5194: 	}
 5195: # ------------------------------------------------------------------ Cascade up
 5196: 	unless ($space eq '0') {
 5197: 	    my @parts=split(/_/,$space);
 5198: 	    my $id=pop(@parts);
 5199: 	    my $part=join('_',@parts);
 5200: 	    if ($part eq '') { $part='0'; }
 5201: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 5202: 				 $symbparm,$udom,$uname,$section,1);
 5203: 	    if (defined($partgeneral)) { return $partgeneral; }
 5204: 	}
 5205: 	if ($recurse) { return undef; }
 5206: 	my $pack_def=&packages_tab_default($filename,$varname);
 5207: 	if (defined($pack_def)) { return $pack_def; }
 5208: 
 5209: # ---------------------------------------------------- Any other user namespace
 5210:     } elsif ($realm eq 'environment') {
 5211: # ----------------------------------------------------------------- environment
 5212: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 5213: 	    return $env{'environment.'.$spacequalifierrest};
 5214: 	} else {
 5215: 	    my %returnhash=&userenvironment($udom,$uname,
 5216: 					    $spacequalifierrest);
 5217: 	    return $returnhash{$spacequalifierrest};
 5218: 	}
 5219:     } elsif ($realm eq 'system') {
 5220: # ----------------------------------------------------------------- system.time
 5221: 	if ($space eq 'time') {
 5222: 	    return time;
 5223:         }
 5224:     } elsif ($realm eq 'server') {
 5225: # ----------------------------------------------------------------- system.time
 5226: 	if ($space eq 'name') {
 5227: 	    return $ENV{'SERVER_NAME'};
 5228:         }
 5229:     }
 5230:     return '';
 5231: }
 5232: 
 5233: sub check_group_parms {
 5234:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 5235:     my @groupitems = ();
 5236:     my $resultitem;
 5237:     my @levels = ($symbparm,$mapparm,$what);
 5238:     foreach my $group (@{$groups}) {
 5239:         foreach my $level (@levels) {
 5240:              my $item = $courseid.'.['.$group.'].'.$level;
 5241:              push(@groupitems,$item);
 5242:         }
 5243:     }
 5244:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 5245:                             $env{'course.'.$courseid.'.domain'},
 5246:                                      'course',@groupitems);
 5247:     return $coursereply;
 5248: }
 5249: 
 5250: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 5251:     my ($grouplist,$courseid) = @_;
 5252:     my @groups = sort(split(/:/,$grouplist));
 5253:     return @groups;
 5254: }
 5255: 
 5256: sub packages_tab_default {
 5257:     my ($uri,$varname)=@_;
 5258:     my (undef,$part,$name)=split(/\./,$varname);
 5259:     my $packages=&metadata($uri,'packages');
 5260:     foreach my $package (split(/,/,$packages)) {
 5261: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 5262: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5263: 	    return $packagetab{"$pack_type&$name&default"};
 5264: 	}
 5265: 	if ($pack_type eq 'part') { $pack_part='0'; }
 5266: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 5267: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 5268: 	}
 5269:     }
 5270:     return undef;
 5271: }
 5272: 
 5273: sub add_prefix_and_part {
 5274:     my ($prefix,$part)=@_;
 5275:     my $keyroot;
 5276:     if (defined($prefix) && $prefix !~ /^__/) {
 5277: 	# prefix that has a part already
 5278: 	$keyroot=$prefix;
 5279:     } elsif (defined($prefix)) {
 5280: 	# prefix that is missing a part
 5281: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 5282:     } else {
 5283: 	# no prefix at all
 5284: 	if (defined($part)) { $keyroot='_'.$part; }
 5285:     }
 5286:     return $keyroot;
 5287: }
 5288: 
 5289: # ---------------------------------------------------------------- Get metadata
 5290: 
 5291: my %metaentry;
 5292: sub metadata {
 5293:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 5294:     $uri=&declutter($uri);
 5295:     # if it is a non metadata possible uri return quickly
 5296:     if (($uri eq '') || 
 5297: 	(($uri =~ m|^/*adm/|) && 
 5298: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 5299:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 5300: 	($uri =~ m|home/[^/]+/public_html/|)) {
 5301: 	return undef;
 5302:     }
 5303:     my $filename=$uri;
 5304:     $uri=~s/\.meta$//;
 5305: #
 5306: # Is the metadata already cached?
 5307: # Look at timestamp of caching
 5308: # Everything is cached by the main uri, libraries are never directly cached
 5309: #
 5310:     if (!defined($liburi)) {
 5311: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 5312: 	if (defined($cached)) { return $result->{':'.$what}; }
 5313:     }
 5314:     {
 5315: #
 5316: # Is this a recursive call for a library?
 5317: #
 5318: #	if (! exists($metacache{$uri})) {
 5319: #	    $metacache{$uri}={};
 5320: #	}
 5321:         if ($liburi) {
 5322: 	    $liburi=&declutter($liburi);
 5323:             $filename=$liburi;
 5324:         } else {
 5325: 	    &devalidate_cache_new('meta',$uri);
 5326: 	    undef(%metaentry);
 5327: 	}
 5328:         my %metathesekeys=();
 5329:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 5330: 	my $metastring;
 5331: 	if ($uri !~ m -^(uploaded|editupload)/-) {
 5332: 	    my $file=&filelocation('',&clutter($filename));
 5333: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 5334: 	    $metastring=&getfile($file);
 5335: 	}
 5336:         my $parser=HTML::LCParser->new(\$metastring);
 5337:         my $token;
 5338:         undef %metathesekeys;
 5339:         while ($token=$parser->get_token) {
 5340: 	    if ($token->[0] eq 'S') {
 5341: 		if (defined($token->[2]->{'package'})) {
 5342: #
 5343: # This is a package - get package info
 5344: #
 5345: 		    my $package=$token->[2]->{'package'};
 5346: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5347: 		    if (defined($token->[2]->{'id'})) { 
 5348: 			$keyroot.='_'.$token->[2]->{'id'}; 
 5349: 		    }
 5350: 		    if ($metaentry{':packages'}) {
 5351: 			$metaentry{':packages'}.=','.$package.$keyroot;
 5352: 		    } else {
 5353: 			$metaentry{':packages'}=$package.$keyroot;
 5354: 		    }
 5355: 		    foreach (sort keys %packagetab) {
 5356: 			my $part=$keyroot;
 5357: 			$part=~s/^\_//;
 5358: 			if ($_=~/^\Q$package\E\&/ || 
 5359: 			    $_=~/^\Q$package\E_0\&/) {
 5360: 			    my ($pack,$name,$subp)=split(/\&/,$_);
 5361: 			    # ignore package.tab specified default values
 5362:                             # here &package_tab_default() will fetch those
 5363: 			    if ($subp eq 'default') { next; }
 5364: 			    my $value=$packagetab{$_};
 5365: 			    my $unikey;
 5366: 			    if ($pack =~ /_0$/) {
 5367: 				$unikey='parameter_0_'.$name;
 5368: 				$part=0;
 5369: 			    } else {
 5370: 				$unikey='parameter'.$keyroot.'_'.$name;
 5371: 			    }
 5372: 			    if ($subp eq 'display') {
 5373: 				$value.=' [Part: '.$part.']';
 5374: 			    }
 5375: 			    $metaentry{':'.$unikey.'.part'}=$part;
 5376: 			    $metathesekeys{$unikey}=1;
 5377: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5378: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 5379: 			    }
 5380: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 5381: 				$metaentry{':'.$unikey}=
 5382: 				    $metaentry{':'.$unikey.'.default'};
 5383: 			    }
 5384: 			}
 5385: 		    }
 5386: 		} else {
 5387: #
 5388: # This is not a package - some other kind of start tag
 5389: #
 5390: 		    my $entry=$token->[1];
 5391: 		    my $unikey;
 5392: 		    if ($entry eq 'import') {
 5393: 			$unikey='';
 5394: 		    } else {
 5395: 			$unikey=$entry;
 5396: 		    }
 5397: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5398: 
 5399: 		    if (defined($token->[2]->{'id'})) { 
 5400: 			$unikey.='_'.$token->[2]->{'id'}; 
 5401: 		    }
 5402: 
 5403: 		    if ($entry eq 'import') {
 5404: #
 5405: # Importing a library here
 5406: #
 5407: 			if ($depthcount<20) {
 5408: 			    my $location=$parser->get_text('/import');
 5409: 			    my $dir=$filename;
 5410: 			    $dir=~s|[^/]*$||;
 5411: 			    $location=&filelocation($dir,$location);
 5412: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
 5413: 							       $location,$unikey,
 5414: 							       $depthcount+1)))) {
 5415: 				$metaentry{':'.$_}=$metaentry{':'.$_};
 5416: 				$metathesekeys{$_}=1;
 5417: 			    }
 5418: 			}
 5419: 		    } else { 
 5420: 			
 5421: 			if (defined($token->[2]->{'name'})) { 
 5422: 			    $unikey.='_'.$token->[2]->{'name'}; 
 5423: 			}
 5424: 			$metathesekeys{$unikey}=1;
 5425: 			foreach (@{$token->[3]}) {
 5426: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
 5427: 			}
 5428: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 5429: 			my $default=$metaentry{':'.$unikey.'.default'};
 5430: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 5431: 		 # only ws inside the tag, and not in default, so use default
 5432: 		 # as value
 5433: 			    $metaentry{':'.$unikey}=$default;
 5434: 			} else {
 5435: 		  # either something interesting inside the tag or default
 5436:                   # uninteresting
 5437: 			    $metaentry{':'.$unikey}=$internaltext;
 5438: 			}
 5439: # end of not-a-package not-a-library import
 5440: 		    }
 5441: # end of not-a-package start tag
 5442: 		}
 5443: # the next is the end of "start tag"
 5444: 	    }
 5445: 	}
 5446: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 5447: 	foreach my $key (sort(keys(%packagetab))) {
 5448: 	    #no specific packages #how's our extension
 5449: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 5450: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 5451: 					 \%metathesekeys);
 5452: 	}
 5453: 	if (!exists($metaentry{':packages'})) {
 5454: 	    foreach my $key (sort(keys(%packagetab))) {
 5455: 		#no specific packages well let's get default then
 5456: 		if ($key!~/^default&/) { next; }
 5457: 		&metadata_create_package_def($uri,$key,'default',
 5458: 					     \%metathesekeys);
 5459: 	    }
 5460: 	}
 5461: # are there custom rights to evaluate
 5462: 	if ($metaentry{':copyright'} eq 'custom') {
 5463: 
 5464:     #
 5465:     # Importing a rights file here
 5466:     #
 5467: 	    unless ($depthcount) {
 5468: 		my $location=$metaentry{':customdistributionfile'};
 5469: 		my $dir=$filename;
 5470: 		$dir=~s|[^/]*$||;
 5471: 		$location=&filelocation($dir,$location);
 5472: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
 5473: 						   $location,'_rights',
 5474: 						   $depthcount+1)))) {
 5475: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
 5476: 		    $metathesekeys{$_}=1;
 5477: 		}
 5478: 	    }
 5479: 	}
 5480: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
 5481: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 5482: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 5483: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 5484: # this is the end of "was not already recently cached
 5485:     }
 5486:     return $metaentry{':'.$what};
 5487: }
 5488: 
 5489: sub metadata_create_package_def {
 5490:     my ($uri,$key,$package,$metathesekeys)=@_;
 5491:     my ($pack,$name,$subp)=split(/\&/,$key);
 5492:     if ($subp eq 'default') { next; }
 5493:     
 5494:     if (defined($metaentry{':packages'})) {
 5495: 	$metaentry{':packages'}.=','.$package;
 5496:     } else {
 5497: 	$metaentry{':packages'}=$package;
 5498:     }
 5499:     my $value=$packagetab{$key};
 5500:     my $unikey;
 5501:     $unikey='parameter_0_'.$name;
 5502:     $metaentry{':'.$unikey.'.part'}=0;
 5503:     $$metathesekeys{$unikey}=1;
 5504:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5505: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 5506:     }
 5507:     if (defined($metaentry{':'.$unikey.'.default'})) {
 5508: 	$metaentry{':'.$unikey}=
 5509: 	    $metaentry{':'.$unikey.'.default'};
 5510:     }
 5511: }
 5512: 
 5513: sub metadata_generate_part0 {
 5514:     my ($metadata,$metacache,$uri) = @_;
 5515:     my %allnames;
 5516:     foreach my $metakey (sort keys %$metadata) {
 5517: 	if ($metakey=~/^parameter\_(.*)/) {
 5518: 	  my $part=$$metacache{':'.$metakey.'.part'};
 5519: 	  my $name=$$metacache{':'.$metakey.'.name'};
 5520: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 5521: 	    $allnames{$name}=$part;
 5522: 	  }
 5523: 	}
 5524:     }
 5525:     foreach my $name (keys(%allnames)) {
 5526:       $$metadata{"parameter_0_$name"}=1;
 5527:       my $key=":parameter_0_$name";
 5528:       $$metacache{"$key.part"}='0';
 5529:       $$metacache{"$key.name"}=$name;
 5530:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 5531: 					   $allnames{$name}.'_'.$name.
 5532: 					   '.type'};
 5533:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 5534: 			     '.display'};
 5535:       my $expr='[Part: '.$allnames{$name}.']';
 5536:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 5537:       $$metacache{"$key.display"}=$olddis;
 5538:     }
 5539: }
 5540: 
 5541: # ------------------------------------------------- Get the title of a resource
 5542: 
 5543: sub gettitle {
 5544:     my $urlsymb=shift;
 5545:     my $symb=&symbread($urlsymb);
 5546:     if ($symb) {
 5547: 	my $key=$env{'request.course.id'}."\0".$symb;
 5548: 	my ($result,$cached)=&is_cached_new('title',$key);
 5549: 	if (defined($cached)) { 
 5550: 	    return $result;
 5551: 	}
 5552: 	my ($map,$resid,$url)=&decode_symb($symb);
 5553: 	my $title='';
 5554: 	my %bighash;
 5555: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5556: 		&GDBM_READER(),0640)) {
 5557: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 5558: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 5559: 	    untie %bighash;
 5560: 	}
 5561: 	$title=~s/\&colon\;/\:/gs;
 5562: 	if ($title) {
 5563: 	    return &do_cache_new('title',$key,$title,600);
 5564: 	}
 5565: 	$urlsymb=$url;
 5566:     }
 5567:     my $title=&metadata($urlsymb,'title');
 5568:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 5569:     return $title;
 5570: }
 5571: 
 5572: sub get_slot {
 5573:     my ($which,$cnum,$cdom)=@_;
 5574:     if (!$cnum || !$cdom) {
 5575: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
 5576: 	$cdom=$env{'course.'.$courseid.'.domain'};
 5577: 	$cnum=$env{'course.'.$courseid.'.num'};
 5578:     }
 5579:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 5580:     my %slotinfo;
 5581:     if (exists($remembered{$key})) {
 5582: 	$slotinfo{$which} = $remembered{$key};
 5583:     } else {
 5584: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 5585: 	&Apache::lonhomework::showhash(%slotinfo);
 5586: 	my ($tmp)=keys(%slotinfo);
 5587: 	if ($tmp=~/^error:/) { return (); }
 5588: 	$remembered{$key} = $slotinfo{$which};
 5589:     }
 5590:     if (ref($slotinfo{$which}) eq 'HASH') {
 5591: 	return %{$slotinfo{$which}};
 5592:     }
 5593:     return $slotinfo{$which};
 5594: }
 5595: # ------------------------------------------------- Update symbolic store links
 5596: 
 5597: sub symblist {
 5598:     my ($mapname,%newhash)=@_;
 5599:     $mapname=&deversion(&declutter($mapname));
 5600:     my %hash;
 5601:     if (($env{'request.course.fn'}) && (%newhash)) {
 5602:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 5603:                       &GDBM_WRCREAT(),0640)) {
 5604: 	    foreach my $url (keys %newhash) {
 5605: 		next if ($url eq 'last_known'
 5606: 			 && $env{'form.no_update_last_known'});
 5607: 		$hash{declutter($url)}=&encode_symb($mapname,
 5608: 						    $newhash{$url}->[1],
 5609: 						    $newhash{$url}->[0]);
 5610:             }
 5611:             if (untie(%hash)) {
 5612: 		return 'ok';
 5613:             }
 5614:         }
 5615:     }
 5616:     return 'error';
 5617: }
 5618: 
 5619: # --------------------------------------------------------------- Verify a symb
 5620: 
 5621: sub symbverify {
 5622:     my ($symb,$thisurl)=@_;
 5623:     my $thisfn=$thisurl;
 5624: # wrapper not part of symbs
 5625:     $thisfn=~s/^\/adm\/wrapper//;
 5626:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
 5627:     $thisfn=&declutter($thisfn);
 5628: # direct jump to resource in page or to a sequence - will construct own symbs
 5629:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 5630: # check URL part
 5631:     my ($map,$resid,$url)=&decode_symb($symb);
 5632: 
 5633:     unless ($url eq $thisfn) { return 0; }
 5634: 
 5635:     $symb=&symbclean($symb);
 5636:     $thisurl=&deversion($thisurl);
 5637:     $thisfn=&deversion($thisfn);
 5638: 
 5639:     my %bighash;
 5640:     my $okay=0;
 5641: 
 5642:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5643:                             &GDBM_READER(),0640)) {
 5644:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 5645:         unless ($ids) { 
 5646:            $ids=$bighash{'ids_/'.$thisurl};
 5647:         }
 5648:         if ($ids) {
 5649: # ------------------------------------------------------------------- Has ID(s)
 5650: 	    foreach (split(/\,/,$ids)) {
 5651: 	       my ($mapid,$resid)=split(/\./,$_);
 5652:                if (
 5653:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 5654:    eq $symb) { 
 5655: 		   if (($env{'request.role.adv'}) ||
 5656: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
 5657: 		       $okay=1; 
 5658: 		   }
 5659: 	       }
 5660: 	   }
 5661:         }
 5662: 	untie(%bighash);
 5663:     }
 5664:     return $okay;
 5665: }
 5666: 
 5667: # --------------------------------------------------------------- Clean-up symb
 5668: 
 5669: sub symbclean {
 5670:     my $symb=shift;
 5671:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 5672: # remove version from map
 5673:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 5674: 
 5675: # remove version from URL
 5676:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 5677: 
 5678: # remove wrapper
 5679: 
 5680:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 5681:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 5682:     return $symb;
 5683: }
 5684: 
 5685: # ---------------------------------------------- Split symb to find map and url
 5686: 
 5687: sub encode_symb {
 5688:     my ($map,$resid,$url)=@_;
 5689:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 5690: }
 5691: 
 5692: sub decode_symb {
 5693:     my $symb=shift;
 5694:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 5695:     my ($map,$resid,$url)=split(/___/,$symb);
 5696:     return (&fixversion($map),$resid,&fixversion($url));
 5697: }
 5698: 
 5699: sub fixversion {
 5700:     my $fn=shift;
 5701:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 5702:     my %bighash;
 5703:     my $uri=&clutter($fn);
 5704:     my $key=$env{'request.course.id'}.'_'.$uri;
 5705: # is this cached?
 5706:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 5707:     if (defined($cached)) { return $result; }
 5708: # unfortunately not cached, or expired
 5709:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5710: 	    &GDBM_READER(),0640)) {
 5711:  	if ($bighash{'version_'.$uri}) {
 5712:  	    my $version=$bighash{'version_'.$uri};
 5713:  	    unless (($version eq 'mostrecent') || 
 5714: 		    ($version==&getversion($uri))) {
 5715:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 5716:  	    }
 5717:  	}
 5718:  	untie %bighash;
 5719:     }
 5720:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 5721: }
 5722: 
 5723: sub deversion {
 5724:     my $url=shift;
 5725:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 5726:     return $url;
 5727: }
 5728: 
 5729: # ------------------------------------------------------ Return symb list entry
 5730: 
 5731: sub symbread {
 5732:     my ($thisfn,$donotrecurse)=@_;
 5733:     my $cache_str='request.symbread.cached.'.$thisfn;
 5734:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 5735: # no filename provided? try from environment
 5736:     unless ($thisfn) {
 5737:         if ($env{'request.symb'}) {
 5738: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 5739: 	}
 5740: 	$thisfn=$env{'request.filename'};
 5741:     }
 5742:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 5743: # is that filename actually a symb? Verify, clean, and return
 5744:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 5745: 	if (&symbverify($thisfn,$1)) {
 5746: 	    return $env{$cache_str}=&symbclean($thisfn);
 5747: 	}
 5748:     }
 5749:     $thisfn=declutter($thisfn);
 5750:     my %hash;
 5751:     my %bighash;
 5752:     my $syval='';
 5753:     if (($env{'request.course.fn'}) && ($thisfn)) {
 5754:         my $targetfn = $thisfn;
 5755:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 5756:             $targetfn = 'adm/wrapper/'.$thisfn;
 5757:         }
 5758: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 5759: 	    $targetfn=$1;
 5760: 	}
 5761:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 5762:                       &GDBM_READER(),0640)) {
 5763: 	    $syval=$hash{$targetfn};
 5764:             untie(%hash);
 5765:         }
 5766: # ---------------------------------------------------------- There was an entry
 5767:         if ($syval) {
 5768: 	    #unless ($syval=~/\_\d+$/) {
 5769: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 5770: 		    #&appenv('request.ambiguous' => $thisfn);
 5771: 		    #return $env{$cache_str}='';
 5772: 		#}    
 5773: 		#$syval.=$1;
 5774: 	    #}
 5775:         } else {
 5776: # ------------------------------------------------------- Was not in symb table
 5777:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5778:                             &GDBM_READER(),0640)) {
 5779: # ---------------------------------------------- Get ID(s) for current resource
 5780:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 5781:               unless ($ids) { 
 5782:                  $ids=$bighash{'ids_/'.$thisfn};
 5783:               }
 5784:               unless ($ids) {
 5785: # alias?
 5786: 		  $ids=$bighash{'mapalias_'.$thisfn};
 5787:               }
 5788:               if ($ids) {
 5789: # ------------------------------------------------------------------- Has ID(s)
 5790:                  my @possibilities=split(/\,/,$ids);
 5791:                  if ($#possibilities==0) {
 5792: # ----------------------------------------------- There is only one possibility
 5793: 		     my ($mapid,$resid)=split(/\./,$ids);
 5794: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 5795: 						    $resid,$thisfn);
 5796:                  } elsif (!$donotrecurse) {
 5797: # ------------------------------------------ There is more than one possibility
 5798:                      my $realpossible=0;
 5799:                      foreach (@possibilities) {
 5800: 			 my $file=$bighash{'src_'.$_};
 5801:                          if (&allowed('bre',$file)) {
 5802:          		    my ($mapid,$resid)=split(/\./,$_);
 5803:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 5804: 				$realpossible++;
 5805:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 5806: 						    $resid,$thisfn);
 5807:                             }
 5808: 			 }
 5809:                      }
 5810: 		     if ($realpossible!=1) { $syval=''; }
 5811:                  } else {
 5812:                      $syval='';
 5813:                  }
 5814: 	      }
 5815:               untie(%bighash)
 5816:            }
 5817:         }
 5818:         if ($syval) {
 5819: 	    return $env{$cache_str}=$syval;
 5820:         }
 5821:     }
 5822:     &appenv('request.ambiguous' => $thisfn);
 5823:     return $env{$cache_str}='';
 5824: }
 5825: 
 5826: # ---------------------------------------------------------- Return random seed
 5827: 
 5828: sub numval {
 5829:     my $txt=shift;
 5830:     $txt=~tr/A-J/0-9/;
 5831:     $txt=~tr/a-j/0-9/;
 5832:     $txt=~tr/K-T/0-9/;
 5833:     $txt=~tr/k-t/0-9/;
 5834:     $txt=~tr/U-Z/0-5/;
 5835:     $txt=~tr/u-z/0-5/;
 5836:     $txt=~s/\D//g;
 5837:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 5838:     return int($txt);
 5839: }
 5840: 
 5841: sub numval2 {
 5842:     my $txt=shift;
 5843:     $txt=~tr/A-J/0-9/;
 5844:     $txt=~tr/a-j/0-9/;
 5845:     $txt=~tr/K-T/0-9/;
 5846:     $txt=~tr/k-t/0-9/;
 5847:     $txt=~tr/U-Z/0-5/;
 5848:     $txt=~tr/u-z/0-5/;
 5849:     $txt=~s/\D//g;
 5850:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 5851:     my $total;
 5852:     foreach my $val (@txts) { $total+=$val; }
 5853:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 5854:     return int($total);
 5855: }
 5856: 
 5857: sub numval3 {
 5858:     use integer;
 5859:     my $txt=shift;
 5860:     $txt=~tr/A-J/0-9/;
 5861:     $txt=~tr/a-j/0-9/;
 5862:     $txt=~tr/K-T/0-9/;
 5863:     $txt=~tr/k-t/0-9/;
 5864:     $txt=~tr/U-Z/0-5/;
 5865:     $txt=~tr/u-z/0-5/;
 5866:     $txt=~s/\D//g;
 5867:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 5868:     my $total;
 5869:     foreach my $val (@txts) { $total+=$val; }
 5870:     if ($_64bit) { $total=(($total<<32)>>32); }
 5871:     return $total;
 5872: }
 5873: 
 5874: sub digest {
 5875:     my ($data)=@_;
 5876:     my $digest=&Digest::MD5::md5($data);
 5877:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 5878:     my ($e,$f);
 5879:     {
 5880:         use integer;
 5881:         $e=($a+$b);
 5882:         $f=($c+$d);
 5883:         if ($_64bit) {
 5884:             $e=(($e<<32)>>32);
 5885:             $f=(($f<<32)>>32);
 5886:         }
 5887:     }
 5888:     if (wantarray) {
 5889: 	return ($e,$f);
 5890:     } else {
 5891: 	my $g;
 5892: 	{
 5893: 	    use integer;
 5894: 	    $g=($e+$f);
 5895: 	    if ($_64bit) {
 5896: 		$g=(($g<<32)>>32);
 5897: 	    }
 5898: 	}
 5899: 	return $g;
 5900:     }
 5901: }
 5902: 
 5903: sub latest_rnd_algorithm_id {
 5904:     return '64bit5';
 5905: }
 5906: 
 5907: sub get_rand_alg {
 5908:     my ($courseid)=@_;
 5909:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 5910:     if ($courseid) {
 5911: 	return $env{"course.$courseid.rndseed"};
 5912:     }
 5913:     return &latest_rnd_algorithm_id();
 5914: }
 5915: 
 5916: sub validCODE {
 5917:     my ($CODE)=@_;
 5918:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 5919:     return 0;
 5920: }
 5921: 
 5922: sub getCODE {
 5923:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 5924:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 5925: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 5926: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 5927: 	return $Apache::lonhomework::history{'resource.CODE'};
 5928:     }
 5929:     return undef;
 5930: }
 5931: 
 5932: sub rndseed {
 5933:     my ($symb,$courseid,$domain,$username)=@_;
 5934: 
 5935:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 5936:     if (!$symb) {
 5937: 	unless ($symb=$wsymb) { return time; }
 5938:     }
 5939:     if (!$courseid) { $courseid=$wcourseid; }
 5940:     if (!$domain) { $domain=$wdomain; }
 5941:     if (!$username) { $username=$wusername }
 5942:     my $which=&get_rand_alg();
 5943:     if (defined(&getCODE())) {
 5944: 	if ($which eq '64bit5') {
 5945: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 5946: 	} elsif ($which eq '64bit4') {
 5947: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 5948: 	} else {
 5949: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 5950: 	}
 5951:     } elsif ($which eq '64bit5') {
 5952: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 5953:     } elsif ($which eq '64bit4') {
 5954: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 5955:     } elsif ($which eq '64bit3') {
 5956: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 5957:     } elsif ($which eq '64bit2') {
 5958: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 5959:     } elsif ($which eq '64bit') {
 5960: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 5961:     }
 5962:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 5963: }
 5964: 
 5965: sub rndseed_32bit {
 5966:     my ($symb,$courseid,$domain,$username)=@_;
 5967:     {
 5968: 	use integer;
 5969: 	my $symbchck=unpack("%32C*",$symb) << 27;
 5970: 	my $symbseed=numval($symb) << 22;
 5971: 	my $namechck=unpack("%32C*",$username) << 17;
 5972: 	my $nameseed=numval($username) << 12;
 5973: 	my $domainseed=unpack("%32C*",$domain) << 7;
 5974: 	my $courseseed=unpack("%32C*",$courseid);
 5975: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 5976: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5977: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5978: 	if ($_64bit) { $num=(($num<<32)>>32); }
 5979: 	return $num;
 5980:     }
 5981: }
 5982: 
 5983: sub rndseed_64bit {
 5984:     my ($symb,$courseid,$domain,$username)=@_;
 5985:     {
 5986: 	use integer;
 5987: 	my $symbchck=unpack("%32S*",$symb) << 21;
 5988: 	my $symbseed=numval($symb) << 10;
 5989: 	my $namechck=unpack("%32S*",$username);
 5990: 	
 5991: 	my $nameseed=numval($username) << 21;
 5992: 	my $domainseed=unpack("%32S*",$domain) << 10;
 5993: 	my $courseseed=unpack("%32S*",$courseid);
 5994: 	
 5995: 	my $num1=$symbchck+$symbseed+$namechck;
 5996: 	my $num2=$nameseed+$domainseed+$courseseed;
 5997: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5998: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5999: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6000: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6001: 	return "$num1,$num2";
 6002:     }
 6003: }
 6004: 
 6005: sub rndseed_64bit2 {
 6006:     my ($symb,$courseid,$domain,$username)=@_;
 6007:     {
 6008: 	use integer;
 6009: 	# strings need to be an even # of cahracters long, it it is odd the
 6010:         # last characters gets thrown away
 6011: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6012: 	my $symbseed=numval($symb) << 10;
 6013: 	my $namechck=unpack("%32S*",$username.' ');
 6014: 	
 6015: 	my $nameseed=numval($username) << 21;
 6016: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6017: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6018: 	
 6019: 	my $num1=$symbchck+$symbseed+$namechck;
 6020: 	my $num2=$nameseed+$domainseed+$courseseed;
 6021: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6022: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6023: 	return "$num1,$num2";
 6024:     }
 6025: }
 6026: 
 6027: sub rndseed_64bit3 {
 6028:     my ($symb,$courseid,$domain,$username)=@_;
 6029:     {
 6030: 	use integer;
 6031: 	# strings need to be an even # of cahracters long, it it is odd the
 6032:         # last characters gets thrown away
 6033: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6034: 	my $symbseed=numval2($symb) << 10;
 6035: 	my $namechck=unpack("%32S*",$username.' ');
 6036: 	
 6037: 	my $nameseed=numval2($username) << 21;
 6038: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6039: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6040: 	
 6041: 	my $num1=$symbchck+$symbseed+$namechck;
 6042: 	my $num2=$nameseed+$domainseed+$courseseed;
 6043: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6044: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6045: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6046: 	
 6047: 	return "$num1:$num2";
 6048:     }
 6049: }
 6050: 
 6051: sub rndseed_64bit4 {
 6052:     my ($symb,$courseid,$domain,$username)=@_;
 6053:     {
 6054: 	use integer;
 6055: 	# strings need to be an even # of cahracters long, it it is odd the
 6056:         # last characters gets thrown away
 6057: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6058: 	my $symbseed=numval3($symb) << 10;
 6059: 	my $namechck=unpack("%32S*",$username.' ');
 6060: 	
 6061: 	my $nameseed=numval3($username) << 21;
 6062: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6063: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6064: 	
 6065: 	my $num1=$symbchck+$symbseed+$namechck;
 6066: 	my $num2=$nameseed+$domainseed+$courseseed;
 6067: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6068: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6069: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6070: 	
 6071: 	return "$num1:$num2";
 6072:     }
 6073: }
 6074: 
 6075: sub rndseed_64bit5 {
 6076:     my ($symb,$courseid,$domain,$username)=@_;
 6077:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6078:     return "$num1:$num2";
 6079: }
 6080: 
 6081: sub rndseed_CODE_64bit {
 6082:     my ($symb,$courseid,$domain,$username)=@_;
 6083:     {
 6084: 	use integer;
 6085: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6086: 	my $symbseed=numval2($symb);
 6087: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6088: 	my $CODEseed=numval(&getCODE());
 6089: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6090: 	my $num1=$symbseed+$CODEchck;
 6091: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6092: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6093: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6094: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6095: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6096: 	return "$num1:$num2";
 6097:     }
 6098: }
 6099: 
 6100: sub rndseed_CODE_64bit4 {
 6101:     my ($symb,$courseid,$domain,$username)=@_;
 6102:     {
 6103: 	use integer;
 6104: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6105: 	my $symbseed=numval3($symb);
 6106: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6107: 	my $CODEseed=numval3(&getCODE());
 6108: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6109: 	my $num1=$symbseed+$CODEchck;
 6110: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6111: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6112: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6113: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6114: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6115: 	return "$num1:$num2";
 6116:     }
 6117: }
 6118: 
 6119: sub rndseed_CODE_64bit5 {
 6120:     my ($symb,$courseid,$domain,$username)=@_;
 6121:     my $code = &getCODE();
 6122:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 6123:     return "$num1:$num2";
 6124: }
 6125: 
 6126: sub setup_random_from_rndseed {
 6127:     my ($rndseed)=@_;
 6128:     if ($rndseed =~/([,:])/) {
 6129: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 6130: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 6131:     } else {
 6132: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 6133:     }
 6134: }
 6135: 
 6136: sub latest_receipt_algorithm_id {
 6137:     return 'receipt2';
 6138: }
 6139: 
 6140: sub recunique {
 6141:     my $fucourseid=shift;
 6142:     my $unique;
 6143:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6144: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 6145:     } else {
 6146: 	$unique=$perlvar{'lonReceipt'};
 6147:     }
 6148:     return unpack("%32C*",$unique);
 6149: }
 6150: 
 6151: sub recprefix {
 6152:     my $fucourseid=shift;
 6153:     my $prefix;
 6154:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6155: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 6156:     } else {
 6157: 	$prefix=$perlvar{'lonHostID'};
 6158:     }
 6159:     return unpack("%32C*",$prefix);
 6160: }
 6161: 
 6162: sub ireceipt {
 6163:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 6164:     my $cuname=unpack("%32C*",$funame);
 6165:     my $cudom=unpack("%32C*",$fudom);
 6166:     my $cucourseid=unpack("%32C*",$fucourseid);
 6167:     my $cusymb=unpack("%32C*",$fusymb);
 6168:     my $cunique=&recunique($fucourseid);
 6169:     my $cpart=unpack("%32S*",$part);
 6170:     my $return =&recprefix($fucourseid).'-';
 6171:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 6172: 	$env{'request.state'} eq 'construct') {
 6173: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 6174: 			       " and ".($cpart%$cudom));
 6175: 			       
 6176: 	$return.= ($cunique%$cuname+
 6177: 		   $cunique%$cudom+
 6178: 		   $cusymb%$cuname+
 6179: 		   $cusymb%$cudom+
 6180: 		   $cucourseid%$cuname+
 6181: 		   $cucourseid%$cudom+
 6182: 		   $cpart%$cuname+
 6183: 		   $cpart%$cudom);
 6184:     } else {
 6185: 	$return.= ($cunique%$cuname+
 6186: 		   $cunique%$cudom+
 6187: 		   $cusymb%$cuname+
 6188: 		   $cusymb%$cudom+
 6189: 		   $cucourseid%$cuname+
 6190: 		   $cucourseid%$cudom);
 6191:     }
 6192:     return $return;
 6193: }
 6194: 
 6195: sub receipt {
 6196:     my ($part)=@_;
 6197:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 6198:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 6199: }
 6200: 
 6201: # ------------------------------------------------------------ Serves up a file
 6202: # returns either the contents of the file or 
 6203: # -1 if the file doesn't exist
 6204: #
 6205: # if the target is a file that was uploaded via DOCS, 
 6206: # a check will be made to see if a current copy exists on the local server,
 6207: # if it does this will be served, otherwise a copy will be retrieved from
 6208: # the home server for the course and stored in /home/httpd/html/userfiles on
 6209: # the local server.   
 6210: 
 6211: sub getfile {
 6212:     my ($file) = @_;
 6213:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6214:     &repcopy($file);
 6215:     return &readfile($file);
 6216: }
 6217: 
 6218: sub repcopy_userfile {
 6219:     my ($file)=@_;
 6220:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6221:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 6222:     my ($cdom,$cnum,$filename) = 
 6223: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 6224:     my ($info,$rtncode);
 6225:     my $uri="/uploaded/$cdom/$cnum/$filename";
 6226:     if (-e "$file") {
 6227: 	my @fileinfo = stat($file);
 6228: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 6229: 	if ($lwpresp ne 'ok') {
 6230: 	    if ($rtncode eq '404') {
 6231: 		unlink($file);
 6232: 	    }
 6233: 	    #my $ua=new LWP::UserAgent;
 6234: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6235: 	    #my $response=$ua->request($request);
 6236: 	    #if ($response->is_success()) {
 6237: 	#	return $response->content;
 6238: 	#    } else {
 6239: 	#	return -1;
 6240: 	#    }
 6241: 	    return -1;
 6242: 	}
 6243: 	if ($info < $fileinfo[9]) {
 6244: 	    return 'ok';
 6245: 	}
 6246: 	$info = '';
 6247: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6248: 	if ($lwpresp ne 'ok') {
 6249: 	    return -1;
 6250: 	}
 6251:     } else {
 6252: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6253: 	if ($lwpresp ne 'ok') {
 6254: 	    my $ua=new LWP::UserAgent;
 6255: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6256: 	    my $response=$ua->request($request);
 6257: 	    if ($response->is_success()) {
 6258: 		$info=$response->content;
 6259: 	    } else {
 6260: 		return -1;
 6261: 	    }
 6262: 	}
 6263: 	my @parts = ($cdom,$cnum); 
 6264: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 6265: 	    push @parts, split(/\//,$1);
 6266: 	}
 6267: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 6268: 	foreach my $part (@parts) {
 6269: 	    $path .= '/'.$part;
 6270: 	    if (!-e $path) {
 6271: 		mkdir($path,0770);
 6272: 	    }
 6273: 	}
 6274:     }
 6275:     open(FILE,">$file");
 6276:     print FILE $info;
 6277:     close(FILE);
 6278:     return 'ok';
 6279: }
 6280: 
 6281: sub tokenwrapper {
 6282:     my $uri=shift;
 6283:     $uri=~s|^http\://([^/]+)||;
 6284:     $uri=~s|^/||;
 6285:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 6286:     my $token=$1;
 6287:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 6288:     if ($udom && $uname && $file) {
 6289: 	$file=~s|(\?\.*)*$||;
 6290:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 6291:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 6292:                (($uri=~/\?/)?'&':'?').'token='.$token.
 6293:                                '&tokenissued='.$perlvar{'lonHostID'};
 6294:     } else {
 6295:         return '/adm/notfound.html';
 6296:     }
 6297: }
 6298: 
 6299: sub getuploaded {
 6300:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 6301:     $uri=~s/^\///;
 6302:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 6303:     my $ua=new LWP::UserAgent;
 6304:     my $request=new HTTP::Request($reqtype,$uri);
 6305:     my $response=$ua->request($request);
 6306:     $$rtncode = $response->code;
 6307:     if (! $response->is_success()) {
 6308: 	return 'failed';
 6309:     }      
 6310:     if ($reqtype eq 'HEAD') {
 6311: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 6312:     } elsif ($reqtype eq 'GET') {
 6313: 	$$info = $response->content;
 6314:     }
 6315:     return 'ok';
 6316: }
 6317: 
 6318: sub readfile {
 6319:     my $file = shift;
 6320:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 6321:     my $fh;
 6322:     open($fh,"<$file");
 6323:     my $a='';
 6324:     while (<$fh>) { $a .=$_; }
 6325:     return $a;
 6326: }
 6327: 
 6328: sub filelocation {
 6329:     my ($dir,$file) = @_;
 6330:     my $location;
 6331:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 6332: 
 6333:     if ($file =~ m-^/adm/-) {
 6334: 	$file=~s-^/adm/wrapper/-/-;
 6335: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6336:     }
 6337:     if ($file=~m:^/~:) { # is a contruction space reference
 6338:         $location = $file;
 6339:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 6340:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 6341: 	# is a correct contruction space reference
 6342:         $location = $file;
 6343:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 6344:         my ($udom,$uname,$filename)=
 6345:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 6346:         my $home=&homeserver($uname,$udom);
 6347:         my $is_me=0;
 6348:         my @ids=&current_machine_ids();
 6349:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 6350:         if ($is_me) {
 6351:   	    $location=&Apache::loncommon::propath($udom,$uname).
 6352:   	      '/userfiles/'.$filename;
 6353:         } else {
 6354:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 6355:   	      $udom.'/'.$uname.'/'.$filename;
 6356:         }
 6357:     } else {
 6358:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6359:         $file=~s:^/res/:/:;
 6360:         if ( !( $file =~ m:^/:) ) {
 6361:             $location = $dir. '/'.$file;
 6362:         } else {
 6363:             $location = '/home/httpd/html/res'.$file;
 6364:         }
 6365:     }
 6366:     $location=~s://+:/:g; # remove duplicate /
 6367:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 6368:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 6369:     return $location;
 6370: }
 6371: 
 6372: sub hreflocation {
 6373:     my ($dir,$file)=@_;
 6374:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 6375: 	$file=filelocation($dir,$file);
 6376:     } elsif ($file=~m-^/adm/-) {
 6377: 	$file=~s-^/adm/wrapper/-/-;
 6378: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6379:     }
 6380:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 6381: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 6382:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 6383: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 6384:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 6385: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 6386: 	    -/uploaded/$1/$2/-x;
 6387:     }
 6388:     return $file;
 6389: }
 6390: 
 6391: sub current_machine_domains {
 6392:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6393:     my @domains;
 6394:     while( my($id, $name) = each(%hostname)) {
 6395: #	&logthis("-$id-$name-$hostname-");
 6396: 	if ($hostname eq $name) {
 6397: 	    push(@domains,$hostdom{$id});
 6398: 	}
 6399:     }
 6400:     return @domains;
 6401: }
 6402: 
 6403: sub current_machine_ids {
 6404:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6405:     my @ids;
 6406:     while( my($id, $name) = each(%hostname)) {
 6407: #	&logthis("-$id-$name-$hostname-");
 6408: 	if ($hostname eq $name) {
 6409: 	    push(@ids,$id);
 6410: 	}
 6411:     }
 6412:     return @ids;
 6413: }
 6414: 
 6415: # ------------------------------------------------------------- Declutters URLs
 6416: 
 6417: sub declutter {
 6418:     my $thisfn=shift;
 6419:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6420:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6421:     $thisfn=~s/^\///;
 6422:     $thisfn=~s|^adm/wrapper/||;
 6423:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 6424:     $thisfn=~s/^res\///;
 6425:     $thisfn=~s/\?.+$//;
 6426:     return $thisfn;
 6427: }
 6428: 
 6429: # ------------------------------------------------------------- Clutter up URLs
 6430: 
 6431: sub clutter {
 6432:     my $thisfn='/'.&declutter(shift);
 6433:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 6434:        $thisfn='/res'.$thisfn; 
 6435:     }
 6436:     if ($thisfn !~m|/adm|) {
 6437: 	if ($thisfn =~ m|/ext/|) {
 6438: 	    $thisfn='/adm/wrapper'.$thisfn;
 6439: 	} else {
 6440: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 6441: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 6442: 	    if ($embstyle eq 'ssi'
 6443: 		|| ($embstyle eq 'hdn')
 6444: 		|| ($embstyle eq 'rat')
 6445: 		|| ($embstyle eq 'prv')
 6446: 		|| ($embstyle eq 'ign')) {
 6447: 		#do nothing with these
 6448: 	    } elsif (($embstyle eq 'img') 
 6449: 		|| ($embstyle eq 'emb')
 6450: 		|| ($embstyle eq 'wrp')) {
 6451: 		$thisfn='/adm/wrapper'.$thisfn;
 6452: 	    } elsif ($embstyle eq 'unk'
 6453: 		     && $thisfn!~/\.(sequence|page)$/) {
 6454: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 6455: 	    } else {
 6456: #		&logthis("Got a blank emb style");
 6457: 	    }
 6458: 	}
 6459:     }
 6460:     return $thisfn;
 6461: }
 6462: 
 6463: sub freeze_escape {
 6464:     my ($value)=@_;
 6465:     if (ref($value)) {
 6466: 	$value=&nfreeze($value);
 6467: 	return '__FROZEN__'.&escape($value);
 6468:     }
 6469:     return &escape($value);
 6470: }
 6471: 
 6472: # -------------------------------------------------------- Escape Special Chars
 6473: 
 6474: sub escape {
 6475:     my $str=shift;
 6476:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 6477:     return $str;
 6478: }
 6479: 
 6480: # ----------------------------------------------------- Un-Escape Special Chars
 6481: 
 6482: sub unescape {
 6483:     my $str=shift;
 6484:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 6485:     return $str;
 6486: }
 6487: 
 6488: sub thaw_unescape {
 6489:     my ($value)=@_;
 6490:     if ($value =~ /^__FROZEN__/) {
 6491: 	substr($value,0,10,undef);
 6492: 	$value=&unescape($value);
 6493: 	return &thaw($value);
 6494:     }
 6495:     return &unescape($value);
 6496: }
 6497: 
 6498: sub correct_line_ends {
 6499:     my ($result)=@_;
 6500:     $$result =~s/\r\n/\n/mg;
 6501:     $$result =~s/\r/\n/mg;
 6502: }
 6503: # ================================================================ Main Program
 6504: 
 6505: sub goodbye {
 6506:    &logthis("Starting Shut down");
 6507: #not converted to using infrastruture and probably shouldn't be
 6508:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 6509: #converted
 6510: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 6511:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 6512: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 6513: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 6514: #1.1 only
 6515: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 6516: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 6517: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 6518: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 6519:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 6520:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 6521:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 6522:    &flushcourselogs();
 6523:    &logthis("Shutting down");
 6524: }
 6525: 
 6526: BEGIN {
 6527: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 6528:     unless ($readit) {
 6529: {
 6530:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
 6531:     open(my $config,"</etc/httpd/conf/loncapa.conf");
 6532: 
 6533:     while (my $configline=<$config>) {
 6534:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
 6535: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 6536:            chomp($varvalue);
 6537:            $perlvar{$varname}=$varvalue;
 6538:         }
 6539:     }
 6540:     close($config);
 6541: }
 6542: {
 6543:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
 6544: 
 6545:     while (my $configline=<$config>) {
 6546:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 6547: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 6548:            chomp($varvalue);
 6549:            $perlvar{$varname}=$varvalue;
 6550:         }
 6551:     }
 6552:     close($config);
 6553: }
 6554: 
 6555: # ------------------------------------------------------------ Read domain file
 6556: {
 6557:     %domaindescription = ();
 6558:     %domain_auth_def = ();
 6559:     %domain_auth_arg_def = ();
 6560:     my $fh;
 6561:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 6562:        while (<$fh>) {
 6563:            next if (/^(\#|\s*$)/);
 6564: #           next if /^\#/;
 6565:            chomp;
 6566:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 6567: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
 6568: 	   $domain_auth_def{$domain}=$def_auth;
 6569:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 6570: 	   $domaindescription{$domain}=$domain_description;
 6571: 	   $domain_lang_def{$domain}=$def_lang;
 6572: 	   $domain_city{$domain}=$city;
 6573: 	   $domain_longi{$domain}=$longi;
 6574: 	   $domain_lati{$domain}=$lati;
 6575:            $domain_primary{$domain}=$primary;
 6576: 
 6577:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 6578: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 6579: 	}
 6580:     }
 6581:     close ($fh);
 6582: }
 6583: 
 6584: 
 6585: # ------------------------------------------------------------- Read hosts file
 6586: {
 6587:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 6588: 
 6589:     while (my $configline=<$config>) {
 6590:        next if ($configline =~ /^(\#|\s*$)/);
 6591:        chomp($configline);
 6592:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 6593:        $name=~s/\s//g;
 6594:        if ($id && $domain && $role && $name) {
 6595: 	 $hostname{$id}=$name;
 6596: 	 $hostdom{$id}=$domain;
 6597: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 6598:        }
 6599:     }
 6600:     close($config);
 6601:     # FIXME: dev server don't want this, production servers _do_ want this
 6602:     #&get_iphost();
 6603: }
 6604: 
 6605: sub get_iphost {
 6606:     if (%iphost) { return %iphost; }
 6607:     my %name_to_ip;
 6608:     foreach my $id (keys(%hostname)) {
 6609: 	my $name=$hostname{$id};
 6610: 	my $ip;
 6611: 	if (!exists($name_to_ip{$name})) {
 6612: 	    $ip = gethostbyname($name);
 6613: 	    if (!$ip || length($ip) ne 4) {
 6614: 		&logthis("Skipping host $id name $name no IP found\n");
 6615: 		next;
 6616: 	    }
 6617: 	    $ip=inet_ntoa($ip);
 6618: 	    $name_to_ip{$name} = $ip;
 6619: 	} else {
 6620: 	    $ip = $name_to_ip{$name};
 6621: 	}
 6622: 	push(@{$iphost{$ip}},$id);
 6623:     }
 6624:     return %iphost;
 6625: }
 6626: 
 6627: # ------------------------------------------------------ Read spare server file
 6628: {
 6629:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 6630: 
 6631:     while (my $configline=<$config>) {
 6632:        chomp($configline);
 6633:        if ($configline) {
 6634:           $spareid{$configline}=1;
 6635:        }
 6636:     }
 6637:     close($config);
 6638: }
 6639: # ------------------------------------------------------------ Read permissions
 6640: {
 6641:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 6642: 
 6643:     while (my $configline=<$config>) {
 6644: 	chomp($configline);
 6645: 	if ($configline) {
 6646: 	    my ($role,$perm)=split(/ /,$configline);
 6647: 	    if ($perm ne '') { $pr{$role}=$perm; }
 6648: 	}
 6649:     }
 6650:     close($config);
 6651: }
 6652: 
 6653: # -------------------------------------------- Read plain texts for permissions
 6654: {
 6655:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 6656: 
 6657:     while (my $configline=<$config>) {
 6658: 	chomp($configline);
 6659: 	if ($configline) {
 6660: 	    my ($short,$plain)=split(/:/,$configline);
 6661: 	    if ($plain ne '') { $prp{$short}=$plain; }
 6662: 	}
 6663:     }
 6664:     close($config);
 6665: }
 6666: 
 6667: # ---------------------------------------------------------- Read package table
 6668: {
 6669:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 6670: 
 6671:     while (my $configline=<$config>) {
 6672: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 6673: 	chomp($configline);
 6674: 	my ($short,$plain)=split(/:/,$configline);
 6675: 	my ($pack,$name)=split(/\&/,$short);
 6676: 	if ($plain ne '') {
 6677: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 6678: 	    $packagetab{$short}=$plain; 
 6679: 	}
 6680:     }
 6681:     close($config);
 6682: }
 6683: 
 6684: # ------------- set up temporary directory
 6685: {
 6686:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 6687: 
 6688: }
 6689: 
 6690: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 6691: 
 6692: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 6693: $dumpcount=0;
 6694: 
 6695: &logtouch();
 6696: &logthis('<font color="yellow">INFO: Read configuration</font>');
 6697: $readit=1;
 6698:     {
 6699: 	use integer;
 6700: 	my $test=(2**32)+1;
 6701: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 6702: 	&logthis(" Detected 64bit platform ($_64bit)");
 6703:     }
 6704: }
 6705: }
 6706: 
 6707: 1;
 6708: __END__
 6709: 
 6710: =pod
 6711: 
 6712: =head1 NAME
 6713: 
 6714: Apache::lonnet - Subroutines to ask questions about things in the network.
 6715: 
 6716: =head1 SYNOPSIS
 6717: 
 6718: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 6719: 
 6720:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 6721: 
 6722: Common parameters:
 6723: 
 6724: =over 4
 6725: 
 6726: =item *
 6727: 
 6728: $uname : an internal username (if $cname expecting a course Id specifically)
 6729: 
 6730: =item *
 6731: 
 6732: $udom : a domain (if $cdom expecting a course's domain specifically)
 6733: 
 6734: =item *
 6735: 
 6736: $symb : a resource instance identifier
 6737: 
 6738: =item *
 6739: 
 6740: $namespace : the name of a .db file that contains the data needed or
 6741: being set.
 6742: 
 6743: =back
 6744: 
 6745: =head1 OVERVIEW
 6746: 
 6747: lonnet provides subroutines which interact with the
 6748: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 6749: about classes, users, and resources.
 6750: 
 6751: For many of these objects you can also use this to store data about
 6752: them or modify them in various ways.
 6753: 
 6754: =head2 Symbs
 6755: 
 6756: To identify a specific instance of a resource, LON-CAPA uses symbols
 6757: or "symbs"X<symb>. These identifiers are built from the URL of the
 6758: map, the resource number of the resource in the map, and the URL of
 6759: the resource itself. The latter is somewhat redundant, but might help
 6760: if maps change.
 6761: 
 6762: An example is
 6763: 
 6764:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 6765: 
 6766: The respective map entry is
 6767: 
 6768:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 6769:   title="Problem 2">
 6770:  </resource>
 6771: 
 6772: Symbs are used by the random number generator, as well as to store and
 6773: restore data specific to a certain instance of for example a problem.
 6774: 
 6775: =head2 Storing And Retrieving Data
 6776: 
 6777: X<store()>X<cstore()>X<restore()>Three of the most important functions
 6778: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 6779: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 6780: is is the non-critical message twin of cstore. These functions are for
 6781: handlers to store a perl hash to a user's permanent data space in an
 6782: easy manner, and to retrieve it again on another call. It is expected
 6783: that a handler would use this once at the beginning to retrieve data,
 6784: and then again once at the end to send only the new data back.
 6785: 
 6786: The data is stored in the user's data directory on the user's
 6787: homeserver under the ID of the course.
 6788: 
 6789: The hash that is returned by restore will have all of the previous
 6790: value for all of the elements of the hash.
 6791: 
 6792: Example:
 6793: 
 6794:  #creating a hash
 6795:  my %hash;
 6796:  $hash{'foo'}='bar';
 6797: 
 6798:  #storing it
 6799:  &Apache::lonnet::cstore(\%hash);
 6800: 
 6801:  #changing a value
 6802:  $hash{'foo'}='notbar';
 6803: 
 6804:  #adding a new value
 6805:  $hash{'bar'}='foo';
 6806:  &Apache::lonnet::cstore(\%hash);
 6807: 
 6808:  #retrieving the hash
 6809:  my %history=&Apache::lonnet::restore();
 6810: 
 6811:  #print the hash
 6812:  foreach my $key (sort(keys(%history))) {
 6813:    print("\%history{$key} = $history{$key}");
 6814:  }
 6815: 
 6816: Will print out:
 6817: 
 6818:  %history{1:foo} = bar
 6819:  %history{1:keys} = foo:timestamp
 6820:  %history{1:timestamp} = 990455579
 6821:  %history{2:bar} = foo
 6822:  %history{2:foo} = notbar
 6823:  %history{2:keys} = foo:bar:timestamp
 6824:  %history{2:timestamp} = 990455580
 6825:  %history{bar} = foo
 6826:  %history{foo} = notbar
 6827:  %history{timestamp} = 990455580
 6828:  %history{version} = 2
 6829: 
 6830: Note that the special hash entries C<keys>, C<version> and
 6831: C<timestamp> were added to the hash. C<version> will be equal to the
 6832: total number of versions of the data that have been stored. The
 6833: C<timestamp> attribute will be the UNIX time the hash was
 6834: stored. C<keys> is available in every historical section to list which
 6835: keys were added or changed at a specific historical revision of a
 6836: hash.
 6837: 
 6838: B<Warning>: do not store the hash that restore returns directly. This
 6839: will cause a mess since it will restore the historical keys as if the
 6840: were new keys. I.E. 1:foo will become 1:1:foo etc.
 6841: 
 6842: Calling convention:
 6843: 
 6844:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 6845:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 6846: 
 6847: For more detailed information, see lonnet specific documentation.
 6848: 
 6849: =head1 RETURN MESSAGES
 6850: 
 6851: =over 4
 6852: 
 6853: =item * B<con_lost>: unable to contact remote host
 6854: 
 6855: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 6856: when the connection is brought back up
 6857: 
 6858: =item * B<con_failed>: unable to contact remote host and unable to save message
 6859: for later delivery
 6860: 
 6861: =item * B<error:>: an error a occured, a description of the error follows the :
 6862: 
 6863: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 6864: that was requested
 6865: 
 6866: =back
 6867: 
 6868: =head1 PUBLIC SUBROUTINES
 6869: 
 6870: =head2 Session Environment Functions
 6871: 
 6872: =over 4
 6873: 
 6874: =item * 
 6875: X<appenv()>
 6876: B<appenv(%hash)>: the value of %hash is written to
 6877: the user envirnoment file, and will be restored for each access this
 6878: user makes during this session, also modifies the %env for the current
 6879: process
 6880: 
 6881: =item *
 6882: X<delenv()>
 6883: B<delenv($regexp)>: removes all items from the session
 6884: environment file that matches the regular expression in $regexp. The
 6885: values are also delted from the current processes %env.
 6886: 
 6887: =back
 6888: 
 6889: =head2 User Information
 6890: 
 6891: =over 4
 6892: 
 6893: =item *
 6894: X<queryauthenticate()>
 6895: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 6896: authentication scheme
 6897: 
 6898: =item *
 6899: X<authenticate()>
 6900: B<authenticate($uname,$upass,$udom)>: try to
 6901: authenticate user from domain's lib servers (first use the current
 6902: one). C<$upass> should be the users password.
 6903: 
 6904: =item *
 6905: X<homeserver()>
 6906: B<homeserver($uname,$udom)>: find the server which has
 6907: the user's directory and files (there must be only one), this caches
 6908: the answer, and also caches if there is a borken connection.
 6909: 
 6910: =item *
 6911: X<idget()>
 6912: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 6913: (IDs are a unique resource in a domain, there must be only 1 ID per
 6914: username, and only 1 username per ID in a specific domain) (returns
 6915: hash: id=>name,id=>name)
 6916: 
 6917: =item *
 6918: X<idrget()>
 6919: B<idrget($udom,@unames)>: find the IDs behind a list of
 6920: usernames (returns hash: name=>id,name=>id)
 6921: 
 6922: =item *
 6923: X<idput()>
 6924: B<idput($udom,%ids)>: store away a list of names and associated IDs
 6925: 
 6926: =item *
 6927: X<rolesinit()>
 6928: B<rolesinit($udom,$username,$authhost)>: get user privileges
 6929: 
 6930: =item *
 6931: X<getsection()>
 6932: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 6933: course $cname, return section name/number or '' for "not in course"
 6934: and '-1' for "no section"
 6935: 
 6936: =item *
 6937: X<userenvironment()>
 6938: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 6939: passed in @what from the requested user's environment, returns a hash
 6940: 
 6941: =back
 6942: 
 6943: =head2 User Roles
 6944: 
 6945: =over 4
 6946: 
 6947: =item *
 6948: 
 6949: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 6950: actions
 6951:  F: full access
 6952:  U,I,K: authentication modes (cxx only)
 6953:  '': forbidden
 6954:  1: user needs to choose course
 6955:  2: browse allowed
 6956: 
 6957: =item *
 6958: 
 6959: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 6960: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 6961: and course level
 6962: 
 6963: =item *
 6964: 
 6965: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 6966: explanation of a user role term
 6967: 
 6968: =back
 6969: 
 6970: =head2 User Modification
 6971: 
 6972: =over 4
 6973: 
 6974: =item *
 6975: 
 6976: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 6977: user for the level given by URL.  Optional start and end dates (leave empty
 6978: string or zero for "no date")
 6979: 
 6980: =item *
 6981: 
 6982: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 6983: change a users, password, possible return values are: ok,
 6984: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 6985: refused
 6986: 
 6987: =item *
 6988: 
 6989: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 6990: 
 6991: =item *
 6992: 
 6993: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 6994: modify user
 6995: 
 6996: =item *
 6997: 
 6998: modifystudent
 6999: 
 7000: modify a students enrollment and identification information.
 7001: The course id is resolved based on the current users environment.  
 7002: This means the envoking user must be a course coordinator or otherwise
 7003: associated with a course.
 7004: 
 7005: This call is essentially a wrapper for lonnet::modifyuser and
 7006: lonnet::modify_student_enrollment
 7007: 
 7008: Inputs: 
 7009: 
 7010: =over 4
 7011: 
 7012: =item B<$udom> Students loncapa domain
 7013: 
 7014: =item B<$uname> Students loncapa login name
 7015: 
 7016: =item B<$uid> Students id/student number
 7017: 
 7018: =item B<$umode> Students authentication mode
 7019: 
 7020: =item B<$upass> Students password
 7021: 
 7022: =item B<$first> Students first name
 7023: 
 7024: =item B<$middle> Students middle name
 7025: 
 7026: =item B<$last> Students last name
 7027: 
 7028: =item B<$gene> Students generation
 7029: 
 7030: =item B<$usec> Students section in course
 7031: 
 7032: =item B<$end> Unix time of the roles expiration
 7033: 
 7034: =item B<$start> Unix time of the roles start date
 7035: 
 7036: =item B<$forceid> If defined, allow $uid to be changed
 7037: 
 7038: =item B<$desiredhome> server to use as home server for student
 7039: 
 7040: =back
 7041: 
 7042: =item *
 7043: 
 7044: modify_student_enrollment
 7045: 
 7046: Change a students enrollment status in a class.  The environment variable
 7047: 'role.request.course' must be defined for this function to proceed.
 7048: 
 7049: Inputs:
 7050: 
 7051: =over 4
 7052: 
 7053: =item $udom, students domain
 7054: 
 7055: =item $uname, students name
 7056: 
 7057: =item $uid, students user id
 7058: 
 7059: =item $first, students first name
 7060: 
 7061: =item $middle
 7062: 
 7063: =item $last
 7064: 
 7065: =item $gene
 7066: 
 7067: =item $usec
 7068: 
 7069: =item $end
 7070: 
 7071: =item $start
 7072: 
 7073: =back
 7074: 
 7075: 
 7076: =item *
 7077: 
 7078: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 7079: custom role; give a custom role to a user for the level given by URL.  Specify
 7080: name and domain of role author, and role name
 7081: 
 7082: =item *
 7083: 
 7084: revokerole($udom,$uname,$url,$role) : revoke a role for url
 7085: 
 7086: =item *
 7087: 
 7088: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 7089: 
 7090: =back
 7091: 
 7092: =head2 Course Infomation
 7093: 
 7094: =over 4
 7095: 
 7096: =item *
 7097: 
 7098: coursedescription($courseid) : returns a hash of information about the
 7099: specified course id, including all environment settings for the
 7100: course, the description of the course will be in the hash under the
 7101: key 'description'
 7102: 
 7103: =item *
 7104: 
 7105: resdata($name,$domain,$type,@which) : request for current parameter
 7106: setting for a specific $type, where $type is either 'course' or 'user',
 7107: @what should be a list of parameters to ask about. This routine caches
 7108: answers for 5 minutes.
 7109: 
 7110: =back
 7111: 
 7112: =head2 Course Modification
 7113: 
 7114: =over 4
 7115: 
 7116: =item *
 7117: 
 7118: writecoursepref($courseid,%prefs) : write preferences (environment
 7119: database) for a course
 7120: 
 7121: =item *
 7122: 
 7123: createcourse($udom,$description,$url) : make/modify course
 7124: 
 7125: =back
 7126: 
 7127: =head2 Resource Subroutines
 7128: 
 7129: =over 4
 7130: 
 7131: =item *
 7132: 
 7133: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 7134: 
 7135: =item *
 7136: 
 7137: repcopy($filename) : subscribes to the requested file, and attempts to
 7138: replicate from the owning library server, Might return
 7139: 'unavailable', 'not_found', 'forbidden', 'ok', or
 7140: 'bad_request', also attempts to grab the metadata for the
 7141: resource. Expects the local filesystem pathname
 7142: (/home/httpd/html/res/....)
 7143: 
 7144: =back
 7145: 
 7146: =head2 Resource Information
 7147: 
 7148: =over 4
 7149: 
 7150: =item *
 7151: 
 7152: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 7153: a vairety of different possible values, $varname should be a request
 7154: string, and the other parameters can be used to specify who and what
 7155: one is asking about.
 7156: 
 7157: Possible values for $varname are environment.lastname (or other item
 7158: from the envirnment hash), user.name (or someother aspect about the
 7159: user), resource.0.maxtries (or some other part and parameter of a
 7160: resource)
 7161: 
 7162: =item *
 7163: 
 7164: directcondval($number) : get current value of a condition; reads from a state
 7165: string
 7166: 
 7167: =item *
 7168: 
 7169: condval($condidx) : value of condition index based on state
 7170: 
 7171: =item *
 7172: 
 7173: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 7174: resource's metadata, $what should be either a specific key, or either
 7175: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 7176: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 7177: 
 7178: this function automatically caches all requests
 7179: 
 7180: =item *
 7181: 
 7182: metadata_query($query,$custom,$customshow) : make a metadata query against the
 7183: network of library servers; returns file handle of where SQL and regex results
 7184: will be stored for query
 7185: 
 7186: =item *
 7187: 
 7188: symbread($filename) : return symbolic list entry (filename argument optional);
 7189: returns the data handle
 7190: 
 7191: =item *
 7192: 
 7193: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 7194: a possible symb for the URL in $thisfn, and if is an encryypted
 7195: resource that the user accessed using /enc/ returns a 1 on success, 0
 7196: on failure, user must be in a course, as it assumes the existance of
 7197: the course initial hash, and uses $env('request.course.id'}
 7198: 
 7199: 
 7200: =item *
 7201: 
 7202: symbclean($symb) : removes versions numbers from a symb, returns the
 7203: cleaned symb
 7204: 
 7205: =item *
 7206: 
 7207: is_on_map($uri) : checks if the $uri is somewhere on the current
 7208: course map, user must be in a course for it to work.
 7209: 
 7210: =item *
 7211: 
 7212: numval($salt) : return random seed value (addend for rndseed)
 7213: 
 7214: =item *
 7215: 
 7216: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 7217: a random seed, all arguments are optional, if they aren't sent it uses the
 7218: environment to derive them. Note: if symb isn't sent and it can't get one
 7219: from &symbread it will use the current time as its return value
 7220: 
 7221: =item *
 7222: 
 7223: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 7224: unfakeable, receipt
 7225: 
 7226: =item *
 7227: 
 7228: receipt() : API to ireceipt working off of env values; given out to users
 7229: 
 7230: =item *
 7231: 
 7232: countacc($url) : count the number of accesses to a given URL
 7233: 
 7234: =item *
 7235: 
 7236: 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
 7237: 
 7238: =item *
 7239: 
 7240: 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)
 7241: 
 7242: =item *
 7243: 
 7244: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 7245: 
 7246: =item *
 7247: 
 7248: devalidate($symb) : devalidate temporary spreadsheet calculations,
 7249: forcing spreadsheet to reevaluate the resource scores next time.
 7250: 
 7251: =back
 7252: 
 7253: =head2 Storing/Retreiving Data
 7254: 
 7255: =over 4
 7256: 
 7257: =item *
 7258: 
 7259: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 7260: for this url; hashref needs to be given and should be a \%hashname; the
 7261: remaining args aren't required and if they aren't passed or are '' they will
 7262: be derived from the env
 7263: 
 7264: =item *
 7265: 
 7266: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 7267: uses critical subroutine
 7268: 
 7269: =item *
 7270: 
 7271: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 7272: all args are optional
 7273: 
 7274: =item *
 7275: 
 7276: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 7277: dumps the complete (or key matching regexp) namespace into a hash
 7278: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 7279: normally &store()ed into
 7280: 
 7281: $range should be either an integer '100' (give me the first 100
 7282:                                            matching records)
 7283:               or be  two integers sperated by a - with no spaces
 7284:                  '30-50' (give me the 30th through the 50th matching
 7285:                           records)
 7286: 
 7287: 
 7288: =item *
 7289: 
 7290: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 7291: replaces a &store() version of data with a replacement set of data
 7292: for a particular resource in a namespace passed in the $storehash hash 
 7293: reference
 7294: 
 7295: =item *
 7296: 
 7297: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 7298: works very similar to store/cstore, but all data is stored in a
 7299: temporary location and can be reset using tmpreset, $storehash should
 7300: be a hash reference, returns nothing on success
 7301: 
 7302: =item *
 7303: 
 7304: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 7305: similar to restore, but all data is stored in a temporary location and
 7306: can be reset using tmpreset. Returns a hash of values on success,
 7307: error string otherwise.
 7308: 
 7309: =item *
 7310: 
 7311: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 7312: deltes all keys for $symb form the temporary storage hash.
 7313: 
 7314: =item *
 7315: 
 7316: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7317: reference filled in from namesp ($udom and $uname are optional)
 7318: 
 7319: =item *
 7320: 
 7321: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 7322: namesp ($udom and $uname are optional)
 7323: 
 7324: =item *
 7325: 
 7326: dump($namespace,$udom,$uname,$regexp,$range) : 
 7327: dumps the complete (or key matching regexp) namespace into a hash
 7328: ($udom, $uname, $regexp, $range are optional)
 7329: 
 7330: $range should be either an integer '100' (give me the first 100
 7331:                                            matching records)
 7332:               or be  two integers sperated by a - with no spaces
 7333:                  '30-50' (give me the 30th through the 50th matching
 7334:                           records)
 7335: =item *
 7336: 
 7337: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 7338: $store can be a scalar, an array reference, or if the amount to be 
 7339: incremented is > 1, a hash reference.
 7340: 
 7341: ($udom and $uname are optional)
 7342: 
 7343: =item *
 7344: 
 7345: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 7346: ($udom and $uname are optional)
 7347: 
 7348: =item *
 7349: 
 7350: cput($namespace,$storehash,$udom,$uname) : critical put
 7351: ($udom and $uname are optional)
 7352: 
 7353: =item *
 7354: 
 7355: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7356: reference filled in from namesp (encrypts the return communication)
 7357: ($udom and $uname are optional)
 7358: 
 7359: =item *
 7360: 
 7361: log($udom,$name,$home,$message) : write to permanent log for user; use
 7362: critical subroutine
 7363: 
 7364: =back
 7365: 
 7366: =head2 Network Status Functions
 7367: 
 7368: =over 4
 7369: 
 7370: =item *
 7371: 
 7372: dirlist($uri) : return directory list based on URI
 7373: 
 7374: =item *
 7375: 
 7376: spareserver() : find server with least workload from spare.tab
 7377: 
 7378: =back
 7379: 
 7380: =head2 Apache Request
 7381: 
 7382: =over 4
 7383: 
 7384: =item *
 7385: 
 7386: ssi($url,%hash) : server side include, does a complete request cycle on url to
 7387: localhost, posts hash
 7388: 
 7389: =back
 7390: 
 7391: =head2 Data to String to Data
 7392: 
 7393: =over 4
 7394: 
 7395: =item *
 7396: 
 7397: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 7398: and '&' separators, supports elements that are arrayrefs and hashrefs
 7399: 
 7400: =item *
 7401: 
 7402: hashref2str($hashref) : convert a hashref into a string complete with
 7403: escaping and '=' and '&' separators, supports elements that are
 7404: arrayrefs and hashrefs
 7405: 
 7406: =item *
 7407: 
 7408: arrayref2str($arrayref) : convert an arrayref into a string complete
 7409: with escaping and '&' separators, supports elements that are arrayrefs
 7410: and hashrefs
 7411: 
 7412: =item *
 7413: 
 7414: str2hash($string) : convert string to hash using unescaping and
 7415: splitting on '=' and '&', supports elements that are arrayrefs and
 7416: hashrefs
 7417: 
 7418: =item *
 7419: 
 7420: str2array($string) : convert string to hash using unescaping and
 7421: splitting on '&', supports elements that are arrayrefs and hashrefs
 7422: 
 7423: =back
 7424: 
 7425: =head2 Logging Routines
 7426: 
 7427: =over 4
 7428: 
 7429: These routines allow one to make log messages in the lonnet.log and
 7430: lonnet.perm logfiles.
 7431: 
 7432: =item *
 7433: 
 7434: logtouch() : make sure the logfile, lonnet.log, exists
 7435: 
 7436: =item *
 7437: 
 7438: logthis() : append message to the normal lonnet.log file, it gets
 7439: preiodically rolled over and deleted.
 7440: 
 7441: =item *
 7442: 
 7443: logperm() : append a permanent message to lonnet.perm.log, this log
 7444: file never gets deleted by any automated portion of the system, only
 7445: messages of critical importance should go in here.
 7446: 
 7447: =back
 7448: 
 7449: =head2 General File Helper Routines
 7450: 
 7451: =over 4
 7452: 
 7453: =item *
 7454: 
 7455: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 7456: (a) files in /uploaded
 7457:   (i) If a local copy of the file exists - 
 7458:       compares modification date of local copy with last-modified date for 
 7459:       definitive version stored on home server for course. If local copy is 
 7460:       stale, requests a new version from the home server and stores it. 
 7461:       If the original has been removed from the home server, then local copy 
 7462:       is unlinked.
 7463:   (ii) If local copy does not exist -
 7464:       requests the file from the home server and stores it. 
 7465:   
 7466:   If $caller is 'uploadrep':  
 7467:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 7468:     for request for files originally uploaded via DOCS. 
 7469:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 7470:   
 7471:   Otherwise:
 7472:      This indicates a call from the content generation phase of the request.
 7473:      -  returns the entire contents of the file or -1.
 7474:      
 7475: (b) files in /res
 7476:    - returns the entire contents of a file or -1; 
 7477:    it properly subscribes to and replicates the file if neccessary.
 7478: 
 7479: 
 7480: =item *
 7481: 
 7482: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 7483:                   reference
 7484: 
 7485: returns either a stat() list of data about the file or an empty list
 7486: if the file doesn't exist or couldn't find out about it (connection
 7487: problems or user unknown)
 7488: 
 7489: =item *
 7490: 
 7491: filelocation($dir,$file) : returns file system location of a file
 7492: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 7493: directory that relative $file lookups are to looked in ($dir of /a/dir
 7494: and a file of ../bob will become /a/bob)
 7495: 
 7496: =item *
 7497: 
 7498: hreflocation($dir,$file) : returns file system location or a URL; same as
 7499: filelocation except for hrefs
 7500: 
 7501: =item *
 7502: 
 7503: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 7504: 
 7505: =back
 7506: 
 7507: =head2 Usererfile file routines (/uploaded*)
 7508: 
 7509: =over 4
 7510: 
 7511: =item *
 7512: 
 7513: userfileupload(): main rotine for putting a file in a user or course's
 7514:                   filespace, arguments are,
 7515: 
 7516:  formname - required - this is the name of the element in $env where the
 7517:            filename, and the contents of the file to create/modifed exist
 7518:            the filename is in $env{'form.'.$formname.'.filename'} and the
 7519:            contents of the file is located in $env{'form.'.$formname}
 7520:  coursedoc - if true, store the file in the course of the active role
 7521:              of the current user
 7522:  subdir - required - subdirectory to put the file in under ../userfiles/
 7523:          if undefined, it will be placed in "unknown"
 7524: 
 7525:  (This routine calls clean_filename() to remove any dangerous
 7526:  characters from the filename, and then calls finuserfileupload() to
 7527:  complete the transaction)
 7528: 
 7529:  returns either the url of the uploaded file (/uploaded/....) if successful
 7530:  and /adm/notfound.html if unsuccessful
 7531: 
 7532: =item *
 7533: 
 7534: clean_filename(): routine for cleaing a filename up for storage in
 7535:                  userfile space, argument is:
 7536: 
 7537:  filename - proposed filename
 7538: 
 7539: returns: the new clean filename
 7540: 
 7541: =item *
 7542: 
 7543: finishuserfileupload(): routine that creaes and sends the file to
 7544: userspace, probably shouldn't be called directly
 7545: 
 7546:   docuname: username or courseid of destination for the file
 7547:   docudom: domain of user/course of destination for the file
 7548:   formname: same as for userfileupload()
 7549:   fname: filename (inculding subdirectories) for the file
 7550: 
 7551:  returns either the url of the uploaded file (/uploaded/....) if successful
 7552:  and /adm/notfound.html if unsuccessful
 7553: 
 7554: =item *
 7555: 
 7556: renameuserfile(): renames an existing userfile to a new name
 7557: 
 7558:   Args:
 7559:    docuname: username or courseid of destination for the file
 7560:    docudom: domain of user/course of destination for the file
 7561:    old: current file name (including any subdirs under userfiles)
 7562:    new: desired file name (including any subdirs under userfiles)
 7563: 
 7564: =item *
 7565: 
 7566: mkdiruserfile(): creates a directory is a userfiles dir
 7567: 
 7568:   Args:
 7569:    docuname: username or courseid of destination for the file
 7570:    docudom: domain of user/course of destination for the file
 7571:    dir: dir to create (including any subdirs under userfiles)
 7572: 
 7573: =item *
 7574: 
 7575: removeuserfile(): removes a file that exists in userfiles
 7576: 
 7577:   Args:
 7578:    docuname: username or courseid of destination for the file
 7579:    docudom: domain of user/course of destination for the file
 7580:    fname: filname to delete (including any subdirs under userfiles)
 7581: 
 7582: =item *
 7583: 
 7584: removeuploadedurl(): convience function for removeuserfile()
 7585: 
 7586:   Args:
 7587:    url:  a full /uploaded/... url to delete
 7588: 
 7589: =back
 7590: 
 7591: =head2 HTTP Helper Routines
 7592: 
 7593: =over 4
 7594: 
 7595: =item *
 7596: 
 7597: escape() : unpack non-word characters into CGI-compatible hex codes
 7598: 
 7599: =item *
 7600: 
 7601: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 7602: 
 7603: =back
 7604: 
 7605: =head1 PRIVATE SUBROUTINES
 7606: 
 7607: =head2 Underlying communication routines (Shouldn't call)
 7608: 
 7609: =over 4
 7610: 
 7611: =item *
 7612: 
 7613: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 7614: 
 7615: =item *
 7616: 
 7617: reply() : uses subreply to send a message to remote machine, logs all failures
 7618: 
 7619: =item *
 7620: 
 7621: critical() : passes a critical message to another server; if cannot
 7622: get through then place message in connection buffer directory and
 7623: returns con_delayed, if incapable of saving message, returns
 7624: con_failed
 7625: 
 7626: =item *
 7627: 
 7628: reconlonc() : tries to reconnect lonc client processes.
 7629: 
 7630: =back
 7631: 
 7632: =head2 Resource Access Logging
 7633: 
 7634: =over 4
 7635: 
 7636: =item *
 7637: 
 7638: flushcourselogs() : flush (save) buffer logs and access logs
 7639: 
 7640: =item *
 7641: 
 7642: courselog($what) : save message for course in hash
 7643: 
 7644: =item *
 7645: 
 7646: courseacclog($what) : save message for course using &courselog().  Perform
 7647: special processing for specific resource types (problems, exams, quizzes, etc).
 7648: 
 7649: =item *
 7650: 
 7651: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 7652: as a PerlChildExitHandler
 7653: 
 7654: =back
 7655: 
 7656: =head2 Other
 7657: 
 7658: =over 4
 7659: 
 7660: =item *
 7661: 
 7662: symblist($mapname,%newhash) : update symbolic storage links
 7663: 
 7664: =back
 7665: 
 7666: =cut

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