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

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

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