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

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

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