File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.161: download - view: text, annotated - select for diffs
Fri Oct 5 17:54:36 2001 UTC (22 years, 9 months ago) by harris41
Branches: MAIN
CVS tags: HEAD
fixing untrapped error condition...

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

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