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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.264   ! matthew     4: # $Id: lonnet.pm,v 1.263 2002/08/08 13:42:01 www Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
                     29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
                     30: # 11/8,11/16,11/18,11/22,11/23,12/22,
                     31: # 01/06,01/13,02/24,02/28,02/29,
                     32: # 03/01,03/02,03/06,03/07,03/13,
                     33: # 04/05,05/29,05/31,06/01,
                     34: # 06/05,06/26 Gerd Kortemeyer
                     35: # 06/26 Ben Tyszka
                     36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
                     37: # 08/14 Ben Tyszka
                     38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
                     39: # 10/04 Gerd Kortemeyer
                     40: # 10/04 Guy Albertelli
                     41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
                     42: # 10/30,10/31,
                     43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
                     44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
                     45: # 05/01/01 Guy Albertelli
                     46: # 05/01,06/01,09/01 Gerd Kortemeyer
                     47: # 09/01 Guy Albertelli
                     48: # 09/01,10/01,11/01 Gerd Kortemeyer
                     49: # YEAR=2001
                     50: # 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.264   ! matthew  1605:     # Domain coordinator is trying to create a course
        !          1606:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
        !          1607:         # uri is the requested domain in this case.
        !          1608:         # comparison to 'request.role.domain' shows if the user has selected
        !          1609:         # a role of dc for the domain in question. 
        !          1610:         return 'F' if ($uri eq $ENV{'request.role.domain'});
        !          1611:     }
1.29      www      1612: 
1.52      www      1613:     my $thisallowed='';
                   1614:     my $statecond=0;
                   1615:     my $courseprivid='';
                   1616: 
                   1617: # Course
                   1618: 
                   1619:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
                   1620:        $thisallowed.=$1;
                   1621:     }
1.29      www      1622: 
1.52      www      1623: # Domain
                   1624: 
                   1625:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
                   1626:        =~/$priv\&([^\:]*)/) {
1.12      www      1627:        $thisallowed.=$1;
                   1628:     }
1.52      www      1629: 
                   1630: # Course: uri itself is a course
1.66      www      1631:     my $courseuri=$uri;
                   1632:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      1633:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      1634: 
1.83      www      1635:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.52      www      1636:        =~/$priv\&([^\:]*)/) {
1.12      www      1637:        $thisallowed.=$1;
                   1638:     }
1.29      www      1639: 
1.52      www      1640: # Full access at system, domain or course-wide level? Exit.
1.29      www      1641: 
                   1642:     if ($thisallowed=~/F/) {
                   1643: 	return 'F';
                   1644:     }
                   1645: 
1.52      www      1646: # If this is generating or modifying users, exit with special codes
1.29      www      1647: 
1.166     www      1648:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1.52      www      1649: 	return $thisallowed;
                   1650:     }
                   1651: #
1.103     harris41 1652: # Gathered so far: system, domain and course wide privileges
1.52      www      1653: #
                   1654: # Course: See if uri or referer is an individual resource that is part of 
                   1655: # the course
                   1656: 
                   1657:     if ($ENV{'request.course.id'}) {
1.232     www      1658: 
1.52      www      1659:        $courseprivid=$ENV{'request.course.id'};
                   1660:        if ($ENV{'request.course.sec'}) {
                   1661:           $courseprivid.='/'.$ENV{'request.course.sec'};
                   1662:        }
                   1663:        $courseprivid=~s/\_/\//;
                   1664:        my $checkreferer=1;
1.232     www      1665:        my ($match,$cond)=&is_on_map($uri);
                   1666:        if ($match) {
                   1667:            $statecond=$cond;
1.52      www      1668:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   1669:                =~/$priv\&([^\:]*)/) {
                   1670:                $thisallowed.=$1;
                   1671:                $checkreferer=0;
                   1672:            }
1.29      www      1673:        }
1.83      www      1674:        
1.148     www      1675:        if ($checkreferer) {
1.152     www      1676: 	  my $refuri=$ENV{'httpref.'.$orguri};
1.148     www      1677:             unless ($refuri) {
1.191     harris41 1678:                 foreach (keys %ENV) {
1.148     www      1679: 		    if ($_=~/^httpref\..*\*/) {
                   1680: 			my $pattern=$_;
1.156     www      1681:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      1682:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   1683:                         $pattern=~s/\//\\\//g;
1.152     www      1684:                         if ($orguri=~/$pattern/) {
1.148     www      1685: 			    $refuri=$ENV{$_};
                   1686:                         }
                   1687:                     }
1.191     harris41 1688:                 }
1.148     www      1689:             }
1.232     www      1690: 
1.148     www      1691:          if ($refuri) { 
1.152     www      1692: 	  $refuri=&declutter($refuri);
1.232     www      1693:           my ($match,$cond)=&is_on_map($refuri);
                   1694:             if ($match) {
                   1695:               my $refstatecond=$cond;
1.52      www      1696:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   1697:                   =~/$priv\&([^\:]*)/) {
                   1698:                   $thisallowed.=$1;
1.53      www      1699:                   $uri=$refuri;
                   1700:                   $statecond=$refstatecond;
1.52      www      1701:               }
                   1702:           }
1.148     www      1703:         }
1.29      www      1704:        }
1.52      www      1705:    }
1.29      www      1706: 
1.52      www      1707: #
1.103     harris41 1708: # Gathered now: all privileges that could apply, and condition number
1.52      www      1709: # 
                   1710: #
                   1711: # Full or no access?
                   1712: #
1.29      www      1713: 
1.52      www      1714:     if ($thisallowed=~/F/) {
                   1715: 	return 'F';
                   1716:     }
1.29      www      1717: 
1.52      www      1718:     unless ($thisallowed) {
                   1719:         return '';
                   1720:     }
1.29      www      1721: 
1.52      www      1722: # Restrictions exist, deal with them
                   1723: #
                   1724: #   C:according to course preferences
                   1725: #   R:according to resource settings
                   1726: #   L:unless locked
                   1727: #   X:according to user session state
                   1728: #
                   1729: 
                   1730: # Possibly locked functionality, check all courses
1.54      www      1731: # Locks might take effect only after 10 minutes cache expiration for other
                   1732: # courses, and 2 minutes for current course
1.52      www      1733: 
                   1734:     my $envkey;
                   1735:     if ($thisallowed=~/L/) {
                   1736:         foreach $envkey (keys %ENV) {
1.54      www      1737:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   1738:                my $courseid=$2;
                   1739:                my $roleid=$1.'.'.$2;
1.92      www      1740:                $courseid=~s/^\///;
1.54      www      1741:                my $expiretime=600;
                   1742:                if ($ENV{'request.role'} eq $roleid) {
                   1743: 		  $expiretime=120;
                   1744:                }
                   1745: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   1746:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
                   1747:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
                   1748: 		   &coursedescription($courseid);
                   1749:                }
                   1750:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
                   1751:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   1752: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57      www      1753:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      1754:                             $ENV{'user.home'},
1.57      www      1755:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      1756:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      1757:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      1758: 		       return '';
                   1759:                    }
                   1760:                }
1.54      www      1761:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
                   1762:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   1763: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57      www      1764:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      1765:                             $ENV{'user.home'},
1.57      www      1766:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      1767:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      1768:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      1769: 		       return '';
                   1770:                    }
                   1771:                }
                   1772: 	   }
1.29      www      1773:        }
1.52      www      1774:     }
                   1775:    
                   1776: #
                   1777: # Rest of the restrictions depend on selected course
                   1778: #
                   1779: 
                   1780:     unless ($ENV{'request.course.id'}) {
                   1781:        return '1';
                   1782:     }
1.29      www      1783: 
1.52      www      1784: #
                   1785: # Now user is definitely in a course
                   1786: #
1.53      www      1787: 
                   1788: 
                   1789: # Course preferences
                   1790: 
                   1791:    if ($thisallowed=~/C/) {
1.54      www      1792:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.237     www      1793:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.54      www      1794:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.194     www      1795: 	   =~/$rolecode/) {
1.57      www      1796:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   1797:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.237     www      1798:                 $ENV{'request.course.id'});
                   1799:            return '';
                   1800:        }
                   1801: 
                   1802:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
                   1803: 	   =~/$unamedom/) {
                   1804:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   1805:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.54      www      1806:                 $ENV{'request.course.id'});
                   1807:            return '';
                   1808:        }
1.53      www      1809:    }
                   1810: 
                   1811: # Resource preferences
                   1812: 
                   1813:    if ($thisallowed=~/R/) {
1.54      www      1814:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
                   1815:        my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
                   1816:        if (-e $filename) {
                   1817:            my @content;
                   1818:            {
                   1819: 	     my $fh=Apache::File->new($filename);
                   1820:              @content=<$fh>;
                   1821: 	   }
                   1822:            if (join('',@content)=~
                   1823:                     /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
1.57      www      1824: 	       &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   1825:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.54      www      1826:            return '';
                   1827: 
                   1828:            }
                   1829:        }
1.53      www      1830:    }
1.30      www      1831: 
1.246     www      1832: # Restricted by state or randomout?
1.30      www      1833: 
1.52      www      1834:    if ($thisallowed=~/X/) {
1.247     www      1835:       if ($ENV{'acc.randomout'}) {
1.249     www      1836:          my $symb=&symbread($uri,1);
1.248     www      1837:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
                   1838:             return ''; 
                   1839:          }
1.247     www      1840:       }
                   1841:       if (&condval($statecond)) {
1.52      www      1842: 	 return '2';
                   1843:       } else {
                   1844:          return '';
                   1845:       }
                   1846:    }
1.30      www      1847: 
1.52      www      1848:    return 'F';
1.232     www      1849: }
                   1850: 
                   1851: # --------------------------------------------------- Is a resource on the map?
                   1852: 
                   1853: sub is_on_map {
                   1854:     my $uri=&declutter(shift);
                   1855:     my @uriparts=split(/\//,$uri);
                   1856:     my $filename=$uriparts[$#uriparts];
                   1857:     my $pathname=$uri;
                   1858:     $pathname=~s/\/$filename$//;
                   1859:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
                   1860: 	       /\&$filename\:([\d\|]+)\&/);
                   1861:     if ($match) {
                   1862:        return (1,$1);
                   1863:    } else {
                   1864:        return (0,0);
                   1865:    }
1.12      www      1866: }
                   1867: 
                   1868: # ----------------------------------------------------------------- Define Role
                   1869: 
                   1870: sub definerole {
                   1871:   if (allowed('mcr','/')) {
                   1872:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.191     harris41 1873:     foreach (split('/',$sysrole)) {
1.21      www      1874: 	my ($crole,$cqual)=split(/\&/,$_);
                   1875:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
                   1876:         if ($pr{'cr:s'}=~/$crole\&/) {
                   1877: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
                   1878:                return "refused:s:$crole&$cqual"; 
                   1879:             }
                   1880:         }
1.191     harris41 1881:     }
                   1882:     foreach (split('/',$domrole)) {
1.21      www      1883: 	my ($crole,$cqual)=split(/\&/,$_);
                   1884:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
                   1885:         if ($pr{'cr:d'}=~/$crole\&/) {
                   1886: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
                   1887:                return "refused:d:$crole&$cqual"; 
                   1888:             }
                   1889:         }
1.191     harris41 1890:     }
                   1891:     foreach (split('/',$courole)) {
1.21      www      1892: 	my ($crole,$cqual)=split(/\&/,$_);
                   1893:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
                   1894:         if ($pr{'cr:c'}=~/$crole\&/) {
                   1895: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
                   1896:                return "refused:c:$crole&$cqual"; 
                   1897:             }
                   1898:         }
1.191     harris41 1899:     }
1.12      www      1900:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   1901:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21      www      1902: 	        "rolesdef_$rolename=".
                   1903:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.12      www      1904:     return reply($command,$ENV{'user.home'});
                   1905:   } else {
                   1906:     return 'refused';
                   1907:   }
1.105     harris41 1908: }
                   1909: 
                   1910: # ---------------- Make a metadata query against the network of library servers
                   1911: 
                   1912: sub metadata_query {
1.244     matthew  1913:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 1914:     my %rhash;
1.244     matthew  1915:     my @server_list = (defined($server_array) ? @$server_array
                   1916:                                               : keys(%libserv) );
                   1917:     for my $server (@server_list) {
1.118     harris41 1918: 	unless ($custom or $customshow) {
                   1919: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   1920: 	    $rhash{$server}=$reply;
                   1921: 	}
                   1922: 	else {
                   1923: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   1924: 			     &escape($custom).':'.&escape($customshow),
                   1925: 			     $server);
                   1926: 	    $rhash{$server}=$reply;
                   1927: 	}
1.112     harris41 1928:     }
1.118     harris41 1929:     return \%rhash;
1.240     www      1930: }
                   1931: 
                   1932: # ----------------------------------------- Send log queries and wait for reply
                   1933: 
                   1934: sub log_query {
                   1935:     my ($uname,$udom,$query,%filters)=@_;
                   1936:     my $uhome=&homeserver($uname,$udom);
                   1937:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   1938:     my $uhost=$hostname{$uhome};
1.241     www      1939:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      1940:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   1941:                        $uhome);
                   1942:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
1.242     www      1943:     return get_query_reply($queryid);
                   1944: }
                   1945: 
                   1946: sub get_query_reply {
                   1947:     my $queryid=shift;
1.240     www      1948:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   1949:     my $reply='';
                   1950:     for (1..100) {
                   1951: 	sleep 2;
                   1952:         if (-e $replyfile.'.end') {
                   1953: 	    if (my $fh=Apache::File->new($replyfile)) {
                   1954:                $reply.=<$fh>;
                   1955:                $fh->close;
                   1956: 	   } else { return 'error: reply_file_error'; }
1.242     www      1957:            return &unescape($reply);
                   1958: 	}
1.240     www      1959:     }
1.242     www      1960:     return 'timeout:'.$queryid;
1.240     www      1961: }
                   1962: 
                   1963: sub courselog_query {
1.241     www      1964: #
                   1965: # possible filters:
                   1966: # url: url or symb
                   1967: # username
                   1968: # domain
                   1969: # action: view, submit, grade
                   1970: # start: timestamp
                   1971: # end: timestamp
                   1972: #
1.240     www      1973:     my (%filters)=@_;
                   1974:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
1.241     www      1975:     if ($filters{'url'}) {
                   1976: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   1977:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   1978:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   1979:     }
1.240     www      1980:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1981:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1982:     return &log_query($cname,$cdom,'courselog',%filters);
                   1983: }
                   1984: 
                   1985: sub userlog_query {
                   1986:     my ($uname,$udom,%filters)=@_;
                   1987:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      1988: }
                   1989: 
                   1990: # ------------------------------------------------------------------ Plain Text
                   1991: 
                   1992: sub plaintext {
1.22      www      1993:     my $short=shift;
                   1994:     return $prp{$short};
1.12      www      1995: }
                   1996: 
                   1997: # ----------------------------------------------------------------- Assign Role
                   1998: 
                   1999: sub assignrole {
1.21      www      2000:     my ($udom,$uname,$url,$role,$end,$start)=@_;
                   2001:     my $mrole;
                   2002:     if ($role =~ /^cr\//) {
1.104     www      2003: 	unless (&allowed('ccr',$url)) {
                   2004:            &logthis('Refused custom assignrole: '.
                   2005:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2006: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2007:            return 'refused'; 
                   2008:         }
1.21      www      2009:         $mrole='cr';
                   2010:     } else {
1.82      www      2011:         my $cwosec=$url;
1.83      www      2012:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.104     www      2013:         unless (&allowed('c'.$role,$cwosec)) { 
                   2014:            &logthis('Refused assignrole: '.
                   2015:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2016: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2017:            return 'refused'; 
                   2018:         }
1.21      www      2019:         $mrole=$role;
                   2020:     }
                   2021:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2022:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      2023:     if ($end) { $command.='_'.$end; }
1.21      www      2024:     if ($start) {
                   2025: 	if ($end) { 
1.81      www      2026:            $command.='_'.$start; 
1.21      www      2027:         } else {
1.81      www      2028:            $command.='_0_'.$start;
1.21      www      2029:         }
                   2030:     }
                   2031:     return &reply($command,&homeserver($uname,$udom));
1.169     harris41 2032: }
                   2033: 
                   2034: # -------------------------------------------------- Modify user authentication
1.197     www      2035: # Overrides without validation
                   2036: 
1.169     harris41 2037: sub modifyuserauth {
                   2038:     my ($udom,$uname,$umode,$upass)=@_;
                   2039:     my $uhome=&homeserver($uname,$udom);
1.197     www      2040:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   2041:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.169     harris41 2042:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'});  
                   2043:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   2044: 		     &escape($upass),$uhome);
1.197     www      2045:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                   2046:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   2047:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   2048:     &log($udom,,$uname,$uhome,
                   2049:         'Authentication changed by '.$ENV{'user.domain'}.', '.
                   2050:                                      $ENV{'user.name'}.', '.$umode.
                   2051:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 2052:     unless ($reply eq 'ok') {
1.197     www      2053:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 2054: 	return 'error: '.$reply;
                   2055:     }   
1.170     harris41 2056:     return 'ok';
1.80      www      2057: }
                   2058: 
1.81      www      2059: # --------------------------------------------------------------- Modify a user
1.80      www      2060: 
1.81      www      2061: sub modifyuser {
1.206     matthew  2062:     my ($udom,    $uname, $uid,
                   2063:         $umode,   $upass, $first,
                   2064:         $middle,  $last,  $gene,
                   2065:         $forceid, $desiredhome)=@_;
1.198     www      2066:     $udom=~s/\W//g;
                   2067:     $uname=~s/\W//g;
1.81      www      2068:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      2069:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  2070: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   2071:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   2072:                                      ' desiredhome not specified'). 
                   2073:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.230     stredwic 2074:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      2075: # ----------------------------------------------------------------- Create User
1.81      www      2076:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
1.80      www      2077:         my $unhome='';
1.209     matthew  2078:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   2079:             $unhome = $desiredhome;
                   2080: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
1.80      www      2081: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.209     matthew  2082:         } else { # load balancing routine for determining $unhome
1.80      www      2083:             my $tryserver;
1.81      www      2084:             my $loadm=10000000;
1.80      www      2085:             foreach $tryserver (keys %libserv) {
                   2086: 	       if ($hostdom{$tryserver} eq $udom) {
                   2087:                   my $answer=reply('load',$tryserver);
                   2088:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   2089: 		      $loadm=$answer;
                   2090:                       $unhome=$tryserver;
                   2091:                   }
                   2092: 	       }
                   2093: 	    }
                   2094:         }
                   2095:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  2096: 	    return 'error: unable to find a home server for '.$uname.
                   2097:                    ' in domain '.$udom;
1.80      www      2098:         }
                   2099:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   2100:                          &escape($upass),$unhome);
                   2101: 	unless ($reply eq 'ok') {
                   2102:             return 'error: '.$reply;
                   2103:         }   
1.230     stredwic 2104:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      2105:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
                   2106: 	    return 'error: verify home';
                   2107:         }
1.209     matthew  2108:     }   # End of creation of new user
1.80      www      2109: # ---------------------------------------------------------------------- Add ID
                   2110:     if ($uid) {
                   2111:        $uid=~tr/A-Z/a-z/;
                   2112:        my %uidhash=&idrget($udom,$uname);
1.196     www      2113:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   2114:          && (!$forceid)) {
1.80      www      2115: 	  unless ($uid eq $uidhash{$uname}) {
                   2116: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
                   2117:           }
                   2118:        } else {
                   2119: 	  &idput($udom,($uname => $uid));
                   2120:        }
                   2121:     }
                   2122: # -------------------------------------------------------------- Add names, etc
1.134     albertel 2123:     my %names=&get('environment',
                   2124: 		   ['firstname','middlename','lastname','generation'],
                   2125: 		   $udom,$uname);
1.207     albertel 2126:     if ($names{'firstname'} =~ m/^error:.*/) { %names=(); }
1.134     albertel 2127:     if ($first)  { $names{'firstname'}  = $first; }
                   2128:     if ($middle) { $names{'middlename'} = $middle; }
                   2129:     if ($last)   { $names{'lastname'}   = $last; }
                   2130:     if ($gene)   { $names{'generation'} = $gene; }
                   2131:     my $reply = &put('environment', \%names, $udom,$uname);
                   2132:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      2133:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      2134:              $umode.', '.$first.', '.$middle.', '.
                   2135: 	     $last.', '.$gene.' by '.
                   2136:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134     albertel 2137:     return 'ok';
1.80      www      2138: }
                   2139: 
1.81      www      2140: # -------------------------------------------------------------- Modify student
1.80      www      2141: 
1.81      www      2142: sub modifystudent {
                   2143:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.209     matthew  2144:         $end,$start,$forceid,$desiredhome)=@_;
1.81      www      2145:     my $cid='';
                   2146:     unless ($cid=$ENV{'request.course.id'}) {
1.80      www      2147: 	return 'not_in_class';
                   2148:     }
                   2149: # --------------------------------------------------------------- Make the user
1.81      www      2150:     my $reply=&modifyuser
1.209     matthew  2151: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
                   2152:          $desiredhome);
1.80      www      2153:     unless ($reply eq 'ok') { return $reply; }
1.81      www      2154:     my $uhome=&homeserver($uname,$udom);
                   2155:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   2156: 	return 'error: no such user';
                   2157:     }
1.80      www      2158: # -------------------------------------------------- Add student to course list
1.160     www      2159:     $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1.81      www      2160: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
                   2161:                       &escape($uname.':'.$udom).'='.
                   2162:                       &escape($end.':'.$start),
                   2163: 	              $ENV{'course.'.$cid.'.home'});
                   2164:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   2165: 	return 'error: '.$reply;
                   2166:     }
1.80      www      2167: # ---------------------------------------------------- Add student role to user
1.83      www      2168:     my $uurl='/'.$cid;
1.81      www      2169:     $uurl=~s/\_/\//g;
                   2170:     if ($usec) {
                   2171: 	$uurl.='/'.$usec;
                   2172:     }
                   2173:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      2174: }
                   2175: 
1.84      www      2176: # ------------------------------------------------- Write to course preferences
                   2177: 
                   2178: sub writecoursepref {
                   2179:     my ($courseid,%prefs)=@_;
                   2180:     $courseid=~s/^\///;
                   2181:     $courseid=~s/\_/\//g;
                   2182:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   2183:     my $chome=homeserver($cnum,$cdomain);
                   2184:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   2185: 	return 'error: no such course';
                   2186:     }
                   2187:     my $cstring='';
1.191     harris41 2188:     foreach (keys %prefs) {
1.84      www      2189: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 2190:     }
1.84      www      2191:     $cstring=~s/\&$//;
                   2192:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   2193: }
                   2194: 
                   2195: # ---------------------------------------------------------- Make/modify course
                   2196: 
                   2197: sub createcourse {
1.264   ! matthew  2198:     my ($udom,$description,$url,$course_server)=@_;
1.84      www      2199:     $url=&declutter($url);
                   2200:     my $cid='';
1.264   ! matthew  2201:     unless (&allowed('ccc',$udom)) {
1.84      www      2202:         return 'refused';
                   2203:     }
                   2204: # ------------------------------------------------------------------- Create ID
                   2205:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   2206:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   2207: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 2208:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      2209:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   2210:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   2211:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 2212:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      2213:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   2214:            return 'error: unable to generate unique course-ID';
                   2215:        } 
                   2216:    }
1.264   ! matthew  2217: # ------------------------------------------------ Check supplied server name
        !          2218:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
        !          2219:     if (! exists($libserv{$course_server})) {
        !          2220:         return 'error:bad server name '.$course_server;
        !          2221:     }
1.84      www      2222: # ------------------------------------------------------------- Make the course
                   2223:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264   ! matthew  2224:                       $course_server);
1.84      www      2225:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 2226:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      2227:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   2228: 	return 'error: no such course';
                   2229:     }
                   2230:     &writecoursepref($udom.'_'.$uname,
                   2231:                      ('description' => $description,
                   2232:                       'url'         => $url));
                   2233:     return '/'.$udom.'/'.$uname;
                   2234: }
                   2235: 
1.21      www      2236: # ---------------------------------------------------------- Assign Custom Role
                   2237: 
                   2238: sub assigncustomrole {
                   2239:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
                   2240:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
                   2241:                        $end,$start);
                   2242: }
                   2243: 
                   2244: # ----------------------------------------------------------------- Revoke Role
                   2245: 
                   2246: sub revokerole {
                   2247:     my ($udom,$uname,$url,$role)=@_;
                   2248:     my $now=time;
                   2249:     return &assignrole($udom,$uname,$url,$role,$now);
                   2250: }
                   2251: 
                   2252: # ---------------------------------------------------------- Revoke Custom Role
                   2253: 
                   2254: sub revokecustomrole {
                   2255:     my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
                   2256:     my $now=time;
                   2257:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
1.17      www      2258: }
                   2259: 
                   2260: # ------------------------------------------------------------ Directory lister
                   2261: 
                   2262: sub dirlist {
1.253     stredwic 2263:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   2264: 
1.18      www      2265:     $uri=~s/^\///;
                   2266:     $uri=~s/\/$//;
1.253     stredwic 2267:     my ($udom, $uname);
                   2268:     (undef,$udom,$uname)=split(/\//,$uri);
                   2269:     if(defined($userdomain)) {
                   2270:         $udom = $userdomain;
                   2271:     }
                   2272:     if(defined($username)) {
                   2273:         $uname = $username;
                   2274:     }
                   2275: 
                   2276:     my $dirRoot = $perlvar{'lonDocRoot'};
                   2277:     if(defined($alternateDirectoryRoot)) {
                   2278:         $dirRoot = $alternateDirectoryRoot;
                   2279:         $dirRoot =~ s/\/$//;
                   2280:     }
                   2281: 
                   2282:     if($udom) {
                   2283:         if($uname) {
                   2284:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   2285:                               homeserver($uname,$udom));
                   2286:             return split(/:/,$listing);
                   2287:         } elsif(!defined($alternateDirectoryRoot)) {
                   2288:             my $tryserver;
                   2289:             my %allusers=();
                   2290:             foreach $tryserver (keys %libserv) {
                   2291:                 if($hostdom{$tryserver} eq $udom) {
                   2292:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   2293:                                       $udom, $tryserver);
                   2294:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
                   2295:                         && ($listing ne 'con_lost')) {
                   2296:                         foreach (split(/:/,$listing)) {
                   2297:                             my ($entry,@stat)=split(/&/,$_);
                   2298:                             $allusers{$entry}=1;
                   2299:                         }
                   2300:                     }
1.191     harris41 2301:                 }
1.253     stredwic 2302:             }
                   2303:             my $alluserstr='';
                   2304:             foreach (sort keys %allusers) {
                   2305:                 $alluserstr.=$_.'&user:';
                   2306:             }
                   2307:             $alluserstr=~s/:$//;
                   2308:             return split(/:/,$alluserstr);
                   2309:         } else {
                   2310:             my @emptyResults = ();
                   2311:             push(@emptyResults, 'missing user name');
                   2312:             return split(':',@emptyResults);
                   2313:         }
                   2314:     } elsif(!defined($alternateDirectoryRoot)) {
                   2315:         my $tryserver;
                   2316:         my %alldom=();
                   2317:         foreach $tryserver (keys %libserv) {
                   2318:             $alldom{$hostdom{$tryserver}}=1;
                   2319:         }
                   2320:         my $alldomstr='';
                   2321:         foreach (sort keys %alldom) {
                   2322:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
                   2323:         }
                   2324:         $alldomstr=~s/:$//;
                   2325:         return split(/:/,$alldomstr);       
                   2326:     } else {
                   2327:         my @emptyResults = ();
                   2328:         push(@emptyResults, 'missing domain');
                   2329:         return split(':',@emptyResults);
                   2330:     }
1.26      www      2331: }
                   2332: 
                   2333: # -------------------------------------------------------- Value of a Condition
                   2334: 
1.40      www      2335: sub directcondval {
                   2336:     my $number=shift;
                   2337:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
                   2338:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
                   2339:     } else {
                   2340:        return 2;
                   2341:     }
                   2342: }
                   2343: 
1.26      www      2344: sub condval {
                   2345:     my $condidx=shift;
                   2346:     my $result=0;
1.54      www      2347:     my $allpathcond='';
1.191     harris41 2348:     foreach (split(/\|/,$condidx)) {
1.54      www      2349:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
                   2350: 	   $allpathcond.=
                   2351:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
                   2352:        }
1.191     harris41 2353:     }
1.54      www      2354:     $allpathcond=~s/\|$//;
1.33      www      2355:     if ($ENV{'request.course.id'}) {
1.54      www      2356:        if ($allpathcond) {
1.26      www      2357:           my $operand='|';
                   2358: 	  my @stack;
1.191     harris41 2359:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      2360:               if ($_ eq '(') {
                   2361:                  push @stack,($operand,$result)
                   2362:               } elsif ($_ eq ')') {
                   2363:                   my $before=pop @stack;
                   2364: 		  if (pop @stack eq '&') {
                   2365: 		      $result=$result>$before?$before:$result;
                   2366:                   } else {
                   2367:                       $result=$result>$before?$result:$before;
                   2368:                   }
                   2369:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   2370:                   $operand=$_;
                   2371:               } else {
1.40      www      2372:                   my $new=directcondval($_);
1.26      www      2373:                   if ($operand eq '&') {
                   2374:                      $result=$result>$new?$new:$result;
                   2375:                   } else {
                   2376:                      $result=$result>$new?$result:$new;
1.191     harris41 2377:                   }
1.26      www      2378:               }
1.191     harris41 2379:           }
1.26      www      2380:        }
                   2381:     }
                   2382:     return $result;
1.28      www      2383: }
                   2384: 
1.200     www      2385: # --------------------------------------------------- Course Resourcedata Query
                   2386: 
                   2387: sub courseresdata {
                   2388:     my ($coursenum,$coursedomain,@which)=@_;
                   2389:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   2390:     my $hashid=$coursenum.':'.$coursedomain;
1.250     albertel 2391:     my $dodump=0;
                   2392:     if (!defined($courseresdatacache{$hashid.'.time'})) {
                   2393: 	$dodump=1;
                   2394:     } else {
                   2395: 	if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
                   2396:     }
                   2397:     if ($dodump) {
1.251     albertel 2398: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
                   2399: 	my ($tmp) = keys(%dumpreply);
                   2400: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   2401: 	    $courseresdatacache{$hashid.'.time'}=time;
                   2402: 	    $courseresdatacache{$hashid}=\%dumpreply;
1.250     albertel 2403: 	}
                   2404:     }
1.251     albertel 2405:     foreach my $item (@which) {
                   2406: 	if ($courseresdatacache{$hashid}->{$item}) {
                   2407: 	    return $courseresdatacache{$hashid}->{$item};
                   2408: 	}
1.250     albertel 2409:     }
                   2410:     return '';
1.200     www      2411: }
                   2412: 
1.28      www      2413: # --------------------------------------------------------- Value of a Variable
                   2414: 
1.58      www      2415: sub EXT {
1.218     albertel 2416:     my ($varname,$symbparm,$udom,$uname)=@_;
                   2417: 
1.68      www      2418:     unless ($varname) { return ''; }
1.218     albertel 2419: 
                   2420:     #get real user name/domain, courseid and symb
                   2421:     my $courseid;
                   2422:     if (!($uname && $udom)) {
                   2423:       (my $cursymb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2424:       if (!$symbparm) {	$symbparm=$cursymb; }
                   2425:     } else {
                   2426: 	$courseid=$ENV{'request.course.id'};
                   2427:     }
                   2428: 
1.48      www      2429:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   2430:     my $rest;
                   2431:     if ($therest[0]) {
                   2432:        $rest=join('.',@therest);
                   2433:     } else {
                   2434:        $rest='';
                   2435:     }
1.57      www      2436:     my $qualifierrest=$qualifier;
                   2437:     if ($rest) { $qualifierrest.='.'.$rest; }
                   2438:     my $spacequalifierrest=$space;
                   2439:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      2440:     if ($realm eq 'user') {
1.48      www      2441: # --------------------------------------------------------------- user.resource
                   2442: 	if ($space eq 'resource') {
1.218     albertel 2443: 	    my %restored=&restore(undef,undef,$udom,$uname);
1.57      www      2444:             return $restored{$qualifierrest};
1.48      www      2445: # ----------------------------------------------------------------- user.access
                   2446:         } elsif ($space eq 'access') {
1.218     albertel 2447: 	    # FIXME - not supporting calls for a specific user
1.48      www      2448:             return &allowed($qualifier,$rest);
                   2449: # ------------------------------------------ user.preferences, user.environment
                   2450:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.218     albertel 2451: 	    if (($uname eq $ENV{'user.name'}) &&
                   2452: 		($udom eq $ENV{'user.domain'})) {
                   2453: 		return $ENV{join('.',('environment',$qualifierrest))};
                   2454: 	    } else {
                   2455: 		my %returnhash=&userenvironment($udom,$uname,$qualifierrest);
                   2456: 		return $returnhash{$qualifierrest};
                   2457: 	    }
1.48      www      2458: # ----------------------------------------------------------------- user.course
                   2459:         } elsif ($space eq 'course') {
1.218     albertel 2460: 	    # FIXME - not supporting calls for a specific user
1.48      www      2461:             return $ENV{join('.',('request.course',$qualifier))};
                   2462: # ------------------------------------------------------------------- user.role
                   2463:         } elsif ($space eq 'role') {
1.218     albertel 2464: 	    # FIXME - not supporting calls for a specific user
1.48      www      2465:             my ($role,$where)=split(/\./,$ENV{'request.role'});
                   2466:             if ($qualifier eq 'value') {
                   2467: 		return $role;
                   2468:             } elsif ($qualifier eq 'extent') {
                   2469:                 return $where;
                   2470:             }
                   2471: # ----------------------------------------------------------------- user.domain
                   2472:         } elsif ($space eq 'domain') {
1.218     albertel 2473:             return $udom;
1.48      www      2474: # ------------------------------------------------------------------- user.name
                   2475:         } elsif ($space eq 'name') {
1.218     albertel 2476:             return $uname;
1.48      www      2477: # ---------------------------------------------------- Any other user namespace
1.29      www      2478:         } else {
1.48      www      2479:             my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
1.131     albertel 2480:             my %reply=&get($space,[$item]);
1.48      www      2481:             return $reply{$item};
                   2482:         }
1.236     www      2483:     } elsif ($realm eq 'query') {
                   2484: # ---------------------------------------------- pull stuff out of query string
                   2485:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},[$space]);
                   2486: 	return $ENV{'form.'.$space}; 
                   2487:    } elsif ($realm eq 'request') {
1.48      www      2488: # ------------------------------------------------------------- request.browser
                   2489:         if ($space eq 'browser') {
                   2490: 	    return $ENV{'browser.'.$qualifier};
1.57      www      2491: # ------------------------------------------------------------ request.filename
                   2492:         } else {
                   2493:             return $ENV{'request.'.$spacequalifierrest};
1.29      www      2494:         }
1.28      www      2495:     } elsif ($realm eq 'course') {
1.48      www      2496: # ---------------------------------------------------------- course.description
1.218     albertel 2497:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      2498:     } elsif ($realm eq 'resource') {
1.165     www      2499: 
1.218     albertel 2500: 	if ($courseid eq $ENV{'request.course.id'}) {
1.165     www      2501: 
1.218     albertel 2502: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      2503: 
1.60      www      2504: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 2505: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   2506: 	    my $symbp=$symbparm;
                   2507: 	    my $mapp=(split(/\_\_\_/,$symbp))[0];
                   2508: 
                   2509: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   2510: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   2511: 
                   2512: 	    my $section;
                   2513: 	    if (($ENV{'user.name'} eq $uname) &&
                   2514: 		($ENV{'user.domain'} eq $udom)) {
1.255     albertel 2515: 		$section=$ENV{'request.course.sec'};
1.218     albertel 2516: 	    } else {
                   2517: 		$section=&usection($udom,$uname,$courseid);
                   2518: 	    }
                   2519: 
                   2520: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   2521: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   2522: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   2523: 
                   2524: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
                   2525: 	    my $courselevelr=$courseid.'.'.$symbparm;
                   2526: 	    my $courselevelm=$courseid.'.'.$mapparm;
1.69      www      2527: 
1.60      www      2528: # ----------------------------------------------------------- first, check user
1.218     albertel 2529: 	    my %resourcedata=&get('resourcedata',
                   2530: 				  [$courselevelr,$courselevelm,$courselevel],
                   2531: 				 $udom,$uname);
                   2532: 	    if (($resourcedata{$courselevelr}!~/^error\:/) &&
                   2533: 		($resourcedata{$courselevelr}!~/^con_lost/)) {
                   2534: 
                   2535: 		if ($resourcedata{$courselevelr}) {
                   2536: 		    return $resourcedata{$courselevelr}; }
                   2537: 		if ($resourcedata{$courselevelm}) {
                   2538: 		    return $resourcedata{$courselevelm}; }
                   2539: 		if ($resourcedata{$courselevel}) {
                   2540: 		    return $resourcedata{$courselevel}; }
                   2541: 	    } else {
                   2542: 		if ($resourcedata{$courselevelr}!~/No such file/) {
                   2543: 		    &logthis("<font color=blue>WARNING:".
                   2544: 			     " Trying to get resource data for ".
                   2545: 			     $uname." at ".$udom.": ".
                   2546: 			     $resourcedata{$courselevelr}."</font>");
                   2547: 		}
                   2548: 	    }
1.95      www      2549: 
1.60      www      2550: # -------------------------------------------------------- second, check course
1.96      www      2551: 
1.218     albertel 2552: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
                   2553: 					  $ENV{'course.'.$courseid.'.domain'},
                   2554: 					  ($seclevelr,$seclevelm,$seclevel,
                   2555: 					   $courselevelr,$courselevelm,
                   2556: 					   $courselevel));
                   2557: 	    if ($coursereply) { return $coursereply; }
1.200     www      2558: 
1.60      www      2559: # ------------------------------------------------------ third, check map parms
1.218     albertel 2560: 	    my %parmhash=();
                   2561: 	    my $thisparm='';
                   2562: 	    if (tie(%parmhash,'GDBM_File',
                   2563: 		    $ENV{'request.course.fn'}.'_parms.db',
1.256     albertel 2564: 		    &GDBM_READER(),0640)) {
1.218     albertel 2565: 		$thisparm=$parmhash{$symbparm};
                   2566: 		untie(%parmhash);
                   2567: 	    }
                   2568: 	    if ($thisparm) { return $thisparm; }
                   2569: 	}
1.60      www      2570: # --------------------------------------------- last, look in resource metadata
1.71      www      2571: 
1.218     albertel 2572: 	$spacequalifierrest=~s/\./\_/;
                   2573: 	my $metadata=&metadata($ENV{'request.filename'},$spacequalifierrest);
                   2574: 	if ($metadata) { return $metadata; }
                   2575: 	$metadata=&metadata($ENV{'request.filename'},
                   2576: 			    'parameter_'.$spacequalifierrest);
                   2577: 	if ($metadata) { return $metadata; }
1.142     www      2578: 
1.145     www      2579: # ------------------------------------------------------------------ Cascade up
1.218     albertel 2580: 	unless ($space eq '0') {
                   2581: 	    my ($part,$id)=split(/\_/,$space);
                   2582: 	    if ($id) {
                   2583: 		my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
                   2584: 				     $symbparm,$udom,$uname);
                   2585: 		if ($partgeneral) { return $partgeneral; }
                   2586: 	    } else {
                   2587: 		my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
                   2588: 					 $symbparm,$udom,$uname);
                   2589: 		if ($resourcegeneral) { return $resourcegeneral; }
                   2590: 	    }
                   2591: 	}
1.71      www      2592: 
1.48      www      2593: # ---------------------------------------------------- Any other user namespace
                   2594:     } elsif ($realm eq 'environment') {
                   2595: # ----------------------------------------------------------------- environment
1.219     albertel 2596: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
                   2597: 	    return $ENV{'environment.'.$spacequalifierrest};
                   2598: 	} else {
                   2599: 	    my %returnhash=&userenvironment($udom,$uname,
                   2600: 					    $spacequalifierrest);
                   2601: 	    return $returnhash{$spacequalifierrest};
                   2602: 	}
1.28      www      2603:     } elsif ($realm eq 'system') {
1.48      www      2604: # ----------------------------------------------------------------- system.time
                   2605: 	if ($space eq 'time') {
                   2606: 	    return time;
                   2607:         }
1.28      www      2608:     }
1.48      www      2609:     return '';
1.61      www      2610: }
                   2611: 
1.71      www      2612: # ---------------------------------------------------------------- Get metadata
                   2613: 
                   2614: sub metadata {
1.176     www      2615:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.78      www      2616: 
1.71      www      2617:     $uri=&declutter($uri);
1.73      www      2618:     my $filename=$uri;
                   2619:     $uri=~s/\.meta$//;
1.172     www      2620: #
                   2621: # Is the metadata already cached?
1.177     www      2622: # Look at timestamp of caching
1.172     www      2623: # Everything is cached by the main uri, libraries are never directly cached
                   2624: #
1.174     www      2625:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600) {
1.172     www      2626: #
                   2627: # Is this a recursive call for a library?
                   2628: #
1.171     www      2629:         if ($liburi) {
                   2630: 	    $liburi=&declutter($liburi);
                   2631:             $filename=$liburi;
                   2632:         }
1.140     www      2633:         my %metathesekeys=();
1.73      www      2634:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
                   2635: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
1.208     albertel 2636:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      2637:         my $token;
1.140     www      2638:         undef %metathesekeys;
1.71      www      2639:         while ($token=$parser->get_token) {
                   2640:            if ($token->[0] eq 'S') {
1.135     www      2641: 	     if (defined($token->[2]->{'package'})) {
1.172     www      2642: #
                   2643: # This is a package - get package info
                   2644: #
1.136     www      2645: 	      my $package=$token->[2]->{'package'};
                   2646: 	      my $keyroot='';
1.172     www      2647:               if ($prefix) {
                   2648: 		  $keyroot.='_'.$prefix;
                   2649:               } else {
                   2650:                 if (defined($token->[2]->{'part'})) { 
                   2651:                    $keyroot.='_'.$token->[2]->{'part'}; 
                   2652: 	        }
1.136     www      2653: 	      }
                   2654:               if (defined($token->[2]->{'id'})) { 
1.165     www      2655:                  $keyroot.='_'.$token->[2]->{'id'}; 
1.136     www      2656: 	      }
                   2657:               if ($metacache{$uri.':packages'}) {
                   2658:                  $metacache{$uri.':packages'}.=','.$package.$keyroot;
                   2659:               } else {
                   2660:                  $metacache{$uri.':packages'}=$package.$keyroot;
                   2661: 	      }
1.191     harris41 2662:               foreach (keys %packagetab) {
1.137     www      2663: 		  if ($_=~/^$package\&/) {
                   2664: 		      my ($pack,$name,$subp)=split(/\&/,$_);
1.139     www      2665:                       my $value=$packagetab{$_};
1.144     www      2666: 		      my $part=$keyroot;
                   2667:                       $part=~s/^\_//;
1.139     www      2668:                       if ($subp eq 'display') {
                   2669: 			  $value.=' [Part: '.$part.']';
                   2670:                       }
                   2671:                       my $unikey='parameter'.$keyroot.'_'.$name;
1.140     www      2672:                       $metathesekeys{$unikey}=1;
1.144     www      2673:                       $metacache{$uri.':'.$unikey.'.part'}=$part;
1.141     www      2674:                       unless 
                   2675:                        (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
                   2676:                          $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
                   2677: 		      }
1.137     www      2678:                   }
1.191     harris41 2679:               }
1.135     www      2680:              } else {
1.172     www      2681: #
                   2682: # This is not a package - some other kind of start tag
                   2683: # 
1.175     www      2684:               my $entry=$token->[1];
1.176     www      2685:               my $unikey;
                   2686:               if ($entry eq 'import') {
                   2687:                  $unikey='';
                   2688:               } else {
                   2689:                  $unikey=$entry;
                   2690: 	      }
1.172     www      2691:               if ($prefix) {
1.176     www      2692: 		  $unikey.=$prefix;
1.172     www      2693:               } else {
                   2694:                 if (defined($token->[2]->{'part'})) { 
                   2695:                    $unikey.='_'.$token->[2]->{'part'}; 
                   2696: 	        }
1.136     www      2697: 	      }
                   2698:               if (defined($token->[2]->{'id'})) { 
1.165     www      2699:                  $unikey.='_'.$token->[2]->{'id'}; 
1.71      www      2700: 	      }
1.175     www      2701: 
                   2702:              if ($entry eq 'import') {
                   2703: #
                   2704: # Importing a library here
1.176     www      2705: #                
                   2706: 		 if (defined($depthcount)) { $depthcount++; } else 
                   2707:                                            { $depthcount=0; }
                   2708:                  if ($depthcount<20) {
1.191     harris41 2709: 		     foreach (split(/\,/,&metadata($uri,'keys',
                   2710:                                   $parser->get_text('/import'),$unikey,
                   2711:                                   $depthcount))) {
1.177     www      2712:                          $metathesekeys{$_}=1;
1.191     harris41 2713: 		     }
1.176     www      2714: 		 }
1.175     www      2715:              } else { 
                   2716: 
1.72      www      2717:               if (defined($token->[2]->{'name'})) { 
1.71      www      2718:                  $unikey.='_'.$token->[2]->{'name'}; 
                   2719: 	      }
1.140     www      2720:               $metathesekeys{$unikey}=1;
1.191     harris41 2721:               foreach (@{$token->[3]}) {
1.71      www      2722: 		  $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.191     harris41 2723:               }
1.78      www      2724:               unless (
1.208     albertel 2725:                  $metacache{$uri.':'.$unikey}=&HTML::Entities::decode($parser->get_text('/'.$entry))
1.78      www      2726: 		      ) { $metacache{$uri.':'.$unikey}=
                   2727: 			      $metacache{$uri.':'.$unikey.'.default'};
                   2728: 		      }
1.172     www      2729: # end of not-a-package not-a-library import
1.175     www      2730: 	   }
1.172     www      2731: # end of not-a-package start tag
                   2732: 	  }
                   2733: # the next is the end of "start tag"
1.140     www      2734: 	 }
1.71      www      2735:        }
1.261     albertel 2736: 	&metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
1.140     www      2737:        $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
1.174     www      2738:        $metacache{$uri.':cachedtimestamp'}=time;
1.177     www      2739: # this is the end of "was not already recently cached
1.71      www      2740:     }
                   2741:     return $metacache{$uri.':'.$what};
1.261     albertel 2742: }
                   2743: 
                   2744: sub metadata_generate_part0 {
                   2745:     my ($metadata,$metacache,$uri) = @_;
                   2746:     my %allnames;
                   2747:     foreach my $metakey (sort keys %$metadata) {
                   2748: 	if ($metakey=~/^parameter\_(.*)/) {
                   2749: 	  my $part=$$metacache{$uri.':'.$metakey.'.part'};
                   2750: 	  my $name=$$metacache{$uri.':'.$metakey.'.name'};
                   2751: 	  if (! exists($$metadata{'parameter_0_'.$name})) {
                   2752: 	    $allnames{$name}=$part;
                   2753: 	  }
                   2754: 	}
                   2755:     }
                   2756:     foreach my $name (keys(%allnames)) {
                   2757:       $$metadata{"parameter_0_$name"}=1;
                   2758:       my $key="$uri:parameter_0_$name";
                   2759:       $$metacache{"$key.part"}='0';
                   2760:       $$metacache{"$key.name"}=$name;
                   2761:       $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
                   2762: 					   $allnames{$name}.'_'.$name.
                   2763: 					   '.type'};
                   2764:       my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
                   2765: 			     '.display'};
                   2766:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
                   2767:       $olddis=~s/$expr/\[Part: 0\]/;
                   2768:       $$metacache{"$key.display"}=$olddis;
                   2769:     }
1.71      www      2770: }
                   2771: 
1.31      www      2772: # ------------------------------------------------- Update symbolic store links
                   2773: 
                   2774: sub symblist {
                   2775:     my ($mapname,%newhash)=@_;
                   2776:     $mapname=declutter($mapname);
                   2777:     my %hash;
                   2778:     if (($ENV{'request.course.fn'}) && (%newhash)) {
                   2779:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 2780:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 2781: 	    foreach (keys %newhash) {
1.211     www      2782:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
1.191     harris41 2783:             }
1.31      www      2784:             if (untie(%hash)) {
                   2785: 		return 'ok';
                   2786:             }
                   2787:         }
                   2788:     }
                   2789:     return 'error';
1.212     www      2790: }
                   2791: 
                   2792: # --------------------------------------------------------------- Verify a symb
                   2793: 
                   2794: sub symbverify {
                   2795:     my ($symb,$thisfn)=@_;
1.213     www      2796:     $thisfn=&declutter($thisfn);
1.215     www      2797: # direct jump to resource in page or to a sequence - will construct own symbs
                   2798:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   2799: # check URL part
1.213     www      2800:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
                   2801:     unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
                   2802: 
1.216     www      2803:     $symb=&symbclean($symb);
1.213     www      2804: 
                   2805:     my %bighash;
                   2806:     my $okay=0;
                   2807:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 2808:                             &GDBM_READER(),0640)) {
1.216     www      2809:         my $ids=$bighash{'ids_/res/'.$thisfn};
                   2810:         unless ($ids) { 
                   2811:            $ids=$bighash{'ids_/'.$thisfn};
                   2812:         }
                   2813:         if ($ids) {
                   2814: # ------------------------------------------------------------------- Has ID(s)
                   2815: 	    foreach (split(/\,/,$ids)) {
                   2816:                my ($mapid,$resid)=split(/\./,$_);
                   2817:                if (
                   2818:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   2819:    eq $symb) { 
                   2820:                   $okay=1; 
                   2821:                }
                   2822: 	   }
                   2823:         }
1.213     www      2824: 	untie(%bighash);
                   2825:     }
                   2826:     return $okay;
1.31      www      2827: }
                   2828: 
1.210     www      2829: # --------------------------------------------------------------- Clean-up symb
                   2830: 
                   2831: sub symbclean {
                   2832:     my $symb=shift;
1.213     www      2833: 
1.210     www      2834: # remove version from map
                   2835:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      2836: 
1.210     www      2837: # remove version from URL
                   2838:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      2839: 
1.210     www      2840:     return $symb;
                   2841: }
                   2842: 
1.31      www      2843: # ------------------------------------------------------ Return symb list entry
                   2844: 
                   2845: sub symbread {
1.249     www      2846:     my ($thisfn,$donotrecurse)=@_;
1.242     www      2847: # no filename provided? try from environment
1.44      www      2848:     unless ($thisfn) {
1.210     www      2849:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
1.44      www      2850: 	$thisfn=$ENV{'request.filename'};
                   2851:     }
1.242     www      2852: # is that filename actually a symb? Verify, clean, and return
                   2853:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
                   2854: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
                   2855:     }
1.44      www      2856:     $thisfn=declutter($thisfn);
1.31      www      2857:     my %hash;
1.37      www      2858:     my %bighash;
                   2859:     my $syval='';
1.45      www      2860:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.31      www      2861:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 2862:                       &GDBM_READER(),0640)) {
1.31      www      2863: 	    $syval=$hash{$thisfn};
1.37      www      2864:             untie(%hash);
                   2865:         }
                   2866: # ---------------------------------------------------------- There was an entry
                   2867:         if ($syval) {
                   2868:            unless ($syval=~/\_\d+$/) {
                   2869: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44      www      2870:                   &appenv('request.ambiguous' => $thisfn);
1.37      www      2871:                   return '';
                   2872:                }    
                   2873:                $syval.=$1;
                   2874: 	   }
                   2875:         } else {
                   2876: # ------------------------------------------------------- Was not in symb table
                   2877:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 2878:                             &GDBM_READER(),0640)) {
1.37      www      2879: # ---------------------------------------------- Get ID(s) for current resource
                   2880:               my $ids=$bighash{'ids_/res/'.$thisfn};
1.65      www      2881:               unless ($ids) { 
                   2882:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      2883:               }
                   2884:               unless ($ids) {
                   2885: # alias?
                   2886: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      2887:               }
1.37      www      2888:               if ($ids) {
                   2889: # ------------------------------------------------------------------- Has ID(s)
                   2890:                  my @possibilities=split(/\,/,$ids);
1.39      www      2891:                  if ($#possibilities==0) {
                   2892: # ----------------------------------------------- There is only one possibility
1.37      www      2893: 		     my ($mapid,$resid)=split(/\./,$ids);
                   2894:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
1.249     www      2895:                  } elsif (!$donotrecurse) {
1.39      www      2896: # ------------------------------------------ There is more than one possibility
                   2897:                      my $realpossible=0;
1.191     harris41 2898:                      foreach (@possibilities) {
1.39      www      2899: 			 my $file=$bighash{'src_'.$_};
                   2900:                          if (&allowed('bre',$file)) {
                   2901:          		    my ($mapid,$resid)=split(/\./,$_);
                   2902:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   2903: 				$realpossible++;
                   2904:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
                   2905:                                        '___'.$resid;
                   2906:                             }
                   2907: 			 }
1.191     harris41 2908:                      }
1.39      www      2909: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      2910:                  } else {
                   2911:                      $syval='';
1.37      www      2912:                  }
                   2913: 	      }
                   2914:               untie(%bighash)
                   2915:            } 
1.31      www      2916:         }
1.62      www      2917:         if ($syval) {
1.210     www      2918:            return &symbclean($syval.'___'.$thisfn); 
1.62      www      2919:         }
1.31      www      2920:     }
1.44      www      2921:     &appenv('request.ambiguous' => $thisfn);
1.31      www      2922:     return '';
                   2923: }
                   2924: 
                   2925: # ---------------------------------------------------------- Return random seed
                   2926: 
1.32      www      2927: sub numval {
                   2928:     my $txt=shift;
                   2929:     $txt=~tr/A-J/0-9/;
                   2930:     $txt=~tr/a-j/0-9/;
                   2931:     $txt=~tr/K-T/0-9/;
                   2932:     $txt=~tr/k-t/0-9/;
                   2933:     $txt=~tr/U-Z/0-5/;
                   2934:     $txt=~tr/u-z/0-5/;
                   2935:     $txt=~s/\D//g;
                   2936:     return int($txt);
                   2937: }    
                   2938: 
1.31      www      2939: sub rndseed {
1.155     albertel 2940:     my ($symb,$courseid,$domain,$username)=@_;
                   2941:     if (!$symb) {
                   2942:       unless ($symb=&symbread()) { return time; }
                   2943:     }
                   2944:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
                   2945:     if (!$domain) {$domain=$ENV{'user.domain'};}
                   2946:     if (!$username) {$username=$ENV{'user.name'};}
                   2947:     {
1.98      albertel 2948:       use integer;
                   2949:       my $symbchck=unpack("%32C*",$symb) << 27;
1.100     albertel 2950:       my $symbseed=numval($symb) << 22;
1.155     albertel 2951:       my $namechck=unpack("%32C*",$username) << 17;
                   2952:       my $nameseed=numval($username) << 12;
                   2953:       my $domainseed=unpack("%32C*",$domain) << 7;
                   2954:       my $courseseed=unpack("%32C*",$courseid);
1.98      albertel 2955:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.99      albertel 2956:       #uncommenting these lines can break things!
                   2957:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   2958:       #&Apache::lonxml::debug("rndseed :$num:$symb");
1.98      albertel 2959:       return $num;
                   2960:     }
1.36      albertel 2961: }
                   2962: 
1.76      www      2963: sub ireceipt {
                   2964:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
                   2965:     my $cuname=unpack("%32C*",$funame);
                   2966:     my $cudom=unpack("%32C*",$fudom);
                   2967:     my $cucourseid=unpack("%32C*",$fucourseid);
                   2968:     my $cusymb=unpack("%32C*",$fusymb);
1.77      www      2969:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
1.76      www      2970:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
                   2971:            ($cunique%$cuname+
                   2972:             $cunique%$cudom+
                   2973:             $cusymb%$cuname+
                   2974:             $cusymb%$cudom+
                   2975:             $cucourseid%$cuname+
                   2976:             $cucourseid%$cudom);
                   2977: }
                   2978: 
                   2979: sub receipt {
1.260     ng       2980:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   2981:   return &ireceipt($name,$domain,$courseid,$symb);
1.76      www      2982: }
1.260     ng       2983: 
1.36      albertel 2984: # ------------------------------------------------------------ Serves up a file
                   2985: # returns either the contents of the file or a -1
                   2986: sub getfile {
                   2987:   my $file=shift;
1.37      www      2988:   &repcopy($file);
1.36      albertel 2989:   if (! -e $file ) { return -1; };
                   2990:   my $fh=Apache::File->new($file);
                   2991:   my $a='';
                   2992:   while (<$fh>) { $a .=$_; }
                   2993:   return $a
                   2994: }
                   2995: 
                   2996: sub filelocation {
                   2997:   my ($dir,$file) = @_;
                   2998:   my $location;
                   2999:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59      albertel 3000:   if ($file=~m:^/~:) { # is a contruction space reference
                   3001:     $location = $file;
                   3002:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.36      albertel 3003:   } else {
1.59      albertel 3004:     $file=~s/^$perlvar{'lonDocRoot'}//;
                   3005:     $file=~s:^/*res::;
                   3006:     if ( !( $file =~ m:^/:) ) {
                   3007:       $location = $dir. '/'.$file;
                   3008:     } else {
                   3009:       $location = '/home/httpd/html/res'.$file;
                   3010:     }
1.36      albertel 3011:   }
                   3012:   $location=~s://+:/:g; # remove duplicate /
1.46      www      3013:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   3014:   return $location;
                   3015: }
1.36      albertel 3016: 
1.46      www      3017: sub hreflocation {
                   3018:     my ($dir,$file)=@_;
1.191     harris41 3019:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
1.46      www      3020:        my $finalpath=filelocation($dir,$file);
                   3021:        $finalpath=~s/^\/home\/httpd\/html//;
1.225     albertel 3022:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
1.46      www      3023:        return $finalpath;
                   3024:     } else {
                   3025:        return $file;
                   3026:     }
1.31      www      3027: }
                   3028: 
                   3029: # ------------------------------------------------------------- Declutters URLs
                   3030: 
                   3031: sub declutter {
                   3032:     my $thisfn=shift;
                   3033:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
                   3034:     $thisfn=~s/^\///;
                   3035:     $thisfn=~s/^res\///;
1.235     www      3036:     $thisfn=~s/\?.+$//;
1.31      www      3037:     return $thisfn;
1.12      www      3038: }
                   3039: 
                   3040: # -------------------------------------------------------- Escape Special Chars
                   3041: 
                   3042: sub escape {
                   3043:     my $str=shift;
                   3044:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   3045:     return $str;
                   3046: }
                   3047: 
                   3048: # ----------------------------------------------------- Un-Escape Special Chars
                   3049: 
                   3050: sub unescape {
                   3051:     my $str=shift;
                   3052:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   3053:     return $str;
                   3054: }
1.11      www      3055: 
1.1       albertel 3056: # ================================================================ Main Program
                   3057: 
1.184     www      3058: sub goodbye {
1.204     albertel 3059:    &logthis("Starting Shut down");
1.184     www      3060:    &flushcourselogs();
                   3061:    &logthis("Shutting down");
                   3062: }
                   3063: 
1.179     www      3064: BEGIN {
1.228     harris41 3065: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      3066:     unless ($readit) {
1.217     harris41 3067: {
                   3068:     my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
                   3069: 
                   3070:     while (my $configline=<$config>) {
                   3071:         if ($configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 3072: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      3073:            chomp($varvalue);
1.1       albertel 3074:            $perlvar{$varname}=$varvalue;
                   3075:         }
                   3076:     }
                   3077: }
1.227     harris41 3078: {
                   3079:     my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
                   3080: 
                   3081:     while (my $configline=<$config>) {
                   3082:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   3083: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   3084:            chomp($varvalue);
                   3085:            $perlvar{$varname}=$varvalue;
                   3086:         }
                   3087:     }
                   3088: }
1.1       albertel 3089: 
                   3090: # ------------------------------------------------------------- Read hosts file
                   3091: {
                   3092:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
                   3093: 
                   3094:     while (my $configline=<$config>) {
1.154     www      3095:        chomp($configline);
1.245     www      3096:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
1.252     albertel 3097:        if ($id && $domain && $role && $name && $ip) {
                   3098: 	 $hostname{$id}=$name;
                   3099: 	 $hostdom{$id}=$domain;
                   3100: 	 $hostip{$id}=$ip;
                   3101: 	 if ($domdescr) { $domaindescription{$domain}=$domdescr; }
                   3102: 	 if ($role eq 'library') { $libserv{$id}=$name; }
                   3103:        } else {
                   3104: 	 if ($configline) {
                   3105: 	   &logthis("Skipping hosts.tab line -$configline-");
                   3106: 	 }
1.245     www      3107:        }
1.1       albertel 3108:     }
                   3109: }
                   3110: 
                   3111: # ------------------------------------------------------ Read spare server file
                   3112: {
                   3113:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
                   3114: 
                   3115:     while (my $configline=<$config>) {
                   3116:        chomp($configline);
                   3117:        if (($configline) && ($configline ne $perlvar{'lonHostID'})) {
                   3118:           $spareid{$configline}=1;
                   3119:        }
                   3120:     }
                   3121: }
1.11      www      3122: # ------------------------------------------------------------ Read permissions
                   3123: {
                   3124:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
                   3125: 
                   3126:     while (my $configline=<$config>) {
                   3127:        chomp($configline);
1.160     www      3128:       if ($configline) {
1.11      www      3129:        my ($role,$perm)=split(/ /,$configline);
                   3130:        if ($perm ne '') { $pr{$role}=$perm; }
1.160     www      3131:       }
1.11      www      3132:     }
                   3133: }
                   3134: 
                   3135: # -------------------------------------------- Read plain texts for permissions
                   3136: {
                   3137:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
                   3138: 
                   3139:     while (my $configline=<$config>) {
                   3140:        chomp($configline);
1.160     www      3141:       if ($configline) {
1.11      www      3142:        my ($short,$plain)=split(/:/,$configline);
                   3143:        if ($plain ne '') { $prp{$short}=$plain; }
1.160     www      3144:       }
1.135     www      3145:     }
                   3146: }
                   3147: 
                   3148: # ---------------------------------------------------------- Read package table
                   3149: {
                   3150:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
                   3151: 
                   3152:     while (my $configline=<$config>) {
                   3153:        chomp($configline);
                   3154:        my ($short,$plain)=split(/:/,$configline);
1.143     www      3155:        my ($pack,$name)=split(/\&/,$short);
                   3156:        if ($plain ne '') {
                   3157:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   3158:           $packagetab{$short}=$plain; 
1.25      www      3159:        }
1.11      www      3160:     }
                   3161: }
                   3162: 
1.71      www      3163: %metacache=();
1.185     www      3164: 
                   3165: $processmarker=$$.'_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      3166: $dumpcount=0;
1.22      www      3167: 
1.163     harris41 3168: &logtouch();
1.12      www      3169: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      3170: $readit=1;
                   3171: }
1.1       albertel 3172: }
1.179     www      3173: 
1.1       albertel 3174: 1;
1.191     harris41 3175: __END__
                   3176: 
1.243     albertel 3177: =pod
                   3178: 
1.191     harris41 3179: =head1 NAME
                   3180: 
1.243     albertel 3181: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 3182: 
                   3183: =head1 SYNOPSIS
                   3184: 
1.243     albertel 3185: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 3186: 
                   3187:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   3188: 
1.243     albertel 3189: Common parameters:
                   3190: 
                   3191: =over 4
                   3192: 
                   3193: =item *
                   3194: 
                   3195: $uname : an internal username (if $cname expecting a course Id specifically)
                   3196: 
                   3197: =item *
                   3198: 
                   3199: $udom : a domain (if $cdom expecting a course's domain specifically)
                   3200: 
                   3201: =item *
                   3202: 
                   3203: $symb : a resource instance identifier
                   3204: 
                   3205: =item *
                   3206: 
                   3207: $namespace : the name of a .db file that contains the data needed or
                   3208: being set.
                   3209: 
                   3210: =back
                   3211: 
1.191     harris41 3212: =head1 INTRODUCTION
                   3213: 
                   3214: This module provides subroutines which interact with the
1.243     albertel 3215: lonc/lond (TCP) network layer of LON-CAPA. And Can be used to ask about 
                   3216: - classes
                   3217: - users 
                   3218: - resources
                   3219: 
                   3220: For many of these objects you can also use this to store data about
                   3221: them or modify them in various ways.
1.191     harris41 3222: 
                   3223: This is part of the LearningOnline Network with CAPA project
                   3224: described at http://www.lon-capa.org.
                   3225: 
1.243     albertel 3226: =head1 RETURN MESSAGES
1.191     harris41 3227: 
                   3228: =over 4
                   3229: 
                   3230: =item *
                   3231: 
1.243     albertel 3232: con_lost : unable to contact remote host
1.191     harris41 3233: 
                   3234: =item *
                   3235: 
1.243     albertel 3236: con_delayed : unable to contact remote host, message will be delivered
                   3237: when the connection is brought back up
1.191     harris41 3238: 
                   3239: =item *
                   3240: 
1.243     albertel 3241: con_failed : unable to contact remote host and unable to save message
                   3242: for later delivery
1.191     harris41 3243: 
                   3244: =item *
                   3245: 
1.243     albertel 3246: error: : an error a occured, a description of the error follows the :
1.191     harris41 3247: 
                   3248: =item *
                   3249: 
1.243     albertel 3250: no_such_host : unable to fund a host associated with the user/domain
                   3251: that was requested
1.191     harris41 3252: 
1.243     albertel 3253: =back
1.191     harris41 3254: 
1.243     albertel 3255: =head1 PUBLIC SUBROUTINES
1.191     harris41 3256: 
1.243     albertel 3257: =head2 Session Environment Functions
1.191     harris41 3258: 
1.243     albertel 3259: =over 4
1.191     harris41 3260: 
                   3261: =item *
                   3262: 
1.243     albertel 3263: appenv(%hash) : the value of %hash is written to the user envirnoment
                   3264: file, and will be restored for each access this user makes during this
                   3265: session, also modifies the %ENV for the current process
1.191     harris41 3266: 
                   3267: =item *
                   3268: 
1.243     albertel 3269: 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 3270: 
1.243     albertel 3271: =back
                   3272: 
                   3273: =head2 User Information
1.191     harris41 3274: 
1.243     albertel 3275: =over 4
1.191     harris41 3276: 
                   3277: =item *
                   3278: 
                   3279: queryauthenticate($uname,$udom) : try to determine user's current
                   3280: authentication scheme
                   3281: 
                   3282: =item *
                   3283: 
                   3284: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
1.243     albertel 3285: servers (first use the current one), $upass should be the users password
1.191     harris41 3286: 
                   3287: =item *
                   3288: 
1.243     albertel 3289: homeserver($uname,$udom) : find the server which has the user's
                   3290: directory and files (there must be only one), this caches the answer,
                   3291: and also caches if there is a borken connection.
1.191     harris41 3292: 
                   3293: =item *
                   3294: 
1.243     albertel 3295: idget($udom,@ids) : find the usernames behind a list of IDs (IDs are a
                   3296: unique resource in a domain, there must be only 1 ID per username, and
                   3297: only 1 username per ID in a specific domain) (returns hash:
1.191     harris41 3298: id=>name,id=>name)
                   3299: 
                   3300: =item *
                   3301: 
                   3302: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
                   3303: name=>id,name=>id)
                   3304: 
                   3305: =item *
                   3306: 
                   3307: idput($udom,%ids) : store away a list of names and associated IDs
                   3308: 
                   3309: =item *
                   3310: 
1.243     albertel 3311: rolesinit($udom,$username,$authhost) : get user privileges
                   3312: 
                   3313: =item *
                   3314: 
                   3315: usection($udom,$uname,$cname) : finds the section of student in the
                   3316: course $cname, return section name/number or '' for "not in course"
                   3317: and '-1' for "no section"
                   3318: 
                   3319: =item *
                   3320: 
                   3321: userenvironment($udom,$uname,@what) : gets the values of the keys
                   3322: passed in @what from the requested user's environment, returns a hash
                   3323: 
                   3324: =back
                   3325: 
                   3326: =head2 User Roles
                   3327: 
                   3328: =over 4
                   3329: 
                   3330: =item *
                   3331: 
                   3332: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   3333: actions
                   3334:  F: full access
                   3335:  U,I,K: authentication modes (cxx only)
                   3336:  '': forbidden
                   3337:  1: user needs to choose course
                   3338:  2: browse allowed
                   3339: 
                   3340: =item *
                   3341: 
                   3342: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   3343: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   3344: and course level
                   3345: 
                   3346: =item *
                   3347: 
                   3348: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   3349: explanation of a user role term
                   3350: 
                   3351: =back
                   3352: 
                   3353: =head2 User Modification
                   3354: 
                   3355: =over 4
                   3356: 
                   3357: =item *
                   3358: 
                   3359: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   3360: user for the level given by URL.  Optional start and end dates (leave empty
                   3361: string or zero for "no date")
1.191     harris41 3362: 
                   3363: =item *
                   3364: 
1.243     albertel 3365: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   3366: change a users, password, possible return values are: ok,
                   3367: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   3368: refused
1.191     harris41 3369: 
                   3370: =item *
                   3371: 
1.243     albertel 3372: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 3373: 
                   3374: =item *
                   3375: 
1.243     albertel 3376: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   3377: modify user
1.191     harris41 3378: 
                   3379: =item *
                   3380: 
1.243     albertel 3381: modifystudent($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,$end,$start) : modify student
1.191     harris41 3382: 
                   3383: =item *
                   3384: 
1.243     albertel 3385: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   3386: custom role; give a custom role to a user for the level given by URL.  Specify
                   3387: name and domain of role author, and role name
1.191     harris41 3388: 
                   3389: =item *
                   3390: 
1.243     albertel 3391: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 3392: 
                   3393: =item *
                   3394: 
1.243     albertel 3395: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   3396: 
                   3397: =back
                   3398: 
                   3399: =head2 Course Infomation
                   3400: 
                   3401: =over 4
1.191     harris41 3402: 
                   3403: =item *
                   3404: 
1.243     albertel 3405: coursedescription($courseid) : course description
1.191     harris41 3406: 
                   3407: =item *
                   3408: 
1.243     albertel 3409: courseresdata($coursenum,$coursedomain,@which) : request for current
                   3410: parameter setting for a specific course, @what should be a list of
                   3411: parameters to ask about. This routine caches answers for 5 minutes.
                   3412: 
                   3413: =back
                   3414: 
                   3415: =head2 Course Modification
                   3416: 
                   3417: =over 4
1.191     harris41 3418: 
                   3419: =item *
                   3420: 
1.243     albertel 3421: writecoursepref($courseid,%prefs) : write preferences (environment
                   3422: database) for a course
1.191     harris41 3423: 
                   3424: =item *
                   3425: 
1.243     albertel 3426: createcourse($udom,$description,$url) : make/modify course
                   3427: 
                   3428: =back
                   3429: 
                   3430: =head2 Resource Subroutines
                   3431: 
                   3432: =over 4
1.191     harris41 3433: 
                   3434: =item *
                   3435: 
1.243     albertel 3436: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 3437: 
                   3438: =item *
                   3439: 
1.243     albertel 3440: repcopy($filename) : subscribes to the requested file, and attempts to
                   3441: replicate from the owning library server, Might return
                   3442: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
                   3443: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
                   3444: resource. Expects the local filesystem pathname
                   3445: (/home/httpd/html/res/....)
                   3446: 
                   3447: =back
                   3448: 
                   3449: =head2 Resource Information
                   3450: 
                   3451: =over 4
1.191     harris41 3452: 
                   3453: =item *
                   3454: 
1.243     albertel 3455: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   3456: a vairety of different possible values, $varname should be a request
                   3457: string, and the other parameters can be used to specify who and what
                   3458: one is asking about.
                   3459: 
                   3460: Possible values for $varname are environment.lastname (or other item
                   3461: from the envirnment hash), user.name (or someother aspect about the
                   3462: user), resource.0.maxtries (or some other part and parameter of a
                   3463: resource)
1.204     albertel 3464: 
                   3465: =item *
                   3466: 
1.243     albertel 3467: directcondval($number) : get current value of a condition; reads from a state
                   3468: string
1.204     albertel 3469: 
                   3470: =item *
                   3471: 
1.243     albertel 3472: condval($condidx) : value of condition index based on state
1.204     albertel 3473: 
                   3474: =item *
                   3475: 
1.243     albertel 3476: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   3477: resource's metadata, $what should be either a specific key, or either
                   3478: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   3479: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   3480: 
                   3481: this function automatically caches all requests
1.191     harris41 3482: 
                   3483: =item *
                   3484: 
1.243     albertel 3485: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   3486: network of library servers; returns file handle of where SQL and regex results
                   3487: will be stored for query
1.191     harris41 3488: 
                   3489: =item *
                   3490: 
1.243     albertel 3491: symbread($filename) : return symbolic list entry (filename argument optional);
                   3492: returns the data handle
1.191     harris41 3493: 
                   3494: =item *
                   3495: 
1.243     albertel 3496: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
                   3497: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
                   3498: failure, user must be in a course, as it assumes the existance of the
                   3499: course initi hash, and uses $ENV('request.course.id'}
                   3500: 
1.191     harris41 3501: 
                   3502: =item *
                   3503: 
1.243     albertel 3504: symbclean($symb) : removes versions numbers from a symb, returns the
                   3505: cleaned symb
1.191     harris41 3506: 
                   3507: =item *
                   3508: 
1.243     albertel 3509: is_on_map($uri) : checks if the $uri is somewhere on the current
                   3510: course map, user must be in a course for it to work.
1.191     harris41 3511: 
                   3512: =item *
                   3513: 
1.243     albertel 3514: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 3515: 
                   3516: =item *
                   3517: 
1.243     albertel 3518: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   3519: a random seed, all arguments are optional, if they aren't sent it uses the
                   3520: environment to derive them. Note: if symb isn't sent and it can't get one
                   3521: from &symbread it will use the current time as its return value
1.191     harris41 3522: 
                   3523: =item *
                   3524: 
1.243     albertel 3525: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   3526: unfakeable, receipt
1.191     harris41 3527: 
                   3528: =item *
                   3529: 
1.243     albertel 3530: receipt() : API to ireceipt working off of ENV values; given out to users
1.191     harris41 3531: 
                   3532: =item *
                   3533: 
1.243     albertel 3534: countacc($url) : count the number of accesses to a given URL
1.191     harris41 3535: 
                   3536: =item *
                   3537: 
1.243     albertel 3538: 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 3539: 
                   3540: =item *
                   3541: 
1.243     albertel 3542: 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 3543: 
                   3544: =item *
                   3545: 
1.243     albertel 3546: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 3547: 
                   3548: =item *
                   3549: 
1.243     albertel 3550: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   3551: forcing spreadsheet to reevaluate the resource scores next time.
                   3552: 
                   3553: =back
                   3554: 
                   3555: =head2 Storing/Retreiving Data
                   3556: 
                   3557: =over 4
1.191     harris41 3558: 
                   3559: =item *
                   3560: 
1.243     albertel 3561: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   3562: for this url; hashref needs to be given and should be a \%hashname; the
                   3563: remaining args aren't required and if they aren't passed or are '' they will
                   3564: be derived from the ENV
1.191     harris41 3565: 
                   3566: =item *
                   3567: 
1.243     albertel 3568: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   3569: uses critical subroutine
1.191     harris41 3570: 
                   3571: =item *
                   3572: 
1.243     albertel 3573: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   3574: all args are optional
1.191     harris41 3575: 
                   3576: =item *
                   3577: 
1.243     albertel 3578: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   3579: works very similar to store/cstore, but all data is stored in a
                   3580: temporary location and can be reset using tmpreset, $storehash should
                   3581: be a hash reference, returns nothing on success
1.191     harris41 3582: 
                   3583: =item *
                   3584: 
1.243     albertel 3585: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   3586: similar to restore, but all data is stored in a temporary location and
                   3587: can be reset using tmpreset. Returns a hash of values on success,
                   3588: error string otherwise.
1.191     harris41 3589: 
                   3590: =item *
                   3591: 
1.243     albertel 3592: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   3593: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 3594: 
                   3595: =item *
                   3596: 
1.243     albertel 3597: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   3598: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 3599: 
                   3600: =item *
                   3601: 
1.243     albertel 3602: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   3603: namesp ($udom and $uname are optional)
1.191     harris41 3604: 
                   3605: =item *
                   3606: 
1.243     albertel 3607: dump($namespace,$udom,$uname,$regexp) : 
                   3608: dumps the complete (or key matching regexp) namespace into a hash
                   3609: ($udom, $uname and $regexp are optional)
1.191     harris41 3610: 
                   3611: =item *
                   3612: 
1.243     albertel 3613: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   3614: ($udom and $uname are optional)
1.191     harris41 3615: 
                   3616: =item *
                   3617: 
1.243     albertel 3618: cput($namespace,$storehash,$udom,$uname) : critical put
                   3619: ($udom and $uname are optional)
1.191     harris41 3620: 
                   3621: =item *
                   3622: 
1.243     albertel 3623: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   3624: reference filled in from namesp (encrypts the return communication)
                   3625: ($udom and $uname are optional)
1.191     harris41 3626: 
                   3627: =item *
                   3628: 
1.243     albertel 3629: log($udom,$name,$home,$message) : write to permanent log for user; use
                   3630: critical subroutine
                   3631: 
                   3632: =back
                   3633: 
                   3634: =head2 Network Status Functions
                   3635: 
                   3636: =over 4
1.191     harris41 3637: 
                   3638: =item *
                   3639: 
                   3640: dirlist($uri) : return directory list based on URI
                   3641: 
                   3642: =item *
                   3643: 
1.243     albertel 3644: spareserver() : find server with least workload from spare.tab
                   3645: 
                   3646: =back
                   3647: 
                   3648: =head2 Apache Request
                   3649: 
                   3650: =over 4
1.191     harris41 3651: 
                   3652: =item *
                   3653: 
1.243     albertel 3654: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   3655: localhost, posts hash
                   3656: 
                   3657: =back
                   3658: 
                   3659: =head2 Data to String to Data
                   3660: 
                   3661: =over 4
1.191     harris41 3662: 
                   3663: =item *
                   3664: 
1.243     albertel 3665: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   3666: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 3667: 
                   3668: =item *
                   3669: 
1.243     albertel 3670: hashref2str($hashref) : convert a hashref into a string complete with
                   3671: escaping and '=' and '&' separators, supports elements that are
                   3672: arrayrefs and hashrefs
1.191     harris41 3673: 
                   3674: =item *
                   3675: 
1.243     albertel 3676: arrayref2str($arrayref) : convert an arrayref into a string complete
                   3677: with escaping and '&' separators, supports elements that are arrayrefs
                   3678: and hashrefs
1.191     harris41 3679: 
                   3680: =item *
                   3681: 
1.243     albertel 3682: str2hash($string) : convert string to hash using unescaping and
                   3683: splitting on '=' and '&', supports elements that are arrayrefs and
                   3684: hashrefs
1.191     harris41 3685: 
                   3686: =item *
                   3687: 
1.243     albertel 3688: str2array($string) : convert string to hash using unescaping and
                   3689: splitting on '&', supports elements that are arrayrefs and hashrefs
                   3690: 
                   3691: =back
                   3692: 
                   3693: =head2 Logging Routines
                   3694: 
                   3695: =over 4
                   3696: 
                   3697: These routines allow one to make log messages in the lonnet.log and
                   3698: lonnet.perm logfiles.
1.191     harris41 3699: 
                   3700: =item *
                   3701: 
1.243     albertel 3702: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 3703: 
                   3704: =item *
                   3705: 
1.243     albertel 3706: logthis() : append message to the normal lonnet.log file, it gets
                   3707: preiodically rolled over and deleted.
1.191     harris41 3708: 
                   3709: =item *
                   3710: 
1.243     albertel 3711: logperm() : append a permanent message to lonnet.perm.log, this log
                   3712: file never gets deleted by any automated portion of the system, only
                   3713: messages of critical importance should go in here.
                   3714: 
                   3715: =back
                   3716: 
                   3717: =head2 General File Helper Routines
                   3718: 
                   3719: =over 4
1.191     harris41 3720: 
                   3721: =item *
                   3722: 
1.243     albertel 3723: getfile($file) : returns the entire contents of a file or -1; it
                   3724: properly subscribes to and replicates the file if neccessary.
1.191     harris41 3725: 
                   3726: =item *
                   3727: 
1.243     albertel 3728: filelocation($dir,$file) : returns file system location of a file
                   3729: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   3730: directory that relative $file lookups are to looked in ($dir of /a/dir
                   3731: and a file of ../bob will become /a/bob)
1.191     harris41 3732: 
                   3733: =item *
                   3734: 
                   3735: hreflocation($dir,$file) : returns file system location or a URL; same as
                   3736: filelocation except for hrefs
                   3737: 
                   3738: =item *
                   3739: 
                   3740: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   3741: 
1.243     albertel 3742: =back
                   3743: 
                   3744: =head2 HTTP Helper Routines
                   3745: 
                   3746: =over 4
                   3747: 
1.191     harris41 3748: =item *
                   3749: 
                   3750: escape() : unpack non-word characters into CGI-compatible hex codes
                   3751: 
                   3752: =item *
                   3753: 
                   3754: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   3755: 
1.243     albertel 3756: =back
                   3757: 
                   3758: =head1 PRIVATE SUBROUTINES
                   3759: 
                   3760: =head2 Underlying communication routines (Shouldn't call)
                   3761: 
                   3762: =over 4
                   3763: 
                   3764: =item *
                   3765: 
                   3766: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   3767: 
                   3768: =item *
                   3769: 
                   3770: reply() : uses subreply to send a message to remote machine, logs all failures
                   3771: 
                   3772: =item *
                   3773: 
                   3774: critical() : passes a critical message to another server; if cannot
                   3775: get through then place message in connection buffer directory and
                   3776: returns con_delayed, if incapable of saving message, returns
                   3777: con_failed
                   3778: 
                   3779: =item *
                   3780: 
                   3781: reconlonc() : tries to reconnect lonc client processes.
                   3782: 
                   3783: =back
                   3784: 
                   3785: =head2 Resource Access Logging
                   3786: 
                   3787: =over 4
                   3788: 
                   3789: =item *
                   3790: 
                   3791: flushcourselogs() : flush (save) buffer logs and access logs
                   3792: 
                   3793: =item *
                   3794: 
                   3795: courselog($what) : save message for course in hash
                   3796: 
                   3797: =item *
                   3798: 
                   3799: courseacclog($what) : save message for course using &courselog().  Perform
                   3800: special processing for specific resource types (problems, exams, quizzes, etc).
                   3801: 
1.191     harris41 3802: =item *
                   3803: 
                   3804: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   3805: as a PerlChildExitHandler
1.243     albertel 3806: 
                   3807: =back
                   3808: 
                   3809: =head2 Other
                   3810: 
                   3811: =over 4
                   3812: 
                   3813: =item *
                   3814: 
                   3815: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 3816: 
                   3817: =back
                   3818: 
                   3819: =cut

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