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

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

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