Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.128

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

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