File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.184: download - view: text, annotated - select for diffs
Thu Dec 6 19:23:42 2001 UTC (22 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
PerlChildExitHandler flushes course logs

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.184 2001/12/06 19:23:42 www Exp $
    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: #
   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
   62: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
   63: # 12/5 Matthew Hall
   64: # 12/5 Guy Albertelli
   65: # 12/6 Gerd Kortemeyer
   66: #
   67: # $Id: lonnet.pm,v 1.184 2001/12/06 19:23:42 www Exp $
   68: #
   69: ###
   70: 
   71: # Functions for use by content handlers:
   72: #
   73: # metadata_query(sql-query-string,custom-metadata-regex) : 
   74: #                                    returns file handle of where sql and
   75: #                                    regex results will be stored for query
   76: # plaintext(short)   : plain text explanation of short term
   77: # fileembstyle(ext)  : embed style in page for file extension
   78: # filedescription(ext) : descriptor text for file extension
   79: # allowed(short,url) : returns codes for allowed actions 
   80: #                      F: full access
   81: #                      U,I,K: authentication modes (cxx only)
   82: #                      '': forbidden
   83: #                      1: user needs to choose course
   84: #                      2: browse allowed
   85: # definerole(rolename,sys,dom,cou) : define a custom role rolename
   86: #                      set privileges in format of lonTabs/roles.tab for
   87: #                      system, domain and course level, 
   88: # assignrole(udom,uname,url,role,end,start) : give a role to a user for the
   89: #                      level given by url. Optional start and end dates
   90: #                      (leave empty string or zero for "no date") 
   91: # assigncustomrole (udom,uname,url,rdom,rnam,rolename,end,start) : give a
   92: #                      custom role to a user for the level given by url.
   93: #                      Specify name and domain of role author, and role name
   94: # revokerole (udom,uname,url,role) : Revoke a role for url
   95: # revokecustomrole (udom,uname,url,rdom,rnam,rolename) : Revoke a custom role
   96: # appenv(hash)       : adds hash to session environment
   97: # delenv(varname)    : deletes all environment entries starting with varname
   98: # store(hashref,symb,courseid,udom,uname)
   99: #                    : stores hash permanently for this url
  100: #                      hashref needs to be given, and should be a \%hashname
  101: #                      the remaining args aren't required and if they aren't
  102: #                      passed or are '' they will be derived from the ENV
  103: # cstore(hashref,symb,courseid,udom,uname)
  104: #                    : same as store but uses the critical interface to 
  105: #                      guarentee a store
  106: # restore(symb,courseid,udom,uname)
  107: #                    : returns hash for this symb, all args are optional
  108: #                      if they aren't given they will be derived from the 
  109: #                      current enviroment
  110: #
  111: #
  112: # for the next 6 functions udom and uname are optional
  113: #         if supplied they use udom as the domain and uname
  114: #         as the username for the function (supply a courseid
  115: #         for the uname if you want a course database)
  116: #         if not supplied it uses %ENV and looks at 
  117: #         user. attribute for the values
  118: #
  119: # eget(namesp,arrayref,udom,uname)
  120: #                    : returns hash with keys from array  reference filled
  121: #                      in from namesp (encrypts the return communication)
  122: # get(namesp,arrayref,udom,uname)
  123: #                    : returns hash with keys from array  reference filled
  124: #                      in from namesp
  125: # dump(namesp,udom,uname) : dumps the complete namespace into a hash
  126: # del(namesp,array,udom,uname)  : deletes keys out of array from namesp
  127: # put(namesp,hash,udom,uname)   : stores hash in namesp
  128: # cput(namesp,hash,udom,uname)  : critical put
  129: #
  130: #
  131: # ssi(url,hash)      : does a complete request cycle on url to localhost, posts
  132: #                      hash
  133: # coursedescription(id) : returns and caches course description for id
  134: # repcopy(filename)  : replicate file
  135: # dirlist(url)       : gets a directory listing
  136: # directcondval(index) : reading condition value of single condition from 
  137: #                        state string
  138: # condval(index)     : value of condition index based on state
  139: # EXT(name)          : value of a variable
  140: # symblist(map,hash) : Updates symbolic storage links
  141: # symbread([filename]) : returns the data handle (filename optional)
  142: # rndseed([symb,courseid,domain,uname])
  143: #                    : returns a random seed, all arguments are optional,
  144: #                      if they aren't sent it use the environment to derive
  145: #                      them
  146: #                      Note: if symb isn't sent and it can't get one from
  147: #                      &symbread it will use the current time as it's return
  148: # receipt()          : returns a receipt to be given out to users 
  149: # getfile(filename)  : returns the contents of filename, or a -1 if it can't
  150: #                      be found, replicates and subscribes to the file
  151: # filelocation(dir,file) : returns a fairly clean absolute reference to file 
  152: #                          from the directory dir
  153: # hreflocation(dir,file) : same as filelocation, but for hrefs
  154: # log(domain,user,home,msg) : write to permanent log for user
  155: # usection(domain,user,courseid) : output of section name/number or '' for
  156: #                                  "not in course" and '-1' for "no section"
  157: # userenvironment(domain,user,what) : puts out any environment parameter 
  158: #                                     for a user
  159: # idput(domain,hash) : writes IDs for users from hash (name=>id,name=>id)
  160: # idget(domain,array): returns hash with usernames (id=>name,id=>name) for
  161: #                      an array of IDs
  162: # idrget(domain,array): returns hash with IDs for usernames (name=>id,...) for
  163: #                       an array of names
  164: # metadata(file,entry): returns the metadata entry for a file. entry='keys'
  165: #                       returns a comma separated list of keys
  166: #
  167: 
  168: package Apache::lonnet;
  169: 
  170: use strict;
  171: use Apache::File;
  172: use LWP::UserAgent();
  173: use HTTP::Headers;
  174: use vars 
  175: qw(%perlvar %hostname %homecache %hostip %spareid %hostdom %libserv %pr %prp %fe %fd %metacache %packagetab %courselogs %accesshash);
  176: use IO::Socket;
  177: use GDBM_File;
  178: use Apache::Constants qw(:common :http);
  179: use HTML::TokeParser;
  180: use Fcntl qw(:flock);
  181: 
  182: # --------------------------------------------------------------------- Logging
  183: 
  184: sub logtouch {
  185:     my $execdir=$perlvar{'lonDaemons'};
  186:     unless (-e "$execdir/logs/lonnet.log") {
  187: 	my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
  188: 	close $fh;
  189:     }
  190:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  191:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  192: }
  193: 
  194: sub logthis {
  195:     my $message=shift;
  196:     my $execdir=$perlvar{'lonDaemons'};
  197:     my $now=time;
  198:     my $local=localtime($now);
  199:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
  200:     print $fh "$local ($$): $message\n";
  201:     return 1;
  202: }
  203: 
  204: sub logperm {
  205:     my $message=shift;
  206:     my $execdir=$perlvar{'lonDaemons'};
  207:     my $now=time;
  208:     my $local=localtime($now);
  209:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
  210:     print $fh "$now:$message:$local\n";
  211:     return 1;
  212: }
  213: 
  214: # -------------------------------------------------- Non-critical communication
  215: sub subreply {
  216:     my ($cmd,$server)=@_;
  217:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  218:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  219:                                      Type    => SOCK_STREAM,
  220:                                      Timeout => 10)
  221:        or return "con_lost";
  222:     print $client "$cmd\n";
  223:     my $answer=<$client>;
  224:     if (!$answer) { $answer="con_lost"; }
  225:     chomp($answer);
  226:     return $answer;
  227: }
  228: 
  229: sub reply {
  230:     my ($cmd,$server)=@_;
  231:     my $answer=subreply($cmd,$server);
  232:     if ($answer eq 'con_lost') { $answer=subreply($cmd,$server); }
  233:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  234:        &logthis("<font color=blue>WARNING:".
  235:                 " $cmd to $server returned $answer</font>");
  236:     }
  237:     return $answer;
  238: }
  239: 
  240: # ----------------------------------------------------------- Send USR1 to lonc
  241: 
  242: sub reconlonc {
  243:     my $peerfile=shift;
  244:     &logthis("Trying to reconnect for $peerfile");
  245:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  246:     if (my $fh=Apache::File->new("$loncfile")) {
  247: 	my $loncpid=<$fh>;
  248:         chomp($loncpid);
  249:         if (kill 0 => $loncpid) {
  250: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  251:             kill USR1 => $loncpid;
  252:             sleep 1;
  253:             if (-e "$peerfile") { return; }
  254:             &logthis("$peerfile still not there, give it another try");
  255:             sleep 5;
  256:             if (-e "$peerfile") { return; }
  257:             &logthis(
  258:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  259:         } else {
  260: 	    &logthis(
  261:                "<font color=blue>WARNING:".
  262:                " lonc at pid $loncpid not responding, giving up</font>");
  263:         }
  264:     } else {
  265:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
  266:     }
  267: }
  268: 
  269: # ------------------------------------------------------ Critical communication
  270: 
  271: sub critical {
  272:     my ($cmd,$server)=@_;
  273:     unless ($hostname{$server}) {
  274:         &logthis("<font color=blue>WARNING:".
  275:                " Critical message to unknown server ($server)</font>");
  276:         return 'no_such_host';
  277:     }
  278:     my $answer=reply($cmd,$server);
  279:     if ($answer eq 'con_lost') {
  280:         my $pingreply=reply('ping',$server);
  281: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  282:         my $pongreply=reply('pong',$server);
  283:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
  284:         $answer=reply($cmd,$server);
  285:         if ($answer eq 'con_lost') {
  286:             my $now=time;
  287:             my $middlename=$cmd;
  288:             $middlename=substr($middlename,0,16);
  289:             $middlename=~s/\W//g;
  290:             my $dfilename=
  291:              "$perlvar{'lonSockDir'}/delayed/$now.$middlename.$server";
  292:             {
  293:              my $dfh;
  294:              if ($dfh=Apache::File->new(">$dfilename")) {
  295:                 print $dfh "$cmd\n";
  296: 	     }
  297:             }
  298:             sleep 2;
  299:             my $wcmd='';
  300:             {
  301: 	     my $dfh;
  302:              if ($dfh=Apache::File->new("$dfilename")) {
  303:                 $wcmd=<$dfh>;
  304: 	     }
  305:             }
  306:             chomp($wcmd);
  307:             if ($wcmd eq $cmd) {
  308: 		&logthis("<font color=blue>WARNING: ".
  309:                          "Connection buffer $dfilename: $cmd</font>");
  310:                 &logperm("D:$server:$cmd");
  311: 	        return 'con_delayed';
  312:             } else {
  313:                 &logthis("<font color=red>CRITICAL:"
  314:                         ." Critical connection failed: $server $cmd</font>");
  315:                 &logperm("F:$server:$cmd");
  316:                 return 'con_failed';
  317:             }
  318:         }
  319:     }
  320:     return $answer;
  321: }
  322: 
  323: # ---------------------------------------------------------- Append Environment
  324: 
  325: sub appenv {
  326:     my %newenv=@_;
  327:     map {
  328: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
  329:             &logthis("<font color=blue>WARNING: ".
  330:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
  331:                 .'</font>');
  332: 	    delete($newenv{$_});
  333:         } else {
  334:             $ENV{$_}=$newenv{$_};
  335:         }
  336:     } keys %newenv;
  337: 
  338:     my $lockfh;
  339:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
  340:        return 'error: '.$!;
  341:     }
  342:     unless (flock($lockfh,LOCK_EX)) {
  343:          &logthis("<font color=blue>WARNING: ".
  344:                   'Could not obtain exclusive lock in appenv: '.$!);
  345:          $lockfh->close();
  346:          return 'error: '.$!;
  347:     }
  348: 
  349:     my @oldenv;
  350:     {
  351:      my $fh;
  352:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  353: 	return 'error: '.$!;
  354:      }
  355:      @oldenv=<$fh>;
  356:      $fh->close();
  357:     }
  358:     for (my $i=0; $i<=$#oldenv; $i++) {
  359:         chomp($oldenv[$i]);
  360:         if ($oldenv[$i] ne '') {
  361:            my ($name,$value)=split(/=/,$oldenv[$i]);
  362:            unless (defined($newenv{$name})) {
  363: 	      $newenv{$name}=$value;
  364: 	   }
  365:         }
  366:     }
  367:     {
  368:      my $fh;
  369:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  370: 	return 'error';
  371:      }
  372:      my $newname;
  373:      foreach $newname (keys %newenv) {
  374: 	 print $fh "$newname=$newenv{$newname}\n";
  375:      }
  376:      $fh->close();
  377:     }
  378: 
  379:     $lockfh->close();
  380:     return 'ok';
  381: }
  382: # ----------------------------------------------------- Delete from Environment
  383: 
  384: sub delenv {
  385:     my $delthis=shift;
  386:     my %newenv=();
  387:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  388:         &logthis("<font color=blue>WARNING: ".
  389:                 "Attempt to delete from environment ".$delthis);
  390:         return 'error';
  391:     }
  392:     my @oldenv;
  393:     {
  394:      my $fh;
  395:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  396: 	return 'error';
  397:      }
  398:      unless (flock($fh,LOCK_SH)) {
  399:          &logthis("<font color=blue>WARNING: ".
  400:                   'Could not obtain shared lock in delenv: '.$!);
  401:          $fh->close();
  402:          return 'error: '.$!;
  403:      }
  404:      @oldenv=<$fh>;
  405:      $fh->close();
  406:     }
  407:     {
  408:      my $fh;
  409:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  410: 	return 'error';
  411:      }
  412:      unless (flock($fh,LOCK_EX)) {
  413:          &logthis("<font color=blue>WARNING: ".
  414:                   'Could not obtain exclusive lock in delenv: '.$!);
  415:          $fh->close();
  416:          return 'error: '.$!;
  417:      }
  418:      map {
  419: 	 unless ($_=~/^$delthis/) { print $fh $_; }
  420:      } @oldenv;
  421:      $fh->close();
  422:     }
  423:     return 'ok';
  424: }
  425: 
  426: # ------------------------------ Find server with least workload from spare.tab
  427: 
  428: sub spareserver {
  429:     my $tryserver;
  430:     my $spareserver='';
  431:     my $lowestserver=100;
  432:     foreach $tryserver (keys %spareid) {
  433:        my $answer=reply('load',$tryserver);
  434:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  435: 	   $spareserver="http://$hostname{$tryserver}";
  436:            $lowestserver=$answer;
  437:        }
  438:     }    
  439:     return $spareserver;
  440: }
  441: 
  442: # ----------------------- Try to determine user's current authentication scheme
  443: 
  444: sub queryauthenticate {
  445:     my ($uname,$udom)=@_;
  446:     if (($perlvar{'lonRole'} eq 'library') && 
  447:         ($udom eq $perlvar{'lonDefDomain'})) {
  448: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
  449: 			 $perlvar{'lonHostID'});
  450: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  451: 	    if (length($answer)) {
  452: 		return $answer;
  453: 	    }
  454: 	    else {
  455: 	&logthis("User $uname at $udom lacks an authentication mechanism");
  456: 		return 'no_host';
  457: 	    }
  458: 	}
  459:     }
  460: 
  461:     my $tryserver;
  462:     foreach $tryserver (keys %libserv) {
  463: 	if ($hostdom{$tryserver} eq $udom) {
  464:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
  465: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  466: 	       if (length($answer)) {
  467: 		   return $answer;
  468: 	       }
  469: 	       else {
  470: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
  471: 		   return 'no_host';
  472: 	       }
  473: 	   }
  474:        }
  475:     }
  476:     &logthis("User $uname at $udom lacks an authentication mechanism");    
  477:     return 'no_host';
  478: }
  479: 
  480: # --------- Try to authenticate user from domain's lib servers (first this one)
  481: 
  482: sub authenticate {
  483:     my ($uname,$upass,$udom)=@_;
  484:     $upass=escape($upass);
  485:     if (($perlvar{'lonRole'} eq 'library') && 
  486:         ($udom eq $perlvar{'lonDefDomain'})) {
  487:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
  488:         if ($answer =~ /authorized/) {
  489:               if ($answer eq 'authorized') {
  490:                  &logthis("User $uname at $udom authorized by local server"); 
  491:                  return $perlvar{'lonHostID'}; 
  492:               }
  493:               if ($answer eq 'non_authorized') {
  494:                  &logthis("User $uname at $udom rejected by local server"); 
  495:                  return 'no_host'; 
  496:               }
  497: 	}
  498:     }
  499: 
  500:     my $tryserver;
  501:     foreach $tryserver (keys %libserv) {
  502: 	if ($hostdom{$tryserver} eq $udom) {
  503:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
  504:            if ($answer =~ /authorized/) {
  505:               if ($answer eq 'authorized') {
  506:                  &logthis("User $uname at $udom authorized by $tryserver"); 
  507:                  return $tryserver; 
  508:               }
  509:               if ($answer eq 'non_authorized') {
  510:                  &logthis("User $uname at $udom rejected by $tryserver");
  511:                  return 'no_host';
  512:               } 
  513: 	   }
  514:        }
  515:     }
  516:     &logthis("User $uname at $udom could not be authenticated");    
  517:     return 'no_host';
  518: }
  519: 
  520: # ---------------------- Find the homebase for a user from domain's lib servers
  521: 
  522: sub homeserver {
  523:     my ($uname,$udom)=@_;
  524: 
  525:     my $index="$uname:$udom";
  526:     if ($homecache{$index}) { return "$homecache{$index}"; }
  527: 
  528:     my $tryserver;
  529:     foreach $tryserver (keys %libserv) {
  530: 	if ($hostdom{$tryserver} eq $udom) {
  531:            my $answer=reply("home:$udom:$uname",$tryserver);
  532:            if ($answer eq 'found') { 
  533: 	      $homecache{$index}=$tryserver;
  534:               return $tryserver; 
  535: 	   }
  536:        }
  537:     }    
  538:     return 'no_host';
  539: }
  540: 
  541: # ------------------------------------- Find the usernames behind a list of IDs
  542: 
  543: sub idget {
  544:     my ($udom,@ids)=@_;
  545:     my %returnhash=();
  546:     
  547:     my $tryserver;
  548:     foreach $tryserver (keys %libserv) {
  549:        if ($hostdom{$tryserver} eq $udom) {
  550: 	  my $idlist=join('&',@ids);
  551:           $idlist=~tr/A-Z/a-z/; 
  552: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  553:           my @answer=();
  554:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  555: 	      @answer=split(/\&/,$reply);
  556:           }                    ;
  557:           my $i;
  558:           for ($i=0;$i<=$#ids;$i++) {
  559:               if ($answer[$i]) {
  560: 		  $returnhash{$ids[$i]}=$answer[$i];
  561:               } 
  562:           }
  563:        }
  564:     }    
  565:     return %returnhash;
  566: }
  567: 
  568: # ------------------------------------- Find the IDs behind a list of usernames
  569: 
  570: sub idrget {
  571:     my ($udom,@unames)=@_;
  572:     my %returnhash=();
  573:     map {
  574:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  575:     } @unames;
  576:     return %returnhash;
  577: }
  578: 
  579: # ------------------------------- Store away a list of names and associated IDs
  580: 
  581: sub idput {
  582:     my ($udom,%ids)=@_;
  583:     my %servers=();
  584:     map {
  585:         my $uhom=&homeserver($_,$udom);
  586:         if ($uhom ne 'no_host') {
  587:             my $id=&escape($ids{$_});
  588:             $id=~tr/A-Z/a-z/;
  589:             my $unam=&escape($_);
  590: 	    if ($servers{$uhom}) {
  591: 		$servers{$uhom}.='&'.$id.'='.$unam;
  592:             } else {
  593:                 $servers{$uhom}=$id.'='.$unam;
  594:             }
  595:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
  596:         }
  597:     } keys %ids;
  598:     map {
  599:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  600:     } keys %servers;
  601: }
  602: 
  603: # ------------------------------------- Find the section of student in a course
  604: 
  605: sub usection {
  606:     my ($udom,$unam,$courseid)=@_;
  607:     $courseid=~s/\_/\//g;
  608:     $courseid=~s/^(\w)/\/$1/;
  609:     map {
  610:         my ($key,$value)=split(/\=/,$_);
  611:         $key=&unescape($key);
  612:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
  613:             my $section=$1;
  614:             if ($key eq $courseid.'_st') { $section=''; }
  615: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  616:             my $now=time;
  617:             my $notactive=0;
  618:             if ($start) {
  619: 		if ($now<$start) { $notactive=1; }
  620:             }
  621:             if ($end) {
  622:                 if ($now>$end) { $notactive=1; }
  623:             } 
  624:             unless ($notactive) { return $section; }
  625:         }
  626:     } split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  627:                         &homeserver($unam,$udom)));
  628:     return '-1';
  629: }
  630: 
  631: # ------------------------------------- Read an entry from a user's environment
  632: 
  633: sub userenvironment {
  634:     my ($udom,$unam,@what)=@_;
  635:     my %returnhash=();
  636:     my @answer=split(/\&/,
  637:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  638:                       &homeserver($unam,$udom)));
  639:     my $i;
  640:     for ($i=0;$i<=$#what;$i++) {
  641: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  642:     }
  643:     return %returnhash;
  644: }
  645: 
  646: # ----------------------------- Subscribe to a resource, return URL if possible
  647: 
  648: sub subscribe {
  649:     my $fname=shift;
  650:     my $author=$fname;
  651:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  652:     my ($udom,$uname)=split(/\//,$author);
  653:     my $home=homeserver($uname,$udom);
  654:     if (($home eq 'no_host') || ($home eq $perlvar{'lonHostID'})) { 
  655:         return 'not_found'; 
  656:     }
  657:     my $answer=reply("sub:$fname",$home);
  658:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  659: 	$answer.=' by '.$home;
  660:     }
  661:     return $answer;
  662: }
  663:     
  664: # -------------------------------------------------------------- Replicate file
  665: 
  666: sub repcopy {
  667:     my $filename=shift;
  668:     $filename=~s/\/+/\//g;
  669:     my $transname="$filename.in.transfer";
  670:     if ((-e $filename) || (-e $transname)) { return OK; }
  671:     my $remoteurl=subscribe($filename);
  672:     if ($remoteurl =~ /^con_lost by/) {
  673: 	   &logthis("Subscribe returned $remoteurl: $filename");
  674:            return HTTP_SERVICE_UNAVAILABLE;
  675:     } elsif ($remoteurl eq 'not_found') {
  676: 	   &logthis("Subscribe returned not_found: $filename");
  677: 	   return HTTP_NOT_FOUND;
  678:     } elsif ($remoteurl =~ /^rejected by/) {
  679: 	   &logthis("Subscribe returned $remoteurl: $filename");
  680:            return FORBIDDEN;
  681:     } elsif ($remoteurl eq 'directory') {
  682:            return OK;
  683:     } else {
  684:            my @parts=split(/\//,$filename);
  685:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
  686:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
  687:                &logthis("Malconfiguration for replication: $filename");
  688: 	       return HTTP_BAD_REQUEST;
  689:            }
  690:            my $count;
  691:            for ($count=5;$count<$#parts;$count++) {
  692:                $path.="/$parts[$count]";
  693:                if ((-e $path)!=1) {
  694: 		   mkdir($path,0777);
  695:                }
  696:            }
  697:            my $ua=new LWP::UserAgent;
  698:            my $request=new HTTP::Request('GET',"$remoteurl");
  699:            my $response=$ua->request($request,$transname);
  700:            if ($response->is_error()) {
  701: 	       unlink($transname);
  702:                my $message=$response->status_line;
  703:                &logthis("<font color=blue>WARNING:"
  704:                        ." LWP get: $message: $filename</font>");
  705:                return HTTP_SERVICE_UNAVAILABLE;
  706:            } else {
  707: 	       if ($remoteurl!~/\.meta$/) {
  708:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
  709:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
  710:                   if ($mresponse->is_error()) {
  711: 		      unlink($filename.'.meta');
  712:                       &logthis(
  713:                      "<font color=yellow>INFO: No metadata: $filename</font>");
  714:                   }
  715: 	       }
  716:                rename($transname,$filename);
  717:                return OK;
  718:            }
  719:     }
  720: }
  721: 
  722: # --------------------------------------------------------- Server Side Include
  723: 
  724: sub ssi {
  725: 
  726:     my ($fn,%form)=@_;
  727: 
  728:     my $ua=new LWP::UserAgent;
  729:     
  730:     my $request;
  731:     
  732:     if (%form) {
  733:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
  734:       $request->content(join '&', map { "$_=$form{$_}" } keys %form);
  735:     } else {
  736:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
  737:     }
  738: 
  739:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
  740:     my $response=$ua->request($request);
  741: 
  742:     return $response->content;
  743: }
  744: 
  745: # ------------------------------------------------------------------------- Log
  746: 
  747: sub log {
  748:     my ($dom,$nam,$hom,$what)=@_;
  749:     return critical("log:$dom:$nam:$what",$hom);
  750: }
  751: 
  752: # ------------------------------------------------------------------ Course Log
  753: 
  754: sub flushcourselogs {
  755:     &logthis('Flushing course log buffers');
  756:     map {
  757:         my $crsid=$_;
  758:         if (&reply('log:'.$ENV{'course.'.$crsid.'.domain'}.':'.
  759: 		          $ENV{'course.'.$crsid.'.num'}.':'.
  760: 		           &escape($courselogs{$crsid}),
  761: 		          $ENV{'course.'.$crsid.'.home'}) eq 'ok') {
  762: 	    delete $courselogs{$crsid};
  763:         } else {
  764:             &logthis('Failed to flush log buffer for '.$crsid);
  765:             if (length($courselogs{$crsid})>40000) {
  766:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
  767:                         " exceeded maximum size, deleting.</font>");
  768:                delete $courselogs{$crsid};
  769:             }
  770:         }        
  771:     } keys %courselogs;
  772: }
  773: 
  774: sub courselog {
  775:     my $what=shift;
  776:     $what=time.':'.$what;
  777:     unless ($ENV{'request.course.id'}) { return ''; }
  778:     if (defined $courselogs{$ENV{'request.course.id'}}) {
  779: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
  780:     } else {
  781: 	$courselogs{$ENV{'request.course.id'}}.=$what;
  782:     }
  783:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
  784: 	&flushcourselogs();
  785:     }
  786: }
  787: 
  788: sub courseacclog {
  789:     my $fnsymb=shift;
  790:     unless ($ENV{'request.course.id'}) { return ''; }
  791:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
  792:     if ($what=~/(problem|exam|quiz|assess|survey|form)$/) {
  793: 	map {
  794:             if ($_=~/^form\.(.*)/) {
  795: 		$what.=':'.$1.'='.$ENV{$_};
  796:             }
  797:         } keys %ENV;
  798:     }
  799:     &courselog($what);
  800: }
  801: 
  802: # ----------------------------------------------------------- Check out an item
  803: 
  804: sub checkout {
  805:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  806:     my $now=time;
  807:     my $lonhost=$perlvar{'lonHostID'};
  808:     my $infostr=&escape(
  809:                  $tuname.'&'.
  810:                  $tudom.'&'.
  811:                  $tcrsid.'&'.
  812:                  $symb.'&'.
  813: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
  814:     my $token=&reply('tmpput:'.$infostr,$lonhost);
  815:     if ($token=~/^error\:/) { 
  816:         &logthis("<font color=blue>WARNING: ".
  817:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
  818:                  "</font>");
  819:         return ''; 
  820:     }
  821: 
  822:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
  823:     $token=~tr/a-z/A-Z/;
  824: 
  825:     my %infohash=('resource.0.outtoken' => $token,
  826:                   'resource.0.checkouttime' => $now,
  827:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
  828: 
  829:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
  830:        return '';
  831:     } else {
  832:         &logthis("<font color=blue>WARNING: ".
  833:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
  834:                  "</font>");
  835:     }    
  836: 
  837:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
  838:                          &escape('Checkout '.$infostr.' - '.
  839:                                                  $token)) ne 'ok') {
  840: 	return '';
  841:     } else {
  842:         &logthis("<font color=blue>WARNING: ".
  843:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
  844:                  "</font>");
  845:     }
  846:     return $token;
  847: }
  848: 
  849: # ------------------------------------------------------------ Check in an item
  850: 
  851: sub checkin {
  852:     my $token=shift;
  853:     my $now=time;
  854:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
  855:     $lonhost=~tr/A-Z/a-z/;
  856:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
  857:     $dtoken=~s/\W/\_/g;
  858:     my ($tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
  859:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
  860: 
  861:     unless (($tuname) && ($tudom)) {
  862:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
  863:         return '';
  864:     }
  865:     
  866:     unless (&allowed('mgr',$tcrsid)) {
  867:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
  868:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
  869:         return '';
  870:     }
  871: 
  872:     my %infohash=('resource.0.intoken' => $token,
  873:                   'resource.0.checkintime' => $now,
  874:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
  875: 
  876:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
  877:        return '';
  878:     }    
  879: 
  880:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
  881:                          &escape('Checkin - '.$token)) ne 'ok') {
  882: 	return '';
  883:     }
  884: 
  885:     return ($symb,$tuname,$tudom,$tcrsid);    
  886: }
  887: 
  888: # --------------------------------------------- Set Expire Date for Spreadsheet
  889: 
  890: sub expirespread {
  891:     my ($uname,$udom,$stype,$usymb)=@_;
  892:     my $cid=$ENV{'request.course.id'}; 
  893:     if ($cid) {
  894:        my $now=time;
  895:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
  896:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
  897:                             $ENV{'course.'.$cid.'.num'}.
  898: 	        	    ':nohist_expirationdates:'.
  899:                             &escape($key).'='.$now,
  900:                             $ENV{'course.'.$cid.'.home'})
  901:     }
  902:     return 'ok';
  903: }
  904: 
  905: # ----------------------------------------------------- Devalidate Spreadsheets
  906: 
  907: sub devalidate {
  908:     my $symb=shift;
  909:     my $cid=$ENV{'request.course.id'}; 
  910:     if ($cid) {
  911: 	my $key=$ENV{'user.name'}.':'.$ENV{'user.domain'}.':';
  912:         my $status=
  913: 	    &del('nohist_calculatedsheet',
  914: 		 [$key.'studentcalc'],
  915: 		 $ENV{'course.'.$cid.'.domain'},
  916: 		 $ENV{'course.'.$cid.'.num'})
  917: 		.' '.
  918: 	    &del('nohist_calculatedsheets_'.$cid,
  919: 		 [$key.'assesscalc:'.$symb]);
  920:         unless ($status eq 'ok ok') {
  921:            &logthis('Could not devalidate spreadsheet '.
  922:                     $ENV{'user.name'}.' at '.$ENV{'user.domain'}.' for '.
  923: 		    $symb.': '.$status);
  924:         }
  925:     }
  926: }
  927: 
  928: sub hash2str {
  929:   my (%hash)=@_;
  930:   my $result='';
  931:   map { $result.=escape($_).'='.escape($hash{$_}).'&'; } keys %hash;
  932:   $result=~s/\&$//;
  933:   return $result;
  934: }
  935: 
  936: sub str2hash {
  937:   my ($string) = @_;
  938:   my %returnhash;
  939:   map {
  940:     my ($name,$value)=split(/\=/,$_);
  941:     $returnhash{&unescape($name)}=&unescape($value);
  942:   } split(/\&/,$string);
  943:   return %returnhash;
  944: }
  945: 
  946: # -------------------------------------------------------------------Temp Store
  947: 
  948: sub tmpreset {
  949:   my ($symb,$namespace,$domain,$stuname) = @_;
  950:   if (!$symb) {
  951:     $symb=&symbread();
  952:     if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
  953:   }
  954:   $symb=escape($symb);
  955: 
  956:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
  957:   $namespace=~s/\//\_/g;
  958:   $namespace=~s/\W//g;
  959: 
  960:   #FIXME needs to do something for /pub resources
  961:   if (!$domain) { $domain=$ENV{'user.domain'}; }
  962:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
  963:   my $path=$perlvar{'lonDaemons'}.'/tmp';
  964:   my %hash;
  965:   if (tie(%hash,'GDBM_File',
  966: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
  967: 	  &GDBM_WRCREAT,0640)) {
  968:     foreach my $key (keys %hash) {
  969:       if ($key=~ /:$symb/) {
  970: 	delete($hash{$key});
  971:       }
  972:     }
  973:   }
  974: }
  975: 
  976: sub tmpstore {
  977:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
  978: 
  979:   if (!$symb) {
  980:     $symb=&symbread();
  981:     if (!$symb) { $symb= $ENV{'request.url'}; }
  982:   }
  983:   $symb=escape($symb);
  984: 
  985:   if (!$namespace) {
  986:     # I don't think we would ever want to store this for a course.
  987:     # it seems this will only be used if we don't have a course.
  988:     #$namespace=$ENV{'request.course.id'};
  989:     #if (!$namespace) {
  990:       $namespace=$ENV{'request.state'};
  991:     #}
  992:   }
  993:   $namespace=~s/\//\_/g;
  994:   $namespace=~s/\W//g;
  995: #FIXME needs to do something for /pub resources
  996:   if (!$domain) { $domain=$ENV{'user.domain'}; }
  997:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
  998:   my $now=time;
  999:   my %hash;
 1000:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1001:   if (tie(%hash,'GDBM_File',
 1002: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1003: 	  &GDBM_WRCREAT,0640)) {
 1004:     $hash{"version:$symb"}++;
 1005:     my $version=$hash{"version:$symb"};
 1006:     my $allkeys=''; 
 1007:     foreach my $key (keys(%$storehash)) {
 1008:       $allkeys.=$key.':';
 1009:       $hash{"$version:$symb:$key"}=$$storehash{$key};
 1010:     }
 1011:     $hash{"$version:$symb:timestamp"}=$now;
 1012:     $allkeys.='timestamp';
 1013:     $hash{"$version:keys:$symb"}=$allkeys;
 1014:     if (untie(%hash)) {
 1015:       return 'ok';
 1016:     } else {
 1017:       return "error:$!";
 1018:     }
 1019:   } else {
 1020:     return "error:$!";
 1021:   }
 1022: }
 1023: 
 1024: # -----------------------------------------------------------------Temp Restore
 1025: 
 1026: sub tmprestore {
 1027:   my ($symb,$namespace,$domain,$stuname) = @_;
 1028: 
 1029:   if (!$symb) {
 1030:     $symb=&symbread();
 1031:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1032:   }
 1033:   $symb=escape($symb);
 1034: 
 1035:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1036:   #FIXME needs to do something for /pub resources
 1037:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1038:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1039: 
 1040:   my %returnhash;
 1041:   $namespace=~s/\//\_/g;
 1042:   $namespace=~s/\W//g;
 1043:   my %hash;
 1044:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1045:   if (tie(%hash,'GDBM_File',
 1046: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1047: 	  &GDBM_READER,0640)) {
 1048:     my $version=$hash{"version:$symb"};
 1049:     $returnhash{'version'}=$version;
 1050:     my $scope;
 1051:     for ($scope=1;$scope<=$version;$scope++) {
 1052:       my $vkeys=$hash{"$scope:keys:$symb"};
 1053:       my @keys=split(/:/,$vkeys);
 1054:       my $key;
 1055:       $returnhash{"$scope:keys"}=$vkeys;
 1056:       foreach $key (@keys) {
 1057: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
 1058: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
 1059:       }
 1060:     }
 1061:     if (!(untie(%hash))) {
 1062:       return "error:$!";
 1063:     }
 1064:   } else {
 1065:     return "error:$!";
 1066:   }
 1067:   return %returnhash;
 1068: }
 1069: 
 1070: # ----------------------------------------------------------------------- Store
 1071: 
 1072: sub store {
 1073:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1074:     my $home='';
 1075: 
 1076:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1077: 
 1078:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1079: 
 1080:     &devalidate($symb);
 1081: 
 1082:     $symb=escape($symb);
 1083:     if (!$namespace) { unless ($namespace=$ENV{'request.course.id'}) { return ''; } }
 1084:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1085:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1086:     if (!$home) { $home=$ENV{'user.home'}; }
 1087:     my $namevalue='';
 1088:     map {
 1089:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1090:     } keys %$storehash;
 1091:     $namevalue=~s/\&$//;
 1092:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1093: }
 1094: 
 1095: # -------------------------------------------------------------- Critical Store
 1096: 
 1097: sub cstore {
 1098:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1099:     my $home='';
 1100: 
 1101:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1102: 
 1103:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1104: 
 1105:     &devalidate($symb);
 1106: 
 1107:     $symb=escape($symb);
 1108:     if (!$namespace) { unless ($namespace=$ENV{'request.course.id'}) { return ''; } }
 1109:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1110:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1111:     if (!$home) { $home=$ENV{'user.home'}; }
 1112: 
 1113:     my $namevalue='';
 1114:     map {
 1115:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1116:     } keys %$storehash;
 1117:     $namevalue=~s/\&$//;
 1118:     return critical("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1119: }
 1120: 
 1121: # --------------------------------------------------------------------- Restore
 1122: 
 1123: sub restore {
 1124:     my ($symb,$namespace,$domain,$stuname) = @_;
 1125:     my $home='';
 1126: 
 1127:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1128: 
 1129:     if (!$symb) {
 1130:       unless ($symb=escape(&symbread())) { return ''; }
 1131:     } else {
 1132:       $symb=&escape($symb);
 1133:     }
 1134:     if (!$namespace) { unless ($namespace=$ENV{'request.course.id'}) { return ''; } }
 1135:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1136:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1137:     if (!$home) { $home=$ENV{'user.home'}; }
 1138:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 1139: 
 1140:     my %returnhash=();
 1141:     map {
 1142: 	my ($name,$value)=split(/\=/,$_);
 1143:         $returnhash{&unescape($name)}=&unescape($value);
 1144:     } split(/\&/,$answer);
 1145:     my $version;
 1146:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 1147:        map {
 1148:           $returnhash{$_}=$returnhash{$version.':'.$_};
 1149:        } split(/\:/,$returnhash{$version.':keys'});
 1150:     }
 1151:     return %returnhash;
 1152: }
 1153: 
 1154: # ---------------------------------------------------------- Course Description
 1155: 
 1156: sub coursedescription {
 1157:     my $courseid=shift;
 1158:     $courseid=~s/^\///;
 1159:     $courseid=~s/\_/\//g;
 1160:     my ($cdomain,$cnum)=split(/\//,$courseid);
 1161:     my $chome=&homeserver($cnum,$cdomain);
 1162:     if ($chome ne 'no_host') {
 1163:        my %returnhash=&dump('environment',$cdomain,$cnum);
 1164:        if (!exists($returnhash{'con_lost'})) {
 1165:            my $normalid=$cdomain.'_'.$cnum;
 1166:            my %envhash=();
 1167:            $returnhash{'home'}= $chome;
 1168: 	   $returnhash{'domain'} = $cdomain;
 1169: 	   $returnhash{'num'} = $cnum;
 1170:            while (my ($name,$value) = each %returnhash) {
 1171:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 1172:            }
 1173:            $returnhash{'url'}='/res/'.declutter($returnhash{'url'});
 1174:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 1175: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
 1176:            $envhash{'course.'.$normalid.'.last_cache'}=time;
 1177:            $envhash{'course.'.$normalid.'.home'}=$chome;
 1178:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 1179:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 1180:            &appenv(%envhash);
 1181:            return %returnhash;
 1182:        }
 1183:     }
 1184:     return ();
 1185: }
 1186: 
 1187: # -------------------------------------------------------- Get user privileges
 1188: 
 1189: sub rolesinit {
 1190:     my ($domain,$username,$authhost)=@_;
 1191:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 1192:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 1193:     my %allroles=();
 1194:     my %thesepriv=();
 1195:     my $now=time;
 1196:     my $userroles="user.login.time=$now\n";
 1197:     my $thesestr;
 1198: 
 1199:     if ($rolesdump ne '') {
 1200:         map {
 1201: 	  if ($_!~/^rolesdef\&/) {
 1202:             my ($area,$role)=split(/=/,$_);
 1203:             $area=~s/\_\w\w$//;
 1204:             my ($trole,$tend,$tstart)=split(/_/,$role);
 1205:             $userroles.='user.role.'.$trole.'.'.$area.'='.
 1206:                         $tstart.'.'.$tend."\n";
 1207:             if ($tend!=0) {
 1208: 	        if ($tend<$now) {
 1209: 	            $trole='';
 1210:                 } 
 1211:             }
 1212:             if ($tstart!=0) {
 1213:                 if ($tstart>$now) {
 1214:                    $trole='';        
 1215:                 }
 1216:             }
 1217:             if (($area ne '') && ($trole ne '')) {
 1218: 	       my $spec=$trole.'.'.$area;
 1219:                my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 1220:                if ($trole =~ /^cr\//) {
 1221: 		   my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 1222:                    my $homsvr=homeserver($rauthor,$rdomain);
 1223:                    if ($hostname{$homsvr} ne '') {
 1224:                       my $roledef=
 1225: 			  reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
 1226:                                 $homsvr);
 1227:                       if (($roledef ne 'con_lost') && ($roledef ne '')) {
 1228:                          my ($syspriv,$dompriv,$coursepriv)=
 1229: 			     split(/\_/,unescape($roledef));
 1230:  	                 $allroles{'cm./'}.=':'.$syspriv;
 1231:                          $allroles{$spec.'./'}.=':'.$syspriv;
 1232:                          if ($tdomain ne '') {
 1233:                              $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 1234:                              $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 1235:                              if ($trest ne '') {
 1236: 		                $allroles{'cm.'.$area}.=':'.$coursepriv;
 1237: 		                $allroles{$spec.'.'.$area}.=':'.$coursepriv;
 1238:                              }
 1239: 	                 }
 1240:                       }
 1241:                    }
 1242:                } else {
 1243: 	           $allroles{'cm./'}.=':'.$pr{$trole.':s'};
 1244: 	           $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 1245:                    if ($tdomain ne '') {
 1246:                      $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1247:                      $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1248:                       if ($trest ne '') {
 1249: 		          $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 1250: 		          $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 1251:                       }
 1252: 	           }
 1253: 	       }
 1254:             }
 1255:           } 
 1256:         } split(/&/,$rolesdump);
 1257:         my $adv=0;
 1258:         my $author=0;
 1259:         map {
 1260:             %thesepriv=();
 1261:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
 1262:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 1263:             map {
 1264:                 if ($_ ne '') {
 1265: 		    my ($privilege,$restrictions)=split(/&/,$_);
 1266:                     if ($restrictions eq '') {
 1267: 			$thesepriv{$privilege}='F';
 1268:                     } else {
 1269:                         if ($thesepriv{$privilege} ne 'F') {
 1270: 			    $thesepriv{$privilege}.=$restrictions;
 1271:                         }
 1272:                     }
 1273:                 }
 1274:             } split(/:/,$allroles{$_});
 1275:             $thesestr='';
 1276:             map { $thesestr.=':'.$_.'&'.$thesepriv{$_}; } keys %thesepriv;
 1277:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
 1278:         } keys %allroles;            
 1279:         $userroles.='user.adv='.$adv."\n".
 1280: 	            'user.author='.$author."\n";
 1281:         $ENV{'user.adv'}=$adv;
 1282:     }
 1283:     return $userroles;  
 1284: }
 1285: 
 1286: # --------------------------------------------------------------- get interface
 1287: 
 1288: sub get {
 1289:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1290:    my $items='';
 1291:    map {
 1292:        $items.=escape($_).'&';
 1293:    } @$storearr;
 1294:    $items=~s/\&$//;
 1295:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1296:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1297:    my $uhome=&homeserver($uname,$udomain);
 1298: 
 1299:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 1300:    my @pairs=split(/\&/,$rep);
 1301:    my %returnhash=();
 1302:    my $i=0;
 1303:    map {
 1304:       $returnhash{$_}=unescape($pairs[$i]);
 1305:       $i++;
 1306:    } @$storearr;
 1307:    return %returnhash;
 1308: }
 1309: 
 1310: # --------------------------------------------------------------- del interface
 1311: 
 1312: sub del {
 1313:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1314:    my $items='';
 1315:    map {
 1316:        $items.=escape($_).'&';
 1317:    } @$storearr;
 1318:    $items=~s/\&$//;
 1319:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1320:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1321:    my $uhome=&homeserver($uname,$udomain);
 1322: 
 1323:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 1324: }
 1325: 
 1326: # -------------------------------------------------------------- dump interface
 1327: 
 1328: sub dump {
 1329:    my ($namespace,$udomain,$uname)=@_;
 1330:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1331:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1332:    my $uhome=&homeserver($uname,$udomain);
 1333:    my $rep=reply("dump:$udomain:$uname:$namespace",$uhome);
 1334:    my @pairs=split(/\&/,$rep);
 1335:    my %returnhash=();
 1336:    map {
 1337:       my ($key,$value)=split(/=/,$_);
 1338:       $returnhash{unescape($key)}=unescape($value);
 1339:    } @pairs;
 1340:    return %returnhash;
 1341: }
 1342: 
 1343: # --------------------------------------------------------------- put interface
 1344: 
 1345: sub put {
 1346:    my ($namespace,$storehash,$udomain,$uname)=@_;
 1347:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1348:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1349:    my $uhome=&homeserver($uname,$udomain);
 1350:    my $items='';
 1351:    map {
 1352:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
 1353:    } keys %$storehash;
 1354:    $items=~s/\&$//;
 1355:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 1356: }
 1357: 
 1358: # ------------------------------------------------------ critical put interface
 1359: 
 1360: sub cput {
 1361:    my ($namespace,$storehash,$udomain,$uname)=@_;
 1362:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1363:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1364:    my $uhome=&homeserver($uname,$udomain);
 1365:    my $items='';
 1366:    map {
 1367:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
 1368:    } keys %$storehash;
 1369:    $items=~s/\&$//;
 1370:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 1371: }
 1372: 
 1373: # -------------------------------------------------------------- eget interface
 1374: 
 1375: sub eget {
 1376:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1377:    my $items='';
 1378:    map {
 1379:        $items.=escape($_).'&';
 1380:    } @$storearr;
 1381:    $items=~s/\&$//;
 1382:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 1383:    if (!$uname) { $uname=$ENV{'user.name'}; }
 1384:    my $uhome=&homeserver($uname,$udomain);
 1385:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 1386:    my @pairs=split(/\&/,$rep);
 1387:    my %returnhash=();
 1388:    my $i=0;
 1389:    map {
 1390:       $returnhash{$_}=unescape($pairs[$i]);
 1391:       $i++;
 1392:    } @$storearr;
 1393:    return %returnhash;
 1394: }
 1395: 
 1396: # ------------------------------------------------- Check for a user privilege
 1397: 
 1398: sub allowed {
 1399:     my ($priv,$uri)=@_;
 1400: 
 1401:     my $orguri=$uri;
 1402:     $uri=&declutter($uri);
 1403: 
 1404: # Free bre access to adm and meta resources
 1405: 
 1406:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 1407: 	return 'F';
 1408:     }
 1409: 
 1410: # Free bre to public access
 1411: 
 1412:     if ($priv eq 'bre') {
 1413: 	if (&metadata($uri,'copyright') eq 'public') { return 'F'; }
 1414:     }
 1415: 
 1416:     my $thisallowed='';
 1417:     my $statecond=0;
 1418:     my $courseprivid='';
 1419: 
 1420: # Course
 1421: 
 1422:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
 1423:        $thisallowed.=$1;
 1424:     }
 1425: 
 1426: # Domain
 1427: 
 1428:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 1429:        =~/$priv\&([^\:]*)/) {
 1430:        $thisallowed.=$1;
 1431:     }
 1432: 
 1433: # Course: uri itself is a course
 1434:     my $courseuri=$uri;
 1435:     $courseuri=~s/\_(\d)/\/$1/;
 1436:     $courseuri=~s/^([^\/])/\/$1/;
 1437: 
 1438:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
 1439:        =~/$priv\&([^\:]*)/) {
 1440:        $thisallowed.=$1;
 1441:     }
 1442: 
 1443: # Full access at system, domain or course-wide level? Exit.
 1444: 
 1445:     if ($thisallowed=~/F/) {
 1446: 	return 'F';
 1447:     }
 1448: 
 1449: # If this is generating or modifying users, exit with special codes
 1450: 
 1451:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
 1452: 	return $thisallowed;
 1453:     }
 1454: #
 1455: # Gathered so far: system, domain and course wide privileges
 1456: #
 1457: # Course: See if uri or referer is an individual resource that is part of 
 1458: # the course
 1459: 
 1460:     if ($ENV{'request.course.id'}) {
 1461:        $courseprivid=$ENV{'request.course.id'};
 1462:        if ($ENV{'request.course.sec'}) {
 1463:           $courseprivid.='/'.$ENV{'request.course.sec'};
 1464:        }
 1465:        $courseprivid=~s/\_/\//;
 1466:        my $checkreferer=1;
 1467:        my @uriparts=split(/\//,$uri);
 1468:        my $filename=$uriparts[$#uriparts];
 1469:        my $pathname=$uri;
 1470:        $pathname=~s/\/$filename$//;
 1471:        if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 1472:            /\&$filename\:([\d\|]+)\&/) {
 1473:            $statecond=$1;
 1474:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 1475:                =~/$priv\&([^\:]*)/) {
 1476:                $thisallowed.=$1;
 1477:                $checkreferer=0;
 1478:            }
 1479:        }
 1480:        
 1481:        if ($checkreferer) {
 1482: 	  my $refuri=$ENV{'httpref.'.$orguri};
 1483: 
 1484:             unless ($refuri) {
 1485:                 map {
 1486: 		    if ($_=~/^httpref\..*\*/) {
 1487: 			my $pattern=$_;
 1488:                         $pattern=~s/^httpref\.\/res\///;
 1489:                         $pattern=~s/\*/\[\^\/\]\+/g;
 1490:                         $pattern=~s/\//\\\//g;
 1491:                         if ($orguri=~/$pattern/) {
 1492: 			    $refuri=$ENV{$_};
 1493:                         }
 1494:                     }
 1495:                 } keys %ENV;
 1496:             }
 1497:          if ($refuri) { 
 1498: 	  $refuri=&declutter($refuri);
 1499:           my @uriparts=split(/\//,$refuri);
 1500:           my $filename=$uriparts[$#uriparts];
 1501:           my $pathname=$refuri;
 1502:           $pathname=~s/\/$filename$//;
 1503:             if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 1504:               /\&$filename\:([\d\|]+)\&/) {
 1505:               my $refstatecond=$1;
 1506:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 1507:                   =~/$priv\&([^\:]*)/) {
 1508:                   $thisallowed.=$1;
 1509:                   $uri=$refuri;
 1510:                   $statecond=$refstatecond;
 1511:               }
 1512:           }
 1513:         }
 1514:        }
 1515:    }
 1516: 
 1517: #
 1518: # Gathered now: all privileges that could apply, and condition number
 1519: # 
 1520: #
 1521: # Full or no access?
 1522: #
 1523: 
 1524:     if ($thisallowed=~/F/) {
 1525: 	return 'F';
 1526:     }
 1527: 
 1528:     unless ($thisallowed) {
 1529:         return '';
 1530:     }
 1531: 
 1532: # Restrictions exist, deal with them
 1533: #
 1534: #   C:according to course preferences
 1535: #   R:according to resource settings
 1536: #   L:unless locked
 1537: #   X:according to user session state
 1538: #
 1539: 
 1540: # Possibly locked functionality, check all courses
 1541: # Locks might take effect only after 10 minutes cache expiration for other
 1542: # courses, and 2 minutes for current course
 1543: 
 1544:     my $envkey;
 1545:     if ($thisallowed=~/L/) {
 1546:         foreach $envkey (keys %ENV) {
 1547:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 1548:                my $courseid=$2;
 1549:                my $roleid=$1.'.'.$2;
 1550:                $courseid=~s/^\///;
 1551:                my $expiretime=600;
 1552:                if ($ENV{'request.role'} eq $roleid) {
 1553: 		  $expiretime=120;
 1554:                }
 1555: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 1556:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 1557:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
 1558: 		   &coursedescription($courseid);
 1559:                }
 1560:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
 1561:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 1562: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 1563:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 1564:                             $ENV{'user.host'},
 1565:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 1566:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 1567:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 1568: 		       return '';
 1569:                    }
 1570:                }
 1571:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
 1572:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 1573: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
 1574:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 1575:                             $ENV{'user.host'},
 1576:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 1577:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 1578:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 1579: 		       return '';
 1580:                    }
 1581:                }
 1582: 	   }
 1583:        }
 1584:     }
 1585:    
 1586: #
 1587: # Rest of the restrictions depend on selected course
 1588: #
 1589: 
 1590:     unless ($ENV{'request.course.id'}) {
 1591:        return '1';
 1592:     }
 1593: 
 1594: #
 1595: # Now user is definitely in a course
 1596: #
 1597: 
 1598: 
 1599: # Course preferences
 1600: 
 1601:    if ($thisallowed=~/C/) {
 1602:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 1603:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
 1604: 	   =~/\,$rolecode\,/) {
 1605:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 1606:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 1607:                 $ENV{'request.course.id'});
 1608:            return '';
 1609:        }
 1610:    }
 1611: 
 1612: # Resource preferences
 1613: 
 1614:    if ($thisallowed=~/R/) {
 1615:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 1616:        my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
 1617:        if (-e $filename) {
 1618:            my @content;
 1619:            {
 1620: 	     my $fh=Apache::File->new($filename);
 1621:              @content=<$fh>;
 1622: 	   }
 1623:            if (join('',@content)=~
 1624:                     /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
 1625: 	       &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 1626:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 1627:            return '';
 1628: 
 1629:            }
 1630:        }
 1631:    }
 1632: 
 1633: # Restricted by state?
 1634: 
 1635:    if ($thisallowed=~/X/) {
 1636:       if (&condval($statecond)) {
 1637: 	 return '2';
 1638:       } else {
 1639:          return '';
 1640:       }
 1641:    }
 1642: 
 1643:    return 'F';
 1644: }
 1645: 
 1646: # ----------------------------------------------------------------- Define Role
 1647: 
 1648: sub definerole {
 1649:   if (allowed('mcr','/')) {
 1650:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 1651:     map {
 1652: 	my ($crole,$cqual)=split(/\&/,$_);
 1653:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
 1654:         if ($pr{'cr:s'}=~/$crole\&/) {
 1655: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
 1656:                return "refused:s:$crole&$cqual"; 
 1657:             }
 1658:         }
 1659:     } split('/',$sysrole);
 1660:     map {
 1661: 	my ($crole,$cqual)=split(/\&/,$_);
 1662:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
 1663:         if ($pr{'cr:d'}=~/$crole\&/) {
 1664: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
 1665:                return "refused:d:$crole&$cqual"; 
 1666:             }
 1667:         }
 1668:     } split('/',$domrole);
 1669:     map {
 1670: 	my ($crole,$cqual)=split(/\&/,$_);
 1671:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
 1672:         if ($pr{'cr:c'}=~/$crole\&/) {
 1673: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
 1674:                return "refused:c:$crole&$cqual"; 
 1675:             }
 1676:         }
 1677:     } split('/',$courole);
 1678:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 1679:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 1680: 	        "rolesdef_$rolename=".
 1681:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 1682:     return reply($command,$ENV{'user.home'});
 1683:   } else {
 1684:     return 'refused';
 1685:   }
 1686: }
 1687: 
 1688: # ---------------- Make a metadata query against the network of library servers
 1689: 
 1690: sub metadata_query {
 1691:     my ($query,$custom,$customshow)=@_;
 1692:     my %rhash;
 1693:     for my $server (keys %libserv) {
 1694: 	unless ($custom or $customshow) {
 1695: 	    my $reply=&reply("querysend:".&escape($query),$server);
 1696: 	    $rhash{$server}=$reply;
 1697: 	}
 1698: 	else {
 1699: 	    my $reply=&reply("querysend:".&escape($query).':'.
 1700: 			     &escape($custom).':'.&escape($customshow),
 1701: 			     $server);
 1702: 	    $rhash{$server}=$reply;
 1703: 	}
 1704:     }
 1705:     return \%rhash;
 1706: }
 1707: 
 1708: # ------------------------------------------------------------------ Plain Text
 1709: 
 1710: sub plaintext {
 1711:     my $short=shift;
 1712:     return $prp{$short};
 1713: }
 1714: 
 1715: # ------------------------------------------------------------------ Plain Text
 1716: 
 1717: sub fileembstyle {
 1718:     my $ending=lc(shift);
 1719:     return $fe{$ending};
 1720: }
 1721: 
 1722: # ------------------------------------------------------------ Description Text
 1723: 
 1724: sub filedescription {
 1725:     my $ending=lc(shift);
 1726:     return $fd{$ending};
 1727: }
 1728: 
 1729: # ----------------------------------------------------------------- Assign Role
 1730: 
 1731: sub assignrole {
 1732:     my ($udom,$uname,$url,$role,$end,$start)=@_;
 1733:     my $mrole;
 1734:     if ($role =~ /^cr\//) {
 1735: 	unless (&allowed('ccr',$url)) {
 1736:            &logthis('Refused custom assignrole: '.
 1737:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 1738: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 1739:            return 'refused'; 
 1740:         }
 1741:         $mrole='cr';
 1742:     } else {
 1743:         my $cwosec=$url;
 1744:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 1745:         unless (&allowed('c'.$role,$cwosec)) { 
 1746:            &logthis('Refused assignrole: '.
 1747:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 1748: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 1749:            return 'refused'; 
 1750:         }
 1751:         $mrole=$role;
 1752:     }
 1753:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 1754:                 "$udom:$uname:$url".'_'."$mrole=$role";
 1755:     if ($end) { $command.='_'.$end; }
 1756:     if ($start) {
 1757: 	if ($end) { 
 1758:            $command.='_'.$start; 
 1759:         } else {
 1760:            $command.='_0_'.$start;
 1761:         }
 1762:     }
 1763:     return &reply($command,&homeserver($uname,$udom));
 1764: }
 1765: 
 1766: # -------------------------------------------------- Modify user authentication
 1767: sub modifyuserauth {
 1768:     my ($udom,$uname,$umode,$upass)=@_;
 1769:     my $uhome=&homeserver($uname,$udom);
 1770:     &logthis('Call to modify user authentication'.$udom.', '.$uname.', '.
 1771:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'});  
 1772:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 1773: 		     &escape($upass),$uhome);
 1774:     unless ($reply eq 'ok') {
 1775: 	return 'error: '.$reply;
 1776:     }   
 1777:     return 'ok';
 1778: }
 1779: 
 1780: # --------------------------------------------------------------- Modify a user
 1781: 
 1782: 
 1783: sub modifyuser {
 1784:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene)=@_;
 1785:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 1786:              $umode.', '.$first.', '.$middle.', '.
 1787: 	     $last.', '.$gene.' by '.
 1788:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});  
 1789:     my $uhome=&homeserver($uname,$udom);
 1790: # ----------------------------------------------------------------- Create User
 1791:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
 1792:         my $unhome='';
 1793: 	if ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
 1794: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1795:         } else {
 1796:             my $tryserver;
 1797:             my $loadm=10000000;
 1798:             foreach $tryserver (keys %libserv) {
 1799: 	       if ($hostdom{$tryserver} eq $udom) {
 1800:                   my $answer=reply('load',$tryserver);
 1801:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 1802: 		      $loadm=$answer;
 1803:                       $unhome=$tryserver;
 1804:                   }
 1805: 	       }
 1806: 	    }
 1807:         }
 1808:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 1809: 	    return 'error: find home';
 1810:         }
 1811:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 1812:                          &escape($upass),$unhome);
 1813: 	unless ($reply eq 'ok') {
 1814:             return 'error: '.$reply;
 1815:         }   
 1816:         $uhome=&homeserver($uname,$udom);
 1817:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 1818: 	    return 'error: verify home';
 1819:         }
 1820:     }
 1821: # ---------------------------------------------------------------------- Add ID
 1822:     if ($uid) {
 1823:        $uid=~tr/A-Z/a-z/;
 1824:        my %uidhash=&idrget($udom,$uname);
 1825:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)) {
 1826: 	  unless ($uid eq $uidhash{$uname}) {
 1827: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
 1828:           }
 1829:        } else {
 1830: 	  &idput($udom,($uname => $uid));
 1831:        }
 1832:     }
 1833: # -------------------------------------------------------------- Add names, etc
 1834:     my %names=&get('environment',
 1835: 		   ['firstname','middlename','lastname','generation'],
 1836: 		   $udom,$uname);
 1837:     if ($first)  { $names{'firstname'}  = $first; }
 1838:     if ($middle) { $names{'middlename'} = $middle; }
 1839:     if ($last)   { $names{'lastname'}   = $last; }
 1840:     if ($gene)   { $names{'generation'} = $gene; }
 1841:     my $reply = &put('environment', \%names, $udom,$uname);
 1842:     if ($reply ne 'ok') { return 'error: '.$reply; }
 1843:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 1844:              $umode.', '.$first.', '.$middle.', '.
 1845: 	     $last.', '.$gene.' by '.
 1846:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 1847:     return 'ok';
 1848: }
 1849: 
 1850: # -------------------------------------------------------------- Modify student
 1851: 
 1852: sub modifystudent {
 1853:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 1854:         $end,$start)=@_;
 1855:     my $cid='';
 1856:     unless ($cid=$ENV{'request.course.id'}) {
 1857: 	return 'not_in_class';
 1858:     }
 1859: # --------------------------------------------------------------- Make the user
 1860:     my $reply=&modifyuser
 1861: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene);
 1862:     unless ($reply eq 'ok') { return $reply; }
 1863:     my $uhome=&homeserver($uname,$udom);
 1864:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 1865: 	return 'error: no such user';
 1866:     }
 1867: # -------------------------------------------------- Add student to course list
 1868:     $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 1869: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
 1870:                       &escape($uname.':'.$udom).'='.
 1871:                       &escape($end.':'.$start),
 1872: 	              $ENV{'course.'.$cid.'.home'});
 1873:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 1874: 	return 'error: '.$reply;
 1875:     }
 1876: # ---------------------------------------------------- Add student role to user
 1877:     my $uurl='/'.$cid;
 1878:     $uurl=~s/\_/\//g;
 1879:     if ($usec) {
 1880: 	$uurl.='/'.$usec;
 1881:     }
 1882:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 1883: }
 1884: 
 1885: # ------------------------------------------------- Write to course preferences
 1886: 
 1887: sub writecoursepref {
 1888:     my ($courseid,%prefs)=@_;
 1889:     $courseid=~s/^\///;
 1890:     $courseid=~s/\_/\//g;
 1891:     my ($cdomain,$cnum)=split(/\//,$courseid);
 1892:     my $chome=homeserver($cnum,$cdomain);
 1893:     if (($chome eq '') || ($chome eq 'no_host')) { 
 1894: 	return 'error: no such course';
 1895:     }
 1896:     my $cstring='';
 1897:     map {
 1898: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 1899:     } keys %prefs;
 1900:     $cstring=~s/\&$//;
 1901:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 1902: }
 1903: 
 1904: # ---------------------------------------------------------- Make/modify course
 1905: 
 1906: sub createcourse {
 1907:     my ($udom,$description,$url)=@_;
 1908:     $url=&declutter($url);
 1909:     my $cid='';
 1910:     unless (&allowed('ccc',$ENV{'user.domain'})) {
 1911:         return 'refused';
 1912:     }
 1913:     unless ($udom eq $ENV{'user.domain'}) {
 1914:         return 'refused';
 1915:     }
 1916: # ------------------------------------------------------------------- Create ID
 1917:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 1918:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 1919: # ----------------------------------------------- Make sure that does not exist
 1920:    my $uhome=&homeserver($uname,$udom);
 1921:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 1922:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 1923:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 1924:        $uhome=&homeserver($uname,$udom);       
 1925:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 1926:            return 'error: unable to generate unique course-ID';
 1927:        } 
 1928:    }
 1929: # ------------------------------------------------------------- Make the course
 1930:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 1931:                       $ENV{'user.home'});
 1932:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 1933:     $uhome=&homeserver($uname,$udom);
 1934:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 1935: 	return 'error: no such course';
 1936:     }
 1937:     &writecoursepref($udom.'_'.$uname,
 1938:                      ('description' => $description,
 1939:                       'url'         => $url));
 1940:     return '/'.$udom.'/'.$uname;
 1941: }
 1942: 
 1943: # ---------------------------------------------------------- Assign Custom Role
 1944: 
 1945: sub assigncustomrole {
 1946:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
 1947:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 1948:                        $end,$start);
 1949: }
 1950: 
 1951: # ----------------------------------------------------------------- Revoke Role
 1952: 
 1953: sub revokerole {
 1954:     my ($udom,$uname,$url,$role)=@_;
 1955:     my $now=time;
 1956:     return &assignrole($udom,$uname,$url,$role,$now);
 1957: }
 1958: 
 1959: # ---------------------------------------------------------- Revoke Custom Role
 1960: 
 1961: sub revokecustomrole {
 1962:     my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
 1963:     my $now=time;
 1964:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
 1965: }
 1966: 
 1967: # ------------------------------------------------------------ Directory lister
 1968: 
 1969: sub dirlist {
 1970:     my $uri=shift;
 1971:     $uri=~s/^\///;
 1972:     $uri=~s/\/$//;
 1973:     my ($res,$udom,$uname,@rest)=split(/\//,$uri);
 1974:     if ($udom) {
 1975:      if ($uname) {
 1976:        my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/'.$uri,
 1977:                       homeserver($uname,$udom));
 1978:        return split(/:/,$listing);
 1979:      } else {
 1980:        my $tryserver;
 1981:        my %allusers=();
 1982:        foreach $tryserver (keys %libserv) {
 1983: 	  if ($hostdom{$tryserver} eq $udom) {
 1984:              my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.$udom,
 1985: 			       $tryserver);
 1986:              if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 1987:               && ($listing ne 'con_lost')) {
 1988:                 map {
 1989:                   my ($entry,@stat)=split(/&/,$_);
 1990:                   $allusers{$entry}=1;
 1991:                 } split(/:/,$listing);
 1992:              }
 1993: 	  }
 1994:        }
 1995:        my $alluserstr='';
 1996:        map {
 1997:            $alluserstr.=$_.'&user:';
 1998:        } sort keys %allusers;
 1999:        $alluserstr=~s/:$//;
 2000:        return split(/:/,$alluserstr);
 2001:      } 
 2002:    } else {
 2003:        my $tryserver;
 2004:        my %alldom=();
 2005:        foreach $tryserver (keys %libserv) {
 2006: 	   $alldom{$hostdom{$tryserver}}=1;
 2007:        }
 2008:        my $alldomstr='';
 2009:        map {
 2010:           $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
 2011:        } sort keys %alldom;
 2012:        $alldomstr=~s/:$//;
 2013:        return split(/:/,$alldomstr);       
 2014:    }
 2015: }
 2016: 
 2017: # -------------------------------------------------------- Value of a Condition
 2018: 
 2019: sub directcondval {
 2020:     my $number=shift;
 2021:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 2022:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 2023:     } else {
 2024:        return 2;
 2025:     }
 2026: }
 2027: 
 2028: sub condval {
 2029:     my $condidx=shift;
 2030:     my $result=0;
 2031:     my $allpathcond='';
 2032:     map {
 2033:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 2034: 	   $allpathcond.=
 2035:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 2036:        }
 2037:     } split(/\|/,$condidx);
 2038:     $allpathcond=~s/\|$//;
 2039:     if ($ENV{'request.course.id'}) {
 2040:        if ($allpathcond) {
 2041:           my $operand='|';
 2042: 	  my @stack;
 2043:           map {
 2044:               if ($_ eq '(') {
 2045:                  push @stack,($operand,$result)
 2046:               } elsif ($_ eq ')') {
 2047:                   my $before=pop @stack;
 2048: 		  if (pop @stack eq '&') {
 2049: 		      $result=$result>$before?$before:$result;
 2050:                   } else {
 2051:                       $result=$result>$before?$result:$before;
 2052:                   }
 2053:               } elsif (($_ eq '&') || ($_ eq '|')) {
 2054:                   $operand=$_;
 2055:               } else {
 2056:                   my $new=directcondval($_);
 2057:                   if ($operand eq '&') {
 2058:                      $result=$result>$new?$new:$result;
 2059:                   } else {
 2060:                      $result=$result>$new?$result:$new;
 2061:                   }                  
 2062:               }
 2063:           } ($allpathcond=~/(\d+|\(|\)|\&|\|)/g);
 2064:        }
 2065:     }
 2066:     return $result;
 2067: }
 2068: 
 2069: # --------------------------------------------------------- Value of a Variable
 2070: 
 2071: sub EXT {
 2072:     my ($varname,$symbparm)=@_;
 2073:     unless ($varname) { return ''; }
 2074:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 2075:     my $rest;
 2076:     if ($therest[0]) {
 2077:        $rest=join('.',@therest);
 2078:     } else {
 2079:        $rest='';
 2080:     }
 2081:     my $qualifierrest=$qualifier;
 2082:     if ($rest) { $qualifierrest.='.'.$rest; }
 2083:     my $spacequalifierrest=$space;
 2084:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 2085:     if ($realm eq 'user') {
 2086: # --------------------------------------------------------------- user.resource
 2087: 	if ($space eq 'resource') {
 2088: 	    my %restored=&restore();
 2089:             return $restored{$qualifierrest};
 2090: # ----------------------------------------------------------------- user.access
 2091:         } elsif ($space eq 'access') {
 2092:             return &allowed($qualifier,$rest);
 2093: # ------------------------------------------ user.preferences, user.environment
 2094:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 2095:             return $ENV{join('.',('environment',$qualifierrest))};
 2096: # ----------------------------------------------------------------- user.course
 2097:         } elsif ($space eq 'course') {
 2098:             return $ENV{join('.',('request.course',$qualifier))};
 2099: # ------------------------------------------------------------------- user.role
 2100:         } elsif ($space eq 'role') {
 2101:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 2102:             if ($qualifier eq 'value') {
 2103: 		return $role;
 2104:             } elsif ($qualifier eq 'extent') {
 2105:                 return $where;
 2106:             }
 2107: # ----------------------------------------------------------------- user.domain
 2108:         } elsif ($space eq 'domain') {
 2109:             return $ENV{'user.domain'};
 2110: # ------------------------------------------------------------------- user.name
 2111:         } elsif ($space eq 'name') {
 2112:             return $ENV{'user.name'};
 2113: # ---------------------------------------------------- Any other user namespace
 2114:         } else {
 2115:             my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
 2116:             my %reply=&get($space,[$item]);
 2117:             return $reply{$item};
 2118:         }
 2119:     } elsif ($realm eq 'request') {
 2120: # ------------------------------------------------------------- request.browser
 2121:         if ($space eq 'browser') {
 2122: 	    return $ENV{'browser.'.$qualifier};
 2123: # ------------------------------------------------------------ request.filename
 2124:         } else {
 2125:             return $ENV{'request.'.$spacequalifierrest};
 2126:         }
 2127:     } elsif ($realm eq 'course') {
 2128: # ---------------------------------------------------------- course.description
 2129:         return $ENV{'course.'.$ENV{'request.course.id'}.'.'.
 2130:                               $spacequalifierrest};
 2131:     } elsif ($realm eq 'resource') {
 2132:        if ($ENV{'request.course.id'}) {
 2133: 
 2134: #	   print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 2135: 
 2136: 
 2137: # ----------------------------------------------------- Cascading lookup scheme
 2138:          my $symbp;
 2139:          if ($symbparm) {
 2140:             $symbp=$symbparm;
 2141: 	 } else {
 2142:             $symbp=&symbread();
 2143:          }            
 2144:          my $mapp=(split(/\_\_\_/,$symbp))[0];
 2145: 
 2146:          my $symbparm=$symbp.'.'.$spacequalifierrest;
 2147:          my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 2148: 
 2149:          my $seclevel=
 2150:             $ENV{'request.course.id'}.'.['.
 2151: 		$ENV{'request.course.sec'}.'].'.$spacequalifierrest;
 2152:          my $seclevelr=
 2153:             $ENV{'request.course.id'}.'.['.
 2154: 		$ENV{'request.course.sec'}.'].'.$symbparm;
 2155:          my $seclevelm=
 2156:             $ENV{'request.course.id'}.'.['.
 2157: 		$ENV{'request.course.sec'}.'].'.$mapparm;
 2158: 
 2159:          my $courselevel=
 2160:             $ENV{'request.course.id'}.'.'.$spacequalifierrest;
 2161:          my $courselevelr=
 2162:             $ENV{'request.course.id'}.'.'.$symbparm;
 2163:          my $courselevelm=
 2164:             $ENV{'request.course.id'}.'.'.$mapparm;
 2165: 
 2166: # ----------------------------------------------------------- first, check user
 2167:          my %resourcedata=get('resourcedata',
 2168:                            [$courselevelr,$courselevelm,$courselevel]);
 2169:          if (($resourcedata{$courselevelr}!~/^error\:/) &&
 2170:              ($resourcedata{$courselevelr}!~/^con_lost/)) {
 2171: 
 2172:          if ($resourcedata{$courselevelr}) { 
 2173:             return $resourcedata{$courselevelr}; }
 2174:          if ($resourcedata{$courselevelm}) { 
 2175:             return $resourcedata{$courselevelm}; }
 2176:          if ($resourcedata{$courselevel}) { return $resourcedata{$courselevel}; }
 2177: 
 2178:       } else {
 2179: 	  if ($resourcedata{$courselevelr}!~/No such file/) {
 2180: 	    &logthis("<font color=blue>WARNING:".
 2181: 		   " Trying to get resource data for ".$ENV{'user.name'}." at "
 2182:                    .$ENV{'user.domain'}.": ".$resourcedata{$courselevelr}.
 2183:                  "</font>");
 2184: 	  }
 2185:       }
 2186: 
 2187: # -------------------------------------------------------- second, check course
 2188: 
 2189:         my $reply=&reply('get:'.
 2190:               $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
 2191:               $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
 2192: 	      ':resourcedata:'.
 2193:    &escape($seclevelr).'&'.&escape($seclevelm).'&'.&escape($seclevel).'&'.
 2194:    &escape($courselevelr).'&'.&escape($courselevelm).'&'.&escape($courselevel),
 2195: 		   $ENV{'course.'.$ENV{'request.course.id'}.'.home'});
 2196:       if ($reply!~/^error\:/) {
 2197: 	  map {
 2198: 	      if ($_) { return &unescape($_); }
 2199:           } split(/\&/,$reply);
 2200:       }
 2201:       if (($reply=~/^con_lost/) || ($reply=~/^error\:/)) {
 2202: 	  &logthis("<font color=blue>WARNING:".
 2203:                 " Getting ".$reply." asking for ".$varname." for ".
 2204:                 $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
 2205:                 ' at '.
 2206:                 $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.
 2207:                 ' from '.
 2208:                 $ENV{'course.'.$ENV{'request.course.id'}.'.home'}.
 2209:                  "</font>");
 2210:       }
 2211: # ------------------------------------------------------ third, check map parms
 2212:        my %parmhash=();
 2213:        my $thisparm='';       
 2214:        if (tie(%parmhash,'GDBM_File',
 2215:           $ENV{'request.course.fn'}.'_parms.db',&GDBM_READER,0640)) {
 2216:            $thisparm=$parmhash{$symbparm};
 2217: 	   untie(%parmhash);
 2218:        }
 2219:        if ($thisparm) { return $thisparm; }
 2220:      }
 2221:      
 2222: # --------------------------------------------- last, look in resource metadata
 2223: 
 2224:       $spacequalifierrest=~s/\./\_/;
 2225:       my $metadata=&metadata($ENV{'request.filename'},$spacequalifierrest);
 2226:       if ($metadata) { return $metadata; }
 2227:       $metadata=&metadata($ENV{'request.filename'},
 2228:                                          'parameter_'.$spacequalifierrest);
 2229:       if ($metadata) { return $metadata; }
 2230: 
 2231: # ------------------------------------------------------------------ Cascade up
 2232: 
 2233:       unless ($space eq '0') {
 2234:           my ($part,$id)=split(/\_/,$space);
 2235:           if ($id) {
 2236: 	      my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 2237:                                    $symbparm);
 2238:               if ($partgeneral) { return $partgeneral; }
 2239:           } else {
 2240:               my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
 2241:                                        $symbparm);
 2242:               if ($resourcegeneral) { return $resourcegeneral; }
 2243:           }
 2244:       }
 2245: 
 2246: # ---------------------------------------------------- Any other user namespace
 2247:     } elsif ($realm eq 'environment') {
 2248: # ----------------------------------------------------------------- environment
 2249:         return $ENV{'environment.'.$spacequalifierrest};
 2250:     } elsif ($realm eq 'system') {
 2251: # ----------------------------------------------------------------- system.time
 2252: 	if ($space eq 'time') {
 2253: 	    return time;
 2254:         }
 2255:     }
 2256:     return '';
 2257: }
 2258: 
 2259: # ---------------------------------------------------------------- Get metadata
 2260: 
 2261: sub metadata {
 2262:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 2263: 
 2264:     $uri=&declutter($uri);
 2265:     my $filename=$uri;
 2266:     $uri=~s/\.meta$//;
 2267: #
 2268: # Is the metadata already cached?
 2269: # Look at timestamp of caching
 2270: # Everything is cached by the main uri, libraries are never directly cached
 2271: #
 2272:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600) {
 2273: #
 2274: # Is this a recursive call for a library?
 2275: #
 2276:         if ($liburi) {
 2277: 	    $liburi=&declutter($liburi);
 2278:             $filename=$liburi;
 2279:         }
 2280:         my %metathesekeys=();
 2281:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 2282: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
 2283:         my $parser=HTML::TokeParser->new(\$metastring);
 2284:         my $token;
 2285:         undef %metathesekeys;
 2286:         while ($token=$parser->get_token) {
 2287:            if ($token->[0] eq 'S') {
 2288: 	     if (defined($token->[2]->{'package'})) {
 2289: #
 2290: # This is a package - get package info
 2291: #
 2292: 	      my $package=$token->[2]->{'package'};
 2293: 	      my $keyroot='';
 2294:               if ($prefix) {
 2295: 		  $keyroot.='_'.$prefix;
 2296:               } else {
 2297:                 if (defined($token->[2]->{'part'})) { 
 2298:                    $keyroot.='_'.$token->[2]->{'part'}; 
 2299: 	        }
 2300: 	      }
 2301:               if (defined($token->[2]->{'id'})) { 
 2302:                  $keyroot.='_'.$token->[2]->{'id'}; 
 2303: 	      }
 2304:               if ($metacache{$uri.':packages'}) {
 2305:                  $metacache{$uri.':packages'}.=','.$package.$keyroot;
 2306:               } else {
 2307:                  $metacache{$uri.':packages'}=$package.$keyroot;
 2308: 	      }
 2309:               map {
 2310: 		  if ($_=~/^$package\&/) {
 2311: 		      my ($pack,$name,$subp)=split(/\&/,$_);
 2312:                       my $value=$packagetab{$_};
 2313: 		      my $part=$keyroot;
 2314:                       $part=~s/^\_//;
 2315:                       if ($subp eq 'display') {
 2316: 			  $value.=' [Part: '.$part.']';
 2317:                       }
 2318:                       my $unikey='parameter'.$keyroot.'_'.$name;
 2319:                       $metathesekeys{$unikey}=1;
 2320:                       $metacache{$uri.':'.$unikey.'.part'}=$part;
 2321:                       unless 
 2322:                        (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
 2323:                          $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
 2324: 		      }
 2325:                   }
 2326:               } keys %packagetab;
 2327:              } else {
 2328: #
 2329: # This is not a package - some other kind of start tag
 2330: # 
 2331:               my $entry=$token->[1];
 2332:               my $unikey;
 2333:               if ($entry eq 'import') {
 2334:                  $unikey='';
 2335:               } else {
 2336:                  $unikey=$entry;
 2337: 	      }
 2338:               if ($prefix) {
 2339: 		  $unikey.=$prefix;
 2340:               } else {
 2341:                 if (defined($token->[2]->{'part'})) { 
 2342:                    $unikey.='_'.$token->[2]->{'part'}; 
 2343: 	        }
 2344: 	      }
 2345:               if (defined($token->[2]->{'id'})) { 
 2346:                  $unikey.='_'.$token->[2]->{'id'}; 
 2347: 	      }
 2348: 
 2349:              if ($entry eq 'import') {
 2350: #
 2351: # Importing a library here
 2352: #                
 2353: 		 if (defined($depthcount)) { $depthcount++; } else 
 2354:                                            { $depthcount=0; }
 2355:                  if ($depthcount<20) {
 2356: 		     map {
 2357:                          $metathesekeys{$_}=1;
 2358: 		     } split(/\,/,&metadata($uri,'keys',
 2359:                                   $parser->get_text('/import'),$unikey,
 2360:                                   $depthcount));
 2361: 		 }
 2362:              } else { 
 2363: 
 2364:               if (defined($token->[2]->{'name'})) { 
 2365:                  $unikey.='_'.$token->[2]->{'name'}; 
 2366: 	      }
 2367:               $metathesekeys{$unikey}=1;
 2368:               map {
 2369: 		  $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
 2370:               } @{$token->[3]};
 2371:               unless (
 2372:                  $metacache{$uri.':'.$unikey}=$parser->get_text('/'.$entry)
 2373: 		      ) { $metacache{$uri.':'.$unikey}=
 2374: 			      $metacache{$uri.':'.$unikey.'.default'};
 2375: 		      }
 2376: # end of not-a-package not-a-library import
 2377: 	   }
 2378: # end of not-a-package start tag
 2379: 	  }
 2380: # the next is the end of "start tag"
 2381: 	 }
 2382:        }
 2383:        $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
 2384:        $metacache{$uri.':cachedtimestamp'}=time;
 2385: # this is the end of "was not already recently cached
 2386:     }
 2387:     return $metacache{$uri.':'.$what};
 2388: }
 2389: 
 2390: # ------------------------------------------------- Update symbolic store links
 2391: 
 2392: sub symblist {
 2393:     my ($mapname,%newhash)=@_;
 2394:     $mapname=declutter($mapname);
 2395:     my %hash;
 2396:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 2397:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 2398:                       &GDBM_WRCREAT,0640)) {
 2399: 	    map {
 2400:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
 2401:             } keys %newhash;
 2402:             if (untie(%hash)) {
 2403: 		return 'ok';
 2404:             }
 2405:         }
 2406:     }
 2407:     return 'error';
 2408: }
 2409: 
 2410: # ------------------------------------------------------ Return symb list entry
 2411: 
 2412: sub symbread {
 2413:     my $thisfn=shift;
 2414:     unless ($thisfn) {
 2415:         if ($ENV{'request.symb'}) { return $ENV{'request.symb'}; }
 2416: 	$thisfn=$ENV{'request.filename'};
 2417:     }
 2418:     $thisfn=declutter($thisfn);
 2419:     my %hash;
 2420:     my %bighash;
 2421:     my $syval='';
 2422:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 2423:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 2424:                       &GDBM_READER,0640)) {
 2425: 	    $syval=$hash{$thisfn};
 2426:             untie(%hash);
 2427:         }
 2428: # ---------------------------------------------------------- There was an entry
 2429:         if ($syval) {
 2430:            unless ($syval=~/\_\d+$/) {
 2431: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 2432:                   &appenv('request.ambiguous' => $thisfn);
 2433:                   return '';
 2434:                }    
 2435:                $syval.=$1;
 2436: 	   }
 2437:         } else {
 2438: # ------------------------------------------------------- Was not in symb table
 2439:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 2440:                             &GDBM_READER,0640)) {
 2441: # ---------------------------------------------- Get ID(s) for current resource
 2442:               my $ids=$bighash{'ids_/res/'.$thisfn};
 2443:               unless ($ids) { 
 2444:                  $ids=$bighash{'ids_/'.$thisfn};
 2445:               }
 2446:               if ($ids) {
 2447: # ------------------------------------------------------------------- Has ID(s)
 2448:                  my @possibilities=split(/\,/,$ids);
 2449:                  if ($#possibilities==0) {
 2450: # ----------------------------------------------- There is only one possibility
 2451: 		     my ($mapid,$resid)=split(/\./,$ids);
 2452:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 2453:                  } else {
 2454: # ------------------------------------------ There is more than one possibility
 2455:                      my $realpossible=0;
 2456:                      map {
 2457: 			 my $file=$bighash{'src_'.$_};
 2458:                          if (&allowed('bre',$file)) {
 2459:          		    my ($mapid,$resid)=split(/\./,$_);
 2460:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 2461: 				$realpossible++;
 2462:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 2463:                                        '___'.$resid;
 2464:                             }
 2465: 			 }
 2466:                      } @possibilities;
 2467: 		     if ($realpossible!=1) { $syval=''; }
 2468:                  }
 2469: 	      }
 2470:               untie(%bighash)
 2471:            } 
 2472:         }
 2473:         if ($syval) {
 2474:            return $syval.'___'.$thisfn; 
 2475:         }
 2476:     }
 2477:     &appenv('request.ambiguous' => $thisfn);
 2478:     return '';
 2479: }
 2480: 
 2481: # ---------------------------------------------------------- Return random seed
 2482: 
 2483: sub numval {
 2484:     my $txt=shift;
 2485:     $txt=~tr/A-J/0-9/;
 2486:     $txt=~tr/a-j/0-9/;
 2487:     $txt=~tr/K-T/0-9/;
 2488:     $txt=~tr/k-t/0-9/;
 2489:     $txt=~tr/U-Z/0-5/;
 2490:     $txt=~tr/u-z/0-5/;
 2491:     $txt=~s/\D//g;
 2492:     return int($txt);
 2493: }    
 2494: 
 2495: sub rndseed {
 2496:     my ($symb,$courseid,$domain,$username)=@_;
 2497:     if (!$symb) {
 2498:       unless ($symb=&symbread()) { return time; }
 2499:     }
 2500:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
 2501:     if (!$domain) {$domain=$ENV{'user.domain'};}
 2502:     if (!$username) {$username=$ENV{'user.name'};}
 2503:     {
 2504:       use integer;
 2505:       my $symbchck=unpack("%32C*",$symb) << 27;
 2506:       my $symbseed=numval($symb) << 22;
 2507:       my $namechck=unpack("%32C*",$username) << 17;
 2508:       my $nameseed=numval($username) << 12;
 2509:       my $domainseed=unpack("%32C*",$domain) << 7;
 2510:       my $courseseed=unpack("%32C*",$courseid);
 2511:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 2512:       #uncommenting these lines can break things!
 2513:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 2514:       #&Apache::lonxml::debug("rndseed :$num:$symb");
 2515:       return $num;
 2516:     }
 2517: }
 2518: 
 2519: sub ireceipt {
 2520:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
 2521:     my $cuname=unpack("%32C*",$funame);
 2522:     my $cudom=unpack("%32C*",$fudom);
 2523:     my $cucourseid=unpack("%32C*",$fucourseid);
 2524:     my $cusymb=unpack("%32C*",$fusymb);
 2525:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
 2526:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
 2527:            ($cunique%$cuname+
 2528:             $cunique%$cudom+
 2529:             $cusymb%$cuname+
 2530:             $cusymb%$cudom+
 2531:             $cucourseid%$cuname+
 2532:             $cucourseid%$cudom);
 2533: }
 2534: 
 2535: sub receipt {
 2536:     return &ireceipt($ENV{'user.name'},$ENV{'user.domain'},
 2537:                      $ENV{'request.course.id'},&symbread());
 2538: }
 2539:   
 2540: # ------------------------------------------------------------ Serves up a file
 2541: # returns either the contents of the file or a -1
 2542: sub getfile {
 2543:   my $file=shift;
 2544:   &repcopy($file);
 2545:   if (! -e $file ) { return -1; };
 2546:   my $fh=Apache::File->new($file);
 2547:   my $a='';
 2548:   while (<$fh>) { $a .=$_; }
 2549:   return $a
 2550: }
 2551: 
 2552: sub filelocation {
 2553:   my ($dir,$file) = @_;
 2554:   my $location;
 2555:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 2556:   if ($file=~m:^/~:) { # is a contruction space reference
 2557:     $location = $file;
 2558:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 2559:   } else {
 2560:     $file=~s/^$perlvar{'lonDocRoot'}//;
 2561:     $file=~s:^/*res::;
 2562:     if ( !( $file =~ m:^/:) ) {
 2563:       $location = $dir. '/'.$file;
 2564:     } else {
 2565:       $location = '/home/httpd/html/res'.$file;
 2566:     }
 2567:   }
 2568:   $location=~s://+:/:g; # remove duplicate /
 2569:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 2570:   return $location;
 2571: }
 2572: 
 2573: sub hreflocation {
 2574:     my ($dir,$file)=@_;
 2575:     unless (($_=~/^http:\/\//i) || ($_=~/^\//)) {
 2576:        my $finalpath=filelocation($dir,$file);
 2577:        $finalpath=~s/^\/home\/httpd\/html//;
 2578:        return $finalpath;
 2579:     } else {
 2580:        return $file;
 2581:     }
 2582: }
 2583: 
 2584: # ------------------------------------------------------------- Declutters URLs
 2585: 
 2586: sub declutter {
 2587:     my $thisfn=shift;
 2588:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
 2589:     $thisfn=~s/^\///;
 2590:     $thisfn=~s/^res\///;
 2591:     return $thisfn;
 2592: }
 2593: 
 2594: # -------------------------------------------------------- Escape Special Chars
 2595: 
 2596: sub escape {
 2597:     my $str=shift;
 2598:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 2599:     return $str;
 2600: }
 2601: 
 2602: # ----------------------------------------------------- Un-Escape Special Chars
 2603: 
 2604: sub unescape {
 2605:     my $str=shift;
 2606:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2607:     return $str;
 2608: }
 2609: 
 2610: # ================================================================ Main Program
 2611: 
 2612: sub goodbye {
 2613:    &flushcourselogs();
 2614:    &logthis("Shutting down");
 2615: }
 2616: 
 2617: BEGIN {
 2618: # ------------------------------------------------------------ Read access.conf
 2619: {
 2620:     my $config=Apache::File->new("/etc/httpd/conf/access.conf");
 2621: 
 2622:     while (my $configline=<$config>) {
 2623:         if ($configline =~ /PerlSetVar/) {
 2624: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 2625:            chomp($varvalue);
 2626:            $perlvar{$varname}=$varvalue;
 2627:         }
 2628:     }
 2629: }
 2630: 
 2631: # ------------------------------------------------------------- Read hosts file
 2632: {
 2633:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
 2634: 
 2635:     while (my $configline=<$config>) {
 2636:        chomp($configline);
 2637:        my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
 2638:        $hostname{$id}=$name;
 2639:        $hostdom{$id}=$domain;
 2640:        $hostip{$id}=$ip;
 2641:        if ($role eq 'library') { $libserv{$id}=$name; }
 2642:     }
 2643: }
 2644: 
 2645: # ------------------------------------------------------ Read spare server file
 2646: {
 2647:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
 2648: 
 2649:     while (my $configline=<$config>) {
 2650:        chomp($configline);
 2651:        if (($configline) && ($configline ne $perlvar{'lonHostID'})) {
 2652:           $spareid{$configline}=1;
 2653:        }
 2654:     }
 2655: }
 2656: # ------------------------------------------------------------ Read permissions
 2657: {
 2658:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
 2659: 
 2660:     while (my $configline=<$config>) {
 2661:        chomp($configline);
 2662:       if ($configline) {
 2663:        my ($role,$perm)=split(/ /,$configline);
 2664:        if ($perm ne '') { $pr{$role}=$perm; }
 2665:       }
 2666:     }
 2667: }
 2668: 
 2669: # -------------------------------------------- Read plain texts for permissions
 2670: {
 2671:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
 2672: 
 2673:     while (my $configline=<$config>) {
 2674:        chomp($configline);
 2675:       if ($configline) {
 2676:        my ($short,$plain)=split(/:/,$configline);
 2677:        if ($plain ne '') { $prp{$short}=$plain; }
 2678:       }
 2679:     }
 2680: }
 2681: 
 2682: # ---------------------------------------------------------- Read package table
 2683: {
 2684:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
 2685: 
 2686:     while (my $configline=<$config>) {
 2687:        chomp($configline);
 2688:        my ($short,$plain)=split(/:/,$configline);
 2689:        my ($pack,$name)=split(/\&/,$short);
 2690:        if ($plain ne '') {
 2691:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
 2692:           $packagetab{$short}=$plain; 
 2693:        }
 2694:     }
 2695: }
 2696: 
 2697: # ------------------------------------------------------------- Read file types
 2698: {
 2699:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/filetypes.tab");
 2700: 
 2701:     while (my $configline=<$config>) {
 2702:        next if ($configline =~ /^\#/);
 2703:        chomp($configline);
 2704:        my ($ending,$emb,@descr)=split(/\s+/,$configline);
 2705:        if ($descr[0] ne '') { 
 2706:          $fe{$ending}=lc($emb);
 2707:          $fd{$ending}=join(' ',@descr);
 2708:        }
 2709:     }
 2710: }
 2711: 
 2712: %metacache=();
 2713: 
 2714: &logtouch();
 2715: &logthis('<font color=yellow>INFO: Read configuration</font>');
 2716: }
 2717: 
 2718: 1;

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