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

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

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