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

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

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