File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.717: download - view: text, annotated - select for diffs
Sat Mar 4 06:03:30 2006 UTC (18 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- adding a dumpstore wrapper for diferentiating between dumpt hashes that are store/restored to and ones that are put/get from

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

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