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

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

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