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

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

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