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

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

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