Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.617

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

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