File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.60: download - view: text, annotated - select for diffs
Tue Nov 14 02:39:30 2000 UTC (23 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Cascading resource parameters in EXT

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # Functions for use by content handlers:
    5: #
    6: # plaintext(short)   : plain text explanation of short term
    7: # fileembstyle(ext)  : embed style in page for file extension
    8: # filedescription(ext) : descriptor text for file extension
    9: # allowed(short,url) : returns codes for allowed actions 
   10: #                      F: full access
   11: #                      U,I,K: authentication modes (cxx only)
   12: #                      '': forbidden
   13: #                      1: user needs to choose course
   14: #                      2: browse allowed
   15: # definerole(rolename,sys,dom,cou) : define a custom role rolename
   16: #                      set priviledges in format of lonTabs/roles.tab for
   17: #                      system, domain and course level, 
   18: # assignrole(udom,uname,url,role,end,start) : give a role to a user for the
   19: #                      level given by url. Optional start and end dates
   20: #                      (leave empty string or zero for "no date") 
   21: # assigncustomrole (udom,uname,url,rdom,rnam,rolename,end,start) : give a
   22: #                      custom role to a user for the level given by url.
   23: #                      Specify name and domain of role author, and role name
   24: # revokerole (udom,uname,url,role) : Revoke a role for url
   25: # revokecustomrole (udom,uname,url,rdom,rnam,rolename) : Revoke a custom role
   26: # appenv(hash)       : adds hash to session environment
   27: # delenv(varname)    : deletes all environment entries starting with varname
   28: # store(hash)        : stores hash permanently for this url
   29: # cstore(hash)       : critical store
   30: # restore            : returns hash for this url
   31: # eget(namesp,array) : returns hash with keys from array filled in from namesp
   32: # get(namesp,array)  : returns hash with keys from array filled in from namesp
   33: # del(namesp,array)  : deletes keys out of array from namesp
   34: # put(namesp,hash)   : stores hash in namesp
   35: # cput(namesp,hash)  : critical put
   36: # dump(namesp)       : dumps the complete namespace into a hash
   37: # ssi(url,hash)      : does a complete request cycle on url to localhost, posts
   38: #                      hash
   39: # coursedescription(id) : returns and caches course description for id
   40: # repcopy(filename)  : replicate file
   41: # dirlist(url)       : gets a directory listing
   42: # directcondval(index) : reading condition value of single condition from 
   43: #                        state string
   44: # condval(index)     : value of condition index based on state
   45: # EXT(name)          : value of a variable
   46: # refreshstate()     : refresh the state information string
   47: # symblist(map,hash) : Updates symbolic storage links
   48: # symbread([filename]) : returns the data handle (filename optional)
   49: # rndseed()          : returns a random seed  
   50: # getfile(filename)  : returns the contents of filename, or a -1 if it can't
   51: #                      be found, replicates and subscribes to the file
   52: # filelocation(dir,file) : returns a farily clean absolute reference to file 
   53: #                          from the directory dir
   54: # hreflocation(dir,file) : same as filelocation, but for hrefs
   55: # log(domain,user,home,msg) : write to permanent log for user
   56: #
   57: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
   58: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
   59: # 11/8,11/16,11/18,11/22,11/23,12/22,
   60: # 01/06,01/13,02/24,02/28,02/29,
   61: # 03/01,03/02,03/06,03/07,03/13,
   62: # 04/05,05/29,05/31,06/01,
   63: # 06/05,06/26 Gerd Kortemeyer
   64: # 06/26 Ben Tyszka
   65: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
   66: # 08/14 Ben Tyszka
   67: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
   68: # 10/04 Gerd Kortemeyer
   69: # 10/04 Guy Albertelli
   70: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
   71: # 10/30,10/31,11/2,11/14 Gerd Kortemeyer
   72: 
   73: package Apache::lonnet;
   74: 
   75: use strict;
   76: use Apache::File;
   77: use LWP::UserAgent();
   78: use HTTP::Headers;
   79: use vars 
   80: qw(%perlvar %hostname %homecache %spareid %hostdom %libserv %pr %prp %fe %fd $readit);
   81: use IO::Socket;
   82: use GDBM_File;
   83: use Apache::Constants qw(:common :http);
   84: 
   85: # --------------------------------------------------------------------- Logging
   86: 
   87: sub logthis {
   88:     my $message=shift;
   89:     my $execdir=$perlvar{'lonDaemons'};
   90:     my $now=time;
   91:     my $local=localtime($now);
   92:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
   93:     print $fh "$local ($$): $message\n";
   94:     return 1;
   95: }
   96: 
   97: sub logperm {
   98:     my $message=shift;
   99:     my $execdir=$perlvar{'lonDaemons'};
  100:     my $now=time;
  101:     my $local=localtime($now);
  102:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
  103:     print $fh "$now:$message:$local\n";
  104:     return 1;
  105: }
  106: 
  107: # -------------------------------------------------- Non-critical communication
  108: sub subreply {
  109:     my ($cmd,$server)=@_;
  110:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  111:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  112:                                      Type    => SOCK_STREAM,
  113:                                      Timeout => 10)
  114:        or return "con_lost";
  115:     print $client "$cmd\n";
  116:     my $answer=<$client>;
  117:     if (!$answer) { $answer="con_lost"; }
  118:     chomp($answer);
  119:     return $answer;
  120: }
  121: 
  122: sub reply {
  123:     my ($cmd,$server)=@_;
  124:     my $answer=subreply($cmd,$server);
  125:     if ($answer eq 'con_lost') { $answer=subreply($cmd,$server); }
  126:     if (($answer=~/^error:/) || ($answer=~/^refused/) || 
  127:         ($answer=~/^rejected/)) {
  128:        &logthis("<font color=blue>WARNING:".
  129:                 " $cmd to $server returned $answer</font>");
  130:     }
  131:     return $answer;
  132: }
  133: 
  134: # ----------------------------------------------------------- Send USR1 to lonc
  135: 
  136: sub reconlonc {
  137:     my $peerfile=shift;
  138:     &logthis("Trying to reconnect for $peerfile");
  139:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  140:     if (my $fh=Apache::File->new("$loncfile")) {
  141: 	my $loncpid=<$fh>;
  142:         chomp($loncpid);
  143:         if (kill 0 => $loncpid) {
  144: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  145:             kill USR1 => $loncpid;
  146:             sleep 1;
  147:             if (-e "$peerfile") { return; }
  148:             &logthis("$peerfile still not there, give it another try");
  149:             sleep 5;
  150:             if (-e "$peerfile") { return; }
  151:             &logthis(
  152:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  153:         } else {
  154: 	    &logthis(
  155:                "<font color=blue>WARNING:".
  156:                " lonc at pid $loncpid not responding, giving up</font>");
  157:         }
  158:     } else {
  159:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
  160:     }
  161: }
  162: 
  163: # ------------------------------------------------------ Critical communication
  164: 
  165: sub critical {
  166:     my ($cmd,$server)=@_;
  167:     my $answer=reply($cmd,$server);
  168:     if ($answer eq 'con_lost') {
  169:         my $pingreply=reply('ping',$server);
  170: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  171:         my $pongreply=reply('pong',$server);
  172:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
  173:         $answer=reply($cmd,$server);
  174:         if ($answer eq 'con_lost') {
  175:             my $now=time;
  176:             my $middlename=$cmd;
  177:             $middlename=substr($middlename,0,16);
  178:             $middlename=~s/\W//g;
  179:             my $dfilename=
  180:              "$perlvar{'lonSockDir'}/delayed/$now.$middlename.$server";
  181:             {
  182:              my $dfh;
  183:              if ($dfh=Apache::File->new(">$dfilename")) {
  184:                 print $dfh "$cmd\n";
  185: 	     }
  186:             }
  187:             sleep 2;
  188:             my $wcmd='';
  189:             {
  190: 	     my $dfh;
  191:              if ($dfh=Apache::File->new("$dfilename")) {
  192:                 $wcmd=<$dfh>;
  193: 	     }
  194:             }
  195:             chomp($wcmd);
  196:             if ($wcmd eq $cmd) {
  197: 		&logthis("<font color=blue>WARNING: ".
  198:                          "Connection buffer $dfilename: $cmd</font>");
  199:                 &logperm("D:$server:$cmd");
  200: 	        return 'con_delayed';
  201:             } else {
  202:                 &logthis("<font color=red>CRITICAL:"
  203:                         ." Critical connection failed: $server $cmd</font>");
  204:                 &logperm("F:$server:$cmd");
  205:                 return 'con_failed';
  206:             }
  207:         }
  208:     }
  209:     return $answer;
  210: }
  211: 
  212: # ---------------------------------------------------------- Append Environment
  213: 
  214: sub appenv {
  215:     my %newenv=@_;
  216:     map {
  217: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
  218:             &logthis("<font color=blue>WARNING: ".
  219:                 "Attempt to modify environment ".$_." to ".$newenv{$_});
  220: 	    delete($newenv{$_});
  221:         } else {
  222:             $ENV{$_}=$newenv{$_};
  223:         }
  224:     } keys %newenv;
  225:     my @oldenv;
  226:     {
  227:      my $fh;
  228:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  229: 	return 'error';
  230:      }
  231:      @oldenv=<$fh>;
  232:     }
  233:     for (my $i=0; $i<=$#oldenv; $i++) {
  234:         chomp($oldenv[$i]);
  235:         if ($oldenv[$i] ne '') {
  236:            my ($name,$value)=split(/=/,$oldenv[$i]);
  237:            unless (defined($newenv{$name})) {
  238: 	      $newenv{$name}=$value;
  239: 	   }
  240:         }
  241:     }
  242:     {
  243:      my $fh;
  244:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  245: 	return 'error';
  246:      }
  247:      my $newname;
  248:      foreach $newname (keys %newenv) {
  249: 	 print $fh "$newname=$newenv{$newname}\n";
  250:      }
  251:     }
  252:     return 'ok';
  253: }
  254: # ----------------------------------------------------- Delete from Environment
  255: 
  256: sub delenv {
  257:     my $delthis=shift;
  258:     my %newenv=();
  259:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  260:         &logthis("<font color=blue>WARNING: ".
  261:                 "Attempt to delete from environment ".$delthis);
  262:         return 'error';
  263:     }
  264:     my @oldenv;
  265:     {
  266:      my $fh;
  267:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  268: 	return 'error';
  269:      }
  270:      @oldenv=<$fh>;
  271:     }
  272:     {
  273:      my $fh;
  274:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  275: 	return 'error';
  276:      }
  277:      map {
  278: 	 unless ($_=~/^$delthis/) { print $fh $_; }
  279:      } @oldenv;
  280:     }
  281:     return 'ok';
  282: }
  283: 
  284: # ------------------------------ Find server with least workload from spare.tab
  285: 
  286: sub spareserver {
  287:     my $tryserver;
  288:     my $spareserver='';
  289:     my $lowestserver=100;
  290:     foreach $tryserver (keys %spareid) {
  291:        my $answer=reply('load',$tryserver);
  292:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  293: 	   $spareserver="http://$hostname{$tryserver}";
  294:            $lowestserver=$answer;
  295:        }
  296:     }    
  297:     return $spareserver;
  298: }
  299: 
  300: # --------- Try to authenticate user from domain's lib servers (first this one)
  301: 
  302: sub authenticate {
  303:     my ($uname,$upass,$udom)=@_;
  304:     $upass=escape($upass);
  305:     if (($perlvar{'lonRole'} eq 'library') && 
  306:         ($udom eq $perlvar{'lonDefDomain'})) {
  307:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
  308:         if ($answer =~ /authorized/) {
  309:               if ($answer eq 'authorized') {
  310:                  &logthis("User $uname at $udom authorized by local server"); 
  311:                  return $perlvar{'lonHostID'}; 
  312:               }
  313:               if ($answer eq 'non_authorized') {
  314:                  &logthis("User $uname at $udom rejected by local server"); 
  315:                  return 'no_host'; 
  316:               }
  317: 	}
  318:     }
  319: 
  320:     my $tryserver;
  321:     foreach $tryserver (keys %libserv) {
  322: 	if ($hostdom{$tryserver} eq $udom) {
  323:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
  324:            if ($answer =~ /authorized/) {
  325:               if ($answer eq 'authorized') {
  326:                  &logthis("User $uname at $udom authorized by $tryserver"); 
  327:                  return $tryserver; 
  328:               }
  329:               if ($answer eq 'non_authorized') {
  330:                  &logthis("User $uname at $udom rejected by $tryserver");
  331:                  return 'no_host';
  332:               } 
  333: 	   }
  334:        }
  335:     }
  336:     &logthis("User $uname at $udom could not be authenticated");    
  337:     return 'no_host';
  338: }
  339: 
  340: # ---------------------- Find the homebase for a user from domain's lib servers
  341: 
  342: sub homeserver {
  343:     my ($uname,$udom)=@_;
  344: 
  345:     my $index="$uname:$udom";
  346:     if ($homecache{$index}) { return "$homecache{$index}"; }
  347: 
  348:     my $tryserver;
  349:     foreach $tryserver (keys %libserv) {
  350: 	if ($hostdom{$tryserver} eq $udom) {
  351:            my $answer=reply("home:$udom:$uname",$tryserver);
  352:            if ($answer eq 'found') { 
  353: 	      $homecache{$index}=$tryserver;
  354:               return $tryserver; 
  355: 	   }
  356:        }
  357:     }    
  358:     return 'no_host';
  359: }
  360: 
  361: # ----------------------------- Subscribe to a resource, return URL if possible
  362: 
  363: sub subscribe {
  364:     my $fname=shift;
  365:     my $author=$fname;
  366:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  367:     my ($udom,$uname)=split(/\//,$author);
  368:     my $home=homeserver($uname,$udom);
  369:     if (($home eq 'no_host') || ($home eq $perlvar{'lonHostID'})) { 
  370:         return 'not_found'; 
  371:     }
  372:     my $answer=reply("sub:$fname",$home);
  373:     return $answer;
  374: }
  375:     
  376: # -------------------------------------------------------------- Replicate file
  377: 
  378: sub repcopy {
  379:     my $filename=shift;
  380:     $filename=~s/\/+/\//g;
  381:     my $transname="$filename.in.transfer";
  382:     if ((-e $filename) || (-e $transname)) { return OK; }
  383:     my $remoteurl=subscribe($filename);
  384:     if ($remoteurl eq 'con_lost') {
  385: 	   &logthis("Subscribe returned con_lost: $filename");
  386:            return HTTP_SERVICE_UNAVAILABLE;
  387:     } elsif ($remoteurl eq 'not_found') {
  388: 	   &logthis("Subscribe returned not_found: $filename");
  389: 	   return HTTP_NOT_FOUND;
  390:     } elsif ($remoteurl eq 'rejected') {
  391: 	   &logthis("Subscribe returned rejected: $filename");
  392:            return FORBIDDEN;
  393:     } elsif ($remoteurl eq 'directory') {
  394:            return OK;
  395:     } else {
  396:            my @parts=split(/\//,$filename);
  397:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
  398:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
  399:                &logthis("Malconfiguration for replication: $filename");
  400: 	       return HTTP_BAD_REQUEST;
  401:            }
  402:            my $count;
  403:            for ($count=5;$count<$#parts;$count++) {
  404:                $path.="/$parts[$count]";
  405:                if ((-e $path)!=1) {
  406: 		   mkdir($path,0777);
  407:                }
  408:            }
  409:            my $ua=new LWP::UserAgent;
  410:            my $request=new HTTP::Request('GET',"$remoteurl");
  411:            my $response=$ua->request($request,$transname);
  412:            if ($response->is_error()) {
  413: 	       unlink($transname);
  414:                my $message=$response->status_line;
  415:                &logthis("<font color=blue>WARNING:"
  416:                        ." LWP get: $message: $filename</font>");
  417:                return HTTP_SERVICE_UNAVAILABLE;
  418:            } else {
  419: 	       if ($remoteurl!~/\.meta$/) {
  420:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
  421:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
  422:                   if ($mresponse->is_error()) {
  423: 		      unlink($filename.'.meta');
  424:                       &logthis(
  425:                      "<font color=yellow>INFO: No metadata: $filename</font>");
  426:                   }
  427: 	       }
  428:                rename($transname,$filename);
  429:                return OK;
  430:            }
  431:     }
  432: }
  433: 
  434: # --------------------------------------------------------- Server Side Include
  435: 
  436: sub ssi {
  437: 
  438:     my ($fn,%form)=@_;
  439: 
  440:     my $ua=new LWP::UserAgent;
  441:     
  442:     my $request;
  443:     
  444:     if (%form) {
  445:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
  446:       $request->content(join '&', map { "$_=$form{$_}" } keys %form);
  447:     } else {
  448:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
  449:     }
  450: 
  451:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
  452:     my $response=$ua->request($request);
  453: 
  454:     return $response->content;
  455: }
  456: 
  457: # ------------------------------------------------------------------------- Log
  458: 
  459: sub log {
  460:     my ($dom,$nam,$hom,$what)=@_;
  461:     return critical("log:$dom:$nam:$what",$hom);
  462: }
  463: 
  464: # ----------------------------------------------------------------------- Store
  465: 
  466: sub store {
  467:     my %storehash=@_;
  468:     my $symb;
  469:     unless ($symb=escape(&symbread())) { return ''; }
  470:     my $namespace;
  471:     unless ($namespace=$ENV{'request.course.id'}) { return ''; }
  472:     my $namevalue='';
  473:     map {
  474:         $namevalue.=escape($_).'='.escape($storehash{$_}).'&';
  475:     } keys %storehash;
  476:     $namevalue=~s/\&$//;
  477:     return reply(
  478:      "store:$ENV{'user.domain'}:$ENV{'user.name'}:$namespace:$symb:$namevalue",
  479: 		 "$ENV{'user.home'}");
  480: }
  481: 
  482: # -------------------------------------------------------------- Critical Store
  483: 
  484: sub cstore {
  485:     my %storehash=@_;
  486:     my $symb;
  487:     unless ($symb=escape(&symbread())) { return ''; }
  488:     my $namespace;
  489:     unless ($namespace=$ENV{'request.course.id'}) { return ''; }
  490:     my $namevalue='';
  491:     map {
  492:         $namevalue.=escape($_).'='.escape($storehash{$_}).'&';
  493:     } keys %storehash;
  494:     $namevalue=~s/\&$//;
  495:     return critical(
  496:      "store:$ENV{'user.domain'}:$ENV{'user.name'}:$namespace:$symb:$namevalue",
  497: 		 "$ENV{'user.home'}");
  498: }
  499: 
  500: # --------------------------------------------------------------------- Restore
  501: 
  502: sub restore {
  503:     my $symb;
  504:     unless ($symb=escape(&symbread())) { return ''; }
  505:     my $namespace;
  506:     unless ($namespace=$ENV{'request.course.id'}) { return ''; }
  507:     my $answer=reply(
  508:               "restore:$ENV{'user.domain'}:$ENV{'user.name'}:$namespace:$symb",
  509:               "$ENV{'user.home'}");
  510:     my %returnhash=();
  511:     map {
  512: 	my ($name,$value)=split(/\=/,$_);
  513:         $returnhash{&unescape($name)}=&unescape($value);
  514:     } split(/\&/,$answer);
  515:     map {
  516:         $returnhash{$_}=$returnhash{$returnhash{'version'}.':'.$_};
  517:     } split(/\:/,$returnhash{$returnhash{'version'}.':keys'});
  518:     return %returnhash;
  519: }
  520: 
  521: # ---------------------------------------------------------- Course Description
  522: 
  523: sub coursedescription {
  524:     my $courseid=shift;
  525:     $courseid=~s/^\///;
  526:     $courseid=~s/\_/\//g;
  527:     my ($cdomain,$cnum)=split(/\//,$courseid);
  528:     my $chome=homeserver($cnum,$cdomain);
  529:     if ($chome ne 'no_host') {
  530:        my $rep=reply("dump:$cdomain:$cnum:environment",$chome);
  531:        if ($rep ne 'con_lost') {
  532:            my $normalid=$courseid;
  533:            $normalid=~s/\//\_/g;
  534:            my %envhash=();
  535:            my %returnhash=('home'   => $chome, 
  536:                            'domain' => $cdomain,
  537:                            'num'    => $cnum);
  538:            map {
  539:                my ($name,$value)=split(/\=/,$_);
  540:                $name=&unescape($name);
  541:                $value=&unescape($value);
  542:                $returnhash{$name}=$value;
  543:                $envhash{'course.'.$normalid.'.'.$name}=$value;
  544:            } split(/\&/,$rep);
  545:            $returnhash{'url'}='/res/'.declutter($returnhash{'url'});
  546:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
  547: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
  548:            $envhash{'course.'.$normalid.'.last_cache'}=time;
  549:            $envhash{'course.'.$normalid.'.home'}=$chome;
  550:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
  551:            $envhash{'course.'.$normalid.'.num'}=$cnum;
  552:            &appenv(%envhash);
  553:            return %returnhash;
  554:        }
  555:     }
  556:     return ();
  557: }
  558: 
  559: # -------------------------------------------------------- Get user priviledges
  560: 
  561: sub rolesinit {
  562:     my ($domain,$username,$authhost)=@_;
  563:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
  564:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
  565:     my %allroles=();
  566:     my %thesepriv=();
  567:     my $now=time;
  568:     my $userroles="user.login.time=$now\n";
  569:     my $thesestr;
  570: 
  571:     if ($rolesdump ne '') {
  572:         map {
  573: 	  if ($_!~/^rolesdef\&/) {
  574:             my ($area,$role)=split(/=/,$_);
  575:             $area=~s/\_\w\w$//;
  576:             my ($trole,$tend,$tstart)=split(/_/,$role);
  577:             $userroles.='user.role.'.$trole.'.'.$area.'='.
  578:                         $tstart.'.'.$tend."\n";
  579:             if ($tend!=0) {
  580: 	        if ($tend<$now) {
  581: 	            $trole='';
  582:                 } 
  583:             }
  584:             if ($tstart!=0) {
  585:                 if ($tstart>$now) {
  586:                    $trole='';        
  587:                 }
  588:             }
  589:             if (($area ne '') && ($trole ne '')) {
  590: 	       my $spec=$trole.'.'.$area;
  591:                my ($tdummy,$tdomain,$trest)=split(/\//,$area);
  592:                if ($trole =~ /^cr\//) {
  593: 		   my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
  594:                    my $homsvr=homeserver($rauthor,$rdomain);
  595:                    if ($hostname{$homsvr} ne '') {
  596:                       my $roledef=
  597: 			  reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
  598:                                 $homsvr);
  599:                       if (($roledef ne 'con_lost') && ($roledef ne '')) {
  600:                          my ($syspriv,$dompriv,$coursepriv)=
  601: 			     split(/\_/,unescape($roledef));
  602:  	                 $allroles{'cm./'}.=':'.$syspriv;
  603:                          $allroles{$spec.'./'}.=':'.$syspriv;
  604:                          if ($tdomain ne '') {
  605:                              $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
  606:                              $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
  607:                              if ($trest ne '') {
  608: 		                $allroles{'cm.'.$area}.=':'.$coursepriv;
  609: 		                $allroles{$spec.'.'.$area}.=':'.$coursepriv;
  610:                              }
  611: 	                 }
  612:                       }
  613:                    }
  614:                } else {
  615: 	           $allroles{'cm./'}.=':'.$pr{$trole.':s'};
  616: 	           $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
  617:                    if ($tdomain ne '') {
  618:                      $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
  619:                      $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
  620:                       if ($trest ne '') {
  621: 		          $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
  622: 		          $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
  623:                       }
  624: 	           }
  625: 	       }
  626:             }
  627:           } 
  628:         } split(/&/,$rolesdump);
  629:         map {
  630:             %thesepriv=();
  631:             map {
  632:                 if ($_ ne '') {
  633: 		    my ($priviledge,$restrictions)=split(/&/,$_);
  634:                     if ($restrictions eq '') {
  635: 			$thesepriv{$priviledge}='F';
  636:                     } else {
  637:                         if ($thesepriv{$priviledge} ne 'F') {
  638: 			    $thesepriv{$priviledge}.=$restrictions;
  639:                         }
  640:                     }
  641:                 }
  642:             } split(/:/,$allroles{$_});
  643:             $thesestr='';
  644:             map { $thesestr.=':'.$_.'&'.$thesepriv{$_}; } keys %thesepriv;
  645:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
  646:         } keys %allroles;            
  647:     }
  648:     return $userroles;  
  649: }
  650: 
  651: # --------------------------------------------------------------- get interface
  652: 
  653: sub get {
  654:    my ($namespace,@storearr)=@_;
  655:    my $items='';
  656:    map {
  657:        $items.=escape($_).'&';
  658:    } @storearr;
  659:    $items=~s/\&$//;
  660:  my $rep=reply("get:$ENV{'user.domain'}:$ENV{'user.name'}:$namespace:$items",
  661:                  $ENV{'user.home'});
  662:    my @pairs=split(/\&/,$rep);
  663:    my %returnhash=();
  664:    my $i=0;
  665:    map {
  666:       $returnhash{$_}=unescape($pairs[$i]);
  667:       $i++;
  668:    } @storearr;
  669:    return %returnhash;
  670: }
  671: 
  672: # --------------------------------------------------------------- del interface
  673: 
  674: sub del {
  675:    my ($namespace,@storearr)=@_;
  676:    my $items='';
  677:    map {
  678:        $items.=escape($_).'&';
  679:    } @storearr;
  680:    $items=~s/\&$//;
  681:    return reply("del:$ENV{'user.domain'}:$ENV{'user.name'}:$namespace:$items",
  682:                  $ENV{'user.home'});
  683: }
  684: 
  685: # -------------------------------------------------------------- dump interface
  686: 
  687: sub dump {
  688:    my $namespace=shift;
  689:    my $rep=reply("dump:$ENV{'user.domain'}:$ENV{'user.name'}:$namespace",
  690:                 $ENV{'user.home'});
  691:    my @pairs=split(/\&/,$rep);
  692:    my %returnhash=();
  693:    map {
  694:       my ($key,$value)=split(/=/,$_);
  695:       $returnhash{unescape($key)}=unescape($value);
  696:    } @pairs;
  697:    return %returnhash;
  698: }
  699: 
  700: # --------------------------------------------------------------- put interface
  701: 
  702: sub put {
  703:    my ($namespace,%storehash)=@_;
  704:    my $items='';
  705:    map {
  706:        $items.=escape($_).'='.escape($storehash{$_}).'&';
  707:    } keys %storehash;
  708:    $items=~s/\&$//;
  709:    return reply("put:$ENV{'user.domain'}:$ENV{'user.name'}:$namespace:$items",
  710:                  $ENV{'user.home'});
  711: }
  712: 
  713: # ------------------------------------------------------ critical put interface
  714: 
  715: sub cput {
  716:    my ($namespace,%storehash)=@_;
  717:    my $items='';
  718:    map {
  719:        $items.=escape($_).'='.escape($storehash{$_}).'&';
  720:    } keys %storehash;
  721:    $items=~s/\&$//;
  722:    return critical
  723:            ("put:$ENV{'user.domain'}:$ENV{'user.name'}:$namespace:$items",
  724:                  $ENV{'user.home'});
  725: }
  726: 
  727: # -------------------------------------------------------------- eget interface
  728: 
  729: sub eget {
  730:    my ($namespace,@storearr)=@_;
  731:    my $items='';
  732:    map {
  733:        $items.=escape($_).'&';
  734:    } @storearr;
  735:    $items=~s/\&$//;
  736:  my $rep=reply("eget:$ENV{'user.domain'}:$ENV{'user.name'}:$namespace:$items",
  737:                  $ENV{'user.home'});
  738:    my @pairs=split(/\&/,$rep);
  739:    my %returnhash=();
  740:    my $i=0;
  741:    map {
  742:       $returnhash{$_}=unescape($pairs[$i]);
  743:       $i++;
  744:    } @storearr;
  745:    return %returnhash;
  746: }
  747: 
  748: # ------------------------------------------------- Check for a user priviledge
  749: 
  750: sub allowed {
  751:     my ($priv,$uri)=@_;
  752:     $uri=&declutter($uri);
  753: 
  754: # Free bre access to adm and meta resources
  755: 
  756:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
  757: 	return 'F';
  758:     }
  759: 
  760:     my $thisallowed='';
  761:     my $statecond=0;
  762:     my $courseprivid='';
  763: 
  764: # Course
  765: 
  766:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
  767:        $thisallowed.=$1;
  768:     }
  769: 
  770: # Domain
  771: 
  772:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
  773:        =~/$priv\&([^\:]*)/) {
  774:        $thisallowed.=$1;
  775:     }
  776: 
  777: # Course: uri itself is a course
  778: 
  779:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$uri}
  780:        =~/$priv\&([^\:]*)/) {
  781:        $thisallowed.=$1;
  782:     }
  783: 
  784: # Full access at system, domain or course-wide level? Exit.
  785: 
  786:     if ($thisallowed=~/F/) {
  787: 	return 'F';
  788:     }
  789: 
  790: # If this is generating or modifying users, exit with special codes
  791: 
  792:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:'=~/\:$priv\:/) {
  793: 	return $thisallowed;
  794:     }
  795: #
  796: # Gathered so far: system, domain and course wide priviledges
  797: #
  798: # Course: See if uri or referer is an individual resource that is part of 
  799: # the course
  800: 
  801:     if ($ENV{'request.course.id'}) {
  802:        $courseprivid=$ENV{'request.course.id'};
  803:        if ($ENV{'request.course.sec'}) {
  804:           $courseprivid.='/'.$ENV{'request.course.sec'};
  805:        }
  806:        $courseprivid=~s/\_/\//;
  807:        my $checkreferer=1;
  808:        my @uriparts=split(/\//,$uri);
  809:        my $filename=$uriparts[$#uriparts];
  810:        my $pathname=$uri;
  811:        $pathname=~s/\/$filename$//;
  812:        if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
  813:            /\&$filename\:([\d\|]+)\&/) {
  814:            $statecond=$1;
  815:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
  816:                =~/$priv\&([^\:]*)/) {
  817:                $thisallowed.=$1;
  818:                $checkreferer=0;
  819:            }
  820:        }
  821: 
  822:        if (($ENV{'HTTP_REFERER'}) && ($checkreferer)) {
  823: 	  my $refuri=$ENV{'HTTP_REFERER'};
  824:           $refuri=~s/^http\:\/\/$ENV{'request.host'}//i;
  825:           $refuri=&declutter($refuri);
  826:           my @uriparts=split(/\//,$refuri);
  827:           my $filename=$uriparts[$#uriparts];
  828:           my $pathname=$refuri;
  829:           $pathname=~s/\/$filename$//;
  830:           my @filenameparts=split(/\./,$uri);
  831:           if (&fileembstyle($filenameparts[$#filenameparts]) ne 'ssi') {
  832:             if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
  833:               /\&$filename\:([\d\|]+)\&/) {
  834:               my $refstatecond=$1;
  835:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
  836:                   =~/$priv\&([^\:]*)/) {
  837:                   $thisallowed.=$1;
  838:                   $uri=$refuri;
  839:                   $statecond=$refstatecond;
  840:               }
  841:             }
  842:           }
  843:        }
  844:    }
  845: 
  846: #
  847: # Gathered now: all priviledges that could apply, and condition number
  848: # 
  849: #
  850: # Full or no access?
  851: #
  852: 
  853:     if ($thisallowed=~/F/) {
  854: 	return 'F';
  855:     }
  856: 
  857:     unless ($thisallowed) {
  858:         return '';
  859:     }
  860: 
  861: # Restrictions exist, deal with them
  862: #
  863: #   C:according to course preferences
  864: #   R:according to resource settings
  865: #   L:unless locked
  866: #   X:according to user session state
  867: #
  868: 
  869: # Possibly locked functionality, check all courses
  870: # Locks might take effect only after 10 minutes cache expiration for other
  871: # courses, and 2 minutes for current course
  872: 
  873:     my $envkey;
  874:     if ($thisallowed=~/L/) {
  875:         foreach $envkey (keys %ENV) {
  876:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
  877:                my $courseid=$2;
  878:                my $roleid=$1.'.'.$2;
  879:                my $expiretime=600;
  880:                if ($ENV{'request.role'} eq $roleid) {
  881: 		  $expiretime=120;
  882:                }
  883: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
  884:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
  885:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
  886: 		   &coursedescription($courseid);
  887:                }
  888:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
  889:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
  890: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
  891:                        &log($ENV{'user.domain'},$ENV{'user.name'},
  892:                             $ENV{'user.host'},
  893:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
  894:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
  895:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
  896: 		       return '';
  897:                    }
  898:                }
  899:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
  900:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
  901: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
  902:                        &log($ENV{'user.domain'},$ENV{'user.name'},
  903:                             $ENV{'user.host'},
  904:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
  905:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
  906:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
  907: 		       return '';
  908:                    }
  909:                }
  910: 	   }
  911:        }
  912:     }
  913:    
  914: #
  915: # Rest of the restrictions depend on selected course
  916: #
  917: 
  918:     unless ($ENV{'request.course.id'}) {
  919:        return '1';
  920:     }
  921: 
  922: #
  923: # Now user is definitely in a course
  924: #
  925: 
  926: 
  927: # Course preferences
  928: 
  929:    if ($thisallowed=~/C/) {
  930:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
  931:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
  932: 	   =~/\,$rolecode\,/) {
  933:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
  934:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
  935:                 $ENV{'request.course.id'});
  936:            return '';
  937:        }
  938:    }
  939: 
  940: # Resource preferences
  941: 
  942:    if ($thisallowed=~/R/) {
  943:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
  944:        my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
  945:        if (-e $filename) {
  946:            my @content;
  947:            {
  948: 	     my $fh=Apache::File->new($filename);
  949:              @content=<$fh>;
  950: 	   }
  951:            if (join('',@content)=~
  952:                     /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
  953: 	       &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
  954:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
  955:            return '';
  956: 
  957:            }
  958:        }
  959:    }
  960: 
  961: # Restricted by state?
  962: 
  963:    if ($thisallowed=~/X/) {
  964:       if (&condval($statecond)) {
  965: 	 return '2';
  966:       } else {
  967:          return '';
  968:       }
  969:    }
  970: 
  971:    return 'F';
  972: }
  973: 
  974: # ---------------------------------------------------------- Refresh State Info
  975: 
  976: sub refreshstate {
  977: }
  978: 
  979: # ----------------------------------------------------------------- Define Role
  980: 
  981: sub definerole {
  982:   if (allowed('mcr','/')) {
  983:     my ($rolename,$sysrole,$domrole,$courole)=@_;
  984:     map {
  985: 	my ($crole,$cqual)=split(/\&/,$_);
  986:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
  987:         if ($pr{'cr:s'}=~/$crole\&/) {
  988: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
  989:                return "refused:s:$crole&$cqual"; 
  990:             }
  991:         }
  992:     } split('/',$sysrole);
  993:     map {
  994: 	my ($crole,$cqual)=split(/\&/,$_);
  995:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
  996:         if ($pr{'cr:d'}=~/$crole\&/) {
  997: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
  998:                return "refused:d:$crole&$cqual"; 
  999:             }
 1000:         }
 1001:     } split('/',$domrole);
 1002:     map {
 1003: 	my ($crole,$cqual)=split(/\&/,$_);
 1004:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
 1005:         if ($pr{'cr:c'}=~/$crole\&/) {
 1006: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
 1007:                return "refused:c:$crole&$cqual"; 
 1008:             }
 1009:         }
 1010:     } split('/',$courole);
 1011:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 1012:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 1013: 	        "rolesdef_$rolename=".
 1014:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 1015:     return reply($command,$ENV{'user.home'});
 1016:   } else {
 1017:     return 'refused';
 1018:   }
 1019: }
 1020: 
 1021: # ------------------------------------------------------------------ Plain Text
 1022: 
 1023: sub plaintext {
 1024:     my $short=shift;
 1025:     return $prp{$short};
 1026: }
 1027: 
 1028: # ------------------------------------------------------------------ Plain Text
 1029: 
 1030: sub fileembstyle {
 1031:     my $ending=shift;
 1032:     return $fe{$ending};
 1033: }
 1034: 
 1035: # ------------------------------------------------------------ Description Text
 1036: 
 1037: sub filedecription {
 1038:     my $ending=shift;
 1039:     return $fd{$ending};
 1040: }
 1041: 
 1042: # ----------------------------------------------------------------- Assign Role
 1043: 
 1044: sub assignrole {
 1045:     my ($udom,$uname,$url,$role,$end,$start)=@_;
 1046:     my $mrole;
 1047:     $url=declutter($url);
 1048:     if ($role =~ /^cr\//) {
 1049:         unless ($url=~/\.course$/) { return 'invalid'; }
 1050: 	unless (allowed('ccr',$url)) { return 'refused'; }
 1051:         $mrole='cr';
 1052:     } else {
 1053:         unless (($url=~/\.course$/) || ($url=~/\/$/)) { return 'invalid'; }
 1054:         unless (allowed('c'+$role)) { return 'refused'; }
 1055:         $mrole=$role;
 1056:     }
 1057:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 1058:                 "$udom:$uname:$url".'_'."$mrole=$role";
 1059:     if ($end) { $command.='_$end'; }
 1060:     if ($start) {
 1061: 	if ($end) { 
 1062:            $command.='_$start'; 
 1063:         } else {
 1064:            $command.='_0_$start';
 1065:         }
 1066:     }
 1067:     return &reply($command,&homeserver($uname,$udom));
 1068: }
 1069: 
 1070: # ---------------------------------------------------------- Assign Custom Role
 1071: 
 1072: sub assigncustomrole {
 1073:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
 1074:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 1075:                        $end,$start);
 1076: }
 1077: 
 1078: # ----------------------------------------------------------------- Revoke Role
 1079: 
 1080: sub revokerole {
 1081:     my ($udom,$uname,$url,$role)=@_;
 1082:     my $now=time;
 1083:     return &assignrole($udom,$uname,$url,$role,$now);
 1084: }
 1085: 
 1086: # ---------------------------------------------------------- Revoke Custom Role
 1087: 
 1088: sub revokecustomrole {
 1089:     my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
 1090:     my $now=time;
 1091:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
 1092: }
 1093: 
 1094: # ------------------------------------------------------------ Directory lister
 1095: 
 1096: sub dirlist {
 1097:     my $uri=shift;
 1098:     $uri=~s/^\///;
 1099:     $uri=~s/\/$//;
 1100:     my ($res,$udom,$uname,@rest)=split(/\//,$uri);
 1101:     if ($udom) {
 1102:      if ($uname) {
 1103:        my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/'.$uri,
 1104:                       homeserver($uname,$udom));
 1105:        return split(/:/,$listing);
 1106:      } else {
 1107:        my $tryserver;
 1108:        my %allusers=();
 1109:        foreach $tryserver (keys %libserv) {
 1110: 	  if ($hostdom{$tryserver} eq $udom) {
 1111:              my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.$udom,
 1112: 			       $tryserver);
 1113:              if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 1114:               && ($listing ne 'con_lost')) {
 1115:                 map {
 1116:                   my ($entry,@stat)=split(/&/,$_);
 1117:                   $allusers{$entry}=1;
 1118:                 } split(/:/,$listing);
 1119:              }
 1120: 	  }
 1121:        }
 1122:        my $alluserstr='';
 1123:        map {
 1124:            $alluserstr.=$_.'&user:';
 1125:        } sort keys %allusers;
 1126:        $alluserstr=~s/:$//;
 1127:        return split(/:/,$alluserstr);
 1128:      } 
 1129:    } else {
 1130:        my $tryserver;
 1131:        my %alldom=();
 1132:        foreach $tryserver (keys %libserv) {
 1133: 	   $alldom{$hostdom{$tryserver}}=1;
 1134:        }
 1135:        my $alldomstr='';
 1136:        map {
 1137:           $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
 1138:        } sort keys %alldom;
 1139:        $alldomstr=~s/:$//;
 1140:        return split(/:/,$alldomstr);       
 1141:    }
 1142: }
 1143: 
 1144: # -------------------------------------------------------- Value of a Condition
 1145: 
 1146: sub directcondval {
 1147:     my $number=shift;
 1148:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 1149:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 1150:     } else {
 1151:        return 2;
 1152:     }
 1153: }
 1154: 
 1155: sub condval {
 1156:     my $condidx=shift;
 1157:     my $result=0;
 1158:     my $allpathcond='';
 1159:     map {
 1160:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 1161: 	   $allpathcond.=
 1162:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 1163:        }
 1164:     } split(/\|/,$condidx);
 1165:     $allpathcond=~s/\|$//;
 1166:     if ($ENV{'request.course.id'}) {
 1167:        if ($allpathcond) {
 1168:           my $operand='|';
 1169: 	  my @stack;
 1170:           map {
 1171:               if ($_ eq '(') {
 1172:                  push @stack,($operand,$result)
 1173:               } elsif ($_ eq ')') {
 1174:                   my $before=pop @stack;
 1175: 		  if (pop @stack eq '&') {
 1176: 		      $result=$result>$before?$before:$result;
 1177:                   } else {
 1178:                       $result=$result>$before?$result:$before;
 1179:                   }
 1180:               } elsif (($_ eq '&') || ($_ eq '|')) {
 1181:                   $operand=$_;
 1182:               } else {
 1183:                   my $new=directcondval($_);
 1184:                   if ($operand eq '&') {
 1185:                      $result=$result>$new?$new:$result;
 1186:                   } else {
 1187:                      $result=$result>$new?$result:$new;
 1188:                   }                  
 1189:               }
 1190:           } ($allpathcond=~/(\d+|\(|\)|\&|\|)/g);
 1191:        }
 1192:     }
 1193:     return $result;
 1194: }
 1195: 
 1196: # --------------------------------------------------------- Value of a Variable
 1197: 
 1198: sub EXT {
 1199:     my $varname=shift;
 1200:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 1201:     my $rest;
 1202:     if ($therest[0]) {
 1203:        $rest=join('.',@therest);
 1204:     } else {
 1205:        $rest='';
 1206:     }
 1207:     my $qualifierrest=$qualifier;
 1208:     if ($rest) { $qualifierrest.='.'.$rest; }
 1209:     my $spacequalifierrest=$space;
 1210:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 1211:     if ($realm eq 'user') {
 1212: # --------------------------------------------------------------- user.resource
 1213: 	if ($space eq 'resource') {
 1214: 	    my %restored=&restore;
 1215:             return $restored{$qualifierrest};
 1216: # ----------------------------------------------------------------- user.access
 1217:         } elsif ($space eq 'access') {
 1218:             return &allowed($qualifier,$rest);
 1219: # ------------------------------------------ user.preferences, user.environment
 1220:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 1221:             return $ENV{join('.',('environment',$qualifierrest))};
 1222: # ----------------------------------------------------------------- user.course
 1223:         } elsif ($space eq 'course') {
 1224:             return $ENV{join('.',('request.course',$qualifier))};
 1225: # ------------------------------------------------------------------- user.role
 1226:         } elsif ($space eq 'role') {
 1227:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 1228:             if ($qualifier eq 'value') {
 1229: 		return $role;
 1230:             } elsif ($qualifier eq 'extent') {
 1231:                 return $where;
 1232:             }
 1233: # ----------------------------------------------------------------- user.domain
 1234:         } elsif ($space eq 'domain') {
 1235:             return $ENV{'user.domain'};
 1236: # ------------------------------------------------------------------- user.name
 1237:         } elsif ($space eq 'name') {
 1238:             return $ENV{'user.name'};
 1239: # ---------------------------------------------------- Any other user namespace
 1240:         } else {
 1241:             my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
 1242:             my %reply=&get($space,$item);
 1243:             return $reply{$item};
 1244:         }
 1245:     } elsif ($realm eq 'request') {
 1246: # ------------------------------------------------------------- request.browser
 1247:         if ($space eq 'browser') {
 1248: 	    return $ENV{'browser.'.$qualifier};
 1249: # ------------------------------------------------------------ request.filename
 1250:         } else {
 1251:             return $ENV{'request.'.$spacequalifierrest};
 1252:         }
 1253:     } elsif ($realm eq 'course') {
 1254: # ---------------------------------------------------------- course.description
 1255:         my $section='';
 1256:         if ($ENV{'request.course.sec'}) {
 1257: 	    $section='_'.$ENV{'request.course.sec'};
 1258:         }
 1259:         return $ENV{'course.'.$ENV{'request.course.id'}.$section.'.'.
 1260:                               $spacequalifierrest};
 1261:     } elsif ($realm eq 'resource') {
 1262:       if ($ENV{'request.course.id'}) {
 1263: # ----------------------------------------------------- Cascading lookup scheme
 1264:        my $reslevel=
 1265: 	    $ENV{'request.course.id'}.'.'.&symbread().'.'.$spacequalifierrest;
 1266:        my $seclevel=
 1267:             $ENV{'request.course.id'}.'.'.
 1268: 		$ENV{'request.course.sec'}.'.'.$spacequalifierrest;
 1269:        my $courselevel=
 1270:             $ENV{'request.course.id'}.'.'.$spacequalifierrest;
 1271: 
 1272: # ----------------------------------------------------------- first, check user
 1273:        my %resourcedata=get('resourcedata',($reslevel,$seclevel,$courselevel));
 1274:        if ($resourcedata{$reslevel}) { return $resourcedata{$reslevel}; }
 1275:        if ($resourcedata{$seclevel}) { return $resourcedata{$seclevel}; }
 1276:        if ($resourcedata{$courselevel}) { return $resourcedata{$courselevel}; }
 1277: 
 1278: # -------------------------------------------------------- second, check course
 1279:         my $section='';
 1280:         if ($ENV{'request.course.sec'}) {
 1281: 	    $section='_'.$ENV{'request.course.sec'};
 1282:         }
 1283:         my $reply=&reply('get:'.
 1284:               $ENV{'course.'.$ENV{'request.course.id'}.$section.'.domain'}.':'.
 1285:               $ENV{'course.'.$ENV{'request.course.id'}.$section.'.num'}.
 1286:               ':resourcedata:'.
 1287:               escape($reslevel).':'.escape($seclevel).':'.escape($courselevel),
 1288: 		   $ENV{'course.'.$ENV{'request.course.id'}.$section.'.home'});
 1289:         map {
 1290:            my ($name,$value)=split(/\=/,$_);
 1291:            $resourcedata{unescape($name)}=unescape($value);  
 1292:         } split(/\&/,$reply);
 1293:        if ($resourcedata{$reslevel}) { return $resourcedata{$reslevel}; }
 1294:        if ($resourcedata{$seclevel}) { return $resourcedata{$seclevel}; }
 1295:        if ($resourcedata{$courselevel}) { return $resourcedata{$courselevel}; }
 1296: 
 1297: # ------------------------------------------------------ third, check map parms
 1298:        
 1299:        if ($ENV{'resource.parms.'.$reslevel}) {
 1300: 	   return $ENV{'resource.parms.'.$reslevel};
 1301:        }
 1302:      }
 1303:      
 1304: # --------------------------------------------- last, look in resource metadata
 1305: 	my $uri=&declutter($ENV{'request.filename'});
 1306:         my $filename=$perlvar{'lonDocRoot'}.'/res/'.$ENV.'.meta';
 1307:         if (-e $filename) {
 1308:             my @content;
 1309:             {
 1310:              my $fh=Apache::File->new($filename);
 1311:              @content=<$fh>;
 1312:             }
 1313:             if (join('',@content)=~
 1314:                  /\<$space[^\>]*\>([^\<]*)\<\/$space\>/) {
 1315: 	        return $1;
 1316:  	    }
 1317:         }
 1318: # ---------------------------------------------------- Any other user namespace
 1319:     } elsif ($realm eq 'environment') {
 1320: # ----------------------------------------------------------------- environment
 1321:         return $ENV{$spacequalifierrest};
 1322:     } elsif ($realm eq 'system') {
 1323: # ----------------------------------------------------------------- system.time
 1324: 	if ($space eq 'time') {
 1325: 	    return time;
 1326:         }
 1327:     }
 1328:     return '';
 1329: }
 1330: 
 1331: # ------------------------------------------------- Update symbolic store links
 1332: 
 1333: sub symblist {
 1334:     my ($mapname,%newhash)=@_;
 1335:     $mapname=declutter($mapname);
 1336:     my %hash;
 1337:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 1338:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 1339:                       &GDBM_WRCREAT,0640)) {
 1340: 	    map {
 1341:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
 1342:             } keys %newhash;
 1343:             if (untie(%hash)) {
 1344: 		return 'ok';
 1345:             }
 1346:         }
 1347:     }
 1348:     return 'error';
 1349: }
 1350: 
 1351: # ------------------------------------------------------ Return symb list entry
 1352: 
 1353: sub symbread {
 1354:     my $thisfn=shift;
 1355:     unless ($thisfn) {
 1356: 	$thisfn=$ENV{'request.filename'};
 1357:     }
 1358:     $thisfn=declutter($thisfn);
 1359:     my %hash;
 1360:     my %bighash;
 1361:     my $syval='';
 1362:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 1363:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 1364:                       &GDBM_READER,0640)) {
 1365: 	    $syval=$hash{$thisfn};
 1366:             untie(%hash);
 1367:         }
 1368: # ---------------------------------------------------------- There was an entry
 1369:         if ($syval) {
 1370:            unless ($syval=~/\_\d+$/) {
 1371: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 1372:                   &appenv('request.ambiguous' => $thisfn);
 1373:                   return '';
 1374:                }    
 1375:                $syval.=$1;
 1376: 	   }
 1377:         } else {
 1378: # ------------------------------------------------------- Was not in symb table
 1379:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 1380:                             &GDBM_READER,0640)) {
 1381: # ---------------------------------------------- Get ID(s) for current resource
 1382:               my $ids=$bighash{'ids_/res/'.$thisfn};
 1383:               if ($ids) {
 1384: # ------------------------------------------------------------------- Has ID(s)
 1385:                  my @possibilities=split(/\,/,$ids);
 1386:                  if ($#possibilities==0) {
 1387: # ----------------------------------------------- There is only one possibility
 1388: 		     my ($mapid,$resid)=split(/\./,$ids);
 1389:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 1390:                  } else {
 1391: # ------------------------------------------ There is more than one possibility
 1392:                      my $realpossible=0;
 1393:                      map {
 1394: 			 my $file=$bighash{'src_'.$_};
 1395:                          if (&allowed('bre',$file)) {
 1396:          		    my ($mapid,$resid)=split(/\./,$_);
 1397:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 1398: 				$realpossible++;
 1399:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 1400:                                        '___'.$resid;
 1401:                             }
 1402: 			 }
 1403:                      } @possibilities;
 1404: 		     if ($realpossible!=1) { $syval=''; }
 1405:                  }
 1406: 	      }
 1407:               untie(%bighash)
 1408:            } 
 1409:         }
 1410:         if ($syval) { return $syval.'___'.$thisfn; }
 1411:     }
 1412:     &appenv('request.ambiguous' => $thisfn);
 1413:     return '';
 1414: }
 1415: 
 1416: # ---------------------------------------------------------- Return random seed
 1417: 
 1418: sub numval {
 1419:     my $txt=shift;
 1420:     $txt=~tr/A-J/0-9/;
 1421:     $txt=~tr/a-j/0-9/;
 1422:     $txt=~tr/K-T/0-9/;
 1423:     $txt=~tr/k-t/0-9/;
 1424:     $txt=~tr/U-Z/0-5/;
 1425:     $txt=~tr/u-z/0-5/;
 1426:     $txt=~s/\D//g;
 1427:     return int($txt);
 1428: }    
 1429: 
 1430: sub rndseed {
 1431:     my $symb;
 1432:     unless ($symb=&symbread()) { return time; }
 1433:     my $symbchck=unpack("%32C*",$symb);
 1434:     my $symbseed=numval($symb)%$symbchck;
 1435:     my $namechck=unpack("%32C*",$ENV{'user.name'});
 1436:     my $nameseed=numval($ENV{'user.name'})%$namechck;
 1437:     return int( $symbseed
 1438: 	       .$nameseed
 1439:                .unpack("%32C*",$ENV{'user.domain'})
 1440:                .unpack("%32C*",$ENV{'request.course.id'})
 1441:                .$namechck
 1442:                .$symbchck);
 1443: }
 1444: 
 1445: # ------------------------------------------------------------ Serves up a file
 1446: # returns either the contents of the file or a -1
 1447: sub getfile {
 1448:   my $file=shift;
 1449:   &repcopy($file);
 1450:   if (! -e $file ) { return -1; };
 1451:   my $fh=Apache::File->new($file);
 1452:   my $a='';
 1453:   while (<$fh>) { $a .=$_; }
 1454:   return $a
 1455: }
 1456: 
 1457: sub filelocation {
 1458:   my ($dir,$file) = @_;
 1459:   my $location;
 1460:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 1461:   if ($file=~m:^/~:) { # is a contruction space reference
 1462:     $location = $file;
 1463:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 1464:   } else {
 1465:     $file=~s/^$perlvar{'lonDocRoot'}//;
 1466:     $file=~s:^/*res::;
 1467:     if ( !( $file =~ m:^/:) ) {
 1468:       $location = $dir. '/'.$file;
 1469:     } else {
 1470:       $location = '/home/httpd/html/res'.$file;
 1471:     }
 1472:   }
 1473:   $location=~s://+:/:g; # remove duplicate /
 1474:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 1475:   return $location;
 1476: }
 1477: 
 1478: sub hreflocation {
 1479:     my ($dir,$file)=@_;
 1480:     unless (($_=~/^http:\/\//i) || ($_=~/^\//)) {
 1481:        my $finalpath=filelocation($dir,$file);
 1482:        $finalpath=~s/^\/home\/httpd\/html//;
 1483:        return $finalpath;
 1484:     } else {
 1485:        return $file;
 1486:     }
 1487: }
 1488: 
 1489: # ------------------------------------------------------------- Declutters URLs
 1490: 
 1491: sub declutter {
 1492:     my $thisfn=shift;
 1493:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
 1494:     $thisfn=~s/^\///;
 1495:     $thisfn=~s/^res\///;
 1496:     return $thisfn;
 1497: }
 1498: 
 1499: # -------------------------------------------------------- Escape Special Chars
 1500: 
 1501: sub escape {
 1502:     my $str=shift;
 1503:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 1504:     return $str;
 1505: }
 1506: 
 1507: # ----------------------------------------------------- Un-Escape Special Chars
 1508: 
 1509: sub unescape {
 1510:     my $str=shift;
 1511:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 1512:     return $str;
 1513: }
 1514: 
 1515: # ================================================================ Main Program
 1516: 
 1517: sub BEGIN {
 1518: if ($readit ne 'done') {
 1519: # ------------------------------------------------------------ Read access.conf
 1520: {
 1521:     my $config=Apache::File->new("/etc/httpd/conf/access.conf");
 1522: 
 1523:     while (my $configline=<$config>) {
 1524:         if ($configline =~ /PerlSetVar/) {
 1525: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 1526:            chomp($varvalue);
 1527:            $perlvar{$varname}=$varvalue;
 1528:         }
 1529:     }
 1530: }
 1531: 
 1532: # ------------------------------------------------------------- Read hosts file
 1533: {
 1534:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
 1535: 
 1536:     while (my $configline=<$config>) {
 1537:        my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
 1538:        $hostname{$id}=$name;
 1539:        $hostdom{$id}=$domain;
 1540:        if ($role eq 'library') { $libserv{$id}=$name; }
 1541:     }
 1542: }
 1543: 
 1544: # ------------------------------------------------------ Read spare server file
 1545: {
 1546:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
 1547: 
 1548:     while (my $configline=<$config>) {
 1549:        chomp($configline);
 1550:        if (($configline) && ($configline ne $perlvar{'lonHostID'})) {
 1551:           $spareid{$configline}=1;
 1552:        }
 1553:     }
 1554: }
 1555: # ------------------------------------------------------------ Read permissions
 1556: {
 1557:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
 1558: 
 1559:     while (my $configline=<$config>) {
 1560:        chomp($configline);
 1561:        my ($role,$perm)=split(/ /,$configline);
 1562:        if ($perm ne '') { $pr{$role}=$perm; }
 1563:     }
 1564: }
 1565: 
 1566: # -------------------------------------------- Read plain texts for permissions
 1567: {
 1568:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
 1569: 
 1570:     while (my $configline=<$config>) {
 1571:        chomp($configline);
 1572:        my ($short,$plain)=split(/:/,$configline);
 1573:        if ($plain ne '') { $prp{$short}=$plain; }
 1574:     }
 1575: }
 1576: 
 1577: # ------------------------------------------------------------- Read file types
 1578: {
 1579:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/filetypes.tab");
 1580: 
 1581:     while (my $configline=<$config>) {
 1582:        chomp($configline);
 1583:        my ($ending,$emb,@descr)=split(/\s+/,$configline);
 1584:        if ($descr[0] ne '') { 
 1585:          $fe{$ending}=$emb;
 1586:          $fd{$ending}=join(' ',@descr);
 1587:        }
 1588:     }
 1589: }
 1590: 
 1591: 
 1592: $readit='done';
 1593: &logthis('<font color=yellow>INFO: Read configuration</font>');
 1594: }
 1595: }
 1596: 1;

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