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

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

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