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

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

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