File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.182: download - view: text, annotated - select for diffs
Wed Dec 5 14:48:28 2001 UTC (22 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added comment character ^\# for filetypes.tab

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

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