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

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

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