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

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

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