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

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

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