File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.720: download - view: text, annotated - select for diffs
Wed Mar 8 21:47:15 2006 UTC (18 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- transfer_profile_to_env can accept either argument as undfined. (actually I'm not sure arg1 was ever a good idea ...)

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

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