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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.365   ! albertel    4: # $Id: lonnet.pm,v 1.364 2003/04/22 21:00:42 www Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
                     29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
                     30: # 11/8,11/16,11/18,11/22,11/23,12/22,
                     31: # 01/06,01/13,02/24,02/28,02/29,
                     32: # 03/01,03/02,03/06,03/07,03/13,
                     33: # 04/05,05/29,05/31,06/01,
                     34: # 06/05,06/26 Gerd Kortemeyer
                     35: # 06/26 Ben Tyszka
                     36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
                     37: # 08/14 Ben Tyszka
                     38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
                     39: # 10/04 Gerd Kortemeyer
                     40: # 10/04 Guy Albertelli
                     41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
                     42: # 10/30,10/31,
                     43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
                     44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
                     45: # 05/01/01 Guy Albertelli
                     46: # 05/01,06/01,09/01 Gerd Kortemeyer
                     47: # 09/01 Guy Albertelli
                     48: # 09/01,10/01,11/01 Gerd Kortemeyer
                     49: # YEAR=2001
                     50: # 3/2 Gerd Kortemeyer
                     51: # 3/19,3/20 Gerd Kortemeyer
                     52: # 5/26,5/28 Gerd Kortemeyer
                     53: # 5/30 H. K. Ng
                     54: # 6/1 Gerd Kortemeyer
                     55: # July Guy Albertelli
                     56: # 8/4,8/7,8/8,8/9,8/11,8/16,8/17,8/18,8/20,8/23,9/20,9/21,9/26,
                     57: # 10/2 Gerd Kortemeyer
1.179     www        58: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
1.182     matthew    59: # 12/5 Matthew Hall
1.184     www        60: # 12/5 Guy Albertelli
1.190     www        61: # 12/6,12/7,12/12 Gerd Kortemeyer
1.195     www        62: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
1.196     www        63: # YEAR=2002
1.200     www        64: # 1/4,2/4,2/7 Gerd Kortemeyer
1.171     www        65: #
1.169     harris41   66: ###
                     67: 
1.1       albertel   68: package Apache::lonnet;
                     69: 
                     70: use strict;
                     71: use Apache::File;
1.8       www        72: use LWP::UserAgent();
1.15      www        73: use HTTP::Headers;
1.11      www        74: use vars 
1.300     albertel   75: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom 
1.301     www        76:    %libserv %pr %prp %metacache %packagetab %titlecache 
1.349     www        77:    %courselogs %accesshash %userrolehash $processmarker $dumpcount 
1.352     www        78:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseresdatacache 
1.329     matthew    79:    %domaindescription %domain_auth_def %domain_auth_arg_def $tmpdir);
1.1       albertel   80: use IO::Socket;
1.31      www        81: use GDBM_File;
1.8       www        82: use Apache::Constants qw(:common :http);
1.208     albertel   83: use HTML::LCParser;
1.88      www        84: use Fcntl qw(:flock);
1.294     matthew    85: use Apache::loncoursedata;
                     86: 
1.195     www        87: my $readit;
1.1       albertel   88: 
                     89: # --------------------------------------------------------------------- Logging
                     90: 
1.163     harris41   91: sub logtouch {
                     92:     my $execdir=$perlvar{'lonDaemons'};
                     93:     unless (-e "$execdir/logs/lonnet.log") {
                     94: 	my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
                     95: 	close $fh;
                     96:     }
                     97:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                     98:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                     99: }
                    100: 
1.1       albertel  101: sub logthis {
                    102:     my $message=shift;
                    103:     my $execdir=$perlvar{'lonDaemons'};
                    104:     my $now=time;
                    105:     my $local=localtime($now);
1.162     harris41  106:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
                    107:     print $fh "$local ($$): $message\n";
1.1       albertel  108:     return 1;
                    109: }
                    110: 
                    111: sub logperm {
                    112:     my $message=shift;
                    113:     my $execdir=$perlvar{'lonDaemons'};
                    114:     my $now=time;
                    115:     my $local=localtime($now);
1.162     harris41  116:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
                    117:     print $fh "$now:$message:$local\n";
1.1       albertel  118:     return 1;
                    119: }
                    120: 
                    121: # -------------------------------------------------- Non-critical communication
                    122: sub subreply {
                    123:     my ($cmd,$server)=@_;
                    124:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                    125:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    126:                                      Type    => SOCK_STREAM,
                    127:                                      Timeout => 10)
                    128:        or return "con_lost";
                    129:     print $client "$cmd\n";
                    130:     my $answer=<$client>;
1.9       www       131:     if (!$answer) { $answer="con_lost"; }
1.1       albertel  132:     chomp($answer);
                    133:     return $answer;
                    134: }
                    135: 
                    136: sub reply {
                    137:     my ($cmd,$server)=@_;
1.205     www       138:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  139:     my $answer=subreply($cmd,$server);
1.203     www       140:     if ($answer eq 'con_lost') {
1.311     matthew   141:         #sleep 5; 
                    142:         #$answer=subreply($cmd,$server);
                    143:         #if ($answer eq 'con_lost') {
1.233     albertel  144: 	#   &logthis("Second attempt con_lost on $server");
                    145:         #   my $peerfile="$perlvar{'lonSockDir'}/$server";
                    146:         #   my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    147:         #                                    Type    => SOCK_STREAM,
                    148:         #                                    Timeout => 10)
                    149:         #              or return "con_lost";
                    150:         #   &logthis("Killing socket");
                    151:         #   print $client "close_connection_exit\n";
                    152:            #sleep 5;
                    153:         #   $answer=subreply($cmd,$server);       
                    154:        #}   
1.203     www       155:     }
1.65      www       156:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12      www       157:        &logthis("<font color=blue>WARNING:".
                    158:                 " $cmd to $server returned $answer</font>");
                    159:     }
1.1       albertel  160:     return $answer;
                    161: }
                    162: 
                    163: # ----------------------------------------------------------- Send USR1 to lonc
                    164: 
                    165: sub reconlonc {
                    166:     my $peerfile=shift;
                    167:     &logthis("Trying to reconnect for $peerfile");
                    168:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                    169:     if (my $fh=Apache::File->new("$loncfile")) {
                    170: 	my $loncpid=<$fh>;
                    171:         chomp($loncpid);
                    172:         if (kill 0 => $loncpid) {
                    173: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    174:             kill USR1 => $loncpid;
                    175:             sleep 1;
                    176:             if (-e "$peerfile") { return; }
                    177:             &logthis("$peerfile still not there, give it another try");
                    178:             sleep 5;
                    179:             if (-e "$peerfile") { return; }
1.12      www       180:             &logthis(
                    181:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  182:         } else {
1.12      www       183: 	    &logthis(
                    184:                "<font color=blue>WARNING:".
                    185:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  186:         }
                    187:     } else {
1.12      www       188:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1       albertel  189:     }
                    190: }
                    191: 
                    192: # ------------------------------------------------------ Critical communication
1.12      www       193: 
1.1       albertel  194: sub critical {
                    195:     my ($cmd,$server)=@_;
1.89      www       196:     unless ($hostname{$server}) {
                    197:         &logthis("<font color=blue>WARNING:".
                    198:                " Critical message to unknown server ($server)</font>");
                    199:         return 'no_such_host';
                    200:     }
1.1       albertel  201:     my $answer=reply($cmd,$server);
                    202:     if ($answer eq 'con_lost') {
                    203:         my $pingreply=reply('ping',$server);
                    204: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
                    205:         my $pongreply=reply('pong',$server);
                    206:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
                    207:         $answer=reply($cmd,$server);
                    208:         if ($answer eq 'con_lost') {
                    209:             my $now=time;
                    210:             my $middlename=$cmd;
1.5       www       211:             $middlename=substr($middlename,0,16);
1.1       albertel  212:             $middlename=~s/\W//g;
                    213:             my $dfilename=
1.305     www       214:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    215:             $dumpcount++;
1.1       albertel  216:             {
                    217:              my $dfh;
                    218:              if ($dfh=Apache::File->new(">$dfilename")) {
1.7       www       219:                 print $dfh "$cmd\n";
1.1       albertel  220: 	     }
                    221:             }
                    222:             sleep 2;
                    223:             my $wcmd='';
                    224:             {
                    225: 	     my $dfh;
                    226:              if ($dfh=Apache::File->new("$dfilename")) {
                    227:                 $wcmd=<$dfh>;
                    228: 	     }
                    229:             }
                    230:             chomp($wcmd);
1.7       www       231:             if ($wcmd eq $cmd) {
1.12      www       232: 		&logthis("<font color=blue>WARNING: ".
                    233:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  234:                 &logperm("D:$server:$cmd");
                    235: 	        return 'con_delayed';
                    236:             } else {
1.12      www       237:                 &logthis("<font color=red>CRITICAL:"
                    238:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  239:                 &logperm("F:$server:$cmd");
                    240:                 return 'con_failed';
                    241:             }
                    242:         }
                    243:     }
                    244:     return $answer;
                    245: }
                    246: 
1.5       www       247: # ---------------------------------------------------------- Append Environment
                    248: 
                    249: sub appenv {
1.6       www       250:     my %newenv=@_;
1.191     harris41  251:     foreach (keys %newenv) {
1.35      www       252: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
                    253:             &logthis("<font color=blue>WARNING: ".
1.151     www       254:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    255:                 .'</font>');
1.35      www       256: 	    delete($newenv{$_});
                    257:         } else {
                    258:             $ENV{$_}=$newenv{$_};
                    259:         }
1.191     harris41  260:     }
1.95      www       261: 
                    262:     my $lockfh;
                    263:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       264:        return 'error: '.$!;
1.95      www       265:     }
                    266:     unless (flock($lockfh,LOCK_EX)) {
                    267:          &logthis("<font color=blue>WARNING: ".
                    268:                   'Could not obtain exclusive lock in appenv: '.$!);
                    269:          $lockfh->close();
                    270:          return 'error: '.$!;
                    271:     }
                    272: 
1.6       www       273:     my @oldenv;
                    274:     {
                    275:      my $fh;
                    276:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       277: 	return 'error: '.$!;
1.6       www       278:      }
                    279:      @oldenv=<$fh>;
1.89      www       280:      $fh->close();
1.6       www       281:     }
                    282:     for (my $i=0; $i<=$#oldenv; $i++) {
                    283:         chomp($oldenv[$i]);
1.9       www       284:         if ($oldenv[$i] ne '') {
                    285:            my ($name,$value)=split(/=/,$oldenv[$i]);
1.24      www       286:            unless (defined($newenv{$name})) {
                    287: 	      $newenv{$name}=$value;
                    288: 	   }
1.9       www       289:         }
1.6       www       290:     }
                    291:     {
                    292:      my $fh;
                    293:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    294: 	return 'error';
                    295:      }
                    296:      my $newname;
1.93      www       297:      foreach $newname (keys %newenv) {
1.6       www       298: 	 print $fh "$newname=$newenv{$newname}\n";
                    299:      }
1.86      albertel  300:      $fh->close();
1.56      www       301:     }
1.95      www       302: 
                    303:     $lockfh->close();
1.56      www       304:     return 'ok';
                    305: }
                    306: # ----------------------------------------------------- Delete from Environment
                    307: 
                    308: sub delenv {
                    309:     my $delthis=shift;
                    310:     my %newenv=();
                    311:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
                    312:         &logthis("<font color=blue>WARNING: ".
                    313:                 "Attempt to delete from environment ".$delthis);
                    314:         return 'error';
                    315:     }
                    316:     my @oldenv;
                    317:     {
                    318:      my $fh;
                    319:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
                    320: 	return 'error';
                    321:      }
1.89      www       322:      unless (flock($fh,LOCK_SH)) {
                    323:          &logthis("<font color=blue>WARNING: ".
                    324:                   'Could not obtain shared lock in delenv: '.$!);
                    325:          $fh->close();
                    326:          return 'error: '.$!;
                    327:      }
1.56      www       328:      @oldenv=<$fh>;
1.89      www       329:      $fh->close();
1.56      www       330:     }
                    331:     {
                    332:      my $fh;
                    333:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    334: 	return 'error';
                    335:      }
1.89      www       336:      unless (flock($fh,LOCK_EX)) {
                    337:          &logthis("<font color=blue>WARNING: ".
                    338:                   'Could not obtain exclusive lock in delenv: '.$!);
                    339:          $fh->close();
                    340:          return 'error: '.$!;
                    341:      }
1.191     harris41  342:      foreach (@oldenv) {
1.56      www       343: 	 unless ($_=~/^$delthis/) { print $fh $_; }
1.191     harris41  344:      }
1.87      www       345:      $fh->close();
1.5       www       346:     }
                    347:     return 'ok';
1.283     www       348: }
                    349: 
                    350: # ------------------------------------------ Fight off request when overloaded
                    351: 
                    352: sub overloaderror {
                    353:     my ($r,$checkserver)=@_;
                    354:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    355:     my $loadavg;
                    356:     if ($checkserver eq $perlvar{'lonHostID'}) {
                    357:        my $loadfile=Apache::File->new('/proc/loadavg');
                    358:        $loadavg=<$loadfile>;
                    359:        $loadavg =~ s/\s.*//g;
1.285     matthew   360:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.283     www       361:     } else {
                    362:        $loadavg=&reply('load',$checkserver);
                    363:     }
1.285     matthew   364:     my $overload=$loadavg-100;
1.283     www       365:     if ($overload>0) {
1.285     matthew   366: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       367:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
                    368:         return 413;
                    369:     }    
                    370:     return '';
1.5       www       371: }
1.1       albertel  372: 
                    373: # ------------------------------ Find server with least workload from spare.tab
1.11      www       374: 
1.1       albertel  375: sub spareserver {
1.284     matthew   376:     my $loadpercent = shift;
1.1       albertel  377:     my $tryserver;
                    378:     my $spareserver='';
1.284     matthew   379:     my $lowestserver=$loadpercent; 
1.1       albertel  380:     foreach $tryserver (keys %spareid) {
                    381:        my $answer=reply('load',$tryserver);
                    382:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
                    383: 	   $spareserver="http://$hostname{$tryserver}";
                    384:            $lowestserver=$answer;
                    385:        }
                    386:     }    
                    387:     return $spareserver;
1.202     matthew   388: }
                    389: 
                    390: # --------------------------------------------- Try to change a user's password
                    391: 
                    392: sub changepass {
                    393:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    394:     $currentpass = &escape($currentpass);
                    395:     $newpass     = &escape($newpass);
                    396:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    397: 		       $server);
                    398:     if (! $answer) {
                    399: 	&logthis("No reply on password change request to $server ".
                    400: 		 "by $uname in domain $udom.");
                    401:     } elsif ($answer =~ "^ok") {
                    402:         &logthis("$uname in $udom successfully changed their password ".
                    403: 		 "on $server.");
                    404:     } elsif ($answer =~ "^pwchange_failure") {
                    405: 	&logthis("$uname in $udom was unable to change their password ".
                    406: 		 "on $server.  The action was blocked by either lcpasswd ".
                    407: 		 "or pwchange");
                    408:     } elsif ($answer =~ "^non_authorized") {
                    409:         &logthis("$uname in $udom did not get their password correct when ".
                    410: 		 "attempting to change it on $server.");
                    411:     } elsif ($answer =~ "^auth_mode_error") {
                    412:         &logthis("$uname in $udom attempted to change their password despite ".
                    413: 		 "not being locally or internally authenticated on $server.");
                    414:     } elsif ($answer =~ "^unknown_user") {
                    415:         &logthis("$uname in $udom attempted to change their password ".
                    416: 		 "on $server but were unable to because $server is not ".
                    417: 		 "their home server.");
                    418:     } elsif ($answer =~ "^refused") {
                    419: 	&logthis("$server refused to change $uname in $udom password because ".
                    420: 		 "it was sent an unencrypted request to change the password.");
                    421:     }
                    422:     return $answer;
1.1       albertel  423: }
                    424: 
1.169     harris41  425: # ----------------------- Try to determine user's current authentication scheme
                    426: 
                    427: sub queryauthenticate {
                    428:     my ($uname,$udom)=@_;
                    429:     if (($perlvar{'lonRole'} eq 'library') && 
                    430:         ($udom eq $perlvar{'lonDefDomain'})) {
                    431: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
                    432: 			 $perlvar{'lonHostID'});
                    433: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    434: 	    if (length($answer)) {
                    435: 		return $answer;
                    436: 	    }
                    437: 	    else {
                    438: 	&logthis("User $uname at $udom lacks an authentication mechanism");
                    439: 		return 'no_host';
                    440: 	    }
                    441: 	}
                    442:     }
                    443: 
                    444:     my $tryserver;
                    445:     foreach $tryserver (keys %libserv) {
                    446: 	if ($hostdom{$tryserver} eq $udom) {
                    447:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
                    448: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    449: 	       if (length($answer)) {
                    450: 		   return $answer;
                    451: 	       }
                    452: 	       else {
                    453: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
                    454: 		   return 'no_host';
                    455: 	       }
                    456: 	   }
                    457:        }
                    458:     }
                    459:     &logthis("User $uname at $udom lacks an authentication mechanism");    
                    460:     return 'no_host';
                    461: }
                    462: 
1.1       albertel  463: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       464: 
1.1       albertel  465: sub authenticate {
                    466:     my ($uname,$upass,$udom)=@_;
1.12      www       467:     $upass=escape($upass);
1.199     www       468:     $uname=~s/\W//g;
1.1       albertel  469:     if (($perlvar{'lonRole'} eq 'library') && 
                    470:         ($udom eq $perlvar{'lonDefDomain'})) {
1.3       www       471:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
1.2       www       472:         if ($answer =~ /authorized/) {
1.9       www       473:               if ($answer eq 'authorized') {
                    474:                  &logthis("User $uname at $udom authorized by local server"); 
                    475:                  return $perlvar{'lonHostID'}; 
                    476:               }
                    477:               if ($answer eq 'non_authorized') {
                    478:                  &logthis("User $uname at $udom rejected by local server"); 
                    479:                  return 'no_host'; 
                    480:               }
1.2       www       481: 	}
1.1       albertel  482:     }
                    483: 
                    484:     my $tryserver;
                    485:     foreach $tryserver (keys %libserv) {
                    486: 	if ($hostdom{$tryserver} eq $udom) {
1.10      www       487:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
1.1       albertel  488:            if ($answer =~ /authorized/) {
1.9       www       489:               if ($answer eq 'authorized') {
                    490:                  &logthis("User $uname at $udom authorized by $tryserver"); 
                    491:                  return $tryserver; 
                    492:               }
                    493:               if ($answer eq 'non_authorized') {
                    494:                  &logthis("User $uname at $udom rejected by $tryserver");
                    495:                  return 'no_host';
                    496:               } 
1.1       albertel  497: 	   }
                    498:        }
1.9       www       499:     }
                    500:     &logthis("User $uname at $udom could not be authenticated");    
1.1       albertel  501:     return 'no_host';
                    502: }
                    503: 
                    504: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       505: 
1.1       albertel  506: sub homeserver {
1.230     stredwic  507:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  508:     my $index="$uname:$udom";
1.221     matthew   509:     if ($homecache{$index}) { 
                    510:         return "$homecache{$index}"; 
                    511:     }
1.1       albertel  512:     my $tryserver;
                    513:     foreach $tryserver (keys %libserv) {
1.230     stredwic  514:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  515: 		 exists($badServerCache{$tryserver}));
1.1       albertel  516: 	if ($hostdom{$tryserver} eq $udom) {
                    517:            my $answer=reply("home:$udom:$uname",$tryserver);
                    518:            if ($answer eq 'found') { 
1.221     matthew   519:               $homecache{$index}=$tryserver;
1.1       albertel  520:               return $tryserver; 
1.231     stredwic  521:            } elsif ($answer eq 'no_host') {
                    522: 	       $badServerCache{$tryserver}=1;
1.221     matthew   523:            }
1.1       albertel  524:        }
                    525:     }    
                    526:     return 'no_host';
1.70      www       527: }
                    528: 
                    529: # ------------------------------------- Find the usernames behind a list of IDs
                    530: 
                    531: sub idget {
                    532:     my ($udom,@ids)=@_;
                    533:     my %returnhash=();
                    534:     
                    535:     my $tryserver;
                    536:     foreach $tryserver (keys %libserv) {
                    537:        if ($hostdom{$tryserver} eq $udom) {
                    538: 	  my $idlist=join('&',@ids);
                    539:           $idlist=~tr/A-Z/a-z/; 
                    540: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    541:           my @answer=();
1.76      www       542:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       543: 	      @answer=split(/\&/,$reply);
                    544:           }                    ;
                    545:           my $i;
                    546:           for ($i=0;$i<=$#ids;$i++) {
                    547:               if ($answer[$i]) {
                    548: 		  $returnhash{$ids[$i]}=$answer[$i];
                    549:               } 
                    550:           }
                    551:        }
                    552:     }    
                    553:     return %returnhash;
                    554: }
                    555: 
                    556: # ------------------------------------- Find the IDs behind a list of usernames
                    557: 
                    558: sub idrget {
                    559:     my ($udom,@unames)=@_;
                    560:     my %returnhash=();
1.191     harris41  561:     foreach (@unames) {
1.70      www       562:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  563:     }
1.70      www       564:     return %returnhash;
                    565: }
                    566: 
                    567: # ------------------------------- Store away a list of names and associated IDs
                    568: 
                    569: sub idput {
                    570:     my ($udom,%ids)=@_;
                    571:     my %servers=();
1.191     harris41  572:     foreach (keys %ids) {
1.70      www       573:         my $uhom=&homeserver($_,$udom);
                    574:         if ($uhom ne 'no_host') {
                    575:             my $id=&escape($ids{$_});
                    576:             $id=~tr/A-Z/a-z/;
                    577:             my $unam=&escape($_);
                    578: 	    if ($servers{$uhom}) {
                    579: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    580:             } else {
                    581:                 $servers{$uhom}=$id.'='.$unam;
                    582:             }
                    583:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
                    584:         }
1.191     harris41  585:     }
                    586:     foreach (keys %servers) {
1.70      www       587:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  588:     }
1.344     www       589: }
                    590: 
                    591: # --------------------------------------------------- Assign a key to a student
                    592: 
                    593: sub assign_access_key {
1.364     www       594: #
                    595: # a valid key looks like uname:udom#comments
                    596: # comments are being appended
                    597: #
                    598:     my ($ckey,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1.344     www       599:     $cdom=
                    600:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    601:     $cnum=
                    602:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    603:     $udom=$ENV{'user.name'} unless (defined($udom));
                    604:     $uname=$ENV{'user.domain'} unless (defined($uname));
1.345     www       605:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.364     www       606:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
                    607:         ($existing{$ckey}=~/^$uname\:$udom\#(.*)$/)) { 
                    608:                                                   # assigned to this person
                    609:                                                   # - this should not happen,
1.345     www       610:                                                   # unless something went wrong
                    611:                                                   # the first time around
                    612: # ready to assign
1.364     www       613:         $logentry=$1.'; '.$logentry;
                    614:         if (&put('accesskey',{$ckey=>$uname.':'.$udom.'#'.$logentry},
                    615:                                                  $cdom,$cnum) eq 'ok') {
1.345     www       616: # key now belongs to user
1.346     www       617: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       618:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    619:                 &appenv('environment.'.$envkey => $ckey);
                    620:                 return 'ok';
                    621:             } else {
                    622:                 return 
                    623:   'error: Count not permanently assign key, will need to be re-entered later.';
                    624: 	    }
                    625:         } else {
                    626:             return 'error: Could not assign key, try again later.';
                    627:         }
1.364     www       628:     } elsif (!$existing{$ckey}) {
1.345     www       629: # the key does not exist
                    630: 	return 'error: The key does not exist';
                    631:     } else {
                    632: # the key is somebody else's
                    633: 	return 'error: The key is already in use';
                    634:     }
1.344     www       635: }
                    636: 
1.364     www       637: # ------------------------------------------ put an additional comment on a key
                    638: 
                    639: sub comment_access_key {
                    640: #
                    641: # a valid key looks like uname:udom#comments
                    642: # comments are being appended
                    643: #
                    644:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    645:     $cdom=
                    646:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    647:     $cnum=
                    648:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    649:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    650:     if ($existing{$ckey}) {
                    651:         $existing{$ckey}.='; '.$logentry;
                    652: # ready to assign
                    653:         $logentry=$1.'; '.$logentry;
                    654:         if (&put('accesskey',{$ckey=>$existing{$ckey}},
                    655:                                                  $cdom,$cnum) eq 'ok') {
                    656: 	    return 'ok';
                    657:         } else {
                    658: 	    return 'error: Count not store comment.';
                    659:         }
                    660:     } else {
                    661: # the key does not exist
                    662: 	return 'error: The key does not exist';
                    663:     }
                    664: }
                    665: 
1.344     www       666: # ------------------------------------------------------ Generate a set of keys
                    667: 
                    668: sub generate_access_keys {
1.364     www       669:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       670:     $cdom=
                    671:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    672:     $cnum=
                    673:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       674:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       675:     unless (($cdom) && ($cnum)) { return 0; }
                    676:     if ($number>10000) { return 0; }
                    677:     sleep(2); # make sure don't get same seed twice
                    678:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    679:     my $total=0;
                    680:     for (my $i=1;$i<=$number;$i++) {
                    681:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    682:                   sprintf("%lx",int(100000*rand)).'-'.
                    683:                   sprintf("%lx",int(100000*rand));
                    684:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    685:        $newkey=~s/0/h/g; # and also 0 and O
                    686:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    687:        if ($existing{$newkey}) {
                    688:            $i--;
                    689:        } else {
1.364     www       690: 	  if (&put('accesskeys',
                    691:               { $newkey => '# generated '.localtime().
                    692:                            ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}.
                    693:                            '; '.$logentry },
                    694: 		   $cdom,$cnum) eq 'ok') {
1.344     www       695:               $total++;
                    696: 	  }
                    697:        }
                    698:     }
                    699:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                    700:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    701:     return $total;
                    702: }
                    703: 
                    704: # ------------------------------------------------------- Validate an accesskey
                    705: 
                    706: sub validate_access_key {
                    707:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    708:     $cdom=
                    709:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    710:     $cnum=
                    711:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    712:     $udom=$ENV{'user.name'} unless (defined($udom));
                    713:     $uname=$ENV{'user.domain'} unless (defined($uname));
1.345     www       714:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.364     www       715:     return ($existing{$ckey}=~/^$uname\:$udom\#/);
1.70      www       716: }
                    717: 
                    718: # ------------------------------------- Find the section of student in a course
1.298     matthew   719: 
                    720: sub getsection {
                    721:     my ($udom,$unam,$courseid)=@_;
                    722:     $courseid=~s/\_/\//g;
                    723:     $courseid=~s/^(\w)/\/$1/;
                    724:     my %Pending; 
                    725:     my %Expired;
                    726:     #
                    727:     # Each role can either have not started yet (pending), be active, 
                    728:     #    or have expired.
                    729:     #
                    730:     # If there is an active role, we are done.
                    731:     #
                    732:     # If there is more than one role which has not started yet, 
                    733:     #     choose the one which will start sooner
                    734:     # If there is one role which has not started yet, return it.
                    735:     #
                    736:     # If there is more than one expired role, choose the one which ended last.
                    737:     # If there is a role which has expired, return it.
                    738:     #
                    739:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    740:                         &homeserver($unam,$udom)))) {
                    741:         my ($key,$value)=split(/\=/,$_);
                    742:         $key=&unescape($key);
                    743:         next if ($key !~/^$courseid(?:\/)*(\w+)*\_st$/);
                    744:         my $section=$1;
                    745:         if ($key eq $courseid.'_st') { $section=''; }
                    746:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    747:         my $now=time;
                    748:         if (defined($end) && ($now > $end)) {
                    749:             $Expired{$end}=$section;
                    750:             next;
                    751:         }
                    752:         if (defined($start) && ($now < $start)) {
                    753:             $Pending{$start}=$section;
                    754:             next;
                    755:         }
                    756:         return $section;
                    757:     }
                    758:     #
                    759:     # Presumedly there will be few matching roles from the above
                    760:     # loop and the sorting time will be negligible.
                    761:     if (scalar(keys(%Pending))) {
                    762:         my ($time) = sort {$a <=> $b} keys(%Pending);
                    763:         return $Pending{$time};
                    764:     } 
                    765:     if (scalar(keys(%Expired))) {
                    766:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    767:         my $time = pop(@sorted);
                    768:         return $Expired{$time};
                    769:     }
                    770:     return '-1';
                    771: }
1.70      www       772: 
                    773: sub usection {
                    774:     my ($udom,$unam,$courseid)=@_;
                    775:     $courseid=~s/\_/\//g;
                    776:     $courseid=~s/^(\w)/\/$1/;
1.191     harris41  777:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    778:                         &homeserver($unam,$udom)))) {
1.70      www       779:         my ($key,$value)=split(/\=/,$_);
                    780:         $key=&unescape($key);
                    781:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
                    782:             my $section=$1;
                    783:             if ($key eq $courseid.'_st') { $section=''; }
                    784: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    785:             my $now=time;
                    786:             my $notactive=0;
                    787:             if ($start) {
                    788: 		if ($now<$start) { $notactive=1; }
                    789:             }
                    790:             if ($end) {
                    791:                 if ($now>$end) { $notactive=1; }
                    792:             } 
                    793:             unless ($notactive) { return $section; }
                    794:         }
1.191     harris41  795:     }
1.70      www       796:     return '-1';
                    797: }
                    798: 
                    799: # ------------------------------------- Read an entry from a user's environment
                    800: 
                    801: sub userenvironment {
                    802:     my ($udom,$unam,@what)=@_;
                    803:     my %returnhash=();
                    804:     my @answer=split(/\&/,
                    805:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    806:                       &homeserver($unam,$udom)));
                    807:     my $i;
                    808:     for ($i=0;$i<=$#what;$i++) {
                    809: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    810:     }
                    811:     return %returnhash;
1.1       albertel  812: }
                    813: 
1.263     www       814: # -------------------------------------------------------------------- New chat
                    815: 
                    816: sub chatsend {
                    817:     my ($newentry,$anon)=@_;
                    818:     my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                    819:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                    820:     my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                    821:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
                    822: 	   &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
                    823: 		   &escape($newentry)),$chome);
1.292     www       824: }
                    825: 
                    826: # ------------------------------------------ Find current version of a resource
                    827: 
                    828: sub getversion {
                    829:     my $fname=&clutter(shift);
                    830:     unless ($fname=~/^\/res\//) { return -1; }
                    831:     return &currentversion(&filelocation('',$fname));
                    832: }
                    833: 
                    834: sub currentversion {
                    835:     my $fname=shift;
                    836:     my $author=$fname;
                    837:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    838:     my ($udom,$uname)=split(/\//,$author);
                    839:     my $home=homeserver($uname,$udom);
                    840:     if ($home eq 'no_host') { 
                    841:         return -1; 
                    842:     }
                    843:     my $answer=reply("currentversion:$fname",$home);
                    844:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    845: 	return -1;
                    846:     }
                    847:     return $answer;
1.263     www       848: }
                    849: 
1.1       albertel  850: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www       851: 
1.1       albertel  852: sub subscribe {
                    853:     my $fname=shift;
1.312     www       854:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.1       albertel  855:     my $author=$fname;
                    856:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    857:     my ($udom,$uname)=split(/\//,$author);
                    858:     my $home=homeserver($uname,$udom);
1.335     albertel  859:     if ($home eq 'no_host') {
                    860:         return 'not_found';
1.1       albertel  861:     }
                    862:     my $answer=reply("sub:$fname",$home);
1.64      www       863:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    864: 	$answer.=' by '.$home;
                    865:     }
1.1       albertel  866:     return $answer;
                    867: }
                    868:     
1.8       www       869: # -------------------------------------------------------------- Replicate file
                    870: 
                    871: sub repcopy {
                    872:     my $filename=shift;
1.23      www       873:     $filename=~s/\/+/\//g;
1.214     www       874:     if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
1.8       www       875:     my $transname="$filename.in.transfer";
1.17      www       876:     if ((-e $filename) || (-e $transname)) { return OK; }
1.8       www       877:     my $remoteurl=subscribe($filename);
1.64      www       878:     if ($remoteurl =~ /^con_lost by/) {
                    879: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       880:            return HTTP_SERVICE_UNAVAILABLE;
                    881:     } elsif ($remoteurl eq 'not_found') {
                    882: 	   &logthis("Subscribe returned not_found: $filename");
                    883: 	   return HTTP_NOT_FOUND;
1.64      www       884:     } elsif ($remoteurl =~ /^rejected by/) {
                    885: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       886:            return FORBIDDEN;
1.20      www       887:     } elsif ($remoteurl eq 'directory') {
                    888:            return OK;
1.8       www       889:     } else {
1.290     www       890:         my $author=$filename;
                    891:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    892:         my ($udom,$uname)=split(/\//,$author);
                    893:         my $home=homeserver($uname,$udom);
                    894:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www       895:            my @parts=split(/\//,$filename);
                    896:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                    897:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                    898:                &logthis("Malconfiguration for replication: $filename");
                    899: 	       return HTTP_BAD_REQUEST;
                    900:            }
                    901:            my $count;
                    902:            for ($count=5;$count<$#parts;$count++) {
                    903:                $path.="/$parts[$count]";
                    904:                if ((-e $path)!=1) {
                    905: 		   mkdir($path,0777);
                    906:                }
                    907:            }
                    908:            my $ua=new LWP::UserAgent;
                    909:            my $request=new HTTP::Request('GET',"$remoteurl");
                    910:            my $response=$ua->request($request,$transname);
                    911:            if ($response->is_error()) {
                    912: 	       unlink($transname);
                    913:                my $message=$response->status_line;
1.12      www       914:                &logthis("<font color=blue>WARNING:"
                    915:                        ." LWP get: $message: $filename</font>");
1.8       www       916:                return HTTP_SERVICE_UNAVAILABLE;
                    917:            } else {
1.16      www       918: 	       if ($remoteurl!~/\.meta$/) {
                    919:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                    920:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                    921:                   if ($mresponse->is_error()) {
                    922: 		      unlink($filename.'.meta');
                    923:                       &logthis(
                    924:                      "<font color=yellow>INFO: No metadata: $filename</font>");
                    925:                   }
                    926: 	       }
1.8       www       927:                rename($transname,$filename);
                    928:                return OK;
                    929:            }
1.290     www       930:        }
1.8       www       931:     }
1.330     www       932: }
                    933: 
                    934: # ------------------------------------------------ Get server side include body
                    935: sub ssi_body {
                    936:     my $filelink=shift;
                    937:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
                    938:                                      &ssi($filelink));
                    939:     $output=~s/^.*\<body[^\>]*\>//si;
                    940:     $output=~s/\<\/body\s*\>.*$//si;
1.331     www       941:     $output=~
                    942:             s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs;
1.330     www       943:     return $output;
1.8       www       944: }
                    945: 
1.15      www       946: # --------------------------------------------------------- Server Side Include
                    947: 
                    948: sub ssi {
                    949: 
1.23      www       950:     my ($fn,%form)=@_;
1.15      www       951: 
                    952:     my $ua=new LWP::UserAgent;
1.23      www       953:     
                    954:     my $request;
                    955:     
                    956:     if (%form) {
                    957:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel  958:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www       959:     } else {
                    960:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                    961:     }
                    962: 
1.15      www       963:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                    964:     my $response=$ua->request($request);
                    965: 
1.324     www       966:     return $response->content;
                    967: }
                    968: 
                    969: sub externalssi {
                    970:     my ($url)=@_;
                    971:     my $ua=new LWP::UserAgent;
                    972:     my $request=new HTTP::Request('GET',$url);
                    973:     my $response=$ua->request($request);
1.15      www       974:     return $response->content;
                    975: }
1.254     www       976: 
                    977: # ------- Add a token to a remote URI's query string to vouch for access rights
                    978: 
                    979: sub tokenwrapper {
                    980:     my $uri=shift;
1.259     www       981:     $uri=~s/^http\:\/\/([^\/]+)//;
                    982:     $uri=~s/^\///;
                    983:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
                    984:     my $token=$1;
                    985:     if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
                    986: 	&appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
                    987:         return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
1.304     www       988:                (($uri=~/\?/)?'&':'?').'token='.$token.
                    989:                                '&tokenissued='.$perlvar{'lonHostID'};
1.259     www       990:     } else {
                    991: 	return '/adm/notfound.html';
                    992:     }
1.254     www       993: }
                    994:     
1.257     www       995: # --------------- Take an uploaded file and put it into the userfiles directory
1.259     www       996: # input: name of form element, coursedoc=1 means this is for the course
1.257     www       997: # output: url of file in userspace
                    998: 
                    999: sub userfileupload {
1.259     www      1000:     my ($formname,$coursedoc)=@_;
1.257     www      1001:     my $fname=$ENV{'form.'.$formname.'.filename'};
1.315     www      1002: # Replace Windows backslashes by forward slashes
1.257     www      1003:     $fname=~s/\\/\//g;
1.315     www      1004: # Get rid of everything but the actual filename
1.257     www      1005:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1006: # Replace spaces by underscores
                   1007:     $fname=~s/\s+/\_/g;
                   1008: # Replace all other weird characters by nothing
1.317     www      1009:     $fname=~s/[^\w\.\-]//g;
1.315     www      1010: # See if there is anything left
1.257     www      1011:     unless ($fname) { return 'error: no uploaded file'; }
                   1012:     chop($ENV{'form.'.$formname});
1.258     www      1013: # Create the directory if not present
1.259     www      1014:     my $docuname='';
                   1015:     my $docudom='';
                   1016:     my $docuhome='';
                   1017:     if ($coursedoc) {
                   1018: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1019: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1020: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                   1021:     } else {
                   1022:         $docuname=$ENV{'user.name'};
                   1023:         $docudom=$ENV{'user.domain'};
                   1024:         $docuhome=$ENV{'user.home'};
                   1025:     }
1.271     www      1026:     return 
                   1027:         &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
                   1028: }
                   1029: 
                   1030: sub finishuserfileupload {
                   1031:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
1.259     www      1032:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1033:     my $filepath=$perlvar{'lonDocRoot'};
1.259     www      1034:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1035:     my $count;
                   1036:     for ($count=4;$count<=$#parts;$count++) {
                   1037:         $filepath.="/$parts[$count]";
                   1038:         if ((-e $filepath)!=1) {
                   1039: 	    mkdir($filepath,0777);
                   1040:         }
                   1041:     }
                   1042: # Save the file
                   1043:     {
                   1044:        my $fh=Apache::File->new('>'.$filepath.'/'.$fname);
                   1045:        print $fh $ENV{'form.'.$formname};
                   1046:     }
1.259     www      1047: # Notify homeserver to grep it
                   1048: #
1.295     www      1049:     
                   1050:     my $fetchresult= 
                   1051:  &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome);
                   1052:     if ($fetchresult eq 'ok') {
1.259     www      1053: #
1.258     www      1054: # Return the URL to it
1.263     www      1055:         return '/uploaded/'.$path.$fname;
                   1056:     } else {
1.295     www      1057:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$fname.
                   1058:          ' to host '.$docuhome.': '.$fetchresult);
1.263     www      1059:         return '/adm/notfound.html';
                   1060:     }    
1.257     www      1061: }
1.15      www      1062: 
1.14      www      1063: # ------------------------------------------------------------------------- Log
                   1064: 
                   1065: sub log {
                   1066:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1067:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1068: }
                   1069: 
                   1070: # ------------------------------------------------------------------ Course Log
1.352     www      1071: #
                   1072: # This routine flushes several buffers of non-mission-critical nature
                   1073: #
1.157     www      1074: 
                   1075: sub flushcourselogs {
1.352     www      1076:     &logthis('Flushing log buffers');
                   1077: #
                   1078: # course logs
                   1079: # This is a log of all transactions in a course, which can be used
                   1080: # for data mining purposes
                   1081: #
                   1082: # It also collects the courseid database, which lists last transaction
                   1083: # times and course titles for all courseids
                   1084: #
                   1085:     my %courseidbuffer=();
1.191     harris41 1086:     foreach (keys %courselogs) {
1.157     www      1087:         my $crsid=$_;
1.352     www      1088:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1089: 		          &escape($courselogs{$crsid}),
                   1090: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1091: 	    delete $courselogs{$crsid};
                   1092:         } else {
                   1093:             &logthis('Failed to flush log buffer for '.$crsid);
                   1094:             if (length($courselogs{$crsid})>40000) {
                   1095:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
                   1096:                         " exceeded maximum size, deleting.</font>");
                   1097:                delete $courselogs{$crsid};
                   1098:             }
1.352     www      1099:         }
                   1100:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1101:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
                   1102: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
                   1103:         } else {
                   1104:            $courseidbuffer{$coursehombuf{$crsid}}=
                   1105: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
                   1106:         }    
1.191     harris41 1107:     }
1.352     www      1108: #
                   1109: # Write course id database (reverse lookup) to homeserver of courses 
                   1110: # Is used in pickcourse
                   1111: #
                   1112:     foreach (keys %courseidbuffer) {
1.353     www      1113:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1114:     }
                   1115: #
                   1116: # File accesses
                   1117: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1118: #
1.191     harris41 1119:     foreach (keys %accesshash) {
1.185     www      1120:         my $entry=$_;
                   1121:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
                   1122:         my %temphash=($entry => $accesshash{$entry});
1.266     albertel 1123:         if (&Apache::lonnet::put('nohist_resevaldata',\%temphash,$1,$2) eq 'ok') {
1.185     www      1124: 	    delete $accesshash{$entry};
                   1125:         }
1.191     harris41 1126:     }
1.352     www      1127: #
                   1128: # Roles
                   1129: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1130: #
1.349     www      1131:     foreach (keys %userrolehash) {
                   1132:         my $entry=$_;
1.351     www      1133:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1134: 	    split(/\:/,$entry);
                   1135:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1136:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1137:                 $rudom,$runame) eq 'ok') {
                   1138: 	    delete $userrolehash{$entry};
                   1139:         }
                   1140:     }
1.186     www      1141:     $dumpcount++;
1.157     www      1142: }
                   1143: 
                   1144: sub courselog {
                   1145:     my $what=shift;
1.158     www      1146:     $what=time.':'.$what;
1.157     www      1147:     unless ($ENV{'request.course.id'}) { return ''; }
1.188     www      1148:     $coursedombuf{$ENV{'request.course.id'}}=
1.352     www      1149:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1150:     $coursenumbuf{$ENV{'request.course.id'}}=
1.188     www      1151:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1152:     $coursehombuf{$ENV{'request.course.id'}}=
                   1153:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.352     www      1154:     $coursedescrbuf{$ENV{'request.course.id'}}=
                   1155:        $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.157     www      1156:     if (defined $courselogs{$ENV{'request.course.id'}}) {
                   1157: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
                   1158:     } else {
                   1159: 	$courselogs{$ENV{'request.course.id'}}.=$what;
                   1160:     }
                   1161:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
                   1162: 	&flushcourselogs();
                   1163:     }
1.158     www      1164: }
                   1165: 
                   1166: sub courseacclog {
                   1167:     my $fnsymb=shift;
                   1168:     unless ($ENV{'request.course.id'}) { return ''; }
                   1169:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.192     www      1170:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
1.187     www      1171:         $what.=':POST';
1.191     harris41 1172: 	foreach (keys %ENV) {
1.158     www      1173:             if ($_=~/^form\.(.*)/) {
                   1174: 		$what.=':'.$1.'='.$ENV{$_};
                   1175:             }
1.191     harris41 1176:         }
1.158     www      1177:     }
                   1178:     &courselog($what);
1.149     www      1179: }
                   1180: 
1.185     www      1181: sub countacc {
                   1182:     my $url=&declutter(shift);
                   1183:     unless ($ENV{'request.course.id'}) { return ''; }
                   1184:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1185:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.185     www      1186:     if (defined($accesshash{$key})) {
                   1187: 	$accesshash{$key}++;
                   1188:     } else {
                   1189:         $accesshash{$key}=1;
                   1190:     }
                   1191: }
1.349     www      1192: 
1.361     www      1193: sub linklog {
                   1194:     my ($from,$to)=@_;
                   1195:     $from=&declutter($from);
                   1196:     $to=&declutter($to);
                   1197:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1198:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1199: }
                   1200:   
1.349     www      1201: sub userrolelog {
                   1202:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
                   1203:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
                   1204:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   1205:         ($trole=~/^cr/)) {
1.350     www      1206:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1207:        $userrolehash
                   1208:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1209:                     =$tend.':'.$tstart;
                   1210:    }
1.351     www      1211: }
                   1212: 
                   1213: sub get_course_adv_roles {
                   1214:     my $cid=shift;
                   1215:     $cid=$ENV{'request.course.id'} unless (defined($cid));
                   1216:     my %coursehash=&coursedescription($cid);
                   1217:     my %returnhash=();
                   1218:     my %dumphash=
                   1219:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1220:     my $now=time;
                   1221:     foreach (keys %dumphash) {
                   1222: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1223:         if (($tstart) && ($tstart<0)) { next; }
                   1224:         if (($tend) && ($tend<$now)) { next; }
                   1225:         if (($tstart) && ($now<$tstart)) { next; }
                   1226:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1227:         my $key=&plaintext($role);
                   1228:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1229:         if ($returnhash{$key}) {
                   1230: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1231:         } else {
                   1232:             $returnhash{$key}=$username.':'.$domain;
                   1233:         }
                   1234:     }
                   1235:     return sort %returnhash;
                   1236: }
1.353     www      1237: 
                   1238: # ---------------------------------------------------------- Course ID routines
                   1239: # Deal with domain's nohist_courseid.db files
                   1240: #
                   1241: 
                   1242: sub courseidput {
                   1243:     my ($domain,$what,$coursehome)=@_;
                   1244:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1245: }
                   1246: 
                   1247: sub courseiddump {
                   1248:     my ($domfilter,$descfilter,$sincefilter)=@_;
                   1249:     my %returnhash=();
1.355     www      1250:     unless ($domfilter) { $domfilter=''; }
1.353     www      1251:     foreach my $tryserver (keys %libserv) {
1.355     www      1252: 	if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.353     www      1253: 	    foreach (
                   1254:              split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.354     www      1255: 			       $sincefilter.':'.&escape($descfilter),
                   1256:                                $tryserver))) {
1.353     www      1257: 		my ($key,$value)=split(/\=/,$_);
                   1258:                 if (($key) && ($value)) {
                   1259: 		    $returnhash{&unescape($key)}=&unescape($value);
                   1260:                 }
                   1261:             }
                   1262: 
                   1263:         }
                   1264:     }
                   1265:     return %returnhash;
                   1266: }
                   1267: 
                   1268: #
1.149     www      1269: # ----------------------------------------------------------- Check out an item
                   1270: 
                   1271: sub checkout {
                   1272:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   1273:     my $now=time;
                   1274:     my $lonhost=$perlvar{'lonHostID'};
                   1275:     my $infostr=&escape(
1.234     www      1276:                  'CHECKOUTTOKEN&'.
1.149     www      1277:                  $tuname.'&'.
                   1278:                  $tudom.'&'.
                   1279:                  $tcrsid.'&'.
                   1280:                  $symb.'&'.
                   1281: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   1282:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      1283:     if ($token=~/^error\:/) { 
                   1284:         &logthis("<font color=blue>WARNING: ".
                   1285:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1286:                  "</font>");
                   1287:         return ''; 
                   1288:     }
                   1289: 
1.149     www      1290:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   1291:     $token=~tr/a-z/A-Z/;
                   1292: 
1.153     www      1293:     my %infohash=('resource.0.outtoken' => $token,
                   1294:                   'resource.0.checkouttime' => $now,
                   1295:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      1296: 
                   1297:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1298:        return '';
1.151     www      1299:     } else {
                   1300:         &logthis("<font color=blue>WARNING: ".
                   1301:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1302:                  "</font>");
1.149     www      1303:     }    
                   1304: 
                   1305:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1306:                          &escape('Checkout '.$infostr.' - '.
                   1307:                                                  $token)) ne 'ok') {
                   1308: 	return '';
1.151     www      1309:     } else {
                   1310:         &logthis("<font color=blue>WARNING: ".
                   1311:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1312:                  "</font>");
1.149     www      1313:     }
1.151     www      1314:     return $token;
1.149     www      1315: }
                   1316: 
                   1317: # ------------------------------------------------------------ Check in an item
                   1318: 
                   1319: sub checkin {
                   1320:     my $token=shift;
1.150     www      1321:     my $now=time;
                   1322:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   1323:     $lonhost=~tr/A-Z/a-z/;
                   1324:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
                   1325:     $dtoken=~s/\W/\_/g;
1.234     www      1326:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      1327:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   1328: 
1.154     www      1329:     unless (($tuname) && ($tudom)) {
                   1330:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   1331:         return '';
                   1332:     }
                   1333:     
                   1334:     unless (&allowed('mgr',$tcrsid)) {
                   1335:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   1336:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
                   1337:         return '';
                   1338:     }
                   1339: 
1.153     www      1340:     my %infohash=('resource.0.intoken' => $token,
                   1341:                   'resource.0.checkintime' => $now,
                   1342:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      1343: 
                   1344:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1345:        return '';
                   1346:     }    
                   1347: 
                   1348:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1349:                          &escape('Checkin - '.$token)) ne 'ok') {
                   1350: 	return '';
                   1351:     }
                   1352: 
                   1353:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      1354: }
                   1355: 
                   1356: # --------------------------------------------- Set Expire Date for Spreadsheet
                   1357: 
                   1358: sub expirespread {
                   1359:     my ($uname,$udom,$stype,$usymb)=@_;
                   1360:     my $cid=$ENV{'request.course.id'}; 
                   1361:     if ($cid) {
                   1362:        my $now=time;
                   1363:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
                   1364:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
                   1365:                             $ENV{'course.'.$cid.'.num'}.
                   1366: 	        	    ':nohist_expirationdates:'.
                   1367:                             &escape($key).'='.$now,
                   1368:                             $ENV{'course.'.$cid.'.home'})
                   1369:     }
                   1370:     return 'ok';
1.14      www      1371: }
                   1372: 
1.109     www      1373: # ----------------------------------------------------- Devalidate Spreadsheets
                   1374: 
                   1375: sub devalidate {
1.325     www      1376:     my ($symb,$uname,$udom)=@_;
1.109     www      1377:     my $cid=$ENV{'request.course.id'}; 
                   1378:     if ($cid) {
1.325     www      1379: # delete the stored spreadsheets for
                   1380: # - the student level sheet of this user in course's homespace
                   1381: # - the assessment level sheet for this resource 
                   1382: #   for this user in user's homespace
                   1383: 	my $key=$uname.':'.$udom.':';
1.109     www      1384:         my $status=
1.299     matthew  1385: 	    &del('nohist_calculatedsheets',
1.133     albertel 1386: 		 [$key.'studentcalc'],
                   1387: 		 $ENV{'course.'.$cid.'.domain'},
                   1388: 		 $ENV{'course.'.$cid.'.num'})
                   1389: 		.' '.
                   1390: 	    &del('nohist_calculatedsheets_'.$cid,
                   1391: 		 [$key.'assesscalc:'.$symb]);
1.109     www      1392:         unless ($status eq 'ok ok') {
                   1393:            &logthis('Could not devalidate spreadsheet '.
1.325     www      1394:                     $uname.' at '.$udom.' for '.
1.109     www      1395: 		    $symb.': '.$status);
1.133     albertel 1396:         }
1.109     www      1397:     }
                   1398: }
                   1399: 
1.265     albertel 1400: sub get_scalar {
                   1401:     my ($string,$end) = @_;
                   1402:     my $value;
                   1403:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   1404: 	$value = $1;
                   1405:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   1406: 	$value = $1;
                   1407:     }
                   1408:     return &unescape($value);
                   1409: }
                   1410: 
                   1411: sub array2str {
                   1412:   my (@array) = @_;
                   1413:   my $result=&arrayref2str(\@array);
                   1414:   $result=~s/^__ARRAY_REF__//;
                   1415:   $result=~s/__END_ARRAY_REF__$//;
                   1416:   return $result;
                   1417: }
                   1418: 
1.204     albertel 1419: sub arrayref2str {
                   1420:   my ($arrayref) = @_;
1.265     albertel 1421:   my $result='__ARRAY_REF__';
1.204     albertel 1422:   foreach my $elem (@$arrayref) {
1.265     albertel 1423:     if(ref($elem) eq 'ARRAY') {
                   1424:       $result.=&arrayref2str($elem).'&';
                   1425:     } elsif(ref($elem) eq 'HASH') {
                   1426:       $result.=&hashref2str($elem).'&';
                   1427:     } elsif(ref($elem)) {
                   1428:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 1429:     } else {
                   1430:       $result.=&escape($elem).'&';
                   1431:     }
                   1432:   }
                   1433:   $result=~s/\&$//;
1.265     albertel 1434:   $result .= '__END_ARRAY_REF__';
1.204     albertel 1435:   return $result;
                   1436: }
                   1437: 
1.168     albertel 1438: sub hash2str {
1.204     albertel 1439:   my (%hash) = @_;
                   1440:   my $result=&hashref2str(\%hash);
1.265     albertel 1441:   $result=~s/^__HASH_REF__//;
                   1442:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 1443:   return $result;
                   1444: }
                   1445: 
                   1446: sub hashref2str {
                   1447:   my ($hashref)=@_;
1.265     albertel 1448:   my $result='__HASH_REF__';
1.204     albertel 1449:   foreach (keys(%$hashref)) {
                   1450:     if (ref($_) eq 'ARRAY') {
1.265     albertel 1451:       $result.=&arrayref2str($_).'=';
1.204     albertel 1452:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 1453:       $result.=&hashref2str($_).'=';
1.204     albertel 1454:     } elsif (ref($_)) {
1.265     albertel 1455:       $result.='=';
                   1456:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 1457:     } else {
1.265     albertel 1458: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 1459:     }
                   1460: 
1.265     albertel 1461:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   1462:       $result.=&arrayref2str($hashref->{$_}).'&';
                   1463:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   1464:       $result.=&hashref2str($hashref->{$_}).'&';
                   1465:     } elsif(ref($hashref->{$_})) {
                   1466:        $result.='&';
                   1467:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 1468:     } else {
1.265     albertel 1469:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 1470:     }
                   1471:   }
1.168     albertel 1472:   $result=~s/\&$//;
1.265     albertel 1473:   $result .= '__END_HASH_REF__';
1.168     albertel 1474:   return $result;
                   1475: }
                   1476: 
                   1477: sub str2hash {
1.265     albertel 1478:     my ($string)=@_;
                   1479:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   1480:     return %$hash;
                   1481: }
                   1482: 
                   1483: sub str2hashref {
1.168     albertel 1484:   my ($string) = @_;
1.265     albertel 1485: 
                   1486:   my %hash;
                   1487: 
                   1488:   if($string !~ /^__HASH_REF__/) {
                   1489:       if (! ($string eq '' || !defined($string))) {
                   1490: 	  $hash{'error'}='Not hash reference';
                   1491:       }
                   1492:       return (\%hash, $string);
                   1493:   }
                   1494: 
                   1495:   $string =~ s/^__HASH_REF__//;
                   1496: 
                   1497:   while($string !~ /^__END_HASH_REF__/) {
                   1498:       #key
                   1499:       my $key='';
                   1500:       if($string =~ /^__HASH_REF__/) {
                   1501:           ($key, $string)=&str2hashref($string);
                   1502:           if(defined($key->{'error'})) {
                   1503:               $hash{'error'}='Bad data';
                   1504:               return (\%hash, $string);
                   1505:           }
                   1506:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1507:           ($key, $string)=&str2arrayref($string);
                   1508:           if($key->[0] eq 'Array reference error') {
                   1509:               $hash{'error'}='Bad data';
                   1510:               return (\%hash, $string);
                   1511:           }
                   1512:       } else {
                   1513:           $string =~ s/^(.*?)=//;
1.267     albertel 1514: 	  $key=&unescape($1);
1.265     albertel 1515:       }
                   1516:       $string =~ s/^=//;
                   1517: 
                   1518:       #value
                   1519:       my $value='';
                   1520:       if($string =~ /^__HASH_REF__/) {
                   1521:           ($value, $string)=&str2hashref($string);
                   1522:           if(defined($value->{'error'})) {
                   1523:               $hash{'error'}='Bad data';
                   1524:               return (\%hash, $string);
                   1525:           }
                   1526:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1527:           ($value, $string)=&str2arrayref($string);
                   1528:           if($value->[0] eq 'Array reference error') {
                   1529:               $hash{'error'}='Bad data';
                   1530:               return (\%hash, $string);
                   1531:           }
                   1532:       } else {
                   1533: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   1534:       }
                   1535:       $string =~ s/^&//;
                   1536: 
                   1537:       $hash{$key}=$value;
1.204     albertel 1538:   }
1.265     albertel 1539: 
                   1540:   $string =~ s/^__END_HASH_REF__//;
                   1541: 
                   1542:   return (\%hash, $string);
1.204     albertel 1543: }
                   1544: 
                   1545: sub str2array {
1.265     albertel 1546:     my ($string)=@_;
                   1547:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   1548:     return @$array;
                   1549: }
                   1550: 
                   1551: sub str2arrayref {
1.204     albertel 1552:   my ($string) = @_;
1.265     albertel 1553:   my @array;
                   1554: 
                   1555:   if($string !~ /^__ARRAY_REF__/) {
                   1556:       if (! ($string eq '' || !defined($string))) {
                   1557: 	  $array[0]='Array reference error';
                   1558:       }
                   1559:       return (\@array, $string);
                   1560:   }
                   1561: 
                   1562:   $string =~ s/^__ARRAY_REF__//;
                   1563: 
                   1564:   while($string !~ /^__END_ARRAY_REF__/) {
                   1565:       my $value='';
                   1566:       if($string =~ /^__HASH_REF__/) {
                   1567:           ($value, $string)=&str2hashref($string);
                   1568:           if(defined($value->{'error'})) {
                   1569:               $array[0] ='Array reference error';
                   1570:               return (\@array, $string);
                   1571:           }
                   1572:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1573:           ($value, $string)=&str2arrayref($string);
                   1574:           if($value->[0] eq 'Array reference error') {
                   1575:               $array[0] ='Array reference error';
                   1576:               return (\@array, $string);
                   1577:           }
                   1578:       } else {
                   1579: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   1580:       }
                   1581:       $string =~ s/^&//;
                   1582: 
                   1583:       push(@array, $value);
1.191     harris41 1584:   }
1.265     albertel 1585: 
                   1586:   $string =~ s/^__END_ARRAY_REF__//;
                   1587: 
                   1588:   return (\@array, $string);
1.168     albertel 1589: }
                   1590: 
1.167     albertel 1591: # -------------------------------------------------------------------Temp Store
                   1592: 
1.168     albertel 1593: sub tmpreset {
                   1594:   my ($symb,$namespace,$domain,$stuname) = @_;
                   1595:   if (!$symb) {
                   1596:     $symb=&symbread();
                   1597:     if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
                   1598:   }
                   1599:   $symb=escape($symb);
                   1600: 
                   1601:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1602:   $namespace=~s/\//\_/g;
                   1603:   $namespace=~s/\W//g;
                   1604: 
                   1605:   #FIXME needs to do something for /pub resources
                   1606:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1607:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1608:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1609:   my %hash;
                   1610:   if (tie(%hash,'GDBM_File',
                   1611: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1612: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 1613:     foreach my $key (keys %hash) {
1.180     albertel 1614:       if ($key=~ /:$symb/) {
1.168     albertel 1615: 	delete($hash{$key});
                   1616:       }
                   1617:     }
                   1618:   }
                   1619: }
                   1620: 
1.167     albertel 1621: sub tmpstore {
1.168     albertel 1622:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1623: 
                   1624:   if (!$symb) {
                   1625:     $symb=&symbread();
                   1626:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1627:   }
                   1628:   $symb=escape($symb);
                   1629: 
                   1630:   if (!$namespace) {
                   1631:     # I don't think we would ever want to store this for a course.
                   1632:     # it seems this will only be used if we don't have a course.
                   1633:     #$namespace=$ENV{'request.course.id'};
                   1634:     #if (!$namespace) {
                   1635:       $namespace=$ENV{'request.state'};
                   1636:     #}
                   1637:   }
                   1638:   $namespace=~s/\//\_/g;
                   1639:   $namespace=~s/\W//g;
                   1640: #FIXME needs to do something for /pub resources
                   1641:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1642:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1643:   my $now=time;
                   1644:   my %hash;
                   1645:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1646:   if (tie(%hash,'GDBM_File',
                   1647: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1648: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 1649:     $hash{"version:$symb"}++;
                   1650:     my $version=$hash{"version:$symb"};
                   1651:     my $allkeys=''; 
                   1652:     foreach my $key (keys(%$storehash)) {
                   1653:       $allkeys.=$key.':';
                   1654:       $hash{"$version:$symb:$key"}=$$storehash{$key};
                   1655:     }
                   1656:     $hash{"$version:$symb:timestamp"}=$now;
                   1657:     $allkeys.='timestamp';
                   1658:     $hash{"$version:keys:$symb"}=$allkeys;
                   1659:     if (untie(%hash)) {
                   1660:       return 'ok';
                   1661:     } else {
                   1662:       return "error:$!";
                   1663:     }
                   1664:   } else {
                   1665:     return "error:$!";
                   1666:   }
                   1667: }
1.167     albertel 1668: 
1.168     albertel 1669: # -----------------------------------------------------------------Temp Restore
1.167     albertel 1670: 
1.168     albertel 1671: sub tmprestore {
                   1672:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 1673: 
1.168     albertel 1674:   if (!$symb) {
                   1675:     $symb=&symbread();
                   1676:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1677:   }
                   1678:   $symb=escape($symb);
                   1679: 
                   1680:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1681:   #FIXME needs to do something for /pub resources
                   1682:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1683:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1684: 
                   1685:   my %returnhash;
                   1686:   $namespace=~s/\//\_/g;
                   1687:   $namespace=~s/\W//g;
                   1688:   my %hash;
                   1689:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1690:   if (tie(%hash,'GDBM_File',
                   1691: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1692: 	  &GDBM_READER(),0640)) {
1.168     albertel 1693:     my $version=$hash{"version:$symb"};
                   1694:     $returnhash{'version'}=$version;
                   1695:     my $scope;
                   1696:     for ($scope=1;$scope<=$version;$scope++) {
                   1697:       my $vkeys=$hash{"$scope:keys:$symb"};
                   1698:       my @keys=split(/:/,$vkeys);
                   1699:       my $key;
                   1700:       $returnhash{"$scope:keys"}=$vkeys;
                   1701:       foreach $key (@keys) {
                   1702: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
                   1703: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
1.167     albertel 1704:       }
                   1705:     }
1.168     albertel 1706:     if (!(untie(%hash))) {
                   1707:       return "error:$!";
                   1708:     }
                   1709:   } else {
                   1710:     return "error:$!";
                   1711:   }
                   1712:   return %returnhash;
1.167     albertel 1713: }
                   1714: 
1.9       www      1715: # ----------------------------------------------------------------------- Store
                   1716: 
                   1717: sub store {
1.124     www      1718:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1719:     my $home='';
                   1720: 
1.168     albertel 1721:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1722: 
1.213     www      1723:     $symb=&symbclean($symb);
1.122     albertel 1724:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1725: 
1.325     www      1726:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1727:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1728: 
                   1729:     &devalidate($symb,$stuname,$domain);
1.109     www      1730: 
                   1731:     $symb=escape($symb);
1.187     www      1732:     if (!$namespace) { 
                   1733:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1734:           return ''; 
                   1735:        } 
                   1736:     }
1.122     albertel 1737:     if (!$home) { $home=$ENV{'user.home'}; }
1.12      www      1738:     my $namevalue='';
1.191     harris41 1739:     foreach (keys %$storehash) {
1.122     albertel 1740:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1741:     }
1.12      www      1742:     $namevalue=~s/\&$//;
1.187     www      1743:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      1744:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      1745: }
                   1746: 
1.47      www      1747: # -------------------------------------------------------------- Critical Store
                   1748: 
                   1749: sub cstore {
1.124     www      1750:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1751:     my $home='';
                   1752: 
1.168     albertel 1753:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1754: 
1.213     www      1755:     $symb=&symbclean($symb);
1.122     albertel 1756:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1757: 
1.325     www      1758:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1759:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1760: 
                   1761:     &devalidate($symb,$stuname,$domain);
1.109     www      1762: 
                   1763:     $symb=escape($symb);
1.187     www      1764:     if (!$namespace) { 
                   1765:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1766:           return ''; 
                   1767:        } 
                   1768:     }
1.122     albertel 1769:     if (!$home) { $home=$ENV{'user.home'}; }
                   1770: 
1.47      www      1771:     my $namevalue='';
1.191     harris41 1772:     foreach (keys %$storehash) {
1.122     albertel 1773:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1774:     }
1.47      www      1775:     $namevalue=~s/\&$//;
1.187     www      1776:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      1777:     return critical
                   1778:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      1779: }
                   1780: 
1.9       www      1781: # --------------------------------------------------------------------- Restore
                   1782: 
                   1783: sub restore {
1.124     www      1784:     my ($symb,$namespace,$domain,$stuname) = @_;
                   1785:     my $home='';
                   1786: 
1.168     albertel 1787:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1788: 
1.122     albertel 1789:     if (!$symb) {
                   1790:       unless ($symb=escape(&symbread())) { return ''; }
                   1791:     } else {
1.213     www      1792:       $symb=&escape(&symbclean($symb));
1.122     albertel 1793:     }
1.188     www      1794:     if (!$namespace) { 
                   1795:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1796:           return ''; 
                   1797:        } 
                   1798:     }
1.122     albertel 1799:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1800:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1801:     if (!$home) { $home=$ENV{'user.home'}; }
                   1802:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   1803: 
1.12      www      1804:     my %returnhash=();
1.191     harris41 1805:     foreach (split(/\&/,$answer)) {
1.12      www      1806: 	my ($name,$value)=split(/\=/,$_);
                   1807:         $returnhash{&unescape($name)}=&unescape($value);
1.191     harris41 1808:     }
1.75      www      1809:     my $version;
                   1810:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 1811:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      1812:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 1813:        }
1.75      www      1814:     }
1.13      www      1815:     return %returnhash;
1.34      www      1816: }
                   1817: 
                   1818: # ---------------------------------------------------------- Course Description
                   1819: 
                   1820: sub coursedescription {
                   1821:     my $courseid=shift;
                   1822:     $courseid=~s/^\///;
1.49      www      1823:     $courseid=~s/\_/\//g;
1.34      www      1824:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 1825:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 1826:     my $normalid=$cdomain.'_'.$cnum;
                   1827:     # need to always cache even if we get errors otherwise we keep 
                   1828:     # trying and trying and trying to get the course description.
                   1829:     my %envhash=();
                   1830:     my %returnhash=();
                   1831:     $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34      www      1832:     if ($chome ne 'no_host') {
1.302     albertel 1833:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 1834:        if (!exists($returnhash{'con_lost'})) {
                   1835:            $returnhash{'home'}= $chome;
                   1836: 	   $returnhash{'domain'} = $cdomain;
                   1837: 	   $returnhash{'num'} = $cnum;
1.130     albertel 1838:            while (my ($name,$value) = each %returnhash) {
1.53      www      1839:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 1840:            }
1.270     www      1841:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      1842:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.38      www      1843: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      1844:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   1845:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   1846:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      1847:        }
                   1848:     }
1.302     albertel 1849:     &appenv(%envhash);
                   1850:     return %returnhash;
1.9       www      1851: }
1.1       albertel 1852: 
1.103     harris41 1853: # -------------------------------------------------------- Get user privileges
1.11      www      1854: 
                   1855: sub rolesinit {
                   1856:     my ($domain,$username,$authhost)=@_;
                   1857:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      1858:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      1859:     my %allroles=();
                   1860:     my %thesepriv=();
                   1861:     my $now=time;
1.21      www      1862:     my $userroles="user.login.time=$now\n";
1.11      www      1863:     my $thesestr;
                   1864: 
                   1865:     if ($rolesdump ne '') {
1.191     harris41 1866:         foreach (split(/&/,$rolesdump)) {
1.21      www      1867: 	  if ($_!~/^rolesdef\&/) {
1.11      www      1868:             my ($area,$role)=split(/=/,$_);
1.21      www      1869:             $area=~s/\_\w\w$//;
1.11      www      1870:             my ($trole,$tend,$tstart)=split(/_/,$role);
1.21      www      1871:             $userroles.='user.role.'.$trole.'.'.$area.'='.
                   1872:                         $tstart.'.'.$tend."\n";
1.349     www      1873: # log the associated role with the area
                   1874:             &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.11      www      1875:             if ($tend!=0) {
                   1876: 	        if ($tend<$now) {
                   1877: 	            $trole='';
                   1878:                 } 
                   1879:             }
                   1880:             if ($tstart!=0) {
                   1881:                 if ($tstart>$now) {
                   1882:                    $trole='';        
                   1883:                 }
                   1884:             }
                   1885:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 1886: 		my $spec=$trole.'.'.$area;
                   1887: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   1888: 		if ($trole =~ /^cr\//) {
                   1889: 		    my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   1890: 		    my $homsvr=homeserver($rauthor,$rdomain);
                   1891: 		    if ($hostname{$homsvr} ne '') {
                   1892: 			my $roledef=
                   1893: 			    reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
                   1894: 				  $homsvr);
                   1895: 			if (($roledef ne 'con_lost') && ($roledef ne '')) {
                   1896: 			    my ($syspriv,$dompriv,$coursepriv)=
                   1897: 				split(/\_/,unescape($roledef));
                   1898: 			    if (defined($syspriv)) {
                   1899: 				$allroles{'cm./'}.=':'.$syspriv;
                   1900: 				$allroles{$spec.'./'}.=':'.$syspriv;
                   1901: 			    }
                   1902: 			    if ($tdomain ne '') {
                   1903: 				if (defined($dompriv)) {
                   1904: 				    $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   1905: 				    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   1906: 				}
                   1907: 				if ($trest ne '') {
                   1908: 				    if (defined($coursepriv)) {
                   1909: 					$allroles{'cm.'.$area}.=':'.$coursepriv;
                   1910: 					$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   1911: 				    }
                   1912: 				}
                   1913: 			    }
                   1914: 			}
                   1915: 		    }
                   1916: 		} else {
                   1917: 		    if (defined($pr{$trole.':s'})) {
                   1918: 			$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   1919: 			$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   1920: 		    }
                   1921: 		    if ($tdomain ne '') {
                   1922: 			if (defined($pr{$trole.':d'})) {
                   1923: 			    $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   1924: 			    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   1925: 			}
                   1926: 			if ($trest ne '') {
                   1927: 			    if (defined($pr{$trole.':c'})) {
                   1928: 				$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   1929: 				$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   1930: 			    }
                   1931: 			}
                   1932: 		    }
                   1933: 		}
1.12      www      1934:             }
                   1935:           } 
1.191     harris41 1936:         }
1.125     www      1937:         my $adv=0;
1.128     www      1938:         my $author=0;
1.191     harris41 1939:         foreach (keys %allroles) {
1.11      www      1940:             %thesepriv=();
1.146     www      1941:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1.128     www      1942:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1.191     harris41 1943:             foreach (split(/:/,$allroles{$_})) {
1.11      www      1944:                 if ($_ ne '') {
1.103     harris41 1945: 		    my ($privilege,$restrictions)=split(/&/,$_);
1.11      www      1946:                     if ($restrictions eq '') {
1.103     harris41 1947: 			$thesepriv{$privilege}='F';
1.11      www      1948:                     } else {
1.103     harris41 1949:                         if ($thesepriv{$privilege} ne 'F') {
                   1950: 			    $thesepriv{$privilege}.=$restrictions;
1.11      www      1951:                         }
                   1952:                     }
                   1953:                 }
1.191     harris41 1954:             }
1.11      www      1955:             $thesestr='';
1.191     harris41 1956:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.11      www      1957:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1.191     harris41 1958:         }
1.128     www      1959:         $userroles.='user.adv='.$adv."\n".
                   1960: 	            'user.author='.$author."\n";
1.126     www      1961:         $ENV{'user.adv'}=$adv;
1.11      www      1962:     }
                   1963:     return $userroles;  
                   1964: }
                   1965: 
1.12      www      1966: # --------------------------------------------------------------- get interface
                   1967: 
                   1968: sub get {
1.131     albertel 1969:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      1970:    my $items='';
1.191     harris41 1971:    foreach (@$storearr) {
1.12      www      1972:        $items.=escape($_).'&';
1.191     harris41 1973:    }
1.12      www      1974:    $items=~s/\&$//;
1.131     albertel 1975:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1976:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1977:    my $uhome=&homeserver($uname,$udomain);
                   1978: 
1.133     albertel 1979:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      1980:    my @pairs=split(/\&/,$rep);
1.273     albertel 1981:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1982:      return @pairs;
                   1983:    }
1.15      www      1984:    my %returnhash=();
1.42      www      1985:    my $i=0;
1.191     harris41 1986:    foreach (@$storearr) {
1.42      www      1987:       $returnhash{$_}=unescape($pairs[$i]);
                   1988:       $i++;
1.191     harris41 1989:    }
1.15      www      1990:    return %returnhash;
1.27      www      1991: }
                   1992: 
                   1993: # --------------------------------------------------------------- del interface
                   1994: 
                   1995: sub del {
1.133     albertel 1996:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      1997:    my $items='';
1.191     harris41 1998:    foreach (@$storearr) {
1.27      www      1999:        $items.=escape($_).'&';
1.191     harris41 2000:    }
1.27      www      2001:    $items=~s/\&$//;
1.133     albertel 2002:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2003:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2004:    my $uhome=&homeserver($uname,$udomain);
                   2005: 
                   2006:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2007: }
                   2008: 
                   2009: # -------------------------------------------------------------- dump interface
                   2010: 
                   2011: sub dump {
1.193     www      2012:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.129     albertel 2013:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2014:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2015:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2016:    if ($regexp) {
                   2017:        $regexp=&escape($regexp);
                   2018:    } else {
                   2019:        $regexp='.';
                   2020:    }
                   2021:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      2022:    my @pairs=split(/\&/,$rep);
                   2023:    my %returnhash=();
1.191     harris41 2024:    foreach (@pairs) {
1.12      www      2025:       my ($key,$value)=split(/=/,$_);
1.29      www      2026:       $returnhash{unescape($key)}=unescape($value);
1.318     matthew  2027:    }
                   2028:    return %returnhash;
                   2029: }
                   2030: 
1.319     matthew  2031: # --------------------------------------------------------------- currentdump
                   2032: sub currentdump {
1.328     matthew  2033:    my ($courseid,$sdom,$sname)=@_;
1.326     matthew  2034:    $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   2035:    $sdom     = $ENV{'user.domain'}       if (! defined($sdom));
                   2036:    $sname    = $ENV{'user.name'}         if (! defined($sname));
                   2037:    my $uhome = &homeserver($sname,$sdom);
                   2038:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2039:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2040:    #
1.318     matthew  2041:    my %returnhash=();
1.319     matthew  2042:    #
                   2043:    if ($rep eq "unknown_cmd") { 
                   2044:        # an old lond will not know currentdump
                   2045:        # Do a dump and make it look like a currentdump
1.326     matthew  2046:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2047:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2048:        my %hash = @tmp;
                   2049:        @tmp=();
                   2050:        # Code ripped from lond, essentially.  The only difference
                   2051:        # here is the unescaping done by lonnet::dump().  Conceivably
                   2052:        # we might run in to problems with parameter names =~ /^v\./
                   2053:        while (my ($key,$value) = each(%hash)) {
                   2054:            my ($v,$symb,$param) = split(/:/,$key);
                   2055:            next if ($v eq 'version' || $symb eq 'keys');
                   2056:            next if (exists($returnhash{$symb}) &&
                   2057:                     exists($returnhash{$symb}->{$param}) &&
                   2058:                     $returnhash{$symb}->{'v.'.$param} > $v);
                   2059:            $returnhash{$symb}->{$param}=$value;
                   2060:            $returnhash{$symb}->{'v.'.$param}=$v;
                   2061:        }
                   2062:        #
                   2063:        # Remove all of the keys in the hashes which keep track of
                   2064:        # the version of the parameter.
                   2065:        while (my ($symb,$param_hash) = each(%returnhash)) {
                   2066:            # use a foreach because we are going to delete from the hash.
                   2067:            foreach my $key (keys(%$param_hash)) {
                   2068:                delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2069:            }
                   2070:        }
                   2071:    } else {
                   2072:        my @pairs=split(/\&/,$rep);
                   2073:        foreach (@pairs) {
                   2074:            my ($key,$value)=split(/=/,$_);
                   2075:            my ($symb,$param) = split(/:/,$key);
                   2076:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
                   2077:                                                           &unescape($value);
                   2078:        }
1.191     harris41 2079:    }
1.12      www      2080:    return %returnhash;
                   2081: }
                   2082: 
                   2083: # --------------------------------------------------------------- put interface
                   2084: 
                   2085: sub put {
1.134     albertel 2086:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2087:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2088:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2089:    my $uhome=&homeserver($uname,$udomain);
1.12      www      2090:    my $items='';
1.191     harris41 2091:    foreach (keys %$storehash) {
1.134     albertel 2092:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1.191     harris41 2093:    }
1.12      www      2094:    $items=~s/\&$//;
1.134     albertel 2095:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      2096: }
                   2097: 
                   2098: # ------------------------------------------------------ critical put interface
                   2099: 
                   2100: sub cput {
1.134     albertel 2101:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2102:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2103:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2104:    my $uhome=&homeserver($uname,$udomain);
1.47      www      2105:    my $items='';
1.191     harris41 2106:    foreach (keys %$storehash) {
1.134     albertel 2107:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 2108:    }
1.47      www      2109:    $items=~s/\&$//;
1.134     albertel 2110:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2111: }
                   2112: 
                   2113: # -------------------------------------------------------------- eget interface
                   2114: 
                   2115: sub eget {
1.133     albertel 2116:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2117:    my $items='';
1.191     harris41 2118:    foreach (@$storearr) {
1.12      www      2119:        $items.=escape($_).'&';
1.191     harris41 2120:    }
1.12      www      2121:    $items=~s/\&$//;
1.133     albertel 2122:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2123:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2124:    my $uhome=&homeserver($uname,$udomain);
                   2125:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2126:    my @pairs=split(/\&/,$rep);
                   2127:    my %returnhash=();
1.42      www      2128:    my $i=0;
1.191     harris41 2129:    foreach (@$storearr) {
1.42      www      2130:       $returnhash{$_}=unescape($pairs[$i]);
                   2131:       $i++;
1.191     harris41 2132:    }
1.12      www      2133:    return %returnhash;
                   2134: }
                   2135: 
1.341     www      2136: # ---------------------------------------------- Custom access rule evaluation
                   2137: 
                   2138: sub customaccess {
                   2139:     my ($priv,$uri)=@_;
1.342     www      2140:     my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
1.343     www      2141:     $urealm=~s/^\W//;
                   2142:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      2143:     my $access=0;
                   2144:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      2145: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      2146:         if ($role) {
                   2147: 	   if ($role ne $urole) { next; }
                   2148:         }
                   2149:         foreach (split(/\s*\,\s*/,$realm)) {
                   2150:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   2151:             if ($tdom) {
                   2152: 		if ($tdom ne $udom) { next; }
                   2153:             }
                   2154:             if ($tcrs) {
                   2155: 		if ($tcrs ne $ucrs) { next; }
                   2156:             }
                   2157:             if ($tsec) {
                   2158: 		if ($tsec ne $usec) { next; }
                   2159:             }
                   2160:             $access=($effect eq 'allow');
                   2161:             last;
1.342     www      2162:         }
1.341     www      2163:     }
                   2164:     return $access;
                   2165: }
                   2166: 
1.103     harris41 2167: # ------------------------------------------------- Check for a user privilege
1.12      www      2168: 
                   2169: sub allowed {
                   2170:     my ($priv,$uri)=@_;
1.152     www      2171: 
                   2172:     my $orguri=$uri;
1.52      www      2173:     $uri=&declutter($uri);
1.29      www      2174: 
1.54      www      2175: # Free bre access to adm and meta resources
1.29      www      2176: 
1.54      www      2177:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      2178: 	return 'F';
1.159     www      2179:     }
                   2180: 
                   2181: # Free bre to public access
                   2182: 
                   2183:     if ($priv eq 'bre') {
1.238     www      2184:         my $copyright=&metadata($uri,'copyright');
1.301     www      2185: 	if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 
                   2186:            return 'F'; 
                   2187:         }
1.238     www      2188:         if ($copyright eq 'priv') {
                   2189:             $uri=~/([^\/]+)\/([^\/]+)\//;
                   2190: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
                   2191: 		return '';
                   2192:             }
                   2193:         }
                   2194:         if ($copyright eq 'domain') {
                   2195:             $uri=~/([^\/]+)\/([^\/]+)\//;
                   2196: 	    unless (($ENV{'user.domain'} eq $1) ||
                   2197:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
                   2198: 		return '';
                   2199:             }
1.262     matthew  2200:         }
                   2201:         if ($ENV{'request.role'}=~ /li\.\//) {
                   2202:             # Library role, so allow browsing of resources in this domain.
                   2203:             return 'F';
1.238     www      2204:         }
1.341     www      2205:         if ($copyright eq 'custom') {
                   2206: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   2207:         }
1.14      www      2208:     }
1.264     matthew  2209:     # Domain coordinator is trying to create a course
                   2210:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
                   2211:         # uri is the requested domain in this case.
                   2212:         # comparison to 'request.role.domain' shows if the user has selected
                   2213:         # a role of dc for the domain in question. 
                   2214:         return 'F' if ($uri eq $ENV{'request.role.domain'});
                   2215:     }
1.29      www      2216: 
1.52      www      2217:     my $thisallowed='';
                   2218:     my $statecond=0;
                   2219:     my $courseprivid='';
                   2220: 
                   2221: # Course
                   2222: 
                   2223:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
                   2224:        $thisallowed.=$1;
                   2225:     }
1.29      www      2226: 
1.52      www      2227: # Domain
                   2228: 
                   2229:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
                   2230:        =~/$priv\&([^\:]*)/) {
1.12      www      2231:        $thisallowed.=$1;
                   2232:     }
1.52      www      2233: 
                   2234: # Course: uri itself is a course
1.66      www      2235:     my $courseuri=$uri;
                   2236:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      2237:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      2238: 
1.83      www      2239:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.52      www      2240:        =~/$priv\&([^\:]*)/) {
1.12      www      2241:        $thisallowed.=$1;
                   2242:     }
1.29      www      2243: 
1.314     www      2244: # URI is an uploaded document for this course
                   2245: 
                   2246:     if (($priv eq 'bre') && 
                   2247:         ($uri=~/^uploaded\/$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}\/$ENV{'course.'.$ENV{'request.course.id'}.'.num'}/)) {
                   2248:         return 'F';
                   2249:     }
1.52      www      2250: # Full access at system, domain or course-wide level? Exit.
1.29      www      2251: 
                   2252:     if ($thisallowed=~/F/) {
                   2253: 	return 'F';
                   2254:     }
                   2255: 
1.52      www      2256: # If this is generating or modifying users, exit with special codes
1.29      www      2257: 
1.166     www      2258:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1.52      www      2259: 	return $thisallowed;
                   2260:     }
                   2261: #
1.103     harris41 2262: # Gathered so far: system, domain and course wide privileges
1.52      www      2263: #
                   2264: # Course: See if uri or referer is an individual resource that is part of 
                   2265: # the course
                   2266: 
                   2267:     if ($ENV{'request.course.id'}) {
1.232     www      2268: 
1.52      www      2269:        $courseprivid=$ENV{'request.course.id'};
                   2270:        if ($ENV{'request.course.sec'}) {
                   2271:           $courseprivid.='/'.$ENV{'request.course.sec'};
                   2272:        }
                   2273:        $courseprivid=~s/\_/\//;
                   2274:        my $checkreferer=1;
1.232     www      2275:        my ($match,$cond)=&is_on_map($uri);
                   2276:        if ($match) {
                   2277:            $statecond=$cond;
1.52      www      2278:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   2279:                =~/$priv\&([^\:]*)/) {
                   2280:                $thisallowed.=$1;
                   2281:                $checkreferer=0;
                   2282:            }
1.29      www      2283:        }
1.83      www      2284:        
1.148     www      2285:        if ($checkreferer) {
1.152     www      2286: 	  my $refuri=$ENV{'httpref.'.$orguri};
1.148     www      2287:             unless ($refuri) {
1.191     harris41 2288:                 foreach (keys %ENV) {
1.148     www      2289: 		    if ($_=~/^httpref\..*\*/) {
                   2290: 			my $pattern=$_;
1.156     www      2291:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      2292:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   2293:                         $pattern=~s/\//\\\//g;
1.152     www      2294:                         if ($orguri=~/$pattern/) {
1.148     www      2295: 			    $refuri=$ENV{$_};
                   2296:                         }
                   2297:                     }
1.191     harris41 2298:                 }
1.148     www      2299:             }
1.232     www      2300: 
1.148     www      2301:          if ($refuri) { 
1.152     www      2302: 	  $refuri=&declutter($refuri);
1.232     www      2303:           my ($match,$cond)=&is_on_map($refuri);
                   2304:             if ($match) {
                   2305:               my $refstatecond=$cond;
1.52      www      2306:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   2307:                   =~/$priv\&([^\:]*)/) {
                   2308:                   $thisallowed.=$1;
1.53      www      2309:                   $uri=$refuri;
                   2310:                   $statecond=$refstatecond;
1.52      www      2311:               }
                   2312:           }
1.148     www      2313:         }
1.29      www      2314:        }
1.52      www      2315:    }
1.29      www      2316: 
1.52      www      2317: #
1.103     harris41 2318: # Gathered now: all privileges that could apply, and condition number
1.52      www      2319: # 
                   2320: #
                   2321: # Full or no access?
                   2322: #
1.29      www      2323: 
1.52      www      2324:     if ($thisallowed=~/F/) {
                   2325: 	return 'F';
                   2326:     }
1.29      www      2327: 
1.52      www      2328:     unless ($thisallowed) {
                   2329:         return '';
                   2330:     }
1.29      www      2331: 
1.52      www      2332: # Restrictions exist, deal with them
                   2333: #
                   2334: #   C:according to course preferences
                   2335: #   R:according to resource settings
                   2336: #   L:unless locked
                   2337: #   X:according to user session state
                   2338: #
                   2339: 
                   2340: # Possibly locked functionality, check all courses
1.54      www      2341: # Locks might take effect only after 10 minutes cache expiration for other
                   2342: # courses, and 2 minutes for current course
1.52      www      2343: 
                   2344:     my $envkey;
                   2345:     if ($thisallowed=~/L/) {
                   2346:         foreach $envkey (keys %ENV) {
1.54      www      2347:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   2348:                my $courseid=$2;
                   2349:                my $roleid=$1.'.'.$2;
1.92      www      2350:                $courseid=~s/^\///;
1.54      www      2351:                my $expiretime=600;
                   2352:                if ($ENV{'request.role'} eq $roleid) {
                   2353: 		  $expiretime=120;
                   2354:                }
                   2355: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   2356:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
                   2357:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
                   2358: 		   &coursedescription($courseid);
                   2359:                }
                   2360:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
                   2361:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   2362: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57      www      2363:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      2364:                             $ENV{'user.home'},
1.57      www      2365:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      2366:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      2367:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2368: 		       return '';
                   2369:                    }
                   2370:                }
1.54      www      2371:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
                   2372:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   2373: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57      www      2374:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      2375:                             $ENV{'user.home'},
1.57      www      2376:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      2377:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      2378:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2379: 		       return '';
                   2380:                    }
                   2381:                }
                   2382: 	   }
1.29      www      2383:        }
1.52      www      2384:     }
                   2385:    
                   2386: #
                   2387: # Rest of the restrictions depend on selected course
                   2388: #
                   2389: 
                   2390:     unless ($ENV{'request.course.id'}) {
                   2391:        return '1';
                   2392:     }
1.29      www      2393: 
1.52      www      2394: #
                   2395: # Now user is definitely in a course
                   2396: #
1.53      www      2397: 
                   2398: 
                   2399: # Course preferences
                   2400: 
                   2401:    if ($thisallowed=~/C/) {
1.54      www      2402:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.237     www      2403:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.54      www      2404:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.194     www      2405: 	   =~/$rolecode/) {
1.57      www      2406:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   2407:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.237     www      2408:                 $ENV{'request.course.id'});
                   2409:            return '';
                   2410:        }
                   2411: 
                   2412:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
                   2413: 	   =~/$unamedom/) {
                   2414:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   2415:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.54      www      2416:                 $ENV{'request.course.id'});
                   2417:            return '';
                   2418:        }
1.53      www      2419:    }
                   2420: 
                   2421: # Resource preferences
                   2422: 
                   2423:    if ($thisallowed=~/R/) {
1.54      www      2424:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.341     www      2425:        if (&metadata($uri,'roledeny')=~/$rolecode/) {
                   2426: 	  &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1.57      www      2427:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341     www      2428:           return '';
1.54      www      2429:        }
1.53      www      2430:    }
1.30      www      2431: 
1.246     www      2432: # Restricted by state or randomout?
1.30      www      2433: 
1.52      www      2434:    if ($thisallowed=~/X/) {
1.247     www      2435:       if ($ENV{'acc.randomout'}) {
1.249     www      2436:          my $symb=&symbread($uri,1);
1.248     www      2437:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
                   2438:             return ''; 
                   2439:          }
1.247     www      2440:       }
                   2441:       if (&condval($statecond)) {
1.52      www      2442: 	 return '2';
                   2443:       } else {
                   2444:          return '';
                   2445:       }
                   2446:    }
1.30      www      2447: 
1.52      www      2448:    return 'F';
1.232     www      2449: }
                   2450: 
                   2451: # --------------------------------------------------- Is a resource on the map?
                   2452: 
                   2453: sub is_on_map {
                   2454:     my $uri=&declutter(shift);
                   2455:     my @uriparts=split(/\//,$uri);
                   2456:     my $filename=$uriparts[$#uriparts];
                   2457:     my $pathname=$uri;
1.289     bowersj2 2458:     $pathname=~s|/\Q$filename\E$||;
1.332     www      2459:     $pathname=~s/^adm\/wrapper\///;    
1.289     bowersj2 2460:     #Trying to find the conditional for the file
1.232     www      2461:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 2462: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      2463:     if ($match) {
1.289     bowersj2 2464: 	return (1,$1);
                   2465:     } else {
                   2466: 	return (0,0);
                   2467:     }
1.12      www      2468: }
                   2469: 
                   2470: # ----------------------------------------------------------------- Define Role
                   2471: 
                   2472: sub definerole {
                   2473:   if (allowed('mcr','/')) {
                   2474:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.191     harris41 2475:     foreach (split('/',$sysrole)) {
1.21      www      2476: 	my ($crole,$cqual)=split(/\&/,$_);
                   2477:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
                   2478:         if ($pr{'cr:s'}=~/$crole\&/) {
                   2479: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
                   2480:                return "refused:s:$crole&$cqual"; 
                   2481:             }
                   2482:         }
1.191     harris41 2483:     }
                   2484:     foreach (split('/',$domrole)) {
1.21      www      2485: 	my ($crole,$cqual)=split(/\&/,$_);
                   2486:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
                   2487:         if ($pr{'cr:d'}=~/$crole\&/) {
                   2488: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
                   2489:                return "refused:d:$crole&$cqual"; 
                   2490:             }
                   2491:         }
1.191     harris41 2492:     }
                   2493:     foreach (split('/',$courole)) {
1.21      www      2494: 	my ($crole,$cqual)=split(/\&/,$_);
                   2495:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
                   2496:         if ($pr{'cr:c'}=~/$crole\&/) {
                   2497: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
                   2498:                return "refused:c:$crole&$cqual"; 
                   2499:             }
                   2500:         }
1.191     harris41 2501:     }
1.12      www      2502:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2503:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21      www      2504: 	        "rolesdef_$rolename=".
                   2505:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.12      www      2506:     return reply($command,$ENV{'user.home'});
                   2507:   } else {
                   2508:     return 'refused';
                   2509:   }
1.105     harris41 2510: }
                   2511: 
                   2512: # ---------------- Make a metadata query against the network of library servers
                   2513: 
                   2514: sub metadata_query {
1.244     matthew  2515:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 2516:     my %rhash;
1.244     matthew  2517:     my @server_list = (defined($server_array) ? @$server_array
                   2518:                                               : keys(%libserv) );
                   2519:     for my $server (@server_list) {
1.118     harris41 2520: 	unless ($custom or $customshow) {
                   2521: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   2522: 	    $rhash{$server}=$reply;
                   2523: 	}
                   2524: 	else {
                   2525: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   2526: 			     &escape($custom).':'.&escape($customshow),
                   2527: 			     $server);
                   2528: 	    $rhash{$server}=$reply;
                   2529: 	}
1.112     harris41 2530:     }
1.118     harris41 2531:     return \%rhash;
1.240     www      2532: }
                   2533: 
                   2534: # ----------------------------------------- Send log queries and wait for reply
                   2535: 
                   2536: sub log_query {
                   2537:     my ($uname,$udom,$query,%filters)=@_;
                   2538:     my $uhome=&homeserver($uname,$udom);
                   2539:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   2540:     my $uhost=$hostname{$uhome};
1.241     www      2541:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      2542:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   2543:                        $uhome);
                   2544:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
1.242     www      2545:     return get_query_reply($queryid);
                   2546: }
                   2547: 
                   2548: sub get_query_reply {
                   2549:     my $queryid=shift;
1.240     www      2550:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   2551:     my $reply='';
                   2552:     for (1..100) {
                   2553: 	sleep 2;
                   2554:         if (-e $replyfile.'.end') {
                   2555: 	    if (my $fh=Apache::File->new($replyfile)) {
                   2556:                $reply.=<$fh>;
                   2557:                $fh->close;
                   2558: 	   } else { return 'error: reply_file_error'; }
1.242     www      2559:            return &unescape($reply);
                   2560: 	}
1.240     www      2561:     }
1.242     www      2562:     return 'timeout:'.$queryid;
1.240     www      2563: }
                   2564: 
                   2565: sub courselog_query {
1.241     www      2566: #
                   2567: # possible filters:
                   2568: # url: url or symb
                   2569: # username
                   2570: # domain
                   2571: # action: view, submit, grade
                   2572: # start: timestamp
                   2573: # end: timestamp
                   2574: #
1.240     www      2575:     my (%filters)=@_;
                   2576:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
1.241     www      2577:     if ($filters{'url'}) {
                   2578: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   2579:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   2580:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   2581:     }
1.240     www      2582:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   2583:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   2584:     return &log_query($cname,$cdom,'courselog',%filters);
                   2585: }
                   2586: 
                   2587: sub userlog_query {
                   2588:     my ($uname,$udom,%filters)=@_;
                   2589:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      2590: }
                   2591: 
                   2592: # ------------------------------------------------------------------ Plain Text
                   2593: 
                   2594: sub plaintext {
1.22      www      2595:     my $short=shift;
                   2596:     return $prp{$short};
1.12      www      2597: }
                   2598: 
                   2599: # ----------------------------------------------------------------- Assign Role
                   2600: 
                   2601: sub assignrole {
1.357     www      2602:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      2603:     my $mrole;
                   2604:     if ($role =~ /^cr\//) {
1.104     www      2605: 	unless (&allowed('ccr',$url)) {
                   2606:            &logthis('Refused custom assignrole: '.
                   2607:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2608: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2609:            return 'refused'; 
                   2610:         }
1.21      www      2611:         $mrole='cr';
                   2612:     } else {
1.82      www      2613:         my $cwosec=$url;
1.83      www      2614:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.104     www      2615:         unless (&allowed('c'.$role,$cwosec)) { 
                   2616:            &logthis('Refused assignrole: '.
                   2617:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2618: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2619:            return 'refused'; 
                   2620:         }
1.21      www      2621:         $mrole=$role;
                   2622:     }
                   2623:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2624:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      2625:     if ($end) { $command.='_'.$end; }
1.21      www      2626:     if ($start) {
                   2627: 	if ($end) { 
1.81      www      2628:            $command.='_'.$start; 
1.21      www      2629:         } else {
1.81      www      2630:            $command.='_0_'.$start;
1.21      www      2631:         }
                   2632:     }
1.357     www      2633: # actually delete
                   2634:     if ($deleteflag) {
                   2635: 	if (&allowed('dro',$udom)) {
                   2636: # modify command to delete the role
                   2637:            $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2638:                 "$udom:$uname:$url".'_'."$mrole";
                   2639: # set start and finish to negative values for userrolelog
                   2640:            $start=-1;
                   2641:            $end=-1;
                   2642:         }
                   2643:     }
                   2644: # send command
1.349     www      2645:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      2646: # log new user role if status is ok
1.349     www      2647:     if ($answer eq 'ok') {
                   2648: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
                   2649:     }
                   2650:     return $answer;
1.169     harris41 2651: }
                   2652: 
                   2653: # -------------------------------------------------- Modify user authentication
1.197     www      2654: # Overrides without validation
                   2655: 
1.169     harris41 2656: sub modifyuserauth {
                   2657:     my ($udom,$uname,$umode,$upass)=@_;
                   2658:     my $uhome=&homeserver($uname,$udom);
1.197     www      2659:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   2660:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.272     matthew  2661:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
                   2662:              ' in domain '.$ENV{'request.role.domain'});  
1.169     harris41 2663:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   2664: 		     &escape($upass),$uhome);
1.197     www      2665:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                   2666:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   2667:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   2668:     &log($udom,,$uname,$uhome,
                   2669:         'Authentication changed by '.$ENV{'user.domain'}.', '.
                   2670:                                      $ENV{'user.name'}.', '.$umode.
                   2671:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 2672:     unless ($reply eq 'ok') {
1.197     www      2673:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 2674: 	return 'error: '.$reply;
                   2675:     }   
1.170     harris41 2676:     return 'ok';
1.80      www      2677: }
                   2678: 
1.81      www      2679: # --------------------------------------------------------------- Modify a user
1.80      www      2680: 
1.81      www      2681: sub modifyuser {
1.206     matthew  2682:     my ($udom,    $uname, $uid,
                   2683:         $umode,   $upass, $first,
                   2684:         $middle,  $last,  $gene,
                   2685:         $forceid, $desiredhome)=@_;
1.198     www      2686:     $udom=~s/\W//g;
                   2687:     $uname=~s/\W//g;
1.81      www      2688:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      2689:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  2690: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   2691:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   2692:                                      ' desiredhome not specified'). 
1.272     matthew  2693:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
                   2694:              ' in domain '.$ENV{'request.role.domain'});
1.230     stredwic 2695:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      2696: # ----------------------------------------------------------------- Create User
1.81      www      2697:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
1.80      www      2698:         my $unhome='';
1.209     matthew  2699:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   2700:             $unhome = $desiredhome;
                   2701: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
1.80      www      2702: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.209     matthew  2703:         } else { # load balancing routine for determining $unhome
1.80      www      2704:             my $tryserver;
1.81      www      2705:             my $loadm=10000000;
1.80      www      2706:             foreach $tryserver (keys %libserv) {
                   2707: 	       if ($hostdom{$tryserver} eq $udom) {
                   2708:                   my $answer=reply('load',$tryserver);
                   2709:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   2710: 		      $loadm=$answer;
                   2711:                       $unhome=$tryserver;
                   2712:                   }
                   2713: 	       }
                   2714: 	    }
                   2715:         }
                   2716:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  2717: 	    return 'error: unable to find a home server for '.$uname.
                   2718:                    ' in domain '.$udom;
1.80      www      2719:         }
                   2720:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   2721:                          &escape($upass),$unhome);
                   2722: 	unless ($reply eq 'ok') {
                   2723:             return 'error: '.$reply;
                   2724:         }   
1.230     stredwic 2725:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      2726:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
                   2727: 	    return 'error: verify home';
                   2728:         }
1.209     matthew  2729:     }   # End of creation of new user
1.80      www      2730: # ---------------------------------------------------------------------- Add ID
                   2731:     if ($uid) {
                   2732:        $uid=~tr/A-Z/a-z/;
                   2733:        my %uidhash=&idrget($udom,$uname);
1.196     www      2734:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   2735:          && (!$forceid)) {
1.80      www      2736: 	  unless ($uid eq $uidhash{$uname}) {
                   2737: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
                   2738:           }
                   2739:        } else {
                   2740: 	  &idput($udom,($uname => $uid));
                   2741:        }
                   2742:     }
                   2743: # -------------------------------------------------------------- Add names, etc
1.313     matthew  2744:     my @tmp=&get('environment',
1.134     albertel 2745: 		   ['firstname','middlename','lastname','generation'],
                   2746: 		   $udom,$uname);
1.313     matthew  2747:     my %names;
                   2748:     if ($tmp[0] =~ m/^error:.*/) { 
                   2749:         %names=(); 
                   2750:     } else {
                   2751:         %names = @tmp;
                   2752:     }
1.134     albertel 2753:     if ($first)  { $names{'firstname'}  = $first; }
                   2754:     if ($middle) { $names{'middlename'} = $middle; }
                   2755:     if ($last)   { $names{'lastname'}   = $last; }
                   2756:     if ($gene)   { $names{'generation'} = $gene; }
                   2757:     my $reply = &put('environment', \%names, $udom,$uname);
                   2758:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      2759:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      2760:              $umode.', '.$first.', '.$middle.', '.
                   2761: 	     $last.', '.$gene.' by '.
                   2762:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134     albertel 2763:     return 'ok';
1.80      www      2764: }
                   2765: 
1.81      www      2766: # -------------------------------------------------------------- Modify student
1.80      www      2767: 
1.81      www      2768: sub modifystudent {
                   2769:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.209     matthew  2770:         $end,$start,$forceid,$desiredhome)=@_;
1.81      www      2771:     my $cid='';
                   2772:     unless ($cid=$ENV{'request.course.id'}) {
1.80      www      2773: 	return 'not_in_class';
                   2774:     }
                   2775: # --------------------------------------------------------------- Make the user
1.81      www      2776:     my $reply=&modifyuser
1.209     matthew  2777: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
                   2778:          $desiredhome);
1.80      www      2779:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  2780:     # This will cause &modify_student_enrollment to get the uid from the
                   2781:     # students environment
                   2782:     $uid = undef if (!$forceid);
                   2783:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
                   2784:                                         $last,$gene,$usec,$end,$start);
                   2785:     return $reply;
                   2786: }
                   2787: 
                   2788: sub modify_student_enrollment {
                   2789:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
                   2790:     # Get the course id from the environment
                   2791:     my $cid='';
                   2792:     unless ($cid=$ENV{'request.course.id'}) {
                   2793: 	return 'not_in_class';
                   2794:     }
                   2795:     # Make sure the user exists
1.81      www      2796:     my $uhome=&homeserver($uname,$udom);
                   2797:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   2798: 	return 'error: no such user';
                   2799:     }
1.297     matthew  2800:     #
                   2801:     # Get student data if we were not given enough information
                   2802:     if (!defined($first)  || $first  eq '' || 
                   2803:         !defined($last)   || $last   eq '' || 
                   2804:         !defined($uid)    || $uid    eq '' || 
                   2805:         !defined($middle) || $middle eq '' || 
                   2806:         !defined($gene)   || $gene   eq '') {
1.294     matthew  2807:         # They did not supply us with enough data to enroll the student, so
                   2808:         # we need to pick up more information.
1.297     matthew  2809:         my %tmp = &get('environment',
1.294     matthew  2810:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  2811:                        ,$udom,$uname);
                   2812: 
                   2813:         foreach (keys(%tmp)) {
                   2814:             &logthis("key $_ = ".$tmp{$_});
                   2815:         }
1.294     matthew  2816:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   2817:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   2818:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  2819:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  2820:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   2821:     }
                   2822:     my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
                   2823:                                                            $first,$middle);
1.297     matthew  2824:     my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1.81      www      2825: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
                   2826:                       &escape($uname.':'.$udom).'='.
1.294     matthew  2827:                       &escape(join(':',$end,$start,$uid,$usec,$fullname)),
1.81      www      2828: 	              $ENV{'course.'.$cid.'.home'});
                   2829:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   2830: 	return 'error: '.$reply;
                   2831:     }
1.297     matthew  2832:     # Add student role to user
1.83      www      2833:     my $uurl='/'.$cid;
1.81      www      2834:     $uurl=~s/\_/\//g;
                   2835:     if ($usec) {
                   2836: 	$uurl.='/'.$usec;
                   2837:     }
                   2838:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      2839: }
                   2840: 
1.84      www      2841: # ------------------------------------------------- Write to course preferences
                   2842: 
                   2843: sub writecoursepref {
                   2844:     my ($courseid,%prefs)=@_;
                   2845:     $courseid=~s/^\///;
                   2846:     $courseid=~s/\_/\//g;
                   2847:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   2848:     my $chome=homeserver($cnum,$cdomain);
                   2849:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   2850: 	return 'error: no such course';
                   2851:     }
                   2852:     my $cstring='';
1.191     harris41 2853:     foreach (keys %prefs) {
1.84      www      2854: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 2855:     }
1.84      www      2856:     $cstring=~s/\&$//;
                   2857:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   2858: }
                   2859: 
                   2860: # ---------------------------------------------------------- Make/modify course
                   2861: 
                   2862: sub createcourse {
1.271     www      2863:     my ($udom,$description,$url,$course_server,$nonstandard)=@_;
1.84      www      2864:     $url=&declutter($url);
                   2865:     my $cid='';
1.264     matthew  2866:     unless (&allowed('ccc',$udom)) {
1.84      www      2867:         return 'refused';
                   2868:     }
                   2869: # ------------------------------------------------------------------- Create ID
                   2870:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   2871:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   2872: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 2873:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      2874:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   2875:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   2876:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 2877:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      2878:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   2879:            return 'error: unable to generate unique course-ID';
                   2880:        } 
                   2881:    }
1.264     matthew  2882: # ------------------------------------------------ Check supplied server name
                   2883:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
                   2884:     if (! exists($libserv{$course_server})) {
                   2885:         return 'error:bad server name '.$course_server;
                   2886:     }
1.84      www      2887: # ------------------------------------------------------------- Make the course
                   2888:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  2889:                       $course_server);
1.84      www      2890:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 2891:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      2892:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   2893: 	return 'error: no such course';
                   2894:     }
1.271     www      2895: # ----------------------------------------------------------------- Course made
1.358     www      2896: # log existance
                   2897:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description),
                   2898:                  $uhome);
                   2899:     &flushcourselogs();
                   2900: # set toplevel url
1.271     www      2901:     my $topurl=$url;
                   2902:     unless ($nonstandard) {
                   2903: # ------------------------------------------ For standard courses, make top url
                   2904:         my $mapurl=&clutter($url);
1.278     www      2905:         if ($mapurl eq '/res/') { $mapurl=''; }
1.271     www      2906:         $ENV{'form.initmap'}=(<<ENDINITMAP);
                   2907: <map>
                   2908: <resource id="1" type="start"></resource>
                   2909: <resource id="2" src="$mapurl"></resource>
                   2910: <resource id="3" type="finish"></resource>
                   2911: <link index="1" from="1" to="2"></link>
                   2912: <link index="2" from="2" to="3"></link>
                   2913: </map>
                   2914: ENDINITMAP
                   2915:         $topurl=&declutter(
                   2916:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
                   2917:                           );
                   2918:     }
                   2919: # ----------------------------------------------------------- Write preferences
1.84      www      2920:     &writecoursepref($udom.'_'.$uname,
                   2921:                      ('description' => $description,
1.271     www      2922:                       'url'         => $topurl));
1.84      www      2923:     return '/'.$udom.'/'.$uname;
                   2924: }
                   2925: 
1.21      www      2926: # ---------------------------------------------------------- Assign Custom Role
                   2927: 
                   2928: sub assigncustomrole {
1.357     www      2929:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      2930:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      2931:                        $end,$start,$deleteflag);
1.21      www      2932: }
                   2933: 
                   2934: # ----------------------------------------------------------------- Revoke Role
                   2935: 
                   2936: sub revokerole {
1.357     www      2937:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      2938:     my $now=time;
1.357     www      2939:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      2940: }
                   2941: 
                   2942: # ---------------------------------------------------------- Revoke Custom Role
                   2943: 
                   2944: sub revokecustomrole {
1.357     www      2945:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      2946:     my $now=time;
1.357     www      2947:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   2948:            $deleteflag);
1.17      www      2949: }
                   2950: 
                   2951: # ------------------------------------------------------------ Directory lister
                   2952: 
                   2953: sub dirlist {
1.253     stredwic 2954:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   2955: 
1.18      www      2956:     $uri=~s/^\///;
                   2957:     $uri=~s/\/$//;
1.253     stredwic 2958:     my ($udom, $uname);
                   2959:     (undef,$udom,$uname)=split(/\//,$uri);
                   2960:     if(defined($userdomain)) {
                   2961:         $udom = $userdomain;
                   2962:     }
                   2963:     if(defined($username)) {
                   2964:         $uname = $username;
                   2965:     }
                   2966: 
                   2967:     my $dirRoot = $perlvar{'lonDocRoot'};
                   2968:     if(defined($alternateDirectoryRoot)) {
                   2969:         $dirRoot = $alternateDirectoryRoot;
                   2970:         $dirRoot =~ s/\/$//;
                   2971:     }
                   2972: 
                   2973:     if($udom) {
                   2974:         if($uname) {
                   2975:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   2976:                               homeserver($uname,$udom));
                   2977:             return split(/:/,$listing);
                   2978:         } elsif(!defined($alternateDirectoryRoot)) {
                   2979:             my $tryserver;
                   2980:             my %allusers=();
                   2981:             foreach $tryserver (keys %libserv) {
                   2982:                 if($hostdom{$tryserver} eq $udom) {
                   2983:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   2984:                                       $udom, $tryserver);
                   2985:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
                   2986:                         && ($listing ne 'con_lost')) {
                   2987:                         foreach (split(/:/,$listing)) {
                   2988:                             my ($entry,@stat)=split(/&/,$_);
                   2989:                             $allusers{$entry}=1;
                   2990:                         }
                   2991:                     }
1.191     harris41 2992:                 }
1.253     stredwic 2993:             }
                   2994:             my $alluserstr='';
                   2995:             foreach (sort keys %allusers) {
                   2996:                 $alluserstr.=$_.'&user:';
                   2997:             }
                   2998:             $alluserstr=~s/:$//;
                   2999:             return split(/:/,$alluserstr);
                   3000:         } else {
                   3001:             my @emptyResults = ();
                   3002:             push(@emptyResults, 'missing user name');
                   3003:             return split(':',@emptyResults);
                   3004:         }
                   3005:     } elsif(!defined($alternateDirectoryRoot)) {
                   3006:         my $tryserver;
                   3007:         my %alldom=();
                   3008:         foreach $tryserver (keys %libserv) {
                   3009:             $alldom{$hostdom{$tryserver}}=1;
                   3010:         }
                   3011:         my $alldomstr='';
                   3012:         foreach (sort keys %alldom) {
                   3013:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
                   3014:         }
                   3015:         $alldomstr=~s/:$//;
                   3016:         return split(/:/,$alldomstr);       
                   3017:     } else {
                   3018:         my @emptyResults = ();
                   3019:         push(@emptyResults, 'missing domain');
                   3020:         return split(':',@emptyResults);
1.275     stredwic 3021:     }
                   3022: }
                   3023: 
                   3024: # --------------------------------------------- GetFileTimestamp
                   3025: # This function utilizes dirlist and returns the date stamp for
                   3026: # when it was last modified.  It will also return an error of -1
                   3027: # if an error occurs
                   3028: 
                   3029: sub GetFileTimestamp {
                   3030:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   3031:     $studentDomain=~s/\W//g;
                   3032:     $studentName=~s/\W//g;
                   3033:     my $subdir=$studentName.'__';
                   3034:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3035:     my $proname="$studentDomain/$subdir/$studentName";
                   3036:     $proname .= '/'.$filename;
                   3037:     my @dir = &Apache::lonnet::dirlist($proname, $studentDomain, $studentName,
                   3038:                                        $root);
                   3039:     my $fileStat = $dir[0];
                   3040:     my @stats = split('&', $fileStat);
                   3041:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   3042:         return $stats[9];
                   3043:     } else {
                   3044:         return -1;
1.253     stredwic 3045:     }
1.26      www      3046: }
                   3047: 
                   3048: # -------------------------------------------------------- Value of a Condition
                   3049: 
1.40      www      3050: sub directcondval {
                   3051:     my $number=shift;
                   3052:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
                   3053:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
                   3054:     } else {
                   3055:        return 2;
                   3056:     }
                   3057: }
                   3058: 
1.26      www      3059: sub condval {
                   3060:     my $condidx=shift;
                   3061:     my $result=0;
1.54      www      3062:     my $allpathcond='';
1.191     harris41 3063:     foreach (split(/\|/,$condidx)) {
1.54      www      3064:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
                   3065: 	   $allpathcond.=
                   3066:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
                   3067:        }
1.191     harris41 3068:     }
1.54      www      3069:     $allpathcond=~s/\|$//;
1.33      www      3070:     if ($ENV{'request.course.id'}) {
1.54      www      3071:        if ($allpathcond) {
1.26      www      3072:           my $operand='|';
                   3073: 	  my @stack;
1.191     harris41 3074:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      3075:               if ($_ eq '(') {
                   3076:                  push @stack,($operand,$result)
                   3077:               } elsif ($_ eq ')') {
                   3078:                   my $before=pop @stack;
                   3079: 		  if (pop @stack eq '&') {
                   3080: 		      $result=$result>$before?$before:$result;
                   3081:                   } else {
                   3082:                       $result=$result>$before?$result:$before;
                   3083:                   }
                   3084:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   3085:                   $operand=$_;
                   3086:               } else {
1.40      www      3087:                   my $new=directcondval($_);
1.26      www      3088:                   if ($operand eq '&') {
                   3089:                      $result=$result>$new?$new:$result;
                   3090:                   } else {
                   3091:                      $result=$result>$new?$result:$new;
1.191     harris41 3092:                   }
1.26      www      3093:               }
1.191     harris41 3094:           }
1.26      www      3095:        }
                   3096:     }
                   3097:     return $result;
1.279     www      3098: }
                   3099: 
                   3100: # ---------------------------------------------------- Devalidate courseresdata
                   3101: 
                   3102: sub devalidatecourseresdata {
                   3103:     my ($coursenum,$coursedomain)=@_;
                   3104:     my $hashid=$coursenum.':'.$coursedomain;
                   3105:     delete $courseresdatacache{$hashid.'.time'};
1.28      www      3106: }
                   3107: 
1.200     www      3108: # --------------------------------------------------- Course Resourcedata Query
                   3109: 
                   3110: sub courseresdata {
                   3111:     my ($coursenum,$coursedomain,@which)=@_;
                   3112:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   3113:     my $hashid=$coursenum.':'.$coursedomain;
1.250     albertel 3114:     my $dodump=0;
                   3115:     if (!defined($courseresdatacache{$hashid.'.time'})) {
                   3116: 	$dodump=1;
                   3117:     } else {
                   3118: 	if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
                   3119:     }
                   3120:     if ($dodump) {
1.251     albertel 3121: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
                   3122: 	my ($tmp) = keys(%dumpreply);
                   3123: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   3124: 	    $courseresdatacache{$hashid.'.time'}=time;
                   3125: 	    $courseresdatacache{$hashid}=\%dumpreply;
1.306     albertel 3126: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   3127: 	    return $tmp;
1.250     albertel 3128: 	}
                   3129:     }
1.251     albertel 3130:     foreach my $item (@which) {
1.287     albertel 3131: 	if (defined($courseresdatacache{$hashid}->{$item})) {
1.251     albertel 3132: 	    return $courseresdatacache{$hashid}->{$item};
                   3133: 	}
1.250     albertel 3134:     }
1.291     albertel 3135:     return undef;
1.200     www      3136: }
                   3137: 
1.28      www      3138: # --------------------------------------------------------- Value of a Variable
                   3139: 
1.58      www      3140: sub EXT {
1.282     albertel 3141:     my ($varname,$symbparm,$udom,$uname,)=@_;
1.218     albertel 3142: 
1.68      www      3143:     unless ($varname) { return ''; }
1.218     albertel 3144:     #get real user name/domain, courseid and symb
                   3145:     my $courseid;
1.359     albertel 3146:     my $publicuser;
1.218     albertel 3147:     if (!($uname && $udom)) {
1.360     albertel 3148:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
                   3149: 	  &Apache::lonxml::whichuser();
1.218     albertel 3150:       if (!$symbparm) {	$symbparm=$cursymb; }
                   3151:     } else {
                   3152: 	$courseid=$ENV{'request.course.id'};
                   3153:     }
1.48      www      3154:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   3155:     my $rest;
1.320     albertel 3156:     if (defined($therest[0])) {
1.48      www      3157:        $rest=join('.',@therest);
                   3158:     } else {
                   3159:        $rest='';
                   3160:     }
1.320     albertel 3161: 
1.57      www      3162:     my $qualifierrest=$qualifier;
                   3163:     if ($rest) { $qualifierrest.='.'.$rest; }
                   3164:     my $spacequalifierrest=$space;
                   3165:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      3166:     if ($realm eq 'user') {
1.48      www      3167: # --------------------------------------------------------------- user.resource
                   3168: 	if ($space eq 'resource') {
1.335     albertel 3169: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
                   3170: 		return $Apache::lonhomework::history{$qualifierrest};
                   3171: 	    } else {
1.359     albertel 3172: 		my %restored;
                   3173: 		if ($publicuser || $ENV{'request.state'} eq 'construct') {
                   3174: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   3175: 		} else {
                   3176: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   3177: 		}
1.335     albertel 3178: 		return $restored{$qualifierrest};
                   3179: 	    }
1.48      www      3180: # ----------------------------------------------------------------- user.access
                   3181:         } elsif ($space eq 'access') {
1.218     albertel 3182: 	    # FIXME - not supporting calls for a specific user
1.48      www      3183:             return &allowed($qualifier,$rest);
                   3184: # ------------------------------------------ user.preferences, user.environment
                   3185:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.218     albertel 3186: 	    if (($uname eq $ENV{'user.name'}) &&
                   3187: 		($udom eq $ENV{'user.domain'})) {
                   3188: 		return $ENV{join('.',('environment',$qualifierrest))};
                   3189: 	    } else {
1.359     albertel 3190: 		my %returnhash;
                   3191: 		if (!$publicuser) {
                   3192: 		    %returnhash=&userenvironment($udom,$uname,
                   3193: 						 $qualifierrest);
                   3194: 		}
1.218     albertel 3195: 		return $returnhash{$qualifierrest};
                   3196: 	    }
1.48      www      3197: # ----------------------------------------------------------------- user.course
                   3198:         } elsif ($space eq 'course') {
1.218     albertel 3199: 	    # FIXME - not supporting calls for a specific user
1.48      www      3200:             return $ENV{join('.',('request.course',$qualifier))};
                   3201: # ------------------------------------------------------------------- user.role
                   3202:         } elsif ($space eq 'role') {
1.218     albertel 3203: 	    # FIXME - not supporting calls for a specific user
1.48      www      3204:             my ($role,$where)=split(/\./,$ENV{'request.role'});
                   3205:             if ($qualifier eq 'value') {
                   3206: 		return $role;
                   3207:             } elsif ($qualifier eq 'extent') {
                   3208:                 return $where;
                   3209:             }
                   3210: # ----------------------------------------------------------------- user.domain
                   3211:         } elsif ($space eq 'domain') {
1.218     albertel 3212:             return $udom;
1.48      www      3213: # ------------------------------------------------------------------- user.name
                   3214:         } elsif ($space eq 'name') {
1.218     albertel 3215:             return $uname;
1.48      www      3216: # ---------------------------------------------------- Any other user namespace
1.29      www      3217:         } else {
1.359     albertel 3218: 	    my %reply;
                   3219: 	    if (!$publicuser) {
                   3220: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   3221: 	    }
                   3222: 	    return $reply{$qualifierrest};
1.48      www      3223:         }
1.236     www      3224:     } elsif ($realm eq 'query') {
                   3225: # ---------------------------------------------- pull stuff out of query string
                   3226:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},[$space]);
                   3227: 	return $ENV{'form.'.$space}; 
                   3228:    } elsif ($realm eq 'request') {
1.48      www      3229: # ------------------------------------------------------------- request.browser
                   3230:         if ($space eq 'browser') {
                   3231: 	    return $ENV{'browser.'.$qualifier};
1.57      www      3232: # ------------------------------------------------------------ request.filename
                   3233:         } else {
                   3234:             return $ENV{'request.'.$spacequalifierrest};
1.29      www      3235:         }
1.28      www      3236:     } elsif ($realm eq 'course') {
1.48      www      3237: # ---------------------------------------------------------- course.description
1.218     albertel 3238:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      3239:     } elsif ($realm eq 'resource') {
1.165     www      3240: 
1.359     albertel 3241: 	if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
1.165     www      3242: 
1.218     albertel 3243: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      3244: 
1.60      www      3245: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 3246: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   3247: 	    my $symbp=$symbparm;
                   3248: 	    my $mapp=(split(/\_\_\_/,$symbp))[0];
                   3249: 
                   3250: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   3251: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   3252: 
                   3253: 	    my $section;
                   3254: 	    if (($ENV{'user.name'} eq $uname) &&
                   3255: 		($ENV{'user.domain'} eq $udom)) {
1.255     albertel 3256: 		$section=$ENV{'request.course.sec'};
1.218     albertel 3257: 	    } else {
                   3258: 		$section=&usection($udom,$uname,$courseid);
                   3259: 	    }
                   3260: 
                   3261: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   3262: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   3263: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   3264: 
                   3265: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
                   3266: 	    my $courselevelr=$courseid.'.'.$symbparm;
                   3267: 	    my $courselevelm=$courseid.'.'.$mapparm;
1.69      www      3268: 
1.60      www      3269: # ----------------------------------------------------------- first, check user
1.308     albertel 3270: 	    #most student don't have any data set, check if there is some data
                   3271:             #every thirty minutes
1.309     albertel 3272: 	    if (!
                   3273: 		(exists($ENV{'cache.studentresdata'})
                   3274: 		    && (($ENV{'cache.studentresdata'}+1800) > time))) {
1.308     albertel 3275: 		my %resourcedata=&get('resourcedata',
                   3276: 				      [$courselevelr,$courselevelm,$courselevel],
                   3277: 				      $udom,$uname);
                   3278: 		my ($tmp)=keys(%resourcedata);
                   3279: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   3280: 		    if ($resourcedata{$courselevelr}) {
                   3281: 			return $resourcedata{$courselevelr}; }
                   3282: 		    if ($resourcedata{$courselevelm}) {
                   3283: 			return $resourcedata{$courselevelm}; }
                   3284: 		    if ($resourcedata{$courselevel}) {
                   3285: 			return $resourcedata{$courselevel}; }
                   3286: 		} else {
                   3287: 		    if ($tmp!~/No such file/) {
                   3288: 			&logthis("<font color=blue>WARNING:".
                   3289: 				 " Trying to get resource data for ".
                   3290: 				 $uname." at ".$udom.": ".
                   3291: 				 $tmp."</font>");
                   3292: 		    } elsif ($tmp=~/error:No such file/) {
1.309     albertel 3293: 			$ENV{'cache.studentresdata'}=time;
                   3294: 			&appenv(('cache.studentresdata'=>
                   3295: 				 $ENV{'cache.studentresdata'}));
1.308     albertel 3296: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   3297: 			return $tmp;
                   3298: 		    }
1.218     albertel 3299: 		}
                   3300: 	    }
1.95      www      3301: 
1.60      www      3302: # -------------------------------------------------------- second, check course
1.96      www      3303: 
1.218     albertel 3304: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
                   3305: 					  $ENV{'course.'.$courseid.'.domain'},
                   3306: 					  ($seclevelr,$seclevelm,$seclevel,
                   3307: 					   $courselevelr,$courselevelm,
                   3308: 					   $courselevel));
1.287     albertel 3309: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      3310: 
1.60      www      3311: # ------------------------------------------------------ third, check map parms
1.218     albertel 3312: 	    my %parmhash=();
                   3313: 	    my $thisparm='';
                   3314: 	    if (tie(%parmhash,'GDBM_File',
                   3315: 		    $ENV{'request.course.fn'}.'_parms.db',
1.256     albertel 3316: 		    &GDBM_READER(),0640)) {
1.218     albertel 3317: 		$thisparm=$parmhash{$symbparm};
                   3318: 		untie(%parmhash);
                   3319: 	    }
                   3320: 	    if ($thisparm) { return $thisparm; }
                   3321: 	}
1.60      www      3322: # --------------------------------------------- last, look in resource metadata
1.71      www      3323: 
1.218     albertel 3324: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 3325: 	my $filename;
                   3326: 	if (!$symbparm) { $symbparm=&symbread(); }
                   3327: 	if ($symbparm) {
                   3328: 	    $filename=(split(/\_\_\_/,$symbparm))[2];
                   3329: 	} else {
                   3330: 	    $filename=$ENV{'request.filename'};
                   3331: 	}
                   3332: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 3333: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 3334: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 3335: 	if (defined($metadata)) { return $metadata; }
1.142     www      3336: 
1.145     www      3337: # ------------------------------------------------------------------ Cascade up
1.218     albertel 3338: 	unless ($space eq '0') {
1.336     albertel 3339: 	    my @parts=split(/_/,$space);
                   3340: 	    my $id=pop(@parts);
                   3341: 	    my $part=join('_',@parts);
                   3342: 	    if ($part eq '') { $part='0'; }
                   3343: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
                   3344: 				 $symbparm,$udom,$uname);
1.337     albertel 3345: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 3346: 	}
1.71      www      3347: 
1.48      www      3348: # ---------------------------------------------------- Any other user namespace
                   3349:     } elsif ($realm eq 'environment') {
                   3350: # ----------------------------------------------------------------- environment
1.219     albertel 3351: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
                   3352: 	    return $ENV{'environment.'.$spacequalifierrest};
                   3353: 	} else {
                   3354: 	    my %returnhash=&userenvironment($udom,$uname,
                   3355: 					    $spacequalifierrest);
                   3356: 	    return $returnhash{$spacequalifierrest};
                   3357: 	}
1.28      www      3358:     } elsif ($realm eq 'system') {
1.48      www      3359: # ----------------------------------------------------------------- system.time
                   3360: 	if ($space eq 'time') {
                   3361: 	    return time;
                   3362:         }
1.28      www      3363:     }
1.48      www      3364:     return '';
1.61      www      3365: }
                   3366: 
1.334     albertel 3367: sub add_prefix_and_part {
                   3368:     my ($prefix,$part)=@_;
                   3369:     my $keyroot;
                   3370:     if (defined($prefix) && $prefix !~ /^__/) {
                   3371: 	# prefix that has a part already
                   3372: 	$keyroot=$prefix;
                   3373:     } elsif (defined($prefix)) {
                   3374: 	# prefix that is missing a part
                   3375: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   3376:     } else {
                   3377: 	# no prefix at all
                   3378: 	if (defined($part)) { $keyroot='_'.$part; }
                   3379:     }
                   3380:     return $keyroot;
                   3381: }
                   3382: 
1.71      www      3383: # ---------------------------------------------------------------- Get metadata
                   3384: 
                   3385: sub metadata {
1.176     www      3386:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.78      www      3387: 
1.71      www      3388:     $uri=&declutter($uri);
1.288     albertel 3389:     # if it is a non metadata possible uri return quickly
1.293     matthew  3390:     if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
                   3391:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|)) {
1.288     albertel 3392: 	return '';
                   3393:     }
1.73      www      3394:     my $filename=$uri;
                   3395:     $uri=~s/\.meta$//;
1.172     www      3396: #
                   3397: # Is the metadata already cached?
1.177     www      3398: # Look at timestamp of caching
1.172     www      3399: # Everything is cached by the main uri, libraries are never directly cached
                   3400: #
1.277     albertel 3401:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
1.172     www      3402: #
                   3403: # Is this a recursive call for a library?
                   3404: #
1.171     www      3405:         if ($liburi) {
                   3406: 	    $liburi=&declutter($liburi);
                   3407:             $filename=$liburi;
                   3408:         }
1.140     www      3409:         my %metathesekeys=();
1.73      www      3410:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.335     albertel 3411: 	my $metastring=&getfile(&filelocation('',&clutter($filename)));
1.208     albertel 3412:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      3413:         my $token;
1.140     www      3414:         undef %metathesekeys;
1.365   ! albertel 3415: 	delete($metacache{$uri.':packages'});
1.71      www      3416:         while ($token=$parser->get_token) {
1.339     albertel 3417: 	    if ($token->[0] eq 'S') {
                   3418: 		if (defined($token->[2]->{'package'})) {
1.172     www      3419: #
                   3420: # This is a package - get package info
                   3421: #
1.339     albertel 3422: 		    my $package=$token->[2]->{'package'};
                   3423: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   3424: 		    if (defined($token->[2]->{'id'})) { 
                   3425: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   3426: 		    }
                   3427: 		    if ($metacache{$uri.':packages'}) {
                   3428: 			$metacache{$uri.':packages'}.=','.$package.$keyroot;
                   3429: 		    } else {
                   3430: 			$metacache{$uri.':packages'}=$package.$keyroot;
                   3431: 		    }
                   3432: 		    foreach (keys %packagetab) {
                   3433: 			if ($_=~/^$package\&/) {
                   3434: 			    my ($pack,$name,$subp)=split(/\&/,$_);
                   3435: 			    my $value=$packagetab{$_};
                   3436: 			    my $part=$keyroot;
                   3437: 			    $part=~s/^\_//;
                   3438: 			    if ($subp eq 'display') {
                   3439: 				$value.=' [Part: '.$part.']';
                   3440: 			    }
                   3441: 			    my $unikey='parameter'.$keyroot.'_'.$name;
1.356     albertel 3442: 			    if ($subp eq 'default') {
                   3443: 				$unikey='parameter_0_'.$name;
                   3444: 				$metacache{$uri.':'.$unikey.'.part'}='0';
                   3445: 			    } else {
                   3446: 				$metacache{$uri.':'.$unikey.'.part'}=$part;
                   3447: 				$metathesekeys{$unikey}=1;
                   3448: 			    }
1.339     albertel 3449: 			    unless (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
                   3450: 				$metacache{$uri.':'.$unikey.'.'.$subp}=$value;
                   3451: 			    }
                   3452: 			    if (defined($metacache{$uri.':'.$unikey.'.default'})) {
                   3453: 				$metacache{$uri.':'.$unikey}=
1.356     albertel 3454: 				    $metacache{$uri.':'.$unikey.'.default'};
                   3455: 			    }
1.339     albertel 3456: 			}
                   3457: 		    }
                   3458: 		} else {
1.172     www      3459: #
                   3460: # This is not a package - some other kind of start tag
1.339     albertel 3461: #
                   3462: 		    my $entry=$token->[1];
                   3463: 		    my $unikey;
                   3464: 		    if ($entry eq 'import') {
                   3465: 			$unikey='';
                   3466: 		    } else {
                   3467: 			$unikey=$entry;
                   3468: 		    }
                   3469: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   3470: 
                   3471: 		    if (defined($token->[2]->{'id'})) { 
                   3472: 			$unikey.='_'.$token->[2]->{'id'}; 
                   3473: 		    }
1.175     www      3474: 
1.339     albertel 3475: 		    if ($entry eq 'import') {
1.175     www      3476: #
                   3477: # Importing a library here
1.339     albertel 3478: #
                   3479: 			if ($depthcount<20) {
                   3480: 			    my $location=$parser->get_text('/import');
                   3481: 			    my $dir=$filename;
                   3482: 			    $dir=~s|[^/]*$||;
                   3483: 			    $location=&filelocation($dir,$location);
                   3484: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   3485: 							       $location,$unikey,
                   3486: 							       $depthcount+1)))) {
                   3487: 				$metathesekeys{$_}=1;
                   3488: 			    }
                   3489: 			}
                   3490: 		    } else { 
                   3491: 			
                   3492: 			if (defined($token->[2]->{'name'})) { 
                   3493: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   3494: 			}
                   3495: 			$metathesekeys{$unikey}=1;
                   3496: 			foreach (@{$token->[3]}) {
                   3497: 			    $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
                   3498: 			}
                   3499: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
                   3500: 			my $default=$metacache{$uri.':'.$unikey.'.default'};
                   3501: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   3502: 		 # only ws inside the tag, and not in default, so use default
                   3503: 		 # as value
                   3504: 			    $metacache{$uri.':'.$unikey}=$default;
                   3505: 			} else {
1.321     albertel 3506: 		  # either something interesting inside the tag or default
                   3507:                   # uninteresting
1.339     albertel 3508: 			    $metacache{$uri.':'.$unikey}=$internaltext;
                   3509: 			}
1.172     www      3510: # end of not-a-package not-a-library import
1.339     albertel 3511: 		    }
1.172     www      3512: # end of not-a-package start tag
1.339     albertel 3513: 		}
1.172     www      3514: # the next is the end of "start tag"
1.339     albertel 3515: 	    }
                   3516: 	}
1.338     www      3517: # are there custom rights to evaluate
                   3518: 	if ($metacache{$uri.':copyright'} eq 'custom') {
1.339     albertel 3519: 
1.338     www      3520:     #
                   3521:     # Importing a rights file here
1.339     albertel 3522:     #
                   3523: 	    unless ($depthcount) {
                   3524: 		my $location=$metacache{$uri.':customdistributionfile'};
                   3525: 		my $dir=$filename;
                   3526: 		$dir=~s|[^/]*$||;
                   3527: 		$location=&filelocation($dir,$location);
                   3528: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   3529: 						   $location,'_rights',
                   3530: 						   $depthcount+1)))) {
                   3531: 		    $metathesekeys{$_}=1;
                   3532: 		}
                   3533: 	    }
                   3534: 	}
                   3535: 	$metacache{$uri.':keys'}=join(',',keys %metathesekeys);
1.261     albertel 3536: 	&metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
1.339     albertel 3537: 	$metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
                   3538: 	$metacache{$uri.':cachedtimestamp'}=time;
1.177     www      3539: # this is the end of "was not already recently cached
1.71      www      3540:     }
                   3541:     return $metacache{$uri.':'.$what};
1.261     albertel 3542: }
                   3543: 
                   3544: sub metadata_generate_part0 {
                   3545:     my ($metadata,$metacache,$uri) = @_;
                   3546:     my %allnames;
                   3547:     foreach my $metakey (sort keys %$metadata) {
                   3548: 	if ($metakey=~/^parameter\_(.*)/) {
                   3549: 	  my $part=$$metacache{$uri.':'.$metakey.'.part'};
                   3550: 	  my $name=$$metacache{$uri.':'.$metakey.'.name'};
1.356     albertel 3551: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 3552: 	    $allnames{$name}=$part;
                   3553: 	  }
                   3554: 	}
                   3555:     }
                   3556:     foreach my $name (keys(%allnames)) {
                   3557:       $$metadata{"parameter_0_$name"}=1;
                   3558:       my $key="$uri:parameter_0_$name";
                   3559:       $$metacache{"$key.part"}='0';
                   3560:       $$metacache{"$key.name"}=$name;
                   3561:       $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
                   3562: 					   $allnames{$name}.'_'.$name.
                   3563: 					   '.type'};
                   3564:       my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
                   3565: 			     '.display'};
                   3566:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
                   3567:       $olddis=~s/$expr/\[Part: 0\]/;
                   3568:       $$metacache{"$key.display"}=$olddis;
                   3569:     }
1.71      www      3570: }
                   3571: 
1.301     www      3572: # ------------------------------------------------- Get the title of a resource
                   3573: 
                   3574: sub gettitle {
                   3575:     my $urlsymb=shift;
                   3576:     my $symb=&symbread($urlsymb);
                   3577:     unless ($symb) {
                   3578: 	unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
                   3579:         return &metadata($urlsymb,'title'); 
                   3580:     }
                   3581:     if ($titlecache{$symb}) { return $titlecache{$symb}; }
                   3582:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
                   3583:     my $title='';
                   3584:     my %bighash;
                   3585:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
                   3586:                             &GDBM_READER(),0640)) {
                   3587:         my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   3588:         $title=$bighash{'title_'.$mapid.'.'.$resid};
                   3589:         untie %bighash;
                   3590:     }
1.363     www      3591:     $title=~s/\&colon\;/\:/gs;
1.301     www      3592:     if ($title) {
                   3593:         $titlecache{$symb}=$title;
                   3594:         return $title;
                   3595:     } else {
                   3596: 	return &metadata($urlsymb,'title');
                   3597:     }
                   3598: }
                   3599:     
1.31      www      3600: # ------------------------------------------------- Update symbolic store links
                   3601: 
                   3602: sub symblist {
                   3603:     my ($mapname,%newhash)=@_;
                   3604:     $mapname=declutter($mapname);
                   3605:     my %hash;
                   3606:     if (($ENV{'request.course.fn'}) && (%newhash)) {
                   3607:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 3608:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 3609: 	    foreach (keys %newhash) {
1.211     www      3610:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
1.191     harris41 3611:             }
1.31      www      3612:             if (untie(%hash)) {
                   3613: 		return 'ok';
                   3614:             }
                   3615:         }
                   3616:     }
                   3617:     return 'error';
1.212     www      3618: }
                   3619: 
                   3620: # --------------------------------------------------------------- Verify a symb
                   3621: 
                   3622: sub symbverify {
                   3623:     my ($symb,$thisfn)=@_;
1.213     www      3624:     $thisfn=&declutter($thisfn);
1.215     www      3625: # direct jump to resource in page or to a sequence - will construct own symbs
                   3626:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   3627: # check URL part
1.213     www      3628:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
                   3629:     unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
                   3630: 
1.216     www      3631:     $symb=&symbclean($symb);
1.213     www      3632: 
                   3633:     my %bighash;
                   3634:     my $okay=0;
                   3635:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 3636:                             &GDBM_READER(),0640)) {
1.280     www      3637:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.216     www      3638:         unless ($ids) { 
                   3639:            $ids=$bighash{'ids_/'.$thisfn};
                   3640:         }
                   3641:         if ($ids) {
                   3642: # ------------------------------------------------------------------- Has ID(s)
                   3643: 	    foreach (split(/\,/,$ids)) {
                   3644:                my ($mapid,$resid)=split(/\./,$_);
                   3645:                if (
                   3646:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   3647:    eq $symb) { 
                   3648:                   $okay=1; 
                   3649:                }
                   3650: 	   }
                   3651:         }
1.213     www      3652: 	untie(%bighash);
                   3653:     }
                   3654:     return $okay;
1.31      www      3655: }
                   3656: 
1.210     www      3657: # --------------------------------------------------------------- Clean-up symb
                   3658: 
                   3659: sub symbclean {
                   3660:     my $symb=shift;
1.213     www      3661: 
1.210     www      3662: # remove version from map
                   3663:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      3664: 
1.210     www      3665: # remove version from URL
                   3666:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      3667: 
1.210     www      3668:     return $symb;
                   3669: }
                   3670: 
1.31      www      3671: # ------------------------------------------------------ Return symb list entry
                   3672: 
                   3673: sub symbread {
1.249     www      3674:     my ($thisfn,$donotrecurse)=@_;
1.242     www      3675: # no filename provided? try from environment
1.44      www      3676:     unless ($thisfn) {
1.210     www      3677:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
1.44      www      3678: 	$thisfn=$ENV{'request.filename'};
                   3679:     }
1.242     www      3680: # is that filename actually a symb? Verify, clean, and return
                   3681:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
                   3682: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
                   3683:     }
1.44      www      3684:     $thisfn=declutter($thisfn);
1.31      www      3685:     my %hash;
1.37      www      3686:     my %bighash;
                   3687:     my $syval='';
1.45      www      3688:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.31      www      3689:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 3690:                       &GDBM_READER(),0640)) {
1.31      www      3691: 	    $syval=$hash{$thisfn};
1.37      www      3692:             untie(%hash);
                   3693:         }
                   3694: # ---------------------------------------------------------- There was an entry
                   3695:         if ($syval) {
                   3696:            unless ($syval=~/\_\d+$/) {
                   3697: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44      www      3698:                   &appenv('request.ambiguous' => $thisfn);
1.37      www      3699:                   return '';
                   3700:                }    
                   3701:                $syval.=$1;
                   3702: 	   }
                   3703:         } else {
                   3704: # ------------------------------------------------------- Was not in symb table
                   3705:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 3706:                             &GDBM_READER(),0640)) {
1.37      www      3707: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      3708:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      3709:               unless ($ids) { 
                   3710:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      3711:               }
                   3712:               unless ($ids) {
                   3713: # alias?
                   3714: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      3715:               }
1.37      www      3716:               if ($ids) {
                   3717: # ------------------------------------------------------------------- Has ID(s)
                   3718:                  my @possibilities=split(/\,/,$ids);
1.39      www      3719:                  if ($#possibilities==0) {
                   3720: # ----------------------------------------------- There is only one possibility
1.37      www      3721: 		     my ($mapid,$resid)=split(/\./,$ids);
                   3722:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
1.249     www      3723:                  } elsif (!$donotrecurse) {
1.39      www      3724: # ------------------------------------------ There is more than one possibility
                   3725:                      my $realpossible=0;
1.191     harris41 3726:                      foreach (@possibilities) {
1.39      www      3727: 			 my $file=$bighash{'src_'.$_};
                   3728:                          if (&allowed('bre',$file)) {
                   3729:          		    my ($mapid,$resid)=split(/\./,$_);
                   3730:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   3731: 				$realpossible++;
                   3732:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
                   3733:                                        '___'.$resid;
                   3734:                             }
                   3735: 			 }
1.191     harris41 3736:                      }
1.39      www      3737: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      3738:                  } else {
                   3739:                      $syval='';
1.37      www      3740:                  }
                   3741: 	      }
                   3742:               untie(%bighash)
                   3743:            } 
1.31      www      3744:         }
1.62      www      3745:         if ($syval) {
1.210     www      3746:            return &symbclean($syval.'___'.$thisfn); 
1.62      www      3747:         }
1.31      www      3748:     }
1.44      www      3749:     &appenv('request.ambiguous' => $thisfn);
1.31      www      3750:     return '';
                   3751: }
                   3752: 
                   3753: # ---------------------------------------------------------- Return random seed
                   3754: 
1.32      www      3755: sub numval {
                   3756:     my $txt=shift;
                   3757:     $txt=~tr/A-J/0-9/;
                   3758:     $txt=~tr/a-j/0-9/;
                   3759:     $txt=~tr/K-T/0-9/;
                   3760:     $txt=~tr/k-t/0-9/;
                   3761:     $txt=~tr/U-Z/0-5/;
                   3762:     $txt=~tr/u-z/0-5/;
                   3763:     $txt=~s/\D//g;
                   3764:     return int($txt);
                   3765: }    
                   3766: 
1.31      www      3767: sub rndseed {
1.155     albertel 3768:     my ($symb,$courseid,$domain,$username)=@_;
                   3769:     if (!$symb) {
                   3770:       unless ($symb=&symbread()) { return time; }
                   3771:     }
                   3772:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
                   3773:     if (!$domain) {$domain=$ENV{'user.domain'};}
                   3774:     if (!$username) {$username=$ENV{'user.name'};}
                   3775:     {
1.98      albertel 3776:       use integer;
                   3777:       my $symbchck=unpack("%32C*",$symb) << 27;
1.100     albertel 3778:       my $symbseed=numval($symb) << 22;
1.155     albertel 3779:       my $namechck=unpack("%32C*",$username) << 17;
                   3780:       my $nameseed=numval($username) << 12;
                   3781:       my $domainseed=unpack("%32C*",$domain) << 7;
                   3782:       my $courseseed=unpack("%32C*",$courseid);
1.98      albertel 3783:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.99      albertel 3784:       #uncommenting these lines can break things!
                   3785:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   3786:       #&Apache::lonxml::debug("rndseed :$num:$symb");
1.98      albertel 3787:       return $num;
                   3788:     }
1.36      albertel 3789: }
                   3790: 
1.76      www      3791: sub ireceipt {
                   3792:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
                   3793:     my $cuname=unpack("%32C*",$funame);
                   3794:     my $cudom=unpack("%32C*",$fudom);
                   3795:     my $cucourseid=unpack("%32C*",$fucourseid);
                   3796:     my $cusymb=unpack("%32C*",$fusymb);
1.77      www      3797:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
1.76      www      3798:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
                   3799:            ($cunique%$cuname+
                   3800:             $cunique%$cudom+
                   3801:             $cusymb%$cuname+
                   3802:             $cusymb%$cudom+
                   3803:             $cucourseid%$cuname+
                   3804:             $cucourseid%$cudom);
                   3805: }
                   3806: 
                   3807: sub receipt {
1.260     ng       3808:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   3809:   return &ireceipt($name,$domain,$courseid,$symb);
1.76      www      3810: }
1.260     ng       3811: 
1.36      albertel 3812: # ------------------------------------------------------------ Serves up a file
                   3813: # returns either the contents of the file or a -1
                   3814: sub getfile {
1.269     www      3815:  my $file=shift;
                   3816:  if ($file=~/^\/*uploaded\//) { # user file
                   3817:     my $ua=new LWP::UserAgent;
                   3818:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
                   3819:     my $response=$ua->request($request);
                   3820:     if ($response->is_success()) {
                   3821:        return $response->content;
                   3822:     } else { 
                   3823:        return -1; 
                   3824:     }
                   3825:  } else { # normal file from res space
1.37      www      3826:   &repcopy($file);
1.36      albertel 3827:   if (! -e $file ) { return -1; };
                   3828:   my $fh=Apache::File->new($file);
                   3829:   my $a='';
                   3830:   while (<$fh>) { $a .=$_; }
1.269     www      3831:   return $a;
                   3832:  }
1.36      albertel 3833: }
                   3834: 
                   3835: sub filelocation {
                   3836:   my ($dir,$file) = @_;
                   3837:   my $location;
                   3838:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59      albertel 3839:   if ($file=~m:^/~:) { # is a contruction space reference
                   3840:     $location = $file;
                   3841:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.270     www      3842:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
                   3843:     $location=$file;
1.36      albertel 3844:   } else {
1.59      albertel 3845:     $file=~s/^$perlvar{'lonDocRoot'}//;
                   3846:     $file=~s:^/*res::;
                   3847:     if ( !( $file =~ m:^/:) ) {
                   3848:       $location = $dir. '/'.$file;
                   3849:     } else {
                   3850:       $location = '/home/httpd/html/res'.$file;
                   3851:     }
1.36      albertel 3852:   }
                   3853:   $location=~s://+:/:g; # remove duplicate /
1.46      www      3854:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   3855:   return $location;
                   3856: }
1.36      albertel 3857: 
1.46      www      3858: sub hreflocation {
                   3859:     my ($dir,$file)=@_;
1.191     harris41 3860:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
1.46      www      3861:        my $finalpath=filelocation($dir,$file);
                   3862:        $finalpath=~s/^\/home\/httpd\/html//;
1.225     albertel 3863:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
1.46      www      3864:        return $finalpath;
                   3865:     } else {
                   3866:        return $file;
                   3867:     }
1.31      www      3868: }
                   3869: 
                   3870: # ------------------------------------------------------------- Declutters URLs
                   3871: 
                   3872: sub declutter {
                   3873:     my $thisfn=shift;
                   3874:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
                   3875:     $thisfn=~s/^\///;
                   3876:     $thisfn=~s/^res\///;
1.235     www      3877:     $thisfn=~s/\?.+$//;
1.268     www      3878:     return $thisfn;
                   3879: }
                   3880: 
                   3881: # ------------------------------------------------------------- Clutter up URLs
                   3882: 
                   3883: sub clutter {
                   3884:     my $thisfn='/'.&declutter(shift);
1.270     www      3885:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
                   3886:        $thisfn='/res'.$thisfn; 
                   3887:     }
1.31      www      3888:     return $thisfn;
1.12      www      3889: }
                   3890: 
                   3891: # -------------------------------------------------------- Escape Special Chars
                   3892: 
                   3893: sub escape {
                   3894:     my $str=shift;
                   3895:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   3896:     return $str;
                   3897: }
                   3898: 
                   3899: # ----------------------------------------------------- Un-Escape Special Chars
                   3900: 
                   3901: sub unescape {
                   3902:     my $str=shift;
                   3903:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   3904:     return $str;
                   3905: }
1.11      www      3906: 
1.1       albertel 3907: # ================================================================ Main Program
                   3908: 
1.184     www      3909: sub goodbye {
1.204     albertel 3910:    &logthis("Starting Shut down");
1.184     www      3911:    &flushcourselogs();
                   3912:    &logthis("Shutting down");
1.362     albertel 3913:    return DONE;
1.184     www      3914: }
                   3915: 
1.179     www      3916: BEGIN {
1.228     harris41 3917: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      3918:     unless ($readit) {
1.217     harris41 3919: {
                   3920:     my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
                   3921: 
                   3922:     while (my $configline=<$config>) {
                   3923:         if ($configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 3924: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      3925:            chomp($varvalue);
1.1       albertel 3926:            $perlvar{$varname}=$varvalue;
                   3927:         }
                   3928:     }
                   3929: }
1.227     harris41 3930: {
                   3931:     my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
                   3932: 
                   3933:     while (my $configline=<$config>) {
                   3934:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   3935: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   3936:            chomp($varvalue);
                   3937:            $perlvar{$varname}=$varvalue;
                   3938:         }
                   3939:     }
                   3940: }
1.1       albertel 3941: 
1.327     albertel 3942: # ------------------------------------------------------------ Read domain file
                   3943: {
                   3944:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
                   3945:                             '/domain.tab');
                   3946:     %domaindescription = ();
                   3947:     %domain_auth_def = ();
                   3948:     %domain_auth_arg_def = ();
                   3949:     if ($fh) {
                   3950:        while (<$fh>) {
                   3951:            next if /^\#/;
                   3952:            chomp;
                   3953:            my ($domain, $domain_description, $def_auth, $def_auth_arg)
                   3954:                = split(/:/,$_,4);
                   3955:            $domain_auth_def{$domain}=$def_auth;
                   3956:            $domain_auth_arg_def{$domain}=$def_auth_arg;
                   3957:            $domaindescription{$domain}=$domain_description;
                   3958: #          &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
                   3959: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
                   3960:        }
                   3961:     }
                   3962: }
                   3963: 
                   3964: 
1.1       albertel 3965: # ------------------------------------------------------------- Read hosts file
                   3966: {
                   3967:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
                   3968: 
                   3969:     while (my $configline=<$config>) {
1.303     matthew  3970:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      3971:        chomp($configline);
1.245     www      3972:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
1.252     albertel 3973:        if ($id && $domain && $role && $name && $ip) {
                   3974: 	 $hostname{$id}=$name;
                   3975: 	 $hostdom{$id}=$domain;
                   3976: 	 $hostip{$id}=$ip;
1.300     albertel 3977: 	 $iphost{$ip}=$id;
1.252     albertel 3978: 	 if ($role eq 'library') { $libserv{$id}=$name; }
                   3979:        } else {
                   3980: 	 if ($configline) {
                   3981: 	   &logthis("Skipping hosts.tab line -$configline-");
                   3982: 	 }
1.245     www      3983:        }
1.1       albertel 3984:     }
                   3985: }
                   3986: 
                   3987: # ------------------------------------------------------ Read spare server file
                   3988: {
                   3989:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
                   3990: 
                   3991:     while (my $configline=<$config>) {
                   3992:        chomp($configline);
1.284     matthew  3993:        if ($configline) {
1.1       albertel 3994:           $spareid{$configline}=1;
                   3995:        }
                   3996:     }
                   3997: }
1.11      www      3998: # ------------------------------------------------------------ Read permissions
                   3999: {
                   4000:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
                   4001: 
                   4002:     while (my $configline=<$config>) {
                   4003:        chomp($configline);
1.160     www      4004:       if ($configline) {
1.11      www      4005:        my ($role,$perm)=split(/ /,$configline);
                   4006:        if ($perm ne '') { $pr{$role}=$perm; }
1.160     www      4007:       }
1.11      www      4008:     }
                   4009: }
                   4010: 
                   4011: # -------------------------------------------- Read plain texts for permissions
                   4012: {
                   4013:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
                   4014: 
                   4015:     while (my $configline=<$config>) {
                   4016:        chomp($configline);
1.160     www      4017:       if ($configline) {
1.11      www      4018:        my ($short,$plain)=split(/:/,$configline);
                   4019:        if ($plain ne '') { $prp{$short}=$plain; }
1.160     www      4020:       }
1.135     www      4021:     }
                   4022: }
                   4023: 
                   4024: # ---------------------------------------------------------- Read package table
                   4025: {
                   4026:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
                   4027: 
                   4028:     while (my $configline=<$config>) {
                   4029:        chomp($configline);
                   4030:        my ($short,$plain)=split(/:/,$configline);
1.143     www      4031:        my ($pack,$name)=split(/\&/,$short);
                   4032:        if ($plain ne '') {
                   4033:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   4034:           $packagetab{$short}=$plain; 
1.25      www      4035:        }
1.11      www      4036:     }
1.329     matthew  4037: }
                   4038: 
                   4039: # ------------- set up temporary directory
                   4040: {
                   4041:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   4042: 
1.11      www      4043: }
                   4044: 
1.71      www      4045: %metacache=();
1.185     www      4046: 
1.281     www      4047: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      4048: $dumpcount=0;
1.22      www      4049: 
1.163     harris41 4050: &logtouch();
1.12      www      4051: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      4052: $readit=1;
                   4053: }
1.1       albertel 4054: }
1.179     www      4055: 
1.1       albertel 4056: 1;
1.191     harris41 4057: __END__
                   4058: 
1.243     albertel 4059: =pod
                   4060: 
1.191     harris41 4061: =head1 NAME
                   4062: 
1.243     albertel 4063: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 4064: 
                   4065: =head1 SYNOPSIS
                   4066: 
1.243     albertel 4067: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 4068: 
                   4069:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   4070: 
1.243     albertel 4071: Common parameters:
                   4072: 
                   4073: =over 4
                   4074: 
                   4075: =item *
                   4076: 
                   4077: $uname : an internal username (if $cname expecting a course Id specifically)
                   4078: 
                   4079: =item *
                   4080: 
                   4081: $udom : a domain (if $cdom expecting a course's domain specifically)
                   4082: 
                   4083: =item *
                   4084: 
                   4085: $symb : a resource instance identifier
                   4086: 
                   4087: =item *
                   4088: 
                   4089: $namespace : the name of a .db file that contains the data needed or
                   4090: being set.
                   4091: 
                   4092: =back
                   4093: 
1.191     harris41 4094: =head1 INTRODUCTION
                   4095: 
                   4096: This module provides subroutines which interact with the
1.243     albertel 4097: lonc/lond (TCP) network layer of LON-CAPA. And Can be used to ask about 
                   4098: - classes
                   4099: - users 
                   4100: - resources
                   4101: 
                   4102: For many of these objects you can also use this to store data about
                   4103: them or modify them in various ways.
1.191     harris41 4104: 
                   4105: This is part of the LearningOnline Network with CAPA project
                   4106: described at http://www.lon-capa.org.
                   4107: 
1.243     albertel 4108: =head1 RETURN MESSAGES
1.191     harris41 4109: 
                   4110: =over 4
                   4111: 
                   4112: =item *
                   4113: 
1.243     albertel 4114: con_lost : unable to contact remote host
1.191     harris41 4115: 
                   4116: =item *
                   4117: 
1.243     albertel 4118: con_delayed : unable to contact remote host, message will be delivered
                   4119: when the connection is brought back up
1.191     harris41 4120: 
                   4121: =item *
                   4122: 
1.243     albertel 4123: con_failed : unable to contact remote host and unable to save message
                   4124: for later delivery
1.191     harris41 4125: 
                   4126: =item *
                   4127: 
1.243     albertel 4128: error: : an error a occured, a description of the error follows the :
1.191     harris41 4129: 
                   4130: =item *
                   4131: 
1.243     albertel 4132: no_such_host : unable to fund a host associated with the user/domain
                   4133: that was requested
1.191     harris41 4134: 
1.243     albertel 4135: =back
1.191     harris41 4136: 
1.243     albertel 4137: =head1 PUBLIC SUBROUTINES
1.191     harris41 4138: 
1.243     albertel 4139: =head2 Session Environment Functions
1.191     harris41 4140: 
1.243     albertel 4141: =over 4
1.191     harris41 4142: 
                   4143: =item *
                   4144: 
1.243     albertel 4145: appenv(%hash) : the value of %hash is written to the user envirnoment
                   4146: file, and will be restored for each access this user makes during this
                   4147: session, also modifies the %ENV for the current process
1.191     harris41 4148: 
                   4149: =item *
                   4150: 
1.243     albertel 4151: delenv($regexp) : removes all items from the session environment file that matches the regular expression in $regexp. The values are also delted from the current processes %ENV.
1.191     harris41 4152: 
1.243     albertel 4153: =back
                   4154: 
                   4155: =head2 User Information
1.191     harris41 4156: 
1.243     albertel 4157: =over 4
1.191     harris41 4158: 
                   4159: =item *
                   4160: 
                   4161: queryauthenticate($uname,$udom) : try to determine user's current
                   4162: authentication scheme
                   4163: 
                   4164: =item *
                   4165: 
                   4166: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
1.243     albertel 4167: servers (first use the current one), $upass should be the users password
1.191     harris41 4168: 
                   4169: =item *
                   4170: 
1.243     albertel 4171: homeserver($uname,$udom) : find the server which has the user's
                   4172: directory and files (there must be only one), this caches the answer,
                   4173: and also caches if there is a borken connection.
1.191     harris41 4174: 
                   4175: =item *
                   4176: 
1.243     albertel 4177: idget($udom,@ids) : find the usernames behind a list of IDs (IDs are a
                   4178: unique resource in a domain, there must be only 1 ID per username, and
                   4179: only 1 username per ID in a specific domain) (returns hash:
1.191     harris41 4180: id=>name,id=>name)
                   4181: 
                   4182: =item *
                   4183: 
                   4184: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
                   4185: name=>id,name=>id)
                   4186: 
                   4187: =item *
                   4188: 
                   4189: idput($udom,%ids) : store away a list of names and associated IDs
                   4190: 
                   4191: =item *
                   4192: 
1.243     albertel 4193: rolesinit($udom,$username,$authhost) : get user privileges
                   4194: 
                   4195: =item *
                   4196: 
                   4197: usection($udom,$uname,$cname) : finds the section of student in the
                   4198: course $cname, return section name/number or '' for "not in course"
                   4199: and '-1' for "no section"
                   4200: 
                   4201: =item *
                   4202: 
                   4203: userenvironment($udom,$uname,@what) : gets the values of the keys
                   4204: passed in @what from the requested user's environment, returns a hash
                   4205: 
                   4206: =back
                   4207: 
                   4208: =head2 User Roles
                   4209: 
                   4210: =over 4
                   4211: 
                   4212: =item *
                   4213: 
                   4214: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   4215: actions
                   4216:  F: full access
                   4217:  U,I,K: authentication modes (cxx only)
                   4218:  '': forbidden
                   4219:  1: user needs to choose course
                   4220:  2: browse allowed
                   4221: 
                   4222: =item *
                   4223: 
                   4224: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   4225: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   4226: and course level
                   4227: 
                   4228: =item *
                   4229: 
                   4230: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   4231: explanation of a user role term
                   4232: 
                   4233: =back
                   4234: 
                   4235: =head2 User Modification
                   4236: 
                   4237: =over 4
                   4238: 
                   4239: =item *
                   4240: 
                   4241: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   4242: user for the level given by URL.  Optional start and end dates (leave empty
                   4243: string or zero for "no date")
1.191     harris41 4244: 
                   4245: =item *
                   4246: 
1.243     albertel 4247: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   4248: change a users, password, possible return values are: ok,
                   4249: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   4250: refused
1.191     harris41 4251: 
                   4252: =item *
                   4253: 
1.243     albertel 4254: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 4255: 
                   4256: =item *
                   4257: 
1.243     albertel 4258: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   4259: modify user
1.191     harris41 4260: 
                   4261: =item *
                   4262: 
1.286     matthew  4263: modifystudent
                   4264: 
                   4265: modify a students enrollment and identification information.
                   4266: The course id is resolved based on the current users environment.  
                   4267: This means the envoking user must be a course coordinator or otherwise
                   4268: associated with a course.
                   4269: 
1.297     matthew  4270: This call is essentially a wrapper for lonnet::modifyuser and
                   4271: lonnet::modify_student_enrollment
1.286     matthew  4272: 
                   4273: Inputs: 
                   4274: 
                   4275: =over 4
                   4276: 
                   4277: =item B<$udom> Students loncapa domain
                   4278: 
                   4279: =item B<$uname> Students loncapa login name
                   4280: 
                   4281: =item B<$uid> Students id/student number
                   4282: 
                   4283: =item B<$umode> Students authentication mode
                   4284: 
                   4285: =item B<$upass> Students password
                   4286: 
                   4287: =item B<$first> Students first name
                   4288: 
                   4289: =item B<$middle> Students middle name
                   4290: 
                   4291: =item B<$last> Students last name
                   4292: 
                   4293: =item B<$gene> Students generation
                   4294: 
                   4295: =item B<$usec> Students section in course
                   4296: 
                   4297: =item B<$end> Unix time of the roles expiration
                   4298: 
                   4299: =item B<$start> Unix time of the roles start date
                   4300: 
                   4301: =item B<$forceid> If defined, allow $uid to be changed
                   4302: 
                   4303: =item B<$desiredhome> server to use as home server for student
                   4304: 
                   4305: =back
1.297     matthew  4306: 
                   4307: =item *
                   4308: 
                   4309: modify_student_enrollment
                   4310: 
                   4311: Change a students enrollment status in a class.  The environment variable
                   4312: 'role.request.course' must be defined for this function to proceed.
                   4313: 
                   4314: Inputs:
                   4315: 
                   4316: =over 4
                   4317: 
                   4318: =item $udom, students domain
                   4319: 
                   4320: =item $uname, students name
                   4321: 
                   4322: =item $uid, students user id
                   4323: 
                   4324: =item $first, students first name
                   4325: 
                   4326: =item $middle
                   4327: 
                   4328: =item $last
                   4329: 
                   4330: =item $gene
                   4331: 
                   4332: =item $usec
                   4333: 
                   4334: =item $end
                   4335: 
                   4336: =item $start
                   4337: 
                   4338: =back
                   4339: 
1.191     harris41 4340: 
                   4341: =item *
                   4342: 
1.243     albertel 4343: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   4344: custom role; give a custom role to a user for the level given by URL.  Specify
                   4345: name and domain of role author, and role name
1.191     harris41 4346: 
                   4347: =item *
                   4348: 
1.243     albertel 4349: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 4350: 
                   4351: =item *
                   4352: 
1.243     albertel 4353: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   4354: 
                   4355: =back
                   4356: 
                   4357: =head2 Course Infomation
                   4358: 
                   4359: =over 4
1.191     harris41 4360: 
                   4361: =item *
                   4362: 
1.243     albertel 4363: coursedescription($courseid) : course description
1.191     harris41 4364: 
                   4365: =item *
                   4366: 
1.243     albertel 4367: courseresdata($coursenum,$coursedomain,@which) : request for current
                   4368: parameter setting for a specific course, @what should be a list of
                   4369: parameters to ask about. This routine caches answers for 5 minutes.
                   4370: 
                   4371: =back
                   4372: 
                   4373: =head2 Course Modification
                   4374: 
                   4375: =over 4
1.191     harris41 4376: 
                   4377: =item *
                   4378: 
1.243     albertel 4379: writecoursepref($courseid,%prefs) : write preferences (environment
                   4380: database) for a course
1.191     harris41 4381: 
                   4382: =item *
                   4383: 
1.243     albertel 4384: createcourse($udom,$description,$url) : make/modify course
                   4385: 
                   4386: =back
                   4387: 
                   4388: =head2 Resource Subroutines
                   4389: 
                   4390: =over 4
1.191     harris41 4391: 
                   4392: =item *
                   4393: 
1.243     albertel 4394: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 4395: 
                   4396: =item *
                   4397: 
1.243     albertel 4398: repcopy($filename) : subscribes to the requested file, and attempts to
                   4399: replicate from the owning library server, Might return
                   4400: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
                   4401: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
                   4402: resource. Expects the local filesystem pathname
                   4403: (/home/httpd/html/res/....)
                   4404: 
                   4405: =back
                   4406: 
                   4407: =head2 Resource Information
                   4408: 
                   4409: =over 4
1.191     harris41 4410: 
                   4411: =item *
                   4412: 
1.243     albertel 4413: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   4414: a vairety of different possible values, $varname should be a request
                   4415: string, and the other parameters can be used to specify who and what
                   4416: one is asking about.
                   4417: 
                   4418: Possible values for $varname are environment.lastname (or other item
                   4419: from the envirnment hash), user.name (or someother aspect about the
                   4420: user), resource.0.maxtries (or some other part and parameter of a
                   4421: resource)
1.204     albertel 4422: 
                   4423: =item *
                   4424: 
1.243     albertel 4425: directcondval($number) : get current value of a condition; reads from a state
                   4426: string
1.204     albertel 4427: 
                   4428: =item *
                   4429: 
1.243     albertel 4430: condval($condidx) : value of condition index based on state
1.204     albertel 4431: 
                   4432: =item *
                   4433: 
1.243     albertel 4434: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   4435: resource's metadata, $what should be either a specific key, or either
                   4436: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   4437: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   4438: 
                   4439: this function automatically caches all requests
1.191     harris41 4440: 
                   4441: =item *
                   4442: 
1.243     albertel 4443: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   4444: network of library servers; returns file handle of where SQL and regex results
                   4445: will be stored for query
1.191     harris41 4446: 
                   4447: =item *
                   4448: 
1.243     albertel 4449: symbread($filename) : return symbolic list entry (filename argument optional);
                   4450: returns the data handle
1.191     harris41 4451: 
                   4452: =item *
                   4453: 
1.243     albertel 4454: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
                   4455: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
                   4456: failure, user must be in a course, as it assumes the existance of the
                   4457: course initi hash, and uses $ENV('request.course.id'}
                   4458: 
1.191     harris41 4459: 
                   4460: =item *
                   4461: 
1.243     albertel 4462: symbclean($symb) : removes versions numbers from a symb, returns the
                   4463: cleaned symb
1.191     harris41 4464: 
                   4465: =item *
                   4466: 
1.243     albertel 4467: is_on_map($uri) : checks if the $uri is somewhere on the current
                   4468: course map, user must be in a course for it to work.
1.191     harris41 4469: 
                   4470: =item *
                   4471: 
1.243     albertel 4472: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 4473: 
                   4474: =item *
                   4475: 
1.243     albertel 4476: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   4477: a random seed, all arguments are optional, if they aren't sent it uses the
                   4478: environment to derive them. Note: if symb isn't sent and it can't get one
                   4479: from &symbread it will use the current time as its return value
1.191     harris41 4480: 
                   4481: =item *
                   4482: 
1.243     albertel 4483: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   4484: unfakeable, receipt
1.191     harris41 4485: 
                   4486: =item *
                   4487: 
1.243     albertel 4488: receipt() : API to ireceipt working off of ENV values; given out to users
1.191     harris41 4489: 
                   4490: =item *
                   4491: 
1.243     albertel 4492: countacc($url) : count the number of accesses to a given URL
1.191     harris41 4493: 
                   4494: =item *
                   4495: 
1.243     albertel 4496: checkout($symb,$tuname,$tudom,$tcrsid) :  creates a record of a user having looked at an item, most likely printed out or otherwise using a resource
1.191     harris41 4497: 
                   4498: =item *
                   4499: 
1.243     albertel 4500: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid)
1.191     harris41 4501: 
                   4502: =item *
                   4503: 
1.243     albertel 4504: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 4505: 
                   4506: =item *
                   4507: 
1.243     albertel 4508: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   4509: forcing spreadsheet to reevaluate the resource scores next time.
                   4510: 
                   4511: =back
                   4512: 
                   4513: =head2 Storing/Retreiving Data
                   4514: 
                   4515: =over 4
1.191     harris41 4516: 
                   4517: =item *
                   4518: 
1.243     albertel 4519: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   4520: for this url; hashref needs to be given and should be a \%hashname; the
                   4521: remaining args aren't required and if they aren't passed or are '' they will
                   4522: be derived from the ENV
1.191     harris41 4523: 
                   4524: =item *
                   4525: 
1.243     albertel 4526: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   4527: uses critical subroutine
1.191     harris41 4528: 
                   4529: =item *
                   4530: 
1.243     albertel 4531: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   4532: all args are optional
1.191     harris41 4533: 
                   4534: =item *
                   4535: 
1.243     albertel 4536: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   4537: works very similar to store/cstore, but all data is stored in a
                   4538: temporary location and can be reset using tmpreset, $storehash should
                   4539: be a hash reference, returns nothing on success
1.191     harris41 4540: 
                   4541: =item *
                   4542: 
1.243     albertel 4543: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   4544: similar to restore, but all data is stored in a temporary location and
                   4545: can be reset using tmpreset. Returns a hash of values on success,
                   4546: error string otherwise.
1.191     harris41 4547: 
                   4548: =item *
                   4549: 
1.243     albertel 4550: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   4551: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 4552: 
                   4553: =item *
                   4554: 
1.243     albertel 4555: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   4556: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 4557: 
                   4558: =item *
                   4559: 
1.243     albertel 4560: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   4561: namesp ($udom and $uname are optional)
1.191     harris41 4562: 
                   4563: =item *
                   4564: 
1.243     albertel 4565: dump($namespace,$udom,$uname,$regexp) : 
                   4566: dumps the complete (or key matching regexp) namespace into a hash
                   4567: ($udom, $uname and $regexp are optional)
1.191     harris41 4568: 
                   4569: =item *
                   4570: 
1.243     albertel 4571: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   4572: ($udom and $uname are optional)
1.191     harris41 4573: 
                   4574: =item *
                   4575: 
1.243     albertel 4576: cput($namespace,$storehash,$udom,$uname) : critical put
                   4577: ($udom and $uname are optional)
1.191     harris41 4578: 
                   4579: =item *
                   4580: 
1.243     albertel 4581: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   4582: reference filled in from namesp (encrypts the return communication)
                   4583: ($udom and $uname are optional)
1.191     harris41 4584: 
                   4585: =item *
                   4586: 
1.243     albertel 4587: log($udom,$name,$home,$message) : write to permanent log for user; use
                   4588: critical subroutine
                   4589: 
                   4590: =back
                   4591: 
                   4592: =head2 Network Status Functions
                   4593: 
                   4594: =over 4
1.191     harris41 4595: 
                   4596: =item *
                   4597: 
                   4598: dirlist($uri) : return directory list based on URI
                   4599: 
                   4600: =item *
                   4601: 
1.243     albertel 4602: spareserver() : find server with least workload from spare.tab
                   4603: 
                   4604: =back
                   4605: 
                   4606: =head2 Apache Request
                   4607: 
                   4608: =over 4
1.191     harris41 4609: 
                   4610: =item *
                   4611: 
1.243     albertel 4612: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   4613: localhost, posts hash
                   4614: 
                   4615: =back
                   4616: 
                   4617: =head2 Data to String to Data
                   4618: 
                   4619: =over 4
1.191     harris41 4620: 
                   4621: =item *
                   4622: 
1.243     albertel 4623: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   4624: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 4625: 
                   4626: =item *
                   4627: 
1.243     albertel 4628: hashref2str($hashref) : convert a hashref into a string complete with
                   4629: escaping and '=' and '&' separators, supports elements that are
                   4630: arrayrefs and hashrefs
1.191     harris41 4631: 
                   4632: =item *
                   4633: 
1.243     albertel 4634: arrayref2str($arrayref) : convert an arrayref into a string complete
                   4635: with escaping and '&' separators, supports elements that are arrayrefs
                   4636: and hashrefs
1.191     harris41 4637: 
                   4638: =item *
                   4639: 
1.243     albertel 4640: str2hash($string) : convert string to hash using unescaping and
                   4641: splitting on '=' and '&', supports elements that are arrayrefs and
                   4642: hashrefs
1.191     harris41 4643: 
                   4644: =item *
                   4645: 
1.243     albertel 4646: str2array($string) : convert string to hash using unescaping and
                   4647: splitting on '&', supports elements that are arrayrefs and hashrefs
                   4648: 
                   4649: =back
                   4650: 
                   4651: =head2 Logging Routines
                   4652: 
                   4653: =over 4
                   4654: 
                   4655: These routines allow one to make log messages in the lonnet.log and
                   4656: lonnet.perm logfiles.
1.191     harris41 4657: 
                   4658: =item *
                   4659: 
1.243     albertel 4660: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 4661: 
                   4662: =item *
                   4663: 
1.243     albertel 4664: logthis() : append message to the normal lonnet.log file, it gets
                   4665: preiodically rolled over and deleted.
1.191     harris41 4666: 
                   4667: =item *
                   4668: 
1.243     albertel 4669: logperm() : append a permanent message to lonnet.perm.log, this log
                   4670: file never gets deleted by any automated portion of the system, only
                   4671: messages of critical importance should go in here.
                   4672: 
                   4673: =back
                   4674: 
                   4675: =head2 General File Helper Routines
                   4676: 
                   4677: =over 4
1.191     harris41 4678: 
                   4679: =item *
                   4680: 
1.243     albertel 4681: getfile($file) : returns the entire contents of a file or -1; it
                   4682: properly subscribes to and replicates the file if neccessary.
1.191     harris41 4683: 
                   4684: =item *
                   4685: 
1.243     albertel 4686: filelocation($dir,$file) : returns file system location of a file
                   4687: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   4688: directory that relative $file lookups are to looked in ($dir of /a/dir
                   4689: and a file of ../bob will become /a/bob)
1.191     harris41 4690: 
                   4691: =item *
                   4692: 
                   4693: hreflocation($dir,$file) : returns file system location or a URL; same as
                   4694: filelocation except for hrefs
                   4695: 
                   4696: =item *
                   4697: 
                   4698: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   4699: 
1.243     albertel 4700: =back
                   4701: 
                   4702: =head2 HTTP Helper Routines
                   4703: 
                   4704: =over 4
                   4705: 
1.191     harris41 4706: =item *
                   4707: 
                   4708: escape() : unpack non-word characters into CGI-compatible hex codes
                   4709: 
                   4710: =item *
                   4711: 
                   4712: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   4713: 
1.243     albertel 4714: =back
                   4715: 
                   4716: =head1 PRIVATE SUBROUTINES
                   4717: 
                   4718: =head2 Underlying communication routines (Shouldn't call)
                   4719: 
                   4720: =over 4
                   4721: 
                   4722: =item *
                   4723: 
                   4724: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   4725: 
                   4726: =item *
                   4727: 
                   4728: reply() : uses subreply to send a message to remote machine, logs all failures
                   4729: 
                   4730: =item *
                   4731: 
                   4732: critical() : passes a critical message to another server; if cannot
                   4733: get through then place message in connection buffer directory and
                   4734: returns con_delayed, if incapable of saving message, returns
                   4735: con_failed
                   4736: 
                   4737: =item *
                   4738: 
                   4739: reconlonc() : tries to reconnect lonc client processes.
                   4740: 
                   4741: =back
                   4742: 
                   4743: =head2 Resource Access Logging
                   4744: 
                   4745: =over 4
                   4746: 
                   4747: =item *
                   4748: 
                   4749: flushcourselogs() : flush (save) buffer logs and access logs
                   4750: 
                   4751: =item *
                   4752: 
                   4753: courselog($what) : save message for course in hash
                   4754: 
                   4755: =item *
                   4756: 
                   4757: courseacclog($what) : save message for course using &courselog().  Perform
                   4758: special processing for specific resource types (problems, exams, quizzes, etc).
                   4759: 
1.191     harris41 4760: =item *
                   4761: 
                   4762: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   4763: as a PerlChildExitHandler
1.243     albertel 4764: 
                   4765: =back
                   4766: 
                   4767: =head2 Other
                   4768: 
                   4769: =over 4
                   4770: 
                   4771: =item *
                   4772: 
                   4773: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 4774: 
                   4775: =back
                   4776: 
                   4777: =cut

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