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

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

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