File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.162: download - view: text, annotated - select for diffs
Sat Oct 6 20:57:45 2001 UTC (22 years, 9 months ago) by harris41
Branches: MAIN
CVS tags: HEAD
reverting back to the way it was..

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

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