File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.188: download - view: text, annotated - select for diffs
Fri Dec 7 20:17:44 2001 UTC (22 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Logging looks like it works.

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

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