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

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

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