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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.683.2.21! albertel    4: # $Id: lonnet.pm,v 1.683.2.20 2006/04/06 19:19:11 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: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.599     albertel   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
                     42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.683.2.2  albertel   43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.8       www        48: use Apache::Constants qw(:common :http);
1.208     albertel   49: use HTML::LCParser;
1.637     raeburn    50: use HTML::Parser;
1.88      www        51: use Fcntl qw(:flock);
1.557     albertel   52: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   53: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   54: use Cache::Memcached;
1.676     albertel   55: use Digest::MD5;
                     56: 
1.195     www        57: my $readit;
1.550     foxr       58: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   59: 
1.619     albertel   60: require Exporter;
                     61: 
                     62: our @ISA = qw (Exporter);
                     63: our @EXPORT = qw(%env);
                     64: 
1.449     matthew    65: =pod
                     66: 
                     67: =head1 Package Variables
                     68: 
                     69: These are largely undocumented, so if you decipher one please note it here.
                     70: 
                     71: =over 4
                     72: 
                     73: =item $processmarker
                     74: 
                     75: Contains the time this process was started and this servers host id.
                     76: 
                     77: =item $dumpcount
                     78: 
                     79: Counts the number of times a message log flush has been attempted (regardless
                     80: of success) by this process.  Used as part of the filename when messages are
                     81: delayed.
                     82: 
                     83: =back
                     84: 
                     85: =cut
                     86: 
                     87: 
1.1       albertel   88: # --------------------------------------------------------------------- Logging
                     89: 
1.163     harris41   90: sub logtouch {
                     91:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel   92:     unless (-e "$execdir/logs/lonnet.log") {	
                     93: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41   94: 	close $fh;
                     95:     }
                     96:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                     97:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                     98: }
                     99: 
1.1       albertel  100: sub logthis {
                    101:     my $message=shift;
                    102:     my $execdir=$perlvar{'lonDaemons'};
                    103:     my $now=time;
                    104:     my $local=localtime($now);
1.448     albertel  105:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    106: 	print $fh "$local ($$): $message\n";
                    107: 	close($fh);
                    108:     }
1.1       albertel  109:     return 1;
                    110: }
                    111: 
                    112: sub logperm {
                    113:     my $message=shift;
                    114:     my $execdir=$perlvar{'lonDaemons'};
                    115:     my $now=time;
                    116:     my $local=localtime($now);
1.448     albertel  117:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    118: 	print $fh "$now:$message:$local\n";
                    119: 	close($fh);
                    120:     }
1.1       albertel  121:     return 1;
                    122: }
                    123: 
                    124: # -------------------------------------------------- Non-critical communication
                    125: sub subreply {
                    126:     my ($cmd,$server)=@_;
                    127:     my $peerfile="$perlvar{'lonSockDir'}/$server";
1.549     foxr      128:     #
                    129:     #  With loncnew process trimming, there's a timing hole between lonc server
                    130:     #  process exit and the master server picking up the listen on the AF_UNIX
                    131:     #  socket.  In that time interval, a lock file will exist:
                    132: 
                    133:     my $lockfile=$peerfile.".lock";
                    134:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    135: 	sleep(1);
                    136:     }
                    137:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      138:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      139:     #
1.550     foxr      140:     #   We'll give the connection a few tries before abandoning it.  If
                    141:     #   connection is not possible, we'll con_lost back to the client.
                    142:     #   
                    143:     my $client;
                    144:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    145: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    146: 				      Type    => SOCK_STREAM,
                    147: 				      Timeout => 10);
                    148: 	if($client) {
                    149: 	    last;		# Connected!
                    150: 	}
                    151: 	sleep(1);		# Try again later if failed connection.
                    152:     }
                    153:     my $answer;
                    154:     if ($client) {
                    155: 	print $client "$cmd\n";
                    156: 	$answer=<$client>;
                    157: 	if (!$answer) { $answer="con_lost"; }
                    158: 	chomp($answer);
                    159:     } else {
                    160: 	$answer = 'con_lost';	# Failed connection.
                    161:     }
1.1       albertel  162:     return $answer;
                    163: }
                    164: 
                    165: sub reply {
                    166:     my ($cmd,$server)=@_;
1.205     www       167:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  168:     my $answer=subreply($cmd,$server);
1.65      www       169:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  170:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       171:                 " $cmd to $server returned $answer</font>");
                    172:     }
1.1       albertel  173:     return $answer;
                    174: }
                    175: 
                    176: # ----------------------------------------------------------- Send USR1 to lonc
                    177: 
                    178: sub reconlonc {
                    179:     my $peerfile=shift;
                    180:     &logthis("Trying to reconnect for $peerfile");
                    181:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  182:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  183: 	my $loncpid=<$fh>;
                    184:         chomp($loncpid);
                    185:         if (kill 0 => $loncpid) {
                    186: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    187:             kill USR1 => $loncpid;
                    188:             sleep 1;
                    189:             if (-e "$peerfile") { return; }
                    190:             &logthis("$peerfile still not there, give it another try");
                    191:             sleep 5;
                    192:             if (-e "$peerfile") { return; }
1.12      www       193:             &logthis(
1.672     albertel  194:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  195:         } else {
1.12      www       196: 	    &logthis(
1.672     albertel  197:                "<font color=\"blue\">WARNING:".
1.12      www       198:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  199:         }
                    200:     } else {
1.672     albertel  201:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  202:     }
                    203: }
                    204: 
                    205: # ------------------------------------------------------ Critical communication
1.12      www       206: 
1.1       albertel  207: sub critical {
                    208:     my ($cmd,$server)=@_;
1.89      www       209:     unless ($hostname{$server}) {
1.672     albertel  210:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       211:                " Critical message to unknown server ($server)</font>");
                    212:         return 'no_such_host';
                    213:     }
1.1       albertel  214:     my $answer=reply($cmd,$server);
                    215:     if ($answer eq 'con_lost') {
                    216: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  217: 	my $answer=reply($cmd,$server);
1.1       albertel  218:         if ($answer eq 'con_lost') {
                    219:             my $now=time;
                    220:             my $middlename=$cmd;
1.5       www       221:             $middlename=substr($middlename,0,16);
1.1       albertel  222:             $middlename=~s/\W//g;
                    223:             my $dfilename=
1.305     www       224:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    225:             $dumpcount++;
1.1       albertel  226:             {
1.448     albertel  227: 		my $dfh;
                    228: 		if (open($dfh,">$dfilename")) {
                    229: 		    print $dfh "$cmd\n"; 
                    230: 		    close($dfh);
                    231: 		}
1.1       albertel  232:             }
                    233:             sleep 2;
                    234:             my $wcmd='';
                    235:             {
1.448     albertel  236: 		my $dfh;
                    237: 		if (open($dfh,"<$dfilename")) {
                    238: 		    $wcmd=<$dfh>; 
                    239: 		    close($dfh);
                    240: 		}
1.1       albertel  241:             }
                    242:             chomp($wcmd);
1.7       www       243:             if ($wcmd eq $cmd) {
1.672     albertel  244: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       245:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  246:                 &logperm("D:$server:$cmd");
                    247: 	        return 'con_delayed';
                    248:             } else {
1.672     albertel  249:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       250:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  251:                 &logperm("F:$server:$cmd");
                    252:                 return 'con_failed';
                    253:             }
                    254:         }
                    255:     }
                    256:     return $answer;
1.405     albertel  257: }
                    258: 
1.374     www       259: # ------------------------------------------- Transfer profile into environment
                    260: 
                    261: sub transfer_profile_to_env {
                    262:     my ($lonidsdir,$handle)=@_;
                    263:     my @profile;
                    264:     {
1.448     albertel  265: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       266: 	flock($idf,LOCK_SH);
                    267: 	@profile=<$idf>;
1.448     albertel  268: 	close($idf);
1.374     www       269:     }
                    270:     my $envi;
1.433     matthew   271:     my %Remove;
1.374     www       272:     for ($envi=0;$envi<=$#profile;$envi++) {
                    273: 	chomp($profile[$envi]);
1.683.2.6  albertel  274: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.683.2.20  albertel  275: 	$envname=&unescape($envname);
                    276: 	$envvalue=&unescape($envvalue);
1.619     albertel  277: 	$env{$envname} = $envvalue;
1.433     matthew   278:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    279:             if ($time < time-300) {
                    280:                 $Remove{$key}++;
                    281:             }
                    282:         }
                    283:     }
1.619     albertel  284:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   285:     foreach my $expired_key (keys(%Remove)) {
                    286:         &delenv($expired_key);
1.374     www       287:     }
1.1       albertel  288: }
                    289: 
1.5       www       290: # ---------------------------------------------------------- Append Environment
                    291: 
                    292: sub appenv {
1.6       www       293:     my %newenv=@_;
1.191     harris41  294:     foreach (keys %newenv) {
1.35      www       295: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
1.672     albertel  296:             &logthis("<font color=\"blue\">WARNING: ".
1.151     www       297:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    298:                 .'</font>');
1.35      www       299: 	    delete($newenv{$_});
                    300:         } else {
1.619     albertel  301:             $env{$_}=$newenv{$_};
1.35      www       302:         }
1.191     harris41  303:     }
1.95      www       304: 
                    305:     my $lockfh;
1.620     albertel  306:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  307: 	return 'error: '.$!;
1.95      www       308:     }
                    309:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  310:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       311:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  312:          close($lockfh);
1.95      www       313:          return 'error: '.$!;
                    314:     }
                    315: 
1.6       www       316:     my @oldenv;
                    317:     {
1.448     albertel  318: 	my $fh;
1.620     albertel  319: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  320: 	    return 'error: '.$!;
                    321: 	}
                    322: 	@oldenv=<$fh>;
                    323: 	close($fh);
1.6       www       324:     }
                    325:     for (my $i=0; $i<=$#oldenv; $i++) {
                    326:         chomp($oldenv[$i]);
1.9       www       327:         if ($oldenv[$i] ne '') {
1.683.2.6  albertel  328: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.683.2.20  albertel  329: 	    $name=&unescape($name);
                    330: 	    $value=&unescape($value);
1.448     albertel  331: 	    unless (defined($newenv{$name})) {
                    332: 		$newenv{$name}=$value;
                    333: 	    }
1.9       www       334:         }
1.6       www       335:     }
                    336:     {
1.448     albertel  337: 	my $fh;
1.620     albertel  338: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  339: 	    return 'error';
                    340: 	}
                    341: 	my $newname;
                    342: 	foreach $newname (keys %newenv) {
1.683.2.20  albertel  343: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
1.448     albertel  344: 	}
                    345: 	close($fh);
1.56      www       346:     }
1.448     albertel  347: 	
                    348:     close($lockfh);
1.56      www       349:     return 'ok';
                    350: }
                    351: # ----------------------------------------------------- Delete from Environment
                    352: 
                    353: sub delenv {
                    354:     my $delthis=shift;
                    355:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  356:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       357:                 "Attempt to delete from environment ".$delthis);
                    358:         return 'error';
                    359:     }
                    360:     my @oldenv;
                    361:     {
1.448     albertel  362: 	my $fh;
1.620     albertel  363: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  364: 	    return 'error';
                    365: 	}
                    366: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  367: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  368: 		     'Could not obtain shared lock in delenv: '.$!);
                    369: 	    close($fh);
                    370: 	    return 'error: '.$!;
                    371: 	}
                    372: 	@oldenv=<$fh>;
                    373: 	close($fh);
1.56      www       374:     }
                    375:     {
1.448     albertel  376: 	my $fh;
1.620     albertel  377: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  378: 	    return 'error';
                    379: 	}
                    380: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  381: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  382: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    383: 	    close($fh);
                    384: 	    return 'error: '.$!;
                    385: 	}
1.683.2.20  albertel  386: 	foreach my $cur_key (@oldenv) {
                    387: 	    my $unescaped_cur_key = &unescape($cur_key);
                    388: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    389:                 my ($key) = split('=',$cur_key,2);
                    390: 		$key = &unescape($key);
1.619     albertel  391:                 delete($env{$key});
1.473     matthew   392:             } else {
1.683.2.20  albertel  393:                 print $fh $cur_key; 
1.473     matthew   394:             }
1.448     albertel  395: 	}
                    396: 	close($fh);
1.5       www       397:     }
                    398:     return 'ok';
1.369     albertel  399: }
                    400: 
                    401: # ------------------------------------------ Find out current server userload
                    402: # there is a copy in lond
                    403: sub userload {
                    404:     my $numusers=0;
                    405:     {
                    406: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    407: 	my $filename;
                    408: 	my $curtime=time;
                    409: 	while ($filename=readdir(LONIDS)) {
                    410: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  411: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  412: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  413: 	}
                    414: 	closedir(LONIDS);
                    415:     }
                    416:     my $userloadpercent=0;
                    417:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    418:     if ($maxuserload) {
1.371     albertel  419: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  420:     }
1.372     albertel  421:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  422:     return $userloadpercent;
1.283     www       423: }
                    424: 
                    425: # ------------------------------------------ Fight off request when overloaded
                    426: 
                    427: sub overloaderror {
                    428:     my ($r,$checkserver)=@_;
                    429:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    430:     my $loadavg;
                    431:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  432:        open(my $loadfile,'/proc/loadavg');
1.283     www       433:        $loadavg=<$loadfile>;
                    434:        $loadavg =~ s/\s.*//g;
1.285     matthew   435:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  436:        close($loadfile);
1.283     www       437:     } else {
                    438:        $loadavg=&reply('load',$checkserver);
                    439:     }
1.285     matthew   440:     my $overload=$loadavg-100;
1.283     www       441:     if ($overload>0) {
1.285     matthew   442: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       443:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       444:         return 413;
1.283     www       445:     }    
                    446:     return '';
1.5       www       447: }
1.1       albertel  448: 
                    449: # ------------------------------ Find server with least workload from spare.tab
1.11      www       450: 
1.1       albertel  451: sub spareserver {
1.670     albertel  452:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  453:     my $tryserver;
                    454:     my $spareserver='';
1.370     albertel  455:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    456:     my $lowestserver=$loadpercent > $userloadpercent?
                    457: 	             $loadpercent :  $userloadpercent;
1.670     albertel  458:     foreach $tryserver (keys(%spareid)) {
                    459: 	my $loadans=&reply('load',$tryserver);
                    460: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  461: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    462: 	    next; #didn't get a number from the server
                    463: 	}
                    464: 	my $answer;
                    465: 	if ($loadans =~ /\d/) {
                    466: 	    if ($userloadans =~ /\d/) {
                    467: 		#both are numbers, pick the bigger one
                    468: 		$answer=$loadans > $userloadans?
                    469: 		    $loadans :  $userloadans;
                    470: 	    } else {
                    471: 		$answer = $loadans;
                    472: 	    }
                    473: 	} else {
                    474: 	    $answer = $userloadans;
                    475: 	}
                    476: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  477: 	    if ($want_server_name) {
                    478: 		$spareserver=$tryserver;
                    479: 	    } else {
                    480: 		$spareserver="http://$hostname{$tryserver}";
                    481: 	    }
1.411     albertel  482: 	    $lowestserver=$answer;
                    483: 	}
1.370     albertel  484:     }
1.1       albertel  485:     return $spareserver;
1.202     matthew   486: }
                    487: 
                    488: # --------------------------------------------- Try to change a user's password
                    489: 
                    490: sub changepass {
                    491:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    492:     $currentpass = &escape($currentpass);
                    493:     $newpass     = &escape($newpass);
                    494:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    495: 		       $server);
                    496:     if (! $answer) {
                    497: 	&logthis("No reply on password change request to $server ".
                    498: 		 "by $uname in domain $udom.");
                    499:     } elsif ($answer =~ "^ok") {
                    500:         &logthis("$uname in $udom successfully changed their password ".
                    501: 		 "on $server.");
                    502:     } elsif ($answer =~ "^pwchange_failure") {
                    503: 	&logthis("$uname in $udom was unable to change their password ".
                    504: 		 "on $server.  The action was blocked by either lcpasswd ".
                    505: 		 "or pwchange");
                    506:     } elsif ($answer =~ "^non_authorized") {
                    507:         &logthis("$uname in $udom did not get their password correct when ".
                    508: 		 "attempting to change it on $server.");
                    509:     } elsif ($answer =~ "^auth_mode_error") {
                    510:         &logthis("$uname in $udom attempted to change their password despite ".
                    511: 		 "not being locally or internally authenticated on $server.");
                    512:     } elsif ($answer =~ "^unknown_user") {
                    513:         &logthis("$uname in $udom attempted to change their password ".
                    514: 		 "on $server but were unable to because $server is not ".
                    515: 		 "their home server.");
                    516:     } elsif ($answer =~ "^refused") {
                    517: 	&logthis("$server refused to change $uname in $udom password because ".
                    518: 		 "it was sent an unencrypted request to change the password.");
                    519:     }
                    520:     return $answer;
1.1       albertel  521: }
                    522: 
1.169     harris41  523: # ----------------------- Try to determine user's current authentication scheme
                    524: 
                    525: sub queryauthenticate {
                    526:     my ($uname,$udom)=@_;
1.456     albertel  527:     my $uhome=&homeserver($uname,$udom);
                    528:     if (!$uhome) {
                    529: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    530: 	return 'no_host';
                    531:     }
                    532:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    533:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    534: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  535:     }
1.456     albertel  536:     return $answer;
1.169     harris41  537: }
                    538: 
1.1       albertel  539: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       540: 
1.1       albertel  541: sub authenticate {
                    542:     my ($uname,$upass,$udom)=@_;
1.12      www       543:     $upass=escape($upass);
1.199     www       544:     $uname=~s/\W//g;
1.471     albertel  545:     my $uhome=&homeserver($uname,$udom);
                    546:     if (!$uhome) {
                    547: 	&logthis("User $uname at $udom is unknown in authenticate");
                    548: 	return 'no_host';
1.1       albertel  549:     }
1.471     albertel  550:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    551:     if ($answer eq 'authorized') {
                    552: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    553: 	return $uhome; 
                    554:     }
                    555:     if ($answer eq 'non_authorized') {
                    556: 	&logthis("User $uname at $udom rejected by $uhome");
                    557: 	return 'no_host'; 
1.9       www       558:     }
1.471     albertel  559:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  560:     return 'no_host';
                    561: }
                    562: 
                    563: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       564: 
1.599     albertel  565: my %homecache;
1.1       albertel  566: sub homeserver {
1.230     stredwic  567:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  568:     my $index="$uname:$udom";
1.426     albertel  569: 
1.599     albertel  570:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  571:     my $tryserver;
                    572:     foreach $tryserver (keys %libserv) {
1.230     stredwic  573:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  574: 		 exists($badServerCache{$tryserver}));
1.1       albertel  575: 	if ($hostdom{$tryserver} eq $udom) {
                    576:            my $answer=reply("home:$udom:$uname",$tryserver);
                    577:            if ($answer eq 'found') { 
1.599     albertel  578: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  579:            } elsif ($answer eq 'no_host') {
                    580: 	       $badServerCache{$tryserver}=1;
1.221     matthew   581:            }
1.1       albertel  582:        }
                    583:     }    
                    584:     return 'no_host';
1.70      www       585: }
                    586: 
                    587: # ------------------------------------- Find the usernames behind a list of IDs
                    588: 
                    589: sub idget {
                    590:     my ($udom,@ids)=@_;
                    591:     my %returnhash=();
                    592:     
                    593:     my $tryserver;
                    594:     foreach $tryserver (keys %libserv) {
                    595:        if ($hostdom{$tryserver} eq $udom) {
                    596: 	  my $idlist=join('&',@ids);
                    597:           $idlist=~tr/A-Z/a-z/; 
                    598: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    599:           my @answer=();
1.76      www       600:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       601: 	      @answer=split(/\&/,$reply);
                    602:           }                    ;
                    603:           my $i;
                    604:           for ($i=0;$i<=$#ids;$i++) {
                    605:               if ($answer[$i]) {
                    606: 		  $returnhash{$ids[$i]}=$answer[$i];
                    607:               } 
                    608:           }
                    609:        }
                    610:     }    
                    611:     return %returnhash;
                    612: }
                    613: 
                    614: # ------------------------------------- Find the IDs behind a list of usernames
                    615: 
                    616: sub idrget {
                    617:     my ($udom,@unames)=@_;
                    618:     my %returnhash=();
1.191     harris41  619:     foreach (@unames) {
1.70      www       620:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  621:     }
1.70      www       622:     return %returnhash;
                    623: }
                    624: 
                    625: # ------------------------------- Store away a list of names and associated IDs
                    626: 
                    627: sub idput {
                    628:     my ($udom,%ids)=@_;
                    629:     my %servers=();
1.191     harris41  630:     foreach (keys %ids) {
1.487     albertel  631: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       632:         my $uhom=&homeserver($_,$udom);
                    633:         if ($uhom ne 'no_host') {
                    634:             my $id=&escape($ids{$_});
                    635:             $id=~tr/A-Z/a-z/;
                    636:             my $unam=&escape($_);
                    637: 	    if ($servers{$uhom}) {
                    638: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    639:             } else {
                    640:                 $servers{$uhom}=$id.'='.$unam;
                    641:             }
                    642:         }
1.191     harris41  643:     }
                    644:     foreach (keys %servers) {
1.70      www       645:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  646:     }
1.344     www       647: }
                    648: 
                    649: # --------------------------------------------------- Assign a key to a student
                    650: 
                    651: sub assign_access_key {
1.364     www       652: #
                    653: # a valid key looks like uname:udom#comments
                    654: # comments are being appended
                    655: #
1.498     www       656:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    657:     $kdom=
1.620     albertel  658:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       659:     $knum=
1.620     albertel  660:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       661:     $cdom=
1.620     albertel  662:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       663:     $cnum=
1.620     albertel  664:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    665:     $udom=$env{'user.name'} unless (defined($udom));
                    666:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       667:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       668:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  669:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       670:                                                   # assigned to this person
                    671:                                                   # - this should not happen,
1.345     www       672:                                                   # unless something went wrong
                    673:                                                   # the first time around
                    674: # ready to assign
1.364     www       675:         $logentry=$1.'; '.$logentry;
1.496     www       676:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       677:                                                  $kdom,$knum) eq 'ok') {
1.345     www       678: # key now belongs to user
1.346     www       679: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       680:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    681:                 &appenv('environment.'.$envkey => $ckey);
                    682:                 return 'ok';
                    683:             } else {
                    684:                 return 
                    685:   'error: Count not permanently assign key, will need to be re-entered later.';
                    686: 	    }
                    687:         } else {
                    688:             return 'error: Could not assign key, try again later.';
                    689:         }
1.364     www       690:     } elsif (!$existing{$ckey}) {
1.345     www       691: # the key does not exist
                    692: 	return 'error: The key does not exist';
                    693:     } else {
                    694: # the key is somebody else's
                    695: 	return 'error: The key is already in use';
                    696:     }
1.344     www       697: }
                    698: 
1.364     www       699: # ------------------------------------------ put an additional comment on a key
                    700: 
                    701: sub comment_access_key {
                    702: #
                    703: # a valid key looks like uname:udom#comments
                    704: # comments are being appended
                    705: #
                    706:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    707:     $cdom=
1.620     albertel  708:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       709:     $cnum=
1.620     albertel  710:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       711:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    712:     if ($existing{$ckey}) {
                    713:         $existing{$ckey}.='; '.$logentry;
                    714: # ready to assign
1.367     www       715:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       716:                                                  $cdom,$cnum) eq 'ok') {
                    717: 	    return 'ok';
                    718:         } else {
                    719: 	    return 'error: Count not store comment.';
                    720:         }
                    721:     } else {
                    722: # the key does not exist
                    723: 	return 'error: The key does not exist';
                    724:     }
                    725: }
                    726: 
1.344     www       727: # ------------------------------------------------------ Generate a set of keys
                    728: 
                    729: sub generate_access_keys {
1.364     www       730:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       731:     $cdom=
1.620     albertel  732:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       733:     $cnum=
1.620     albertel  734:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       735:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       736:     unless (($cdom) && ($cnum)) { return 0; }
                    737:     if ($number>10000) { return 0; }
                    738:     sleep(2); # make sure don't get same seed twice
                    739:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    740:     my $total=0;
                    741:     for (my $i=1;$i<=$number;$i++) {
                    742:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    743:                   sprintf("%lx",int(100000*rand)).'-'.
                    744:                   sprintf("%lx",int(100000*rand));
                    745:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    746:        $newkey=~s/0/h/g; # and also 0 and O
                    747:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    748:        if ($existing{$newkey}) {
                    749:            $i--;
                    750:        } else {
1.364     www       751: 	  if (&put('accesskeys',
                    752:               { $newkey => '# generated '.localtime().
1.620     albertel  753:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       754:                            '; '.$logentry },
                    755: 		   $cdom,$cnum) eq 'ok') {
1.344     www       756:               $total++;
                    757: 	  }
                    758:        }
                    759:     }
1.620     albertel  760:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       761:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    762:     return $total;
                    763: }
                    764: 
                    765: # ------------------------------------------------------- Validate an accesskey
                    766: 
                    767: sub validate_access_key {
                    768:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    769:     $cdom=
1.620     albertel  770:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       771:     $cnum=
1.620     albertel  772:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    773:     $udom=$env{'user.domain'} unless (defined($udom));
                    774:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       775:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  776:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       777: }
                    778: 
                    779: # ------------------------------------- Find the section of student in a course
1.652     albertel  780: sub devalidate_getsection_cache {
                    781:     my ($udom,$unam,$courseid)=@_;
                    782:     $courseid=~s/\_/\//g;
                    783:     $courseid=~s/^(\w)/\/$1/;
                    784:     my $hashid="$udom:$unam:$courseid";
                    785:     &devalidate_cache_new('getsection',$hashid);
                    786: }
1.298     matthew   787: 
                    788: sub getsection {
                    789:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  790:     my $cachetime=1800;
1.298     matthew   791:     $courseid=~s/\_/\//g;
                    792:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  793: 
                    794:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  795:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  796:     if (defined($cached)) { return $result; }
                    797: 
1.298     matthew   798:     my %Pending; 
                    799:     my %Expired;
                    800:     #
                    801:     # Each role can either have not started yet (pending), be active, 
                    802:     #    or have expired.
                    803:     #
                    804:     # If there is an active role, we are done.
                    805:     #
                    806:     # If there is more than one role which has not started yet, 
                    807:     #     choose the one which will start sooner
                    808:     # If there is one role which has not started yet, return it.
                    809:     #
                    810:     # If there is more than one expired role, choose the one which ended last.
                    811:     # If there is a role which has expired, return it.
                    812:     #
                    813:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    814:                         &homeserver($unam,$udom)))) {
                    815:         my ($key,$value)=split(/\=/,$_);
                    816:         $key=&unescape($key);
1.479     albertel  817:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   818:         my $section=$1;
                    819:         if ($key eq $courseid.'_st') { $section=''; }
                    820:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    821:         my $now=time;
1.548     albertel  822:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   823:             $Expired{$end}=$section;
                    824:             next;
                    825:         }
1.548     albertel  826:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   827:             $Pending{$start}=$section;
                    828:             next;
                    829:         }
1.599     albertel  830:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   831:     }
                    832:     #
                    833:     # Presumedly there will be few matching roles from the above
                    834:     # loop and the sorting time will be negligible.
                    835:     if (scalar(keys(%Pending))) {
                    836:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  837:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   838:     } 
                    839:     if (scalar(keys(%Expired))) {
                    840:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    841:         my $time = pop(@sorted);
1.599     albertel  842:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   843:     }
1.599     albertel  844:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   845: }
1.70      www       846: 
1.599     albertel  847: sub save_cache {
1.628     albertel  848:     my ($r)=@_;
                    849:     if (! $r->is_initial_req()) { return DECLINED; }
1.599     albertel  850:     &purge_remembered();
1.620     albertel  851:     undef(%env);
1.628     albertel  852:     return OK;
1.599     albertel  853: }
1.452     albertel  854: 
1.599     albertel  855: my $to_remember=-1;
                    856: my %remembered;
                    857: my %accessed;
                    858: my $kicks=0;
                    859: my $hits=0;
                    860: sub devalidate_cache_new {
                    861:     my ($name,$id,$debug) = @_;
                    862:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    863:     $id=&escape($name.':'.$id);
                    864:     $memcache->delete($id);
                    865:     delete($remembered{$id});
                    866:     delete($accessed{$id});
                    867: }
                    868: 
                    869: sub is_cached_new {
                    870:     my ($name,$id,$debug) = @_;
                    871:     $id=&escape($name.':'.$id);
                    872:     if (exists($remembered{$id})) {
                    873: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    874: 	$accessed{$id}=[&gettimeofday()];
                    875: 	$hits++;
                    876: 	return ($remembered{$id},1);
                    877:     }
                    878:     my $value = $memcache->get($id);
                    879:     if (!(defined($value))) {
                    880: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  881: 	return (undef,undef);
1.416     albertel  882:     }
1.599     albertel  883:     if ($value eq '__undef__') {
                    884: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    885: 	$value=undef;
                    886:     }
                    887:     &make_room($id,$value,$debug);
                    888:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    889:     return ($value,1);
                    890: }
                    891: 
                    892: sub do_cache_new {
                    893:     my ($name,$id,$value,$time,$debug) = @_;
                    894:     $id=&escape($name.':'.$id);
                    895:     my $setvalue=$value;
                    896:     if (!defined($setvalue)) {
                    897: 	$setvalue='__undef__';
                    898:     }
1.623     albertel  899:     if (!defined($time) ) {
                    900: 	$time=600;
                    901:     }
1.599     albertel  902:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  903:     $memcache->set($id,$setvalue,$time);
                    904:     # need to make a copy of $value
                    905:     #&make_room($id,$value,$debug);
1.599     albertel  906:     return $value;
                    907: }
                    908: 
                    909: sub make_room {
                    910:     my ($id,$value,$debug)=@_;
                    911:     $remembered{$id}=$value;
                    912:     if ($to_remember<0) { return; }
                    913:     $accessed{$id}=[&gettimeofday()];
                    914:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    915:     my $to_kick;
                    916:     my $max_time=0;
                    917:     foreach my $other (keys(%accessed)) {
                    918: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    919: 	    $to_kick=$other;
                    920: 	    $max_time=&tv_interval($accessed{$other});
                    921: 	}
                    922:     }
                    923:     delete($remembered{$to_kick});
                    924:     delete($accessed{$to_kick});
                    925:     $kicks++;
                    926:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  927:     return;
                    928: }
                    929: 
1.599     albertel  930: sub purge_remembered {
1.604     albertel  931:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    932:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  933:     undef(%remembered);
                    934:     undef(%accessed);
1.428     albertel  935: }
1.70      www       936: # ------------------------------------- Read an entry from a user's environment
                    937: 
                    938: sub userenvironment {
                    939:     my ($udom,$unam,@what)=@_;
                    940:     my %returnhash=();
                    941:     my @answer=split(/\&/,
                    942:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    943:                       &homeserver($unam,$udom)));
                    944:     my $i;
                    945:     for ($i=0;$i<=$#what;$i++) {
                    946: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    947:     }
                    948:     return %returnhash;
1.1       albertel  949: }
                    950: 
1.617     albertel  951: # ---------------------------------------------------------- Get a studentphoto
                    952: sub studentphoto {
                    953:     my ($udom,$unam,$ext) = @_;
                    954:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.683.2.15  albertel  955:     if (defined($env{'request.course.id'})) {
1.683.2.16  albertel  956:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.683.2.15  albertel  957:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    958:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                    959:             } else {
                    960:                 my ($result,$perm_reqd)=
                    961: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
                    962:                 if ($result eq 'ok') {
                    963:                     if (!($perm_reqd eq 'yes')) {
                    964:                         return(&retrievestudentphoto($udom,$unam,$ext));
                    965:                     }
                    966:                 }
                    967:             }
                    968:         }
                    969:     } else {
                    970:         my ($result,$perm_reqd) = 
                    971: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
                    972:         if ($result eq 'ok') {
                    973:             if (!($perm_reqd eq 'yes')) {
                    974:                 return(&retrievestudentphoto($udom,$unam,$ext));
                    975:             }
                    976:         }
                    977:     }
                    978:     return '/adm/lonKaputt/lonlogo_broken.gif';
                    979: }
                    980: 
                    981: sub retrievestudentphoto {
                    982:     my ($udom,$unam,$ext,$type) = @_;
                    983:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                    984:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                    985:     if ($ret eq 'ok') {
                    986:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                    987:         if ($type eq 'thumbnail') {
                    988:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                    989:         }
                    990:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                    991:         return $tokenurl;
                    992:     } else {
                    993:         if ($type eq 'thumbnail') {
                    994:             return '/adm/lonKaputt/genericstudent_tn.gif';
                    995:         } else { 
                    996:             return '/adm/lonKaputt/lonlogo_broken.gif';
                    997:         }
1.617     albertel  998:     }
                    999: }
                   1000: 
1.263     www      1001: # -------------------------------------------------------------------- New chat
                   1002: 
                   1003: sub chatsend {
                   1004:     my ($newentry,$anon)=@_;
1.620     albertel 1005:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1006:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1007:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1008:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1009: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.263     www      1010: 		   &escape($newentry)),$chome);
1.292     www      1011: }
                   1012: 
                   1013: # ------------------------------------------ Find current version of a resource
                   1014: 
                   1015: sub getversion {
                   1016:     my $fname=&clutter(shift);
                   1017:     unless ($fname=~/^\/res\//) { return -1; }
                   1018:     return &currentversion(&filelocation('',$fname));
                   1019: }
                   1020: 
                   1021: sub currentversion {
                   1022:     my $fname=shift;
1.599     albertel 1023:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1024:     if (defined($cached)) { return $result; }
1.292     www      1025:     my $author=$fname;
                   1026:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1027:     my ($udom,$uname)=split(/\//,$author);
                   1028:     my $home=homeserver($uname,$udom);
                   1029:     if ($home eq 'no_host') { 
                   1030:         return -1; 
                   1031:     }
                   1032:     my $answer=reply("currentversion:$fname",$home);
                   1033:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1034: 	return -1;
                   1035:     }
1.599     albertel 1036:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1037: }
                   1038: 
1.1       albertel 1039: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1040: 
1.1       albertel 1041: sub subscribe {
                   1042:     my $fname=shift;
1.312     www      1043:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1044:     $fname=~s/[\n\r]//g;
1.1       albertel 1045:     my $author=$fname;
                   1046:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1047:     my ($udom,$uname)=split(/\//,$author);
                   1048:     my $home=homeserver($uname,$udom);
1.335     albertel 1049:     if ($home eq 'no_host') {
                   1050:         return 'not_found';
1.1       albertel 1051:     }
                   1052:     my $answer=reply("sub:$fname",$home);
1.64      www      1053:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1054: 	$answer.=' by '.$home;
                   1055:     }
1.1       albertel 1056:     return $answer;
                   1057: }
                   1058:     
1.8       www      1059: # -------------------------------------------------------------- Replicate file
                   1060: 
                   1061: sub repcopy {
                   1062:     my $filename=shift;
1.23      www      1063:     $filename=~s/\/+/\//g;
1.607     raeburn  1064:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1065:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1066:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1067: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1068: 	return &repcopy_userfile($filename);
                   1069:     }
1.532     albertel 1070:     $filename=~s/[\n\r]//g;
1.8       www      1071:     my $transname="$filename.in.transfer";
1.607     raeburn  1072:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1073:     my $remoteurl=subscribe($filename);
1.64      www      1074:     if ($remoteurl =~ /^con_lost by/) {
                   1075: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1076:            return 'unavailable';
1.8       www      1077:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1078: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1079: 	   return 'not_found';
1.64      www      1080:     } elsif ($remoteurl =~ /^rejected by/) {
                   1081: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1082:            return 'forbidden';
1.20      www      1083:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1084:            return 'ok';
1.8       www      1085:     } else {
1.290     www      1086:         my $author=$filename;
                   1087:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1088:         my ($udom,$uname)=split(/\//,$author);
                   1089:         my $home=homeserver($uname,$udom);
                   1090:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1091:            my @parts=split(/\//,$filename);
                   1092:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1093:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1094:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1095: 	       return 'bad_request';
1.8       www      1096:            }
                   1097:            my $count;
                   1098:            for ($count=5;$count<$#parts;$count++) {
                   1099:                $path.="/$parts[$count]";
                   1100:                if ((-e $path)!=1) {
                   1101: 		   mkdir($path,0777);
                   1102:                }
                   1103:            }
                   1104:            my $ua=new LWP::UserAgent;
                   1105:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1106:            my $response=$ua->request($request,$transname);
                   1107:            if ($response->is_error()) {
                   1108: 	       unlink($transname);
                   1109:                my $message=$response->status_line;
1.672     albertel 1110:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1111:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1112:                return 'unavailable';
1.8       www      1113:            } else {
1.16      www      1114: 	       if ($remoteurl!~/\.meta$/) {
                   1115:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1116:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1117:                   if ($mresponse->is_error()) {
                   1118: 		      unlink($filename.'.meta');
                   1119:                       &logthis(
1.672     albertel 1120:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1121:                   }
                   1122: 	       }
1.8       www      1123:                rename($transname,$filename);
1.607     raeburn  1124:                return 'ok';
1.8       www      1125:            }
1.290     www      1126:        }
1.8       www      1127:     }
1.330     www      1128: }
                   1129: 
                   1130: # ------------------------------------------------ Get server side include body
                   1131: sub ssi_body {
1.381     albertel 1132:     my ($filelink,%form)=@_;
1.606     matthew  1133:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1134:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1135:     }
1.330     www      1136:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1137:                                      &ssi($filelink,%form));
1.565     albertel 1138:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1139:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1140:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1141:     return $output;
1.8       www      1142: }
                   1143: 
1.15      www      1144: # --------------------------------------------------------- Server Side Include
                   1145: 
                   1146: sub ssi {
                   1147: 
1.23      www      1148:     my ($fn,%form)=@_;
1.15      www      1149: 
                   1150:     my $ua=new LWP::UserAgent;
1.23      www      1151:     
                   1152:     my $request;
                   1153:     
                   1154:     if (%form) {
                   1155:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1156:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1157:     } else {
                   1158:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1159:     }
                   1160: 
1.15      www      1161:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1162:     my $response=$ua->request($request);
                   1163: 
1.324     www      1164:     return $response->content;
                   1165: }
                   1166: 
                   1167: sub externalssi {
                   1168:     my ($url)=@_;
                   1169:     my $ua=new LWP::UserAgent;
                   1170:     my $request=new HTTP::Request('GET',$url);
                   1171:     my $response=$ua->request($request);
1.15      www      1172:     return $response->content;
                   1173: }
1.254     www      1174: 
1.492     albertel 1175: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1176: 
                   1177: sub allowuploaded {
                   1178:     my ($srcurl,$url)=@_;
                   1179:     $url=&clutter(&declutter($url));
                   1180:     my $dir=$url;
                   1181:     $dir=~s/\/[^\/]+$//;
                   1182:     my %httpref=();
                   1183:     my $httpurl=&hreflocation('',$url);
                   1184:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1185:     &Apache::lonnet::appenv(%httpref);
1.254     www      1186: }
1.477     raeburn  1187: 
1.478     albertel 1188: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1189: # input: action, courseID, current domain, intended
1.637     raeburn  1190: #        path to file, source of file, instruction to parse file for objects,
                   1191: #        ref to hash for embedded objects,
                   1192: #        ref to hash for codebase of java objects.
                   1193: #
1.485     raeburn  1194: # output: url to file (if action was uploaddoc), 
                   1195: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1196: #
1.478     albertel 1197: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1198: # course.
1.477     raeburn  1199: #
1.478     albertel 1200: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1201: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1202: #          course's home server.
1.477     raeburn  1203: #
1.478     albertel 1204: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1205: #          be copied from $source (current location) to 
                   1206: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1207: #         and will then be copied to
                   1208: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1209: #         course's home server.
1.485     raeburn  1210: #
1.481     raeburn  1211: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1212: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1213: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1214: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1215: #         in course's home server.
1.637     raeburn  1216: #
1.477     raeburn  1217: 
                   1218: sub process_coursefile {
1.638     albertel 1219:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1220:     my $fetchresult;
1.638     albertel 1221:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1222:     if ($action eq 'propagate') {
1.638     albertel 1223:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1224: 			     $home);
1.481     raeburn  1225:     } else {
1.477     raeburn  1226:         my $fpath = '';
                   1227:         my $fname = $file;
1.478     albertel 1228:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1229:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1230:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1231:         if ($action eq 'copy') {
                   1232:             if ($source eq '') {
                   1233:                 $fetchresult = 'no source file';
                   1234:                 return $fetchresult;
                   1235:             } else {
                   1236:                 my $destination = $filepath.'/'.$fname;
                   1237:                 rename($source,$destination);
                   1238:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1239:                                  $home);
1.481     raeburn  1240:             }
                   1241:         } elsif ($action eq 'uploaddoc') {
                   1242:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1243:             print $fh $env{'form.'.$source};
1.481     raeburn  1244:             close($fh);
1.637     raeburn  1245:             if ($parser eq 'parse') {
                   1246:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1247:                 unless ($parse_result eq 'ok') {
                   1248:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1249:                 }
                   1250:             }
1.477     raeburn  1251:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1252:                                  $home);
1.481     raeburn  1253:             if ($fetchresult eq 'ok') {
                   1254:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1255:             } else {
                   1256:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1257:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1258:                 return '/adm/notfound.html';
                   1259:             }
1.477     raeburn  1260:         }
                   1261:     }
1.485     raeburn  1262:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1263:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1264:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1265:     }
                   1266:     return $fetchresult;
                   1267: }
                   1268: 
1.637     raeburn  1269: sub build_filepath {
                   1270:     my ($fpath) = @_;
                   1271:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1272:     unless ($fpath eq '') {
                   1273:         my @parts=split('/',$fpath);
                   1274:         foreach my $part (@parts) {
                   1275:             $filepath.= '/'.$part;
                   1276:             if ((-e $filepath)!=1) {
                   1277:                 mkdir($filepath,0777);
                   1278:             }
                   1279:         }
                   1280:     }
                   1281:     return $filepath;
                   1282: }
                   1283: 
                   1284: sub store_edited_file {
1.638     albertel 1285:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1286:     my $file = $primary_url;
                   1287:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1288:     my $fpath = '';
                   1289:     my $fname = $file;
                   1290:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1291:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1292:     my $filepath = &build_filepath($fpath);
                   1293:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1294:     print $fh $content;
                   1295:     close($fh);
1.638     albertel 1296:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1297:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1298: 			  $home);
1.637     raeburn  1299:     if ($$fetchresult eq 'ok') {
                   1300:         return '/uploaded/'.$fpath.'/'.$fname;
                   1301:     } else {
1.638     albertel 1302:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1303: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1304:         return '/adm/notfound.html';
                   1305:     }
                   1306: }
                   1307: 
1.531     albertel 1308: sub clean_filename {
                   1309:     my ($fname)=@_;
1.315     www      1310: # Replace Windows backslashes by forward slashes
1.257     www      1311:     $fname=~s/\\/\//g;
1.315     www      1312: # Get rid of everything but the actual filename
1.257     www      1313:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1314: # Replace spaces by underscores
                   1315:     $fname=~s/\s+/\_/g;
                   1316: # Replace all other weird characters by nothing
1.317     www      1317:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1318: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1319: # numbers
                   1320:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1321:     return $fname;
                   1322: }
                   1323: 
1.608     albertel 1324: # --------------- Take an uploaded file and put it into the userfiles directory
                   1325: # input: name of form element, coursedoc=1 means this is for the course
                   1326: # output: url of file in userspace
                   1327: 
                   1328: 
1.531     albertel 1329: sub userfileupload {
1.637     raeburn  1330:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase)=@_;
1.531     albertel 1331:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1332:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1333:     $fname=&clean_filename($fname);
1.315     www      1334: # See if there is anything left
1.257     www      1335:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1336:     chop($env{'form.'.$formname});
1.523     raeburn  1337:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1338:         my $now = time;
                   1339:         my $filepath = 'tmp/helprequests/'.$now;
                   1340:         my @parts=split(/\//,$filepath);
                   1341:         my $fullpath = $perlvar{'lonDaemons'};
                   1342:         for (my $i=0;$i<@parts;$i++) {
                   1343:             $fullpath .= '/'.$parts[$i];
                   1344:             if ((-e $fullpath)!=1) {
                   1345:                 mkdir($fullpath,0777);
                   1346:             }
                   1347:         }
                   1348:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1349:         print $fh $env{'form.'.$formname};
1.523     raeburn  1350:         close($fh);
                   1351:         return $fullpath.'/'.$fname; 
                   1352:     }
1.258     www      1353: # Create the directory if not present
1.493     albertel 1354:     $fname="$subdir/$fname";
1.259     www      1355:     if ($coursedoc) {
1.638     albertel 1356: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1357: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1358:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1359:             return &finishuserfileupload($docuname,$docudom,
                   1360: 					 $formname,$fname,$parser,$allfiles,
                   1361: 					 $codebase);
1.481     raeburn  1362:         } else {
1.620     albertel 1363:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1364:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1365: 				       $fname,$formname,$parser,
                   1366: 				       $allfiles,$codebase);
1.481     raeburn  1367:         }
1.259     www      1368:     } else {
1.638     albertel 1369:         my $docuname=$env{'user.name'};
                   1370:         my $docudom=$env{'user.domain'};
                   1371: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1372: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1373:     }
1.271     www      1374: }
                   1375: 
                   1376: sub finishuserfileupload {
1.638     albertel 1377:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1378:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1379:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1380:     my ($fnamepath,$file);
                   1381:     $file=$fname;
                   1382:     if ($fname=~m|/|) {
                   1383:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1384: 	$path.=$fnamepath.'/';
                   1385:     }
1.259     www      1386:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1387:     my $count;
                   1388:     for ($count=4;$count<=$#parts;$count++) {
                   1389:         $filepath.="/$parts[$count]";
                   1390:         if ((-e $filepath)!=1) {
                   1391: 	    mkdir($filepath,0777);
                   1392:         }
                   1393:     }
                   1394: # Save the file
                   1395:     {
1.570     albertel 1396: 	open(FH,'>'.$filepath.'/'.$file);
1.620     albertel 1397: 	print FH $env{'form.'.$formname};
1.570     albertel 1398: 	close(FH);
1.258     www      1399:     }
1.637     raeburn  1400:     if ($parser eq 'parse') {
1.638     albertel 1401:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1402: 						   $codebase);
1.637     raeburn  1403:         unless ($parse_result eq 'ok') {
1.638     albertel 1404:             &logthis('Failed to parse '.$filepath.$file.
                   1405: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1406:         }
                   1407:     }
1.259     www      1408: # Notify homeserver to grep it
                   1409: #
1.638     albertel 1410:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1411:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1412:     if ($fetchresult eq 'ok') {
1.259     www      1413: #
1.258     www      1414: # Return the URL to it
1.494     albertel 1415:         return '/uploaded/'.$path.$file;
1.263     www      1416:     } else {
1.494     albertel 1417:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1418: 		 ': '.$fetchresult);
1.263     www      1419:         return '/adm/notfound.html';
                   1420:     }    
1.493     albertel 1421: }
                   1422: 
1.637     raeburn  1423: sub extract_embedded_items {
1.648     raeburn  1424:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1425:     my @state = ();
                   1426:     my %javafiles = (
                   1427:                       codebase => '',
                   1428:                       code => '',
                   1429:                       archive => ''
                   1430:                     );
                   1431:     my %mediafiles = (
                   1432:                       src => '',
                   1433:                       movie => '',
                   1434:                      );
1.648     raeburn  1435:     my $p;
                   1436:     if ($content) {
                   1437:         $p = HTML::LCParser->new($content);
                   1438:     } else {
                   1439:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1440:     }
1.641     albertel 1441:     while (my $t=$p->get_token()) {
1.640     albertel 1442: 	if ($t->[0] eq 'S') {
                   1443: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1444: 	    push (@state, $tagname);
1.648     raeburn  1445:             if (lc($tagname) eq 'allow') {
                   1446:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1447:             }
1.640     albertel 1448: 	    if (lc($tagname) eq 'img') {
                   1449: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1450: 	    }
1.645     raeburn  1451:             if (lc($tagname) eq 'script') {
                   1452:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1453:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1454:                 } else {
                   1455:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1456:                 }
                   1457:             }
                   1458:             if (lc($tagname) eq 'link') {
                   1459:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1460:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1461:                 }
                   1462:             }
1.640     albertel 1463: 	    if (lc($tagname) eq 'object' ||
                   1464: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1465: 		foreach my $item (keys(%javafiles)) {
                   1466: 		    $javafiles{$item} = '';
                   1467: 		}
                   1468: 	    }
                   1469: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1470: 		my $name = lc($attr->{'name'});
                   1471: 		foreach my $item (keys(%javafiles)) {
                   1472: 		    if ($name eq $item) {
                   1473: 			$javafiles{$item} = $attr->{'value'};
                   1474: 			last;
                   1475: 		    }
                   1476: 		}
                   1477: 		foreach my $item (keys(%mediafiles)) {
                   1478: 		    if ($name eq $item) {
                   1479: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1480: 			last;
                   1481: 		    }
                   1482: 		}
                   1483: 	    }
                   1484: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1485: 		foreach my $item (keys(%javafiles)) {
                   1486: 		    if ($attr->{$item}) {
                   1487: 			$javafiles{$item} = $attr->{$item};
                   1488: 			last;
                   1489: 		    }
                   1490: 		}
                   1491: 		foreach my $item (keys(%mediafiles)) {
                   1492: 		    if ($attr->{$item}) {
                   1493: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1494: 			last;
                   1495: 		    }
                   1496: 		}
                   1497: 	    }
                   1498: 	} elsif ($t->[0] eq 'E') {
                   1499: 	    my ($tagname) = ($t->[1]);
                   1500: 	    if ($javafiles{'codebase'} ne '') {
                   1501: 		$javafiles{'codebase'} .= '/';
                   1502: 	    }  
                   1503: 	    if (lc($tagname) eq 'applet' ||
                   1504: 		lc($tagname) eq 'object' ||
                   1505: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1506: 		) {
                   1507: 		foreach my $item (keys(%javafiles)) {
                   1508: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1509: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1510: 			&add_filetype($allfiles,$file,$item);
                   1511: 		    }
                   1512: 		}
                   1513: 	    } 
                   1514: 	    pop @state;
                   1515: 	}
                   1516:     }
1.637     raeburn  1517:     return 'ok';
                   1518: }
                   1519: 
1.639     albertel 1520: sub add_filetype {
                   1521:     my ($allfiles,$file,$type)=@_;
                   1522:     if (exists($allfiles->{$file})) {
                   1523: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1524: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1525: 	}
                   1526:     } else {
                   1527: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1528:     }
                   1529: }
                   1530: 
1.493     albertel 1531: sub removeuploadedurl {
                   1532:     my ($url)=@_;
                   1533:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1534:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1535: }
                   1536: 
                   1537: sub removeuserfile {
                   1538:     my ($docuname,$docudom,$fname)=@_;
                   1539:     my $home=&homeserver($docuname,$docudom);
                   1540:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1541: }
1.15      www      1542: 
1.530     albertel 1543: sub mkdiruserfile {
                   1544:     my ($docuname,$docudom,$dir)=@_;
                   1545:     my $home=&homeserver($docuname,$docudom);
                   1546:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1547: }
                   1548: 
1.531     albertel 1549: sub renameuserfile {
                   1550:     my ($docuname,$docudom,$old,$new)=@_;
                   1551:     my $home=&homeserver($docuname,$docudom);
                   1552:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1553: 		  &escape("$new"),$home);
                   1554: }
                   1555: 
1.14      www      1556: # ------------------------------------------------------------------------- Log
                   1557: 
                   1558: sub log {
                   1559:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1560:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1561: }
                   1562: 
                   1563: # ------------------------------------------------------------------ Course Log
1.352     www      1564: #
                   1565: # This routine flushes several buffers of non-mission-critical nature
                   1566: #
1.157     www      1567: 
                   1568: sub flushcourselogs {
1.352     www      1569:     &logthis('Flushing log buffers');
                   1570: #
                   1571: # course logs
                   1572: # This is a log of all transactions in a course, which can be used
                   1573: # for data mining purposes
                   1574: #
                   1575: # It also collects the courseid database, which lists last transaction
                   1576: # times and course titles for all courseids
                   1577: #
                   1578:     my %courseidbuffer=();
1.191     harris41 1579:     foreach (keys %courselogs) {
1.157     www      1580:         my $crsid=$_;
1.352     www      1581:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1582: 		          &escape($courselogs{$crsid}),
                   1583: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1584: 	    delete $courselogs{$crsid};
                   1585:         } else {
                   1586:             &logthis('Failed to flush log buffer for '.$crsid);
                   1587:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1588:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1589:                         " exceeded maximum size, deleting.</font>");
                   1590:                delete $courselogs{$crsid};
                   1591:             }
1.352     www      1592:         }
                   1593:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1594:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1595: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1596:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1.352     www      1597:         } else {
                   1598:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1599: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1600:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
                   1601:         }
1.191     harris41 1602:     }
1.352     www      1603: #
                   1604: # Write course id database (reverse lookup) to homeserver of courses 
                   1605: # Is used in pickcourse
                   1606: #
                   1607:     foreach (keys %courseidbuffer) {
1.353     www      1608:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1609:     }
                   1610: #
                   1611: # File accesses
                   1612: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1613: #
1.449     matthew  1614:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1615:         if ($entry =~ /___count$/) {
                   1616:             my ($dom,$name);
                   1617:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1618:             if (! defined($dom) || $dom eq '' || 
                   1619:                 ! defined($name) || $name eq '') {
1.620     albertel 1620:                 my $cid = $env{'request.course.id'};
                   1621:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1622:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1623:             }
1.450     matthew  1624:             my $value = $accesshash{$entry};
                   1625:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1626:             my %temphash=($url => $value);
1.449     matthew  1627:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1628:             if ($result eq 'ok') {
                   1629:                 delete $accesshash{$entry};
                   1630:             } elsif ($result eq 'unknown_cmd') {
                   1631:                 # Target server has old code running on it.
1.450     matthew  1632:                 my %temphash=($entry => $value);
1.449     matthew  1633:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1634:                     delete $accesshash{$entry};
                   1635:                 }
                   1636:             }
                   1637:         } else {
1.458     matthew  1638:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1639:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1640:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1641:                 delete $accesshash{$entry};
                   1642:             }
1.185     www      1643:         }
1.191     harris41 1644:     }
1.352     www      1645: #
                   1646: # Roles
                   1647: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1648: #
1.349     www      1649:     foreach (keys %userrolehash) {
                   1650:         my $entry=$_;
1.351     www      1651:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1652: 	    split(/\:/,$entry);
                   1653:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1654:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1655:                 $rudom,$runame) eq 'ok') {
                   1656: 	    delete $userrolehash{$entry};
                   1657:         }
                   1658:     }
1.662     raeburn  1659: #
                   1660: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1661: #
                   1662:     my %domrolebuffer = ();
                   1663:     foreach my $entry (keys %domainrolehash) {
                   1664:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1665:         if ($domrolebuffer{$rudom}) {
                   1666:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1667:                       '='.&escape($domainrolehash{$entry});
                   1668:         } else {
                   1669:             $domrolebuffer{$rudom}.=&escape($entry).
                   1670:                       '='.&escape($domainrolehash{$entry});
                   1671:         }
                   1672:         delete $domainrolehash{$entry};
                   1673:     }
                   1674:     foreach my $dom (keys(%domrolebuffer)) {
                   1675:         foreach my $tryserver (keys %libserv) {
                   1676:             if ($hostdom{$tryserver} eq $dom) {
                   1677:                 unless (&reply('domroleput:'.$dom.':'.
                   1678:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1679:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1680:                 }
                   1681:             }
                   1682:         }
                   1683:     }
1.186     www      1684:     $dumpcount++;
1.157     www      1685: }
                   1686: 
                   1687: sub courselog {
                   1688:     my $what=shift;
1.158     www      1689:     $what=time.':'.$what;
1.620     albertel 1690:     unless ($env{'request.course.id'}) { return ''; }
                   1691:     $coursedombuf{$env{'request.course.id'}}=
                   1692:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1693:     $coursenumbuf{$env{'request.course.id'}}=
                   1694:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1695:     $coursehombuf{$env{'request.course.id'}}=
                   1696:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1697:     $coursedescrbuf{$env{'request.course.id'}}=
                   1698:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1699:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1700:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1701:     $courseownerbuf{$env{'request.course.id'}}=
                   1702:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
                   1703:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1704: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1705:     } else {
1.620     albertel 1706: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1707:     }
1.620     albertel 1708:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1709: 	&flushcourselogs();
                   1710:     }
1.158     www      1711: }
                   1712: 
                   1713: sub courseacclog {
                   1714:     my $fnsymb=shift;
1.620     albertel 1715:     unless ($env{'request.course.id'}) { return ''; }
                   1716:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1717:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1718:         $what.=':POST';
1.583     matthew  1719:         # FIXME: Probably ought to escape things....
1.620     albertel 1720: 	foreach (keys %env) {
1.158     www      1721:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1722: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1723:             }
1.191     harris41 1724:         }
1.583     matthew  1725:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1726:         # FIXME: We should not be depending on a form parameter that someone
                   1727:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1728:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1729:             $what.= ':POST';
                   1730:             # FIXME: Probably ought to escape things....
                   1731:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1732:                                  'crsdiscuss') {
1.620     albertel 1733:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1734:             }
                   1735:         }
1.158     www      1736:     }
                   1737:     &courselog($what);
1.149     www      1738: }
                   1739: 
1.185     www      1740: sub countacc {
                   1741:     my $url=&declutter(shift);
1.458     matthew  1742:     return if (! defined($url) || $url eq '');
1.620     albertel 1743:     unless ($env{'request.course.id'}) { return ''; }
                   1744:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1745:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1746:     $accesshash{$key}++;
1.185     www      1747: }
1.349     www      1748: 
1.361     www      1749: sub linklog {
                   1750:     my ($from,$to)=@_;
                   1751:     $from=&declutter($from);
                   1752:     $to=&declutter($to);
                   1753:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1754:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1755: }
                   1756:   
1.349     www      1757: sub userrolelog {
                   1758:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1759:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1760:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1761:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1762:         ($trole=~/^ta/)) {
1.350     www      1763:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1764:        $userrolehash
                   1765:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1766:                     =$tend.':'.$tstart;
1.662     raeburn  1767:     }
                   1768:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1769:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1770:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1771:         ($trole=~/^sc/)) {
                   1772:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1773:        $domainrolehash
                   1774:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1775:                     = $tend.':'.$tstart;
                   1776:     }
1.351     www      1777: }
                   1778: 
                   1779: sub get_course_adv_roles {
                   1780:     my $cid=shift;
1.620     albertel 1781:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1782:     my %coursehash=&coursedescription($cid);
1.470     www      1783:     my %nothide=();
                   1784:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1785: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1786:     }
1.351     www      1787:     my %returnhash=();
                   1788:     my %dumphash=
                   1789:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1790:     my $now=time;
                   1791:     foreach (keys %dumphash) {
                   1792: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1793:         if (($tstart) && ($tstart<0)) { next; }
                   1794:         if (($tend) && ($tend<$now)) { next; }
                   1795:         if (($tstart) && ($now<$tstart)) { next; }
                   1796:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1797: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1798: 	if ((&privileged($username,$domain)) && 
                   1799: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1800: 	if ($role eq 'cr') { next; }
1.351     www      1801:         my $key=&plaintext($role);
1.656     albertel 1802: 	if ($role =~ /^cr/) {
                   1803: 	    $key=(split('/',$role))[3];
                   1804: 	}
1.351     www      1805:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1806:         if ($returnhash{$key}) {
                   1807: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1808:         } else {
                   1809:             $returnhash{$key}=$username.':'.$domain;
                   1810:         }
1.400     www      1811:      }
                   1812:     return %returnhash;
                   1813: }
                   1814: 
                   1815: sub get_my_roles {
                   1816:     my ($uname,$udom)=@_;
1.620     albertel 1817:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1818:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1819:     my %dumphash=
                   1820:             &dump('nohist_userroles',$udom,$uname);
                   1821:     my %returnhash=();
                   1822:     my $now=time;
                   1823:     foreach (keys %dumphash) {
                   1824: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1825:         if (($tstart) && ($tstart<0)) { next; }
                   1826:         if (($tend) && ($tend<$now)) { next; }
                   1827:         if (($tstart) && ($now<$tstart)) { next; }
                   1828:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1829: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1830:      }
                   1831:     return %returnhash;
1.399     www      1832: }
                   1833: 
                   1834: # ----------------------------------------------------- Frontpage Announcements
                   1835: #
                   1836: #
                   1837: 
                   1838: sub postannounce {
                   1839:     my ($server,$text)=@_;
                   1840:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1841:     unless ($text=~/\w/) { $text=''; }
                   1842:     return &reply('setannounce:'.&escape($text),$server);
                   1843: }
                   1844: 
                   1845: sub getannounce {
1.448     albertel 1846: 
                   1847:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1848: 	my $announcement='';
                   1849: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1850: 	close($fh);
1.399     www      1851: 	if ($announcement=~/\w/) { 
                   1852: 	    return 
                   1853:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1854:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1855: 	} else {
                   1856: 	    return '';
                   1857: 	}
                   1858:     } else {
                   1859: 	return '';
                   1860:     }
1.351     www      1861: }
1.353     www      1862: 
                   1863: # ---------------------------------------------------------- Course ID routines
                   1864: # Deal with domain's nohist_courseid.db files
                   1865: #
                   1866: 
                   1867: sub courseidput {
                   1868:     my ($domain,$what,$coursehome)=@_;
                   1869:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1870: }
                   1871: 
                   1872: sub courseiddump {
1.622     raeburn  1873:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
1.353     www      1874:     my %returnhash=();
1.355     www      1875:     unless ($domfilter) { $domfilter=''; }
1.353     www      1876:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1877:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1878: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1879: 	        foreach (
                   1880:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1881: 			       $sincefilter.':'.&escape($descfilter).':'.
1.622     raeburn  1882:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
1.354     www      1883:                                $tryserver))) {
1.506     raeburn  1884: 		    my ($key,$value)=split(/\=/,$_);
                   1885:                     if (($key) && ($value)) {
1.516     raeburn  1886: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1887:                     }
1.353     www      1888:                 }
                   1889:             }
                   1890:         }
                   1891:     }
                   1892:     return %returnhash;
                   1893: }
                   1894: 
1.658     raeburn  1895: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1896: 
                   1897: sub dcmailput {
1.683.2.2  albertel 1898:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1899:     my $status = &Apache::lonnet::critical(
                   1900:        'dcmailput:'.$domain.':'.&Apache::lonnet::escape($msgid).'='.
1.683.2.2  albertel 1901:        &Apache::lonnet::escape($message),$server);
1.662     raeburn  1902:     return $status;
                   1903: }
                   1904: 
1.658     raeburn  1905: sub dcmaildump {
                   1906:     my ($dom,$startdate,$enddate,$senders) = @_;
1.683.2.2  albertel 1907:     my %returnhash=();
                   1908:     if (exists($domain_primary{$dom})) {
                   1909:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1910:                                                          &escape($enddate).':';
                   1911: 	my @esc_senders=map { &escape($_)} @$senders;
                   1912: 	$cmd.=&escape(join('&',@esc_senders));
                   1913: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   1914:             my ($key,$value) = split(/\=/,$_);
                   1915:             if (($key) && ($value)) {
                   1916:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  1917:             }
                   1918:         }
                   1919:     }
                   1920:     return %returnhash;
                   1921: }
1.662     raeburn  1922: # ---------------------------------------------------------- Domain roles
                   1923: 
                   1924: sub get_domain_roles {
                   1925:     my ($dom,$roles,$startdate,$enddate)=@_;
                   1926:     if (undef($startdate) || $startdate eq '') {
                   1927:         $startdate = '.';
                   1928:     }
                   1929:     if (undef($enddate) || $enddate eq '') {
                   1930:         $enddate = '.';
                   1931:     }
                   1932:     my $rolelist = join(':',@{$roles});
                   1933:     my %personnel = ();
                   1934:     foreach my $tryserver (keys(%libserv)) {
                   1935:         if ($hostdom{$tryserver} eq $dom) {
                   1936:             %{$personnel{$tryserver}}=();
                   1937:             foreach (
                   1938:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   1939:                    &escape($startdate).':'.&escape($enddate).':'.
                   1940:                    &escape($rolelist), $tryserver))) {
                   1941:                 my($key,$value) = split(/\=/,$_);
                   1942:                 if (($key) && ($value)) {
                   1943:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   1944:                 }
                   1945:             }
                   1946:         }
                   1947:     }
                   1948:     return %personnel;
                   1949: }
1.658     raeburn  1950: 
1.149     www      1951: # ----------------------------------------------------------- Check out an item
                   1952: 
1.504     albertel 1953: sub get_first_access {
                   1954:     my ($type,$argsymb)=@_;
                   1955:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   1956:     if ($argsymb) { $symb=$argsymb; }
                   1957:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 1958:     if ($type eq 'map') {
                   1959: 	$res=&symbread($map);
                   1960:     } else {
                   1961: 	$res=$symb;
                   1962:     }
                   1963:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   1964:     return $times{"$courseid\0$res"};
1.504     albertel 1965: }
                   1966: 
                   1967: sub set_first_access {
                   1968:     my ($type)=@_;
                   1969:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   1970:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 1971:     if ($type eq 'map') {
                   1972: 	$res=&symbread($map);
                   1973:     } else {
                   1974: 	$res=$symb;
                   1975:     }
                   1976:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 1977:     if (!$firstaccess) {
1.588     albertel 1978: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 1979:     }
                   1980:     return 'already_set';
1.504     albertel 1981: }
                   1982: 
1.149     www      1983: sub checkout {
                   1984:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   1985:     my $now=time;
                   1986:     my $lonhost=$perlvar{'lonHostID'};
                   1987:     my $infostr=&escape(
1.234     www      1988:                  'CHECKOUTTOKEN&'.
1.149     www      1989:                  $tuname.'&'.
                   1990:                  $tudom.'&'.
                   1991:                  $tcrsid.'&'.
                   1992:                  $symb.'&'.
                   1993: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   1994:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      1995:     if ($token=~/^error\:/) { 
1.672     albertel 1996:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      1997:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1998:                  "</font>");
                   1999:         return ''; 
                   2000:     }
                   2001: 
1.149     www      2002:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2003:     $token=~tr/a-z/A-Z/;
                   2004: 
1.153     www      2005:     my %infohash=('resource.0.outtoken' => $token,
                   2006:                   'resource.0.checkouttime' => $now,
                   2007:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2008: 
                   2009:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2010:        return '';
1.151     www      2011:     } else {
1.672     albertel 2012:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2013:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2014:                  "</font>");
1.149     www      2015:     }    
                   2016: 
                   2017:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2018:                          &escape('Checkout '.$infostr.' - '.
                   2019:                                                  $token)) ne 'ok') {
                   2020: 	return '';
1.151     www      2021:     } else {
1.672     albertel 2022:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2023:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2024:                  "</font>");
1.149     www      2025:     }
1.151     www      2026:     return $token;
1.149     www      2027: }
                   2028: 
                   2029: # ------------------------------------------------------------ Check in an item
                   2030: 
                   2031: sub checkin {
                   2032:     my $token=shift;
1.150     www      2033:     my $now=time;
                   2034:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2035:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2036:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2037:     $dtoken=~s/\W/\_/g;
1.234     www      2038:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2039:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2040: 
1.154     www      2041:     unless (($tuname) && ($tudom)) {
                   2042:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2043:         return '';
                   2044:     }
                   2045:     
                   2046:     unless (&allowed('mgr',$tcrsid)) {
                   2047:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2048:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2049:         return '';
                   2050:     }
                   2051: 
1.153     www      2052:     my %infohash=('resource.0.intoken' => $token,
                   2053:                   'resource.0.checkintime' => $now,
                   2054:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2055: 
                   2056:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2057:        return '';
                   2058:     }    
                   2059: 
                   2060:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2061:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2062: 	return '';
                   2063:     }
                   2064: 
                   2065:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2066: }
                   2067: 
                   2068: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2069: 
                   2070: sub expirespread {
                   2071:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2072:     my $cid=$env{'request.course.id'}; 
1.110     www      2073:     if ($cid) {
                   2074:        my $now=time;
                   2075:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2076:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2077:                             $env{'course.'.$cid.'.num'}.
1.110     www      2078: 	        	    ':nohist_expirationdates:'.
                   2079:                             &escape($key).'='.$now,
1.620     albertel 2080:                             $env{'course.'.$cid.'.home'})
1.110     www      2081:     }
                   2082:     return 'ok';
1.14      www      2083: }
                   2084: 
1.109     www      2085: # ----------------------------------------------------- Devalidate Spreadsheets
                   2086: 
                   2087: sub devalidate {
1.325     www      2088:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2089:     my $cid=$env{'request.course.id'}; 
1.109     www      2090:     if ($cid) {
1.391     matthew  2091:         # delete the stored spreadsheets for
                   2092:         # - the student level sheet of this user in course's homespace
                   2093:         # - the assessment level sheet for this resource 
                   2094:         #   for this user in user's homespace
1.553     albertel 2095: 	# - current conditional state info
1.325     www      2096: 	my $key=$uname.':'.$udom.':';
1.109     www      2097:         my $status=
1.299     matthew  2098: 	    &del('nohist_calculatedsheets',
1.391     matthew  2099: 		 [$key.'studentcalc:'],
1.620     albertel 2100: 		 $env{'course.'.$cid.'.domain'},
                   2101: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2102: 		.' '.
                   2103: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2104: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2105:         unless ($status eq 'ok ok') {
                   2106:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2107:                     $uname.' at '.$udom.' for '.
1.109     www      2108: 		    $symb.': '.$status);
1.133     albertel 2109:         }
1.553     albertel 2110: 	&delenv('user.state.'.$cid);
1.109     www      2111:     }
                   2112: }
                   2113: 
1.265     albertel 2114: sub get_scalar {
                   2115:     my ($string,$end) = @_;
                   2116:     my $value;
                   2117:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2118: 	$value = $1;
                   2119:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2120: 	$value = $1;
                   2121:     }
                   2122:     return &unescape($value);
                   2123: }
                   2124: 
                   2125: sub array2str {
                   2126:   my (@array) = @_;
                   2127:   my $result=&arrayref2str(\@array);
                   2128:   $result=~s/^__ARRAY_REF__//;
                   2129:   $result=~s/__END_ARRAY_REF__$//;
                   2130:   return $result;
                   2131: }
                   2132: 
1.204     albertel 2133: sub arrayref2str {
                   2134:   my ($arrayref) = @_;
1.265     albertel 2135:   my $result='__ARRAY_REF__';
1.204     albertel 2136:   foreach my $elem (@$arrayref) {
1.265     albertel 2137:     if(ref($elem) eq 'ARRAY') {
                   2138:       $result.=&arrayref2str($elem).'&';
                   2139:     } elsif(ref($elem) eq 'HASH') {
                   2140:       $result.=&hashref2str($elem).'&';
                   2141:     } elsif(ref($elem)) {
                   2142:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2143:     } else {
                   2144:       $result.=&escape($elem).'&';
                   2145:     }
                   2146:   }
                   2147:   $result=~s/\&$//;
1.265     albertel 2148:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2149:   return $result;
                   2150: }
                   2151: 
1.168     albertel 2152: sub hash2str {
1.204     albertel 2153:   my (%hash) = @_;
                   2154:   my $result=&hashref2str(\%hash);
1.265     albertel 2155:   $result=~s/^__HASH_REF__//;
                   2156:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2157:   return $result;
                   2158: }
                   2159: 
                   2160: sub hashref2str {
                   2161:   my ($hashref)=@_;
1.265     albertel 2162:   my $result='__HASH_REF__';
1.495     albertel 2163:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2164:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2165:       $result.=&arrayref2str($_).'=';
1.204     albertel 2166:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2167:       $result.=&hashref2str($_).'=';
1.204     albertel 2168:     } elsif (ref($_)) {
1.265     albertel 2169:       $result.='=';
                   2170:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2171:     } else {
1.265     albertel 2172: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2173:     }
                   2174: 
1.265     albertel 2175:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2176:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2177:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2178:       $result.=&hashref2str($hashref->{$_}).'&';
                   2179:     } elsif(ref($hashref->{$_})) {
                   2180:        $result.='&';
                   2181:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2182:     } else {
1.265     albertel 2183:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2184:     }
                   2185:   }
1.168     albertel 2186:   $result=~s/\&$//;
1.265     albertel 2187:   $result .= '__END_HASH_REF__';
1.168     albertel 2188:   return $result;
                   2189: }
                   2190: 
                   2191: sub str2hash {
1.265     albertel 2192:     my ($string)=@_;
                   2193:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2194:     return %$hash;
                   2195: }
                   2196: 
                   2197: sub str2hashref {
1.168     albertel 2198:   my ($string) = @_;
1.265     albertel 2199: 
                   2200:   my %hash;
                   2201: 
                   2202:   if($string !~ /^__HASH_REF__/) {
                   2203:       if (! ($string eq '' || !defined($string))) {
                   2204: 	  $hash{'error'}='Not hash reference';
                   2205:       }
                   2206:       return (\%hash, $string);
                   2207:   }
                   2208: 
                   2209:   $string =~ s/^__HASH_REF__//;
                   2210: 
                   2211:   while($string !~ /^__END_HASH_REF__/) {
                   2212:       #key
                   2213:       my $key='';
                   2214:       if($string =~ /^__HASH_REF__/) {
                   2215:           ($key, $string)=&str2hashref($string);
                   2216:           if(defined($key->{'error'})) {
                   2217:               $hash{'error'}='Bad data';
                   2218:               return (\%hash, $string);
                   2219:           }
                   2220:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2221:           ($key, $string)=&str2arrayref($string);
                   2222:           if($key->[0] eq 'Array reference error') {
                   2223:               $hash{'error'}='Bad data';
                   2224:               return (\%hash, $string);
                   2225:           }
                   2226:       } else {
                   2227:           $string =~ s/^(.*?)=//;
1.267     albertel 2228: 	  $key=&unescape($1);
1.265     albertel 2229:       }
                   2230:       $string =~ s/^=//;
                   2231: 
                   2232:       #value
                   2233:       my $value='';
                   2234:       if($string =~ /^__HASH_REF__/) {
                   2235:           ($value, $string)=&str2hashref($string);
                   2236:           if(defined($value->{'error'})) {
                   2237:               $hash{'error'}='Bad data';
                   2238:               return (\%hash, $string);
                   2239:           }
                   2240:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2241:           ($value, $string)=&str2arrayref($string);
                   2242:           if($value->[0] eq 'Array reference error') {
                   2243:               $hash{'error'}='Bad data';
                   2244:               return (\%hash, $string);
                   2245:           }
                   2246:       } else {
                   2247: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2248:       }
                   2249:       $string =~ s/^&//;
                   2250: 
                   2251:       $hash{$key}=$value;
1.204     albertel 2252:   }
1.265     albertel 2253: 
                   2254:   $string =~ s/^__END_HASH_REF__//;
                   2255: 
                   2256:   return (\%hash, $string);
1.204     albertel 2257: }
                   2258: 
                   2259: sub str2array {
1.265     albertel 2260:     my ($string)=@_;
                   2261:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2262:     return @$array;
                   2263: }
                   2264: 
                   2265: sub str2arrayref {
1.204     albertel 2266:   my ($string) = @_;
1.265     albertel 2267:   my @array;
                   2268: 
                   2269:   if($string !~ /^__ARRAY_REF__/) {
                   2270:       if (! ($string eq '' || !defined($string))) {
                   2271: 	  $array[0]='Array reference error';
                   2272:       }
                   2273:       return (\@array, $string);
                   2274:   }
                   2275: 
                   2276:   $string =~ s/^__ARRAY_REF__//;
                   2277: 
                   2278:   while($string !~ /^__END_ARRAY_REF__/) {
                   2279:       my $value='';
                   2280:       if($string =~ /^__HASH_REF__/) {
                   2281:           ($value, $string)=&str2hashref($string);
                   2282:           if(defined($value->{'error'})) {
                   2283:               $array[0] ='Array reference error';
                   2284:               return (\@array, $string);
                   2285:           }
                   2286:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2287:           ($value, $string)=&str2arrayref($string);
                   2288:           if($value->[0] eq 'Array reference error') {
                   2289:               $array[0] ='Array reference error';
                   2290:               return (\@array, $string);
                   2291:           }
                   2292:       } else {
                   2293: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2294:       }
                   2295:       $string =~ s/^&//;
                   2296: 
                   2297:       push(@array, $value);
1.191     harris41 2298:   }
1.265     albertel 2299: 
                   2300:   $string =~ s/^__END_ARRAY_REF__//;
                   2301: 
                   2302:   return (\@array, $string);
1.168     albertel 2303: }
                   2304: 
1.167     albertel 2305: # -------------------------------------------------------------------Temp Store
                   2306: 
1.168     albertel 2307: sub tmpreset {
                   2308:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2309:   if (!$symb) {
                   2310:     $symb=&symbread();
1.620     albertel 2311:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2312:   }
                   2313:   $symb=escape($symb);
                   2314: 
1.620     albertel 2315:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2316:   $namespace=~s/\//\_/g;
                   2317:   $namespace=~s/\W//g;
                   2318: 
1.620     albertel 2319:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2320:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2321:   if ($domain eq 'public' && $stuname eq 'public') {
                   2322:       $stuname=$ENV{'REMOTE_ADDR'};
                   2323:   }
1.168     albertel 2324:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2325:   my %hash;
                   2326:   if (tie(%hash,'GDBM_File',
                   2327: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2328: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2329:     foreach my $key (keys %hash) {
1.180     albertel 2330:       if ($key=~ /:$symb/) {
1.168     albertel 2331: 	delete($hash{$key});
                   2332:       }
                   2333:     }
                   2334:   }
                   2335: }
                   2336: 
1.167     albertel 2337: sub tmpstore {
1.168     albertel 2338:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2339: 
                   2340:   if (!$symb) {
                   2341:     $symb=&symbread();
1.620     albertel 2342:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2343:   }
                   2344:   $symb=escape($symb);
                   2345: 
                   2346:   if (!$namespace) {
                   2347:     # I don't think we would ever want to store this for a course.
                   2348:     # it seems this will only be used if we don't have a course.
1.620     albertel 2349:     #$namespace=$env{'request.course.id'};
1.168     albertel 2350:     #if (!$namespace) {
1.620     albertel 2351:       $namespace=$env{'request.state'};
1.168     albertel 2352:     #}
                   2353:   }
                   2354:   $namespace=~s/\//\_/g;
                   2355:   $namespace=~s/\W//g;
1.620     albertel 2356:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2357:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2358:   if ($domain eq 'public' && $stuname eq 'public') {
                   2359:       $stuname=$ENV{'REMOTE_ADDR'};
                   2360:   }
1.168     albertel 2361:   my $now=time;
                   2362:   my %hash;
                   2363:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2364:   if (tie(%hash,'GDBM_File',
                   2365: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2366: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2367:     $hash{"version:$symb"}++;
                   2368:     my $version=$hash{"version:$symb"};
                   2369:     my $allkeys=''; 
                   2370:     foreach my $key (keys(%$storehash)) {
                   2371:       $allkeys.=$key.':';
1.591     albertel 2372:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2373:     }
                   2374:     $hash{"$version:$symb:timestamp"}=$now;
                   2375:     $allkeys.='timestamp';
                   2376:     $hash{"$version:keys:$symb"}=$allkeys;
                   2377:     if (untie(%hash)) {
                   2378:       return 'ok';
                   2379:     } else {
                   2380:       return "error:$!";
                   2381:     }
                   2382:   } else {
                   2383:     return "error:$!";
                   2384:   }
                   2385: }
1.167     albertel 2386: 
1.168     albertel 2387: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2388: 
1.168     albertel 2389: sub tmprestore {
                   2390:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2391: 
1.168     albertel 2392:   if (!$symb) {
                   2393:     $symb=&symbread();
1.620     albertel 2394:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2395:   }
                   2396:   $symb=escape($symb);
                   2397: 
1.620     albertel 2398:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2399: 
1.620     albertel 2400:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2401:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2402:   if ($domain eq 'public' && $stuname eq 'public') {
                   2403:       $stuname=$ENV{'REMOTE_ADDR'};
                   2404:   }
1.168     albertel 2405:   my %returnhash;
                   2406:   $namespace=~s/\//\_/g;
                   2407:   $namespace=~s/\W//g;
                   2408:   my %hash;
                   2409:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2410:   if (tie(%hash,'GDBM_File',
                   2411: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2412: 	  &GDBM_READER(),0640)) {
1.168     albertel 2413:     my $version=$hash{"version:$symb"};
                   2414:     $returnhash{'version'}=$version;
                   2415:     my $scope;
                   2416:     for ($scope=1;$scope<=$version;$scope++) {
                   2417:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2418:       my @keys=split(/:/,$vkeys);
                   2419:       my $key;
                   2420:       $returnhash{"$scope:keys"}=$vkeys;
                   2421:       foreach $key (@keys) {
1.591     albertel 2422: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2423: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2424:       }
                   2425:     }
1.168     albertel 2426:     if (!(untie(%hash))) {
                   2427:       return "error:$!";
                   2428:     }
                   2429:   } else {
                   2430:     return "error:$!";
                   2431:   }
                   2432:   return %returnhash;
1.167     albertel 2433: }
                   2434: 
1.9       www      2435: # ----------------------------------------------------------------------- Store
                   2436: 
                   2437: sub store {
1.124     www      2438:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2439:     my $home='';
                   2440: 
1.168     albertel 2441:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2442: 
1.213     www      2443:     $symb=&symbclean($symb);
1.122     albertel 2444:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2445: 
1.620     albertel 2446:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2447:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2448: 
                   2449:     &devalidate($symb,$stuname,$domain);
1.109     www      2450: 
                   2451:     $symb=escape($symb);
1.187     www      2452:     if (!$namespace) { 
1.620     albertel 2453:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2454:           return ''; 
                   2455:        } 
                   2456:     }
1.620     albertel 2457:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2458: 
                   2459:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2460:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2461: 
1.12      www      2462:     my $namevalue='';
1.191     harris41 2463:     foreach (keys %$storehash) {
1.591     albertel 2464:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2465:     }
1.12      www      2466:     $namevalue=~s/\&$//;
1.187     www      2467:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2468:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2469: }
                   2470: 
1.47      www      2471: # -------------------------------------------------------------- Critical Store
                   2472: 
                   2473: sub cstore {
1.124     www      2474:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2475:     my $home='';
                   2476: 
1.168     albertel 2477:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2478: 
1.213     www      2479:     $symb=&symbclean($symb);
1.122     albertel 2480:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2481: 
1.620     albertel 2482:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2483:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2484: 
                   2485:     &devalidate($symb,$stuname,$domain);
1.109     www      2486: 
                   2487:     $symb=escape($symb);
1.187     www      2488:     if (!$namespace) { 
1.620     albertel 2489:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2490:           return ''; 
                   2491:        } 
                   2492:     }
1.620     albertel 2493:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2494: 
                   2495:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2496:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2497: 
1.47      www      2498:     my $namevalue='';
1.191     harris41 2499:     foreach (keys %$storehash) {
1.591     albertel 2500:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2501:     }
1.47      www      2502:     $namevalue=~s/\&$//;
1.187     www      2503:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2504:     return critical
                   2505:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2506: }
                   2507: 
1.9       www      2508: # --------------------------------------------------------------------- Restore
                   2509: 
                   2510: sub restore {
1.124     www      2511:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2512:     my $home='';
                   2513: 
1.168     albertel 2514:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2515: 
1.122     albertel 2516:     if (!$symb) {
                   2517:       unless ($symb=escape(&symbread())) { return ''; }
                   2518:     } else {
1.213     www      2519:       $symb=&escape(&symbclean($symb));
1.122     albertel 2520:     }
1.188     www      2521:     if (!$namespace) { 
1.620     albertel 2522:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2523:           return ''; 
                   2524:        } 
                   2525:     }
1.620     albertel 2526:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2527:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2528:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2529:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2530: 
1.12      www      2531:     my %returnhash=();
1.191     harris41 2532:     foreach (split(/\&/,$answer)) {
1.12      www      2533: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2534:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2535:     }
1.75      www      2536:     my $version;
                   2537:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2538:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2539:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2540:        }
1.75      www      2541:     }
1.13      www      2542:     return %returnhash;
1.34      www      2543: }
                   2544: 
                   2545: # ---------------------------------------------------------- Course Description
                   2546: 
                   2547: sub coursedescription {
                   2548:     my $courseid=shift;
                   2549:     $courseid=~s/^\///;
1.49      www      2550:     $courseid=~s/\_/\//g;
1.34      www      2551:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2552:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2553:     my $normalid=$cdomain.'_'.$cnum;
                   2554:     # need to always cache even if we get errors otherwise we keep 
                   2555:     # trying and trying and trying to get the course description.
                   2556:     my %envhash=();
                   2557:     my %returnhash=();
                   2558:     $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34      www      2559:     if ($chome ne 'no_host') {
1.302     albertel 2560:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2561:        if (!exists($returnhash{'con_lost'})) {
                   2562:            $returnhash{'home'}= $chome;
                   2563: 	   $returnhash{'domain'} = $cdomain;
                   2564: 	   $returnhash{'num'} = $cnum;
1.130     albertel 2565:            while (my ($name,$value) = each %returnhash) {
1.53      www      2566:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2567:            }
1.270     www      2568:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2569:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2570: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2571:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2572:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2573:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2574:        }
                   2575:     }
1.302     albertel 2576:     &appenv(%envhash);
                   2577:     return %returnhash;
1.461     www      2578: }
                   2579: 
                   2580: # -------------------------------------------------See if a user is privileged
                   2581: 
                   2582: sub privileged {
                   2583:     my ($username,$domain)=@_;
                   2584:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2585: 			&homeserver($username,$domain));
                   2586:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2587:     my $now=time;
                   2588:     if ($rolesdump ne '') {
                   2589:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2590: 	    if ($_!~/^rolesdef_/) {
1.461     www      2591: 		my ($area,$role)=split(/=/,$_);
                   2592: 		$area=~s/\_\w\w$//;
                   2593: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2594: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2595: 		    my $active=1;
                   2596: 		    if ($tend) {
                   2597: 			if ($tend<$now) { $active=0; }
                   2598: 		    }
                   2599: 		    if ($tstart) {
                   2600: 			if ($tstart>$now) { $active=0; }
                   2601: 		    }
                   2602: 		    if ($active) { return 1; }
                   2603: 		}
                   2604: 	    }
                   2605: 	}
                   2606:     }
                   2607:     return 0;
1.9       www      2608: }
1.1       albertel 2609: 
1.103     harris41 2610: # -------------------------------------------------------- Get user privileges
1.11      www      2611: 
                   2612: sub rolesinit {
                   2613:     my ($domain,$username,$authhost)=@_;
                   2614:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2615:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2616:     my %allroles=();
1.678     raeburn  2617:     my %allgroups=();   
1.11      www      2618:     my $now=time;
1.21      www      2619:     my $userroles="user.login.time=$now\n";
1.678     raeburn  2620:     my $group_privs;
1.11      www      2621: 
                   2622:     if ($rolesdump ne '') {
1.191     harris41 2623:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2624: 	  if ($_!~/^rolesdef_/) {
1.11      www      2625:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2626: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2627:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2628: 	    if ($role=~/^cr/) { 
1.655     albertel 2629: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2630: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2631: 		    ($tend,$tstart)=split('_',$trest);
                   2632: 		} else {
                   2633: 		    $trole=$role;
                   2634: 		}
1.678     raeburn  2635:             } elsif ($role =~ m|^gr/|) {
                   2636:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2637:                 ($trole,$group_privs) = split(/\//,$trole);
                   2638:                 $group_privs = &unescape($group_privs);
1.587     albertel 2639: 	    } else {
                   2640: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2641: 	    }
1.576     albertel 2642:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
1.567     raeburn  2643:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2644:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2645:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2646: 		my $spec=$trole.'.'.$area;
                   2647: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2648: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2649:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2650:                 } elsif ($trole eq 'gr') {
                   2651:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2652: 		} else {
1.567     raeburn  2653:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2654: 		}
1.12      www      2655:             }
1.662     raeburn  2656:           }
1.191     harris41 2657:         }
1.678     raeburn  2658:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles,\%allgroups);
1.128     www      2659:         $userroles.='user.adv='.$adv."\n".
                   2660: 	            'user.author='.$author."\n";
1.620     albertel 2661:         $env{'user.adv'}=$adv;
1.11      www      2662:     }
                   2663:     return $userroles;  
                   2664: }
                   2665: 
1.567     raeburn  2666: sub set_arearole {
                   2667:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2668: # log the associated role with the area
                   2669:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   2670:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
                   2671: }
                   2672: 
                   2673: sub custom_roleprivs {
                   2674:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2675:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2676:     my $homsvr=homeserver($rauthor,$rdomain);
                   2677:     if ($hostname{$homsvr} ne '') {
                   2678:         my ($rdummy,$roledef)=
                   2679:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2680:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2681:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2682:             if (defined($syspriv)) {
                   2683:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2684:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2685:             }
                   2686:             if ($tdomain ne '') {
                   2687:                 if (defined($dompriv)) {
                   2688:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2689:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2690:                 }
                   2691:                 if (($trest ne '') && (defined($coursepriv))) {
                   2692:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2693:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2694:                 }
                   2695:             }
                   2696:         }
                   2697:     }
                   2698: }
                   2699: 
1.678     raeburn  2700: sub group_roleprivs {
                   2701:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2702:     my $access = 1;
                   2703:     my $now = time;
                   2704:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2705:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2706:     if ($access) {
                   2707:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2708:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2709:     }
                   2710: }
1.567     raeburn  2711: 
                   2712: sub standard_roleprivs {
                   2713:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2714:     if (defined($pr{$trole.':s'})) {
                   2715:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2716:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2717:     }
                   2718:     if ($tdomain ne '') {
                   2719:         if (defined($pr{$trole.':d'})) {
                   2720:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2721:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2722:         }
                   2723:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2724:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2725:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2726:         }
                   2727:     }
                   2728: }
                   2729: 
                   2730: sub set_userprivs {
1.678     raeburn  2731:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2732:     my $author=0;
                   2733:     my $adv=0;
1.678     raeburn  2734:     my %grouproles = ();
                   2735:     if (keys(%{$allgroups}) > 0) {
                   2736:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2737:             my ($trole,$area,$sec,$extendedarea);
                   2738:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2739:                 $trole = $1;
                   2740:                 $area = $2;
1.681     raeburn  2741:                 $sec = $3;
                   2742:                 $extendedarea = $area.$sec;
                   2743:                 if (exists($$allgroups{$area})) {
                   2744:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2745:                         my $spec = $trole.'.'.$extendedarea;
                   2746:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2747:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2748:                     }
                   2749:                 }
                   2750:             }
                   2751:         }
                   2752:     }
                   2753:     foreach (keys(%grouproles)) {
                   2754:         $$allroles{$_} = $grouproles{$_};
                   2755:     }
1.567     raeburn  2756:     foreach (keys %{$allroles}) {
                   2757:         my %thesepriv=();
                   2758:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2759:         foreach (split(/:/,$$allroles{$_})) {
                   2760:             if ($_ ne '') {
                   2761:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2762:                 if ($restrictions eq '') {
                   2763:                     $thesepriv{$privilege}='F';
                   2764:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2765:                     $thesepriv{$privilege}.=$restrictions;
                   2766:                 }
                   2767:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2768:             }
                   2769:         }
                   2770:         my $thesestr='';
                   2771:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
                   2772:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
                   2773:     }
                   2774:     return ($author,$adv);
                   2775: }
                   2776: 
1.12      www      2777: # --------------------------------------------------------------- get interface
                   2778: 
                   2779: sub get {
1.131     albertel 2780:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2781:    my $items='';
1.191     harris41 2782:    foreach (@$storearr) {
1.12      www      2783:        $items.=escape($_).'&';
1.191     harris41 2784:    }
1.12      www      2785:    $items=~s/\&$//;
1.620     albertel 2786:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2787:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2788:    my $uhome=&homeserver($uname,$udomain);
                   2789: 
1.133     albertel 2790:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2791:    my @pairs=split(/\&/,$rep);
1.273     albertel 2792:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2793:      return @pairs;
                   2794:    }
1.15      www      2795:    my %returnhash=();
1.42      www      2796:    my $i=0;
1.191     harris41 2797:    foreach (@$storearr) {
1.557     albertel 2798:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2799:       $i++;
1.191     harris41 2800:    }
1.15      www      2801:    return %returnhash;
1.27      www      2802: }
                   2803: 
                   2804: # --------------------------------------------------------------- del interface
                   2805: 
                   2806: sub del {
1.133     albertel 2807:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2808:    my $items='';
1.191     harris41 2809:    foreach (@$storearr) {
1.27      www      2810:        $items.=escape($_).'&';
1.191     harris41 2811:    }
1.27      www      2812:    $items=~s/\&$//;
1.620     albertel 2813:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2814:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2815:    my $uhome=&homeserver($uname,$udomain);
                   2816: 
                   2817:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2818: }
                   2819: 
                   2820: # -------------------------------------------------------------- dump interface
                   2821: 
                   2822: sub dump {
1.193     www      2823:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.620     albertel 2824:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2825:    if (!$uname) { $uname=$env{'user.name'}; }
1.129     albertel 2826:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2827:    if ($regexp) {
                   2828:        $regexp=&escape($regexp);
                   2829:    } else {
                   2830:        $regexp='.';
                   2831:    }
                   2832:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      2833:    my @pairs=split(/\&/,$rep);
                   2834:    my %returnhash=();
1.191     harris41 2835:    foreach (@pairs) {
1.12      www      2836:       my ($key,$value)=split(/=/,$_);
1.557     albertel 2837:       $returnhash{unescape($key)}=&thaw_unescape($value);
1.318     matthew  2838:    }
                   2839:    return %returnhash;
1.407     www      2840: }
                   2841: 
                   2842: # -------------------------------------------------------------- keys interface
                   2843: 
                   2844: sub getkeys {
                   2845:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2846:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2847:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2848:    my $uhome=&homeserver($uname,$udomain);
                   2849:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2850:    my @keyarray=();
                   2851:    foreach (split(/\&/,$rep)) {
                   2852:       push (@keyarray,&unescape($_));
                   2853:    }
                   2854:    return @keyarray;
1.318     matthew  2855: }
                   2856: 
1.319     matthew  2857: # --------------------------------------------------------------- currentdump
                   2858: sub currentdump {
1.328     matthew  2859:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2860:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2861:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2862:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2863:    my $uhome = &homeserver($sname,$sdom);
                   2864:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2865:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2866:    #
1.318     matthew  2867:    my %returnhash=();
1.319     matthew  2868:    #
                   2869:    if ($rep eq "unknown_cmd") { 
                   2870:        # an old lond will not know currentdump
                   2871:        # Do a dump and make it look like a currentdump
1.326     matthew  2872:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2873:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2874:        my %hash = @tmp;
                   2875:        @tmp=();
1.424     matthew  2876:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2877:    } else {
                   2878:        my @pairs=split(/\&/,$rep);
                   2879:        foreach (@pairs) {
                   2880:            my ($key,$value)=split(/=/,$_);
                   2881:            my ($symb,$param) = split(/:/,$key);
                   2882:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2883:                                                         &thaw_unescape($value);
1.319     matthew  2884:        }
1.191     harris41 2885:    }
1.12      www      2886:    return %returnhash;
1.424     matthew  2887: }
                   2888: 
                   2889: sub convert_dump_to_currentdump{
                   2890:     my %hash = %{shift()};
                   2891:     my %returnhash;
                   2892:     # Code ripped from lond, essentially.  The only difference
                   2893:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2894:     # we might run in to problems with parameter names =~ /^v\./
                   2895:     while (my ($key,$value) = each(%hash)) {
                   2896:         my ($v,$symb,$param) = split(/:/,$key);
                   2897:         next if ($v eq 'version' || $symb eq 'keys');
                   2898:         next if (exists($returnhash{$symb}) &&
                   2899:                  exists($returnhash{$symb}->{$param}) &&
                   2900:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2901:         $returnhash{$symb}->{$param}=$value;
                   2902:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2903:     }
                   2904:     #
                   2905:     # Remove all of the keys in the hashes which keep track of
                   2906:     # the version of the parameter.
                   2907:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   2908:         # use a foreach because we are going to delete from the hash.
                   2909:         foreach my $key (keys(%$param_hash)) {
                   2910:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2911:         }
                   2912:     }
                   2913:     return \%returnhash;
1.12      www      2914: }
                   2915: 
1.627     albertel 2916: # ------------------------------------------------------ critical inc interface
                   2917: 
                   2918: sub cinc {
                   2919:     return &inc(@_,'critical');
                   2920: }
                   2921: 
1.449     matthew  2922: # --------------------------------------------------------------- inc interface
                   2923: 
                   2924: sub inc {
1.627     albertel 2925:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 2926:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2927:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  2928:     my $uhome=&homeserver($uname,$udomain);
                   2929:     my $items='';
                   2930:     if (! ref($store)) {
                   2931:         # got a single value, so use that instead
                   2932:         $items = &escape($store).'=&';
                   2933:     } elsif (ref($store) eq 'SCALAR') {
                   2934:         $items = &escape($$store).'=&';        
                   2935:     } elsif (ref($store) eq 'ARRAY') {
                   2936:         $items = join('=&',map {&escape($_);} @{$store});
                   2937:     } elsif (ref($store) eq 'HASH') {
                   2938:         while (my($key,$value) = each(%{$store})) {
                   2939:             $items.= &escape($key).'='.&escape($value).'&';
                   2940:         }
                   2941:     }
                   2942:     $items=~s/\&$//;
1.627     albertel 2943:     if ($critical) {
                   2944: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2945:     } else {
                   2946: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2947:     }
1.449     matthew  2948: }
                   2949: 
1.12      www      2950: # --------------------------------------------------------------- put interface
                   2951: 
                   2952: sub put {
1.134     albertel 2953:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2954:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2955:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 2956:    my $uhome=&homeserver($uname,$udomain);
1.12      www      2957:    my $items='';
1.191     harris41 2958:    foreach (keys %$storehash) {
1.557     albertel 2959:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2960:    }
1.12      www      2961:    $items=~s/\&$//;
1.134     albertel 2962:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      2963: }
                   2964: 
1.631     albertel 2965: # ------------------------------------------------------------ newput interface
                   2966: 
                   2967: sub newput {
                   2968:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2969:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2970:    if (!$uname) { $uname=$env{'user.name'}; }
                   2971:    my $uhome=&homeserver($uname,$udomain);
                   2972:    my $items='';
                   2973:    foreach my $key (keys(%$storehash)) {
                   2974:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2975:    }
                   2976:    $items=~s/\&$//;
                   2977:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   2978: }
                   2979: 
                   2980: # ---------------------------------------------------------  putstore interface
                   2981: 
1.524     raeburn  2982: sub putstore {
                   2983:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2984:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2985:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  2986:    my $uhome=&homeserver($uname,$udomain);
                   2987:    my $items='';
                   2988:    my %allitems = ();
                   2989:    foreach (keys %$storehash) {
                   2990:        if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   2991:            my $key = $1.':keys:'.$2;
                   2992:            $allitems{$key} .= $3.':';
                   2993:        }
1.591     albertel 2994:        $items.=$_.'='.&freeze_escape($$storehash{$_}).'&';
1.524     raeburn  2995:    }
                   2996:    foreach (keys %allitems) {
                   2997:        $allitems{$_} =~ s/\:$//;
                   2998:        $items.= $_.'='.$allitems{$_}.'&';
                   2999:    }
                   3000:    $items=~s/\&$//;
                   3001:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   3002: }
                   3003: 
1.47      www      3004: # ------------------------------------------------------ critical put interface
                   3005: 
                   3006: sub cput {
1.134     albertel 3007:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3008:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3009:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3010:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3011:    my $items='';
1.191     harris41 3012:    foreach (keys %$storehash) {
1.557     albertel 3013:        $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3014:    }
1.47      www      3015:    $items=~s/\&$//;
1.134     albertel 3016:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3017: }
                   3018: 
                   3019: # -------------------------------------------------------------- eget interface
                   3020: 
                   3021: sub eget {
1.133     albertel 3022:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3023:    my $items='';
1.191     harris41 3024:    foreach (@$storearr) {
1.12      www      3025:        $items.=escape($_).'&';
1.191     harris41 3026:    }
1.12      www      3027:    $items=~s/\&$//;
1.620     albertel 3028:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3029:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3030:    my $uhome=&homeserver($uname,$udomain);
                   3031:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3032:    my @pairs=split(/\&/,$rep);
                   3033:    my %returnhash=();
1.42      www      3034:    my $i=0;
1.191     harris41 3035:    foreach (@$storearr) {
1.557     albertel 3036:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3037:       $i++;
1.191     harris41 3038:    }
1.12      www      3039:    return %returnhash;
                   3040: }
                   3041: 
1.667     albertel 3042: # ------------------------------------------------------------ tmpput interface
                   3043: sub tmpput {
                   3044:     my ($storehash,$server)=@_;
                   3045:     my $items='';
                   3046:     foreach (keys(%$storehash)) {
                   3047: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3048:     }
                   3049:     $items=~s/\&$//;
                   3050:     return &reply("tmpput:$items",$server);
                   3051: }
                   3052: 
                   3053: # ------------------------------------------------------------ tmpget interface
                   3054: sub tmpget {
1.683.2.4  albertel 3055:     my ($token,$server)=@_;
                   3056:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3057:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3058:     my %returnhash;
                   3059:     foreach my $item (split(/\&/,$rep)) {
                   3060: 	my ($key,$value)=split(/=/,$item);
                   3061: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3062:     }
                   3063:     return %returnhash;
                   3064: }
                   3065: 
1.683.2.4  albertel 3066: # ------------------------------------------------------------ tmpget interface
                   3067: sub tmpdel {
                   3068:     my ($token,$server)=@_;
                   3069:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3070:     return &reply("tmpdel:$token",$server);
                   3071: }
                   3072: 
1.341     www      3073: # ---------------------------------------------- Custom access rule evaluation
                   3074: 
                   3075: sub customaccess {
                   3076:     my ($priv,$uri)=@_;
1.620     albertel 3077:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3078:     $urealm=~s/^\W//;
                   3079:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3080:     my $access=0;
                   3081:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3082: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3083:         if ($role) {
                   3084: 	   if ($role ne $urole) { next; }
                   3085:         }
                   3086:         foreach (split(/\s*\,\s*/,$realm)) {
                   3087:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3088:             if ($tdom) {
                   3089: 		if ($tdom ne $udom) { next; }
                   3090:             }
                   3091:             if ($tcrs) {
                   3092: 		if ($tcrs ne $ucrs) { next; }
                   3093:             }
                   3094:             if ($tsec) {
                   3095: 		if ($tsec ne $usec) { next; }
                   3096:             }
                   3097:             $access=($effect eq 'allow');
                   3098:             last;
1.342     www      3099:         }
1.402     bowersj2 3100: 	if ($realm eq '' && $role eq '') {
                   3101:             $access=($effect eq 'allow');
                   3102: 	}
1.341     www      3103:     }
                   3104:     return $access;
                   3105: }
                   3106: 
1.103     harris41 3107: # ------------------------------------------------- Check for a user privilege
1.12      www      3108: 
                   3109: sub allowed {
1.579     albertel 3110:     my ($priv,$uri,$symb)=@_;
1.683.2.14  albertel 3111:     my $ver_orguri=$uri;
1.439     www      3112:     $uri=&deversion($uri);
1.152     www      3113:     my $orguri=$uri;
1.52      www      3114:     $uri=&declutter($uri);
1.545     banghart 3115:     
1.620     albertel 3116:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3117: # Free bre access to adm and meta resources
1.529     albertel 3118:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3119: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3120: 	return 'F';
1.159     www      3121:     }
                   3122: 
1.545     banghart 3123: # Free bre access to user's own portfolio contents
1.546     albertel 3124:     my ($space,$domain,$name,$dir)=split('/',$uri);
1.647     raeburn  3125:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.620     albertel 3126: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
1.545     banghart 3127:         return 'F';
                   3128:     }
                   3129: 
1.159     www      3130: # Free bre to public access
                   3131: 
                   3132:     if ($priv eq 'bre') {
1.238     www      3133:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3134: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3135:            return 'F'; 
                   3136:         }
1.238     www      3137:         if ($copyright eq 'priv') {
                   3138:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3139: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3140: 		return '';
                   3141:             }
                   3142:         }
                   3143:         if ($copyright eq 'domain') {
                   3144:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3145: 	    unless (($env{'user.domain'} eq $1) ||
                   3146:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3147: 		return '';
                   3148:             }
1.262     matthew  3149:         }
1.620     albertel 3150:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3151:             # Library role, so allow browsing of resources in this domain.
                   3152:             return 'F';
1.238     www      3153:         }
1.341     www      3154:         if ($copyright eq 'custom') {
                   3155: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3156:         }
1.14      www      3157:     }
1.264     matthew  3158:     # Domain coordinator is trying to create a course
1.620     albertel 3159:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3160:         # uri is the requested domain in this case.
                   3161:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3162:         # a role of dc for the domain in question.
1.620     albertel 3163:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3164:     }
1.29      www      3165: 
1.52      www      3166:     my $thisallowed='';
                   3167:     my $statecond=0;
                   3168:     my $courseprivid='';
                   3169: 
                   3170: # Course
                   3171: 
1.620     albertel 3172:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3173:        $thisallowed.=$1;
                   3174:     }
1.29      www      3175: 
1.52      www      3176: # Domain
                   3177: 
1.620     albertel 3178:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3179:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3180:        $thisallowed.=$1;
                   3181:     }
1.52      www      3182: 
                   3183: # Course: uri itself is a course
1.66      www      3184:     my $courseuri=$uri;
                   3185:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3186:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3187: 
1.620     albertel 3188:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3189:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3190:        $thisallowed.=$1;
                   3191:     }
1.29      www      3192: 
1.678     raeburn  3193: # Group: uri itself is a group
                   3194:     my $groupuri=$uri;
                   3195:     $groupuri=~s/^([^\/])/\/$1/;
                   3196:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
                   3197:        =~/\Q$priv\E\&([^\:]*)/) {
                   3198:        $thisallowed.=$1;
                   3199:     }
                   3200: 
1.665     albertel 3201: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3202: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3203:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3204: 	$thisallowed='';
1.671     raeburn  3205:         my ($match)=&is_on_map($uri);
                   3206:         if ($match) {
                   3207:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3208:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3209:                 $thisallowed.=$1;
                   3210:             }
                   3211:         } else {
1.683.2.14  albertel 3212:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3213:             if ($refuri) {
                   3214:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3215:                     $thisallowed='F';
1.671     raeburn  3216:                 } else {
                   3217:                     $refuri=&declutter($refuri);
                   3218:                     my ($match) = &is_on_map($refuri);
                   3219:                     if ($match) {
                   3220:                         $thisallowed='F';
                   3221:                     }
1.669     raeburn  3222:                 }
1.671     raeburn  3223:             }
                   3224:         }
1.314     www      3225:     }
1.492     albertel 3226: 
1.52      www      3227: # Full access at system, domain or course-wide level? Exit.
1.29      www      3228: 
                   3229:     if ($thisallowed=~/F/) {
                   3230: 	return 'F';
                   3231:     }
                   3232: 
1.52      www      3233: # If this is generating or modifying users, exit with special codes
1.29      www      3234: 
1.643     www      3235:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3236: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3237: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3238: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3239: 	    unless ($auname) { return $thisallowed; }
                   3240: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3241: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3242: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3243: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3244: 	}
1.52      www      3245: 	return $thisallowed;
                   3246:     }
                   3247: #
1.103     harris41 3248: # Gathered so far: system, domain and course wide privileges
1.52      www      3249: #
                   3250: # Course: See if uri or referer is an individual resource that is part of 
                   3251: # the course
                   3252: 
1.620     albertel 3253:     if ($env{'request.course.id'}) {
1.232     www      3254: 
1.620     albertel 3255:        $courseprivid=$env{'request.course.id'};
                   3256:        if ($env{'request.course.sec'}) {
                   3257:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3258:        }
                   3259:        $courseprivid=~s/\_/\//;
                   3260:        my $checkreferer=1;
1.232     www      3261:        my ($match,$cond)=&is_on_map($uri);
                   3262:        if ($match) {
                   3263:            $statecond=$cond;
1.620     albertel 3264:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3265:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3266:                $thisallowed.=$1;
                   3267:                $checkreferer=0;
                   3268:            }
1.29      www      3269:        }
1.83      www      3270:        
1.148     www      3271:        if ($checkreferer) {
1.620     albertel 3272: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3273:             unless ($refuri) {
1.620     albertel 3274:                 foreach (keys %env) {
1.148     www      3275: 		    if ($_=~/^httpref\..*\*/) {
                   3276: 			my $pattern=$_;
1.156     www      3277:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3278:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3279:                         $pattern=~s/\//\\\//g;
1.152     www      3280:                         if ($orguri=~/$pattern/) {
1.620     albertel 3281: 			    $refuri=$env{$_};
1.148     www      3282:                         }
                   3283:                     }
1.191     harris41 3284:                 }
1.148     www      3285:             }
1.232     www      3286: 
1.148     www      3287:          if ($refuri) { 
1.152     www      3288: 	  $refuri=&declutter($refuri);
1.232     www      3289:           my ($match,$cond)=&is_on_map($refuri);
                   3290:             if ($match) {
                   3291:               my $refstatecond=$cond;
1.620     albertel 3292:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3293:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3294:                   $thisallowed.=$1;
1.53      www      3295:                   $uri=$refuri;
                   3296:                   $statecond=$refstatecond;
1.52      www      3297:               }
                   3298:           }
1.148     www      3299:         }
1.29      www      3300:        }
1.52      www      3301:    }
1.29      www      3302: 
1.52      www      3303: #
1.103     harris41 3304: # Gathered now: all privileges that could apply, and condition number
1.52      www      3305: # 
                   3306: #
                   3307: # Full or no access?
                   3308: #
1.29      www      3309: 
1.52      www      3310:     if ($thisallowed=~/F/) {
                   3311: 	return 'F';
                   3312:     }
1.29      www      3313: 
1.52      www      3314:     unless ($thisallowed) {
                   3315:         return '';
                   3316:     }
1.29      www      3317: 
1.52      www      3318: # Restrictions exist, deal with them
                   3319: #
                   3320: #   C:according to course preferences
                   3321: #   R:according to resource settings
                   3322: #   L:unless locked
                   3323: #   X:according to user session state
                   3324: #
                   3325: 
                   3326: # Possibly locked functionality, check all courses
1.54      www      3327: # Locks might take effect only after 10 minutes cache expiration for other
                   3328: # courses, and 2 minutes for current course
1.52      www      3329: 
                   3330:     my $envkey;
                   3331:     if ($thisallowed=~/L/) {
1.620     albertel 3332:         foreach $envkey (keys %env) {
1.54      www      3333:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3334:                my $courseid=$2;
                   3335:                my $roleid=$1.'.'.$2;
1.92      www      3336:                $courseid=~s/^\///;
1.54      www      3337:                my $expiretime=600;
1.620     albertel 3338:                if ($env{'request.role'} eq $roleid) {
1.54      www      3339: 		  $expiretime=120;
                   3340:                }
                   3341: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3342:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3343:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.54      www      3344: 		   &coursedescription($courseid);
                   3345:                }
1.620     albertel 3346:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3347:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3348: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3349:                        &log($env{'user.domain'},$env{'user.name'},
                   3350:                             $env{'user.home'},
1.57      www      3351:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3352:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3353:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3354: 		       return '';
                   3355:                    }
                   3356:                }
1.620     albertel 3357:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3358:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3359: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3360:                        &log($env{'user.domain'},$env{'user.name'},
                   3361:                             $env{'user.home'},
1.57      www      3362:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3363:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3364:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3365: 		       return '';
                   3366:                    }
                   3367:                }
                   3368: 	   }
1.29      www      3369:        }
1.52      www      3370:     }
                   3371:    
                   3372: #
                   3373: # Rest of the restrictions depend on selected course
                   3374: #
                   3375: 
1.620     albertel 3376:     unless ($env{'request.course.id'}) {
1.52      www      3377:        return '1';
                   3378:     }
1.29      www      3379: 
1.52      www      3380: #
                   3381: # Now user is definitely in a course
                   3382: #
1.53      www      3383: 
                   3384: 
                   3385: # Course preferences
                   3386: 
                   3387:    if ($thisallowed=~/C/) {
1.620     albertel 3388:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3389:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3390:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3391: 	   =~/\Q$rolecode\E/) {
1.683.2.5  albertel 3392: 	   if ($priv ne 'pch') { 
                   3393: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3394: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3395: 			$env{'request.course.id'});
                   3396: 	   }
1.237     www      3397:            return '';
                   3398:        }
                   3399: 
1.620     albertel 3400:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3401: 	   =~/\Q$unamedom\E/) {
1.683.2.5  albertel 3402: 	   if ($priv ne 'pch') { 
                   3403: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3404: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3405: 			$env{'request.course.id'});
                   3406: 	   }
1.54      www      3407:            return '';
                   3408:        }
1.53      www      3409:    }
                   3410: 
                   3411: # Resource preferences
                   3412: 
                   3413:    if ($thisallowed=~/R/) {
1.620     albertel 3414:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3415:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.683.2.5  albertel 3416: 	   if ($priv ne 'pch') { 
                   3417: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3418: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3419: 	   }
                   3420: 	   return '';
1.54      www      3421:        }
1.53      www      3422:    }
1.30      www      3423: 
1.246     www      3424: # Restricted by state or randomout?
1.30      www      3425: 
1.52      www      3426:    if ($thisallowed=~/X/) {
1.620     albertel 3427:       if ($env{'acc.randomout'}) {
1.579     albertel 3428: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3429:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3430:             return ''; 
                   3431:          }
1.247     www      3432:       }
                   3433:       if (&condval($statecond)) {
1.52      www      3434: 	 return '2';
                   3435:       } else {
                   3436:          return '';
                   3437:       }
                   3438:    }
1.30      www      3439: 
1.52      www      3440:    return 'F';
1.232     www      3441: }
                   3442: 
1.683.2.18  albertel 3443: sub split_uri_for_cond {
                   3444:     my $uri=&deversion(&declutter(shift));
                   3445:     my @uriparts=split(/\//,$uri);
                   3446:     my $filename=pop(@uriparts);
                   3447:     my $pathname=join('/',@uriparts);
                   3448:     return ($pathname,$filename);
                   3449: }
1.232     www      3450: # --------------------------------------------------- Is a resource on the map?
                   3451: 
                   3452: sub is_on_map {
1.683.2.18  albertel 3453:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3454:     #Trying to find the conditional for the file
1.620     albertel 3455:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3456: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3457:     if ($match) {
1.289     bowersj2 3458: 	return (1,$1);
                   3459:     } else {
1.434     www      3460: 	return (0,0);
1.289     bowersj2 3461:     }
1.12      www      3462: }
                   3463: 
1.427     www      3464: # --------------------------------------------------------- Get symb from alias
                   3465: 
                   3466: sub get_symb_from_alias {
                   3467:     my $symb=shift;
                   3468:     my ($map,$resid,$url)=&decode_symb($symb);
                   3469: # Already is a symb
                   3470:     if ($url) { return $symb; }
                   3471: # Must be an alias
                   3472:     my $aliassymb='';
                   3473:     my %bighash;
1.620     albertel 3474:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3475:                             &GDBM_READER(),0640)) {
                   3476:         my $rid=$bighash{'mapalias_'.$symb};
                   3477: 	if ($rid) {
                   3478: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3479: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3480: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3481: 	}
                   3482:         untie %bighash;
                   3483:     }
                   3484:     return $aliassymb;
                   3485: }
                   3486: 
1.12      www      3487: # ----------------------------------------------------------------- Define Role
                   3488: 
                   3489: sub definerole {
                   3490:   if (allowed('mcr','/')) {
                   3491:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3492:     foreach (split(':',$sysrole)) {
1.21      www      3493: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3494:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3495:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3496: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3497:                return "refused:s:$crole&$cqual"; 
                   3498:             }
                   3499:         }
1.191     harris41 3500:     }
1.392     www      3501:     foreach (split(':',$domrole)) {
1.21      www      3502: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3503:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3504:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3505: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3506:                return "refused:d:$crole&$cqual"; 
                   3507:             }
                   3508:         }
1.191     harris41 3509:     }
1.392     www      3510:     foreach (split(':',$courole)) {
1.21      www      3511: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3512:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3513:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3514: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3515:                return "refused:c:$crole&$cqual"; 
                   3516:             }
                   3517:         }
1.191     harris41 3518:     }
1.620     albertel 3519:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3520:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3521: 	        "rolesdef_$rolename=".
                   3522:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3523:     return reply($command,$env{'user.home'});
1.12      www      3524:   } else {
                   3525:     return 'refused';
                   3526:   }
1.105     harris41 3527: }
                   3528: 
                   3529: # ---------------- Make a metadata query against the network of library servers
                   3530: 
                   3531: sub metadata_query {
1.244     matthew  3532:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3533:     my %rhash;
1.244     matthew  3534:     my @server_list = (defined($server_array) ? @$server_array
                   3535:                                               : keys(%libserv) );
                   3536:     for my $server (@server_list) {
1.118     harris41 3537: 	unless ($custom or $customshow) {
                   3538: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3539: 	    $rhash{$server}=$reply;
                   3540: 	}
                   3541: 	else {
                   3542: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3543: 			     &escape($custom).':'.&escape($customshow),
                   3544: 			     $server);
                   3545: 	    $rhash{$server}=$reply;
                   3546: 	}
1.112     harris41 3547:     }
1.118     harris41 3548:     return \%rhash;
1.240     www      3549: }
                   3550: 
                   3551: # ----------------------------------------- Send log queries and wait for reply
                   3552: 
                   3553: sub log_query {
                   3554:     my ($uname,$udom,$query,%filters)=@_;
                   3555:     my $uhome=&homeserver($uname,$udom);
                   3556:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3557:     my $uhost=$hostname{$uhome};
1.241     www      3558:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3559:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3560:                        $uhome);
1.479     albertel 3561:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3562:     return get_query_reply($queryid);
                   3563: }
                   3564: 
1.508     raeburn  3565: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3566: 
                   3567: sub fetch_enrollment_query {
1.511     raeburn  3568:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3569:     my $homeserver;
1.547     raeburn  3570:     my $maxtries = 1;
1.508     raeburn  3571:     if ($context eq 'automated') {
                   3572:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3573:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3574:     } else {
                   3575:         $homeserver = &homeserver($cnum,$dom);
                   3576:     }
1.506     raeburn  3577:     my $host=$hostname{$homeserver};
                   3578:     my $cmd = '';
                   3579:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3580:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3581:     }
                   3582:     $cmd =~ s/%%$//;
                   3583:     $cmd = &escape($cmd);
                   3584:     my $query = 'fetchenrollment';
1.620     albertel 3585:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3586:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3587:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3588:         return 'error: '.$queryid;
                   3589:     }
1.506     raeburn  3590:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3591:     my $tries = 1;
                   3592:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3593:         $reply = &get_query_reply($queryid);
                   3594:         $tries ++;
                   3595:     }
1.526     raeburn  3596:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3597:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3598:     } else {
1.515     raeburn  3599:         my @responses = split/:/,$reply;
                   3600:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3601:             foreach (@responses) {
                   3602:                 my ($key,$value) = split/=/,$_;
                   3603:                 $$replyref{$key} = $value;
                   3604:             }
                   3605:         } else {
1.506     raeburn  3606:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3607:             foreach (@responses) {
                   3608:                 my ($key,$value) = split/=/,$_;
                   3609:                 $$replyref{$key} = $value;
                   3610:                 if ($value > 0) {
                   3611:                     foreach (@{$$affiliatesref{$key}}) {
                   3612:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3613:                         my $destname = $pathname.'/'.$filename;
                   3614:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3615:                         if ($xml_classlist =~ /^error/) {
                   3616:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3617:                         } else {
1.506     raeburn  3618:                             if ( open(FILE,">$destname") ) {
                   3619:                                 print FILE &unescape($xml_classlist);
                   3620:                                 close(FILE);
1.526     raeburn  3621:                             } else {
                   3622:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3623:                             }
                   3624:                         }
                   3625:                     }
                   3626:                 }
                   3627:             }
                   3628:         }
                   3629:         return 'ok';
                   3630:     }
                   3631:     return 'error';
                   3632: }
                   3633: 
1.242     www      3634: sub get_query_reply {
                   3635:     my $queryid=shift;
1.240     www      3636:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3637:     my $reply='';
                   3638:     for (1..100) {
                   3639: 	sleep 2;
                   3640:         if (-e $replyfile.'.end') {
1.448     albertel 3641: 	    if (open(my $fh,$replyfile)) {
1.240     www      3642:                $reply.=<$fh>;
1.448     albertel 3643:                close($fh);
1.240     www      3644: 	   } else { return 'error: reply_file_error'; }
1.242     www      3645:            return &unescape($reply);
                   3646: 	}
1.240     www      3647:     }
1.242     www      3648:     return 'timeout:'.$queryid;
1.240     www      3649: }
                   3650: 
                   3651: sub courselog_query {
1.241     www      3652: #
                   3653: # possible filters:
                   3654: # url: url or symb
                   3655: # username
                   3656: # domain
                   3657: # action: view, submit, grade
                   3658: # start: timestamp
                   3659: # end: timestamp
                   3660: #
1.240     www      3661:     my (%filters)=@_;
1.620     albertel 3662:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3663:     if ($filters{'url'}) {
                   3664: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3665:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3666:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3667:     }
1.620     albertel 3668:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3669:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3670:     return &log_query($cname,$cdom,'courselog',%filters);
                   3671: }
                   3672: 
                   3673: sub userlog_query {
                   3674:     my ($uname,$udom,%filters)=@_;
                   3675:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3676: }
                   3677: 
1.506     raeburn  3678: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3679: 
                   3680: sub auto_run {
1.508     raeburn  3681:     my ($cnum,$cdom) = @_;
                   3682:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3683:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3684:     return $response;
                   3685: }
                   3686:                                                                                    
                   3687: sub auto_get_sections {
1.508     raeburn  3688:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3689:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3690:     my @secs = ();
1.511     raeburn  3691:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3692:     unless ($response eq 'refused') {
                   3693:         @secs = split/:/,$response;
                   3694:     }
                   3695:     return @secs;
                   3696: }
                   3697:                                                                                    
                   3698: sub auto_new_course {
1.508     raeburn  3699:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3700:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3701:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3702:     return $response;
                   3703: }
                   3704:                                                                                    
                   3705: sub auto_validate_courseID {
1.508     raeburn  3706:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3707:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3708:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3709:     return $response;
                   3710: }
                   3711:                                                                                    
                   3712: sub auto_create_password {
1.508     raeburn  3713:     my ($cnum,$cdom,$authparam) = @_;
                   3714:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3715:     my $create_passwd = 0;
                   3716:     my $authchk = '';
1.511     raeburn  3717:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3718:     if ($response eq 'refused') {
                   3719:         $authchk = 'refused';
                   3720:     } else {
                   3721:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3722:     }
                   3723:     return ($authparam,$create_passwd,$authchk);
                   3724: }
                   3725: 
1.683.2.15  albertel 3726: sub auto_photo_permission {
                   3727:     my ($cnum,$cdom,$students) = @_;
                   3728:     my $homeserver = &homeserver($cnum,$cdom);
                   3729:     my ($outcome,$perm_reqd,$conditions) = 
                   3730: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.683.2.17  albertel 3731:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3732: 	return (undef,undef);
                   3733:     }
1.683.2.15  albertel 3734:     return ($outcome,$perm_reqd,$conditions);
                   3735: }
                   3736: 
                   3737: sub auto_checkphotos {
                   3738:     my ($uname,$udom,$pid) = @_;
                   3739:     my $homeserver = &homeserver($uname,$udom);
                   3740:     my ($result,$resulttype);
                   3741:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
                   3742: 				   &escape($uname).':'.&escape($pid),
                   3743: 				   $homeserver));
1.683.2.17  albertel 3744:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3745: 	return (undef,undef);
                   3746:     }
1.683.2.15  albertel 3747:     if ($outcome) {
                   3748:         ($result,$resulttype) = split(/:/,$outcome);
                   3749:     } 
                   3750:     return ($result,$resulttype);
                   3751: }
                   3752: 
                   3753: sub auto_photochoice {
                   3754:     my ($cnum,$cdom) = @_;
                   3755:     my $homeserver = &homeserver($cnum,$cdom);
                   3756:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
                   3757: 						       &escape($cdom),
                   3758: 						       $homeserver)));
1.683.2.17  albertel 3759:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3760: 	return (undef,undef);
                   3761:     }
1.683.2.15  albertel 3762:     return ($update,$comment);
                   3763: }
                   3764: 
                   3765: sub auto_photoupdate {
                   3766:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   3767:     my $homeserver = &homeserver($cnum,$dom);
                   3768:     my $host=$hostname{$homeserver};
                   3769:     my $cmd = '';
                   3770:     my $maxtries = 1;
                   3771:     foreach (keys %{$affiliatesref}) {
                   3772:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   3773:     }
                   3774:     $cmd =~ s/%%$//;
                   3775:     $cmd = &escape($cmd);
                   3776:     my $query = 'institutionalphotos';
                   3777:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   3778:     unless ($queryid=~/^\Q$host\E\_/) {
                   3779:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   3780:         return 'error: '.$queryid;
                   3781:     }
                   3782:     my $reply = &get_query_reply($queryid);
                   3783:     my $tries = 1;
                   3784:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3785:         $reply = &get_query_reply($queryid);
                   3786:         $tries ++;
                   3787:     }
                   3788:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   3789:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   3790:     } else {
                   3791:         my @responses = split(/:/,$reply);
                   3792:         my $outcome = shift(@responses); 
                   3793:         foreach my $item (@responses) {
                   3794:             my ($key,$value) = split(/=/,$item);
                   3795:             $$photo{$key} = $value;
                   3796:         }
                   3797:         return $outcome;
                   3798:     }
                   3799:     return 'error';
                   3800: }
                   3801: 
1.521     raeburn  3802: sub auto_instcode_format {
                   3803:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3804:     my $courses = '';
                   3805:     my $homeserver;
                   3806:     if ($caller eq 'global') {
1.584     raeburn  3807:         foreach my $tryserver (keys %libserv) {
                   3808:             if ($hostdom{$tryserver} eq $codedom) {
                   3809:                 $homeserver = $tryserver;
                   3810:                 last;
                   3811:             }
                   3812:         }
1.620     albertel 3813:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3814:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3815:         }
1.521     raeburn  3816:     } else {
                   3817:         $homeserver = &homeserver($caller,$codedom);
                   3818:     }
                   3819:     foreach (keys %{$instcodes}) {
                   3820:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3821:     }
                   3822:     chop($courses);
                   3823:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3824:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3825:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3826:         %{$codes} = &str2hash($codes_str);
                   3827:         @{$codetitles} = &str2array($codetitles_str);
                   3828:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3829:         %{$cat_order} = &str2hash($cat_order_str);
                   3830:         return 'ok';
                   3831:     }
                   3832:     return $response;
                   3833: }
                   3834: 
1.679     raeburn  3835: # ------------------------------------------------------- Course Group routines
                   3836: 
                   3837: sub get_coursegroups {
1.683     raeburn  3838:     my ($cdom,$cnum,$group) = @_;
                   3839:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  3840: }
                   3841: 
                   3842: sub modify_coursegroup {
                   3843:     my ($cdom,$cnum,$groupsettings) = @_;
                   3844:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   3845: }
                   3846: 
                   3847: sub modify_group_roles {
                   3848:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   3849:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   3850:     my $role = 'gr/'.&escape($userprivs);
                   3851:     my ($uname,$udom) = split(/:/,$user);
                   3852:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
                   3853:     return $result;
                   3854: }
                   3855: 
                   3856: sub modify_coursegroup_membership {
                   3857:     my ($cdom,$cnum,$membership) = @_;
                   3858:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   3859:     return $result;
                   3860: }
                   3861: 
1.682     raeburn  3862: sub get_active_groups {
                   3863:     my ($udom,$uname,$cdom,$cnum) = @_;
                   3864:     my $now = time;
                   3865:     my %groups = ();
                   3866:     foreach my $key (keys(%env)) {
                   3867:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   3868:             my ($start,$end) = split(/\./,$env{$key});
                   3869:             if (($end!=0) && ($end<$now)) { next; }
                   3870:             if (($start!=0) && ($start>$now)) { next; }
                   3871:             if ($1 eq $cdom && $2 eq $cnum) {
                   3872:                 $groups{$3} = $env{$key} ;
                   3873:             }
                   3874:         }
                   3875:     }
                   3876:     return %groups;
                   3877: }
                   3878: 
1.683     raeburn  3879: sub get_group_membership {
                   3880:     my ($cdom,$cnum,$group) = @_;
                   3881:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   3882: }
                   3883: 
                   3884: sub get_users_groups {
                   3885:     my ($udom,$uname,$courseid) = @_;
                   3886:     my $cachetime=1800;
                   3887:     $courseid=~s/\_/\//g;
                   3888:     $courseid=~s/^(\w)/\/$1/;
                   3889: 
                   3890:     my $hashid="$udom:$uname:$courseid";
                   3891:     my ($result,$cached)=&is_cached_new('getgroups',$hashid);
                   3892:     if (defined($cached)) { return $result; }
                   3893: 
                   3894:     my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   3895:     my ($tmp) = keys(%roleshash);
                   3896:     if ($tmp=~/^error:/) {
                   3897:         &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   3898:         return '';
                   3899:     } else {
                   3900:         my $grouplist;
                   3901:         foreach my $key (keys %roleshash) {
                   3902:             if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   3903:                 unless ($roleshash{$key} =~ /_1_1$/) {   # deleted membership
                   3904:                     $grouplist .= $1.':';
                   3905:                 }
                   3906:             }
                   3907:         }
                   3908:         $grouplist =~ s/:$//;
                   3909:         return &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
                   3910:     }
                   3911: }
                   3912: 
                   3913: sub devalidate_getgroups_cache {
                   3914:     my ($udom,$uname,$cdom,$cnum)=@_;
                   3915:     my $courseid = $cdom.'_'.$cnum;
                   3916:     $courseid=~s/\_/\//g;
                   3917:     $courseid=~s/^(\w)/\/$1/;
                   3918:     my $hashid="$udom:$uname:$courseid";
                   3919:     &devalidate_cache_new('getgroups',$hashid);
                   3920: }
                   3921: 
1.12      www      3922: # ------------------------------------------------------------------ Plain Text
                   3923: 
                   3924: sub plaintext {
1.22      www      3925:     my $short=shift;
1.676     albertel 3926:     return &Apache::lonlocal::mt($prp{$short});
1.12      www      3927: }
                   3928: 
                   3929: # ----------------------------------------------------------------- Assign Role
                   3930: 
                   3931: sub assignrole {
1.357     www      3932:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      3933:     my $mrole;
                   3934:     if ($role =~ /^cr\//) {
1.393     www      3935:         my $cwosec=$url;
                   3936:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   3937: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      3938:            &logthis('Refused custom assignrole: '.
                   3939:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 3940: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      3941:            return 'refused'; 
                   3942:         }
1.21      www      3943:         $mrole='cr';
1.678     raeburn  3944:     } elsif ($role =~ /^gr\//) {
                   3945:         my $cwogrp=$url;
                   3946:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   3947:         unless (&allowed('mdg',$cwogrp)) {
                   3948:             &logthis('Refused group assignrole: '.
                   3949:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   3950:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   3951:             return 'refused';
                   3952:         }
                   3953:         $mrole='gr';
1.21      www      3954:     } else {
1.82      www      3955:         my $cwosec=$url;
1.83      www      3956:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      3957:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      3958:            &logthis('Refused assignrole: '.
                   3959:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 3960: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      3961:            return 'refused'; 
                   3962:         }
1.21      www      3963:         $mrole=$role;
                   3964:     }
1.620     albertel 3965:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3966:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      3967:     if ($end) { $command.='_'.$end; }
1.21      www      3968:     if ($start) {
                   3969: 	if ($end) { 
1.81      www      3970:            $command.='_'.$start; 
1.21      www      3971:         } else {
1.81      www      3972:            $command.='_0_'.$start;
1.21      www      3973:         }
                   3974:     }
1.357     www      3975: # actually delete
                   3976:     if ($deleteflag) {
1.373     www      3977: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      3978: # modify command to delete the role
1.620     albertel 3979:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      3980:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 3981: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      3982: # set start and finish to negative values for userrolelog
                   3983:            $start=-1;
                   3984:            $end=-1;
                   3985:         }
                   3986:     }
                   3987: # send command
1.349     www      3988:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      3989: # log new user role if status is ok
1.349     www      3990:     if ($answer eq 'ok') {
1.663     raeburn  3991: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.349     www      3992:     }
                   3993:     return $answer;
1.169     harris41 3994: }
                   3995: 
                   3996: # -------------------------------------------------- Modify user authentication
1.197     www      3997: # Overrides without validation
                   3998: 
1.169     harris41 3999: sub modifyuserauth {
                   4000:     my ($udom,$uname,$umode,$upass)=@_;
                   4001:     my $uhome=&homeserver($uname,$udom);
1.197     www      4002:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4003:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4004:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4005:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4006:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4007: 		     &escape($upass),$uhome);
1.620     albertel 4008:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4009:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4010:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4011:     &log($udom,,$uname,$uhome,
1.620     albertel 4012:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4013:                                      $env{'user.name'}.', '.$umode.
1.197     www      4014:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4015:     unless ($reply eq 'ok') {
1.197     www      4016:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4017: 	return 'error: '.$reply;
                   4018:     }   
1.170     harris41 4019:     return 'ok';
1.80      www      4020: }
                   4021: 
1.81      www      4022: # --------------------------------------------------------------- Modify a user
1.80      www      4023: 
1.81      www      4024: sub modifyuser {
1.206     matthew  4025:     my ($udom,    $uname, $uid,
                   4026:         $umode,   $upass, $first,
                   4027:         $middle,  $last,  $gene,
1.387     www      4028:         $forceid, $desiredhome, $email)=@_;
1.198     www      4029:     $udom=~s/\W//g;
                   4030:     $uname=~s/\W//g;
1.81      www      4031:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4032:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4033: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4034:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4035:                                      ' desiredhome not specified'). 
1.620     albertel 4036:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4037:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4038:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4039: # ----------------------------------------------------------------- Create User
1.406     albertel 4040:     if (($uhome eq 'no_host') && 
                   4041: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4042:         my $unhome='';
1.209     matthew  4043:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4044:             $unhome = $desiredhome;
1.620     albertel 4045: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4046: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4047:         } else { # load balancing routine for determining $unhome
1.80      www      4048:             my $tryserver;
1.81      www      4049:             my $loadm=10000000;
1.80      www      4050:             foreach $tryserver (keys %libserv) {
                   4051: 	       if ($hostdom{$tryserver} eq $udom) {
                   4052:                   my $answer=reply('load',$tryserver);
                   4053:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4054: 		      $loadm=$answer;
                   4055:                       $unhome=$tryserver;
                   4056:                   }
                   4057: 	       }
                   4058: 	    }
                   4059:         }
                   4060:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4061: 	    return 'error: unable to find a home server for '.$uname.
                   4062:                    ' in domain '.$udom;
1.80      www      4063:         }
                   4064:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4065:                          &escape($upass),$unhome);
                   4066: 	unless ($reply eq 'ok') {
                   4067:             return 'error: '.$reply;
                   4068:         }   
1.230     stredwic 4069:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4070:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4071: 	    return 'error: unable verify users home machine.';
1.80      www      4072:         }
1.209     matthew  4073:     }   # End of creation of new user
1.80      www      4074: # ---------------------------------------------------------------------- Add ID
                   4075:     if ($uid) {
                   4076:        $uid=~tr/A-Z/a-z/;
                   4077:        my %uidhash=&idrget($udom,$uname);
1.196     www      4078:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4079:          && (!$forceid)) {
1.80      www      4080: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4081: 	      return 'error: user id "'.$uid.'" does not match '.
                   4082:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4083:           }
                   4084:        } else {
                   4085: 	  &idput($udom,($uname => $uid));
                   4086:        }
                   4087:     }
                   4088: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4089:     my @tmp=&get('environment',
1.134     albertel 4090: 		   ['firstname','middlename','lastname','generation'],
                   4091: 		   $udom,$uname);
1.313     matthew  4092:     my %names;
                   4093:     if ($tmp[0] =~ m/^error:.*/) { 
                   4094:         %names=(); 
                   4095:     } else {
                   4096:         %names = @tmp;
                   4097:     }
1.388     www      4098: #
                   4099: # Make sure to not trash student environment if instructor does not bother
                   4100: # to supply name and email information
                   4101: #
                   4102:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4103:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4104:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4105:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4106:     if ($email) {
                   4107:        $email=~s/[^\w\@\.\-\,]//gs;
                   4108:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4109: 			   $names{'critnotification'} = $email;
                   4110: 			   $names{'permanentemail'} = $email; }
                   4111:     }
1.134     albertel 4112:     my $reply = &put('environment', \%names, $udom,$uname);
                   4113:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4114:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4115:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4116:              $umode.', '.$first.', '.$middle.', '.
                   4117: 	     $last.', '.$gene.' by '.
1.620     albertel 4118:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4119:     return 'ok';
1.80      www      4120: }
                   4121: 
1.81      www      4122: # -------------------------------------------------------------- Modify student
1.80      www      4123: 
1.81      www      4124: sub modifystudent {
                   4125:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4126:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4127:     if (!$cid) {
1.620     albertel 4128: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4129: 	    return 'not_in_class';
                   4130: 	}
1.80      www      4131:     }
                   4132: # --------------------------------------------------------------- Make the user
1.81      www      4133:     my $reply=&modifyuser
1.209     matthew  4134: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4135:          $desiredhome,$email);
1.80      www      4136:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4137:     # This will cause &modify_student_enrollment to get the uid from the
                   4138:     # students environment
                   4139:     $uid = undef if (!$forceid);
1.455     albertel 4140:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4141: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4142:     return $reply;
                   4143: }
                   4144: 
                   4145: sub modify_student_enrollment {
1.515     raeburn  4146:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4147:     my ($cdom,$cnum,$chome);
                   4148:     if (!$cid) {
1.620     albertel 4149: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4150: 	    return 'not_in_class';
                   4151: 	}
1.620     albertel 4152: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4153: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4154:     } else {
                   4155: 	($cdom,$cnum)=split(/_/,$cid);
                   4156:     }
1.620     albertel 4157:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4158:     if (!$chome) {
1.457     raeburn  4159: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4160:     }
1.455     albertel 4161:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4162:     # Make sure the user exists
1.81      www      4163:     my $uhome=&homeserver($uname,$udom);
                   4164:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4165: 	return 'error: no such user';
                   4166:     }
1.297     matthew  4167:     # Get student data if we were not given enough information
                   4168:     if (!defined($first)  || $first  eq '' || 
                   4169:         !defined($last)   || $last   eq '' || 
                   4170:         !defined($uid)    || $uid    eq '' || 
                   4171:         !defined($middle) || $middle eq '' || 
                   4172:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4173:         # They did not supply us with enough data to enroll the student, so
                   4174:         # we need to pick up more information.
1.297     matthew  4175:         my %tmp = &get('environment',
1.294     matthew  4176:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4177:                        ,$udom,$uname);
                   4178: 
1.455     albertel 4179:         #foreach (keys(%tmp)) {
                   4180:         #    &logthis("key $_ = ".$tmp{$_});
                   4181:         #}
1.294     matthew  4182:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4183:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4184:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4185:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4186:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4187:     }
1.556     albertel 4188:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4189:     my $reply=cput('classlist',
                   4190: 		   {"$uname:$udom" => 
1.515     raeburn  4191: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4192: 		   $cdom,$cnum);
1.81      www      4193:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4194: 	return 'error: '.$reply;
1.652     albertel 4195:     } else {
                   4196: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4197:     }
1.297     matthew  4198:     # Add student role to user
1.83      www      4199:     my $uurl='/'.$cid;
1.81      www      4200:     $uurl=~s/\_/\//g;
                   4201:     if ($usec) {
                   4202: 	$uurl.='/'.$usec;
                   4203:     }
                   4204:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4205: }
                   4206: 
1.556     albertel 4207: sub format_name {
                   4208:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4209:     my $name;
                   4210:     if ($first ne 'lastname') {
                   4211: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4212:     } else {
                   4213: 	if ($lastname=~/\S/) {
                   4214: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4215: 	    $name=~s/\s+,/,/;
                   4216: 	} else {
                   4217: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4218: 	}
                   4219:     }
                   4220:     $name=~s/^\s+//;
                   4221:     $name=~s/\s+$//;
                   4222:     $name=~s/\s+/ /g;
                   4223:     return $name;
                   4224: }
                   4225: 
1.84      www      4226: # ------------------------------------------------- Write to course preferences
                   4227: 
                   4228: sub writecoursepref {
                   4229:     my ($courseid,%prefs)=@_;
                   4230:     $courseid=~s/^\///;
                   4231:     $courseid=~s/\_/\//g;
                   4232:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4233:     my $chome=homeserver($cnum,$cdomain);
                   4234:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4235: 	return 'error: no such course';
                   4236:     }
                   4237:     my $cstring='';
1.191     harris41 4238:     foreach (keys %prefs) {
1.84      www      4239: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4240:     }
1.84      www      4241:     $cstring=~s/\&$//;
                   4242:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4243: }
                   4244: 
                   4245: # ---------------------------------------------------------- Make/modify course
                   4246: 
                   4247: sub createcourse {
1.571     raeburn  4248:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84      www      4249:     $url=&declutter($url);
                   4250:     my $cid='';
1.264     matthew  4251:     unless (&allowed('ccc',$udom)) {
1.84      www      4252:         return 'refused';
                   4253:     }
                   4254: # ------------------------------------------------------------------- Create ID
1.674     www      4255:    my $uname=int(1+rand(9)).
                   4256:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4257:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4258:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4259: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4260:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4261:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4262:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4263:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4264:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4265:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4266:            return 'error: unable to generate unique course-ID';
                   4267:        } 
                   4268:    }
1.264     matthew  4269: # ------------------------------------------------ Check supplied server name
1.620     albertel 4270:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4271:     if (! exists($libserv{$course_server})) {
                   4272:         return 'error:bad server name '.$course_server;
                   4273:     }
1.84      www      4274: # ------------------------------------------------------------- Make the course
                   4275:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4276:                       $course_server);
1.84      www      4277:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4278:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4279:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4280: 	return 'error: no such course';
                   4281:     }
1.271     www      4282: # ----------------------------------------------------------------- Course made
1.516     raeburn  4283: # log existence
                   4284:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571     raeburn  4285:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358     www      4286:     &flushcourselogs();
                   4287: # set toplevel url
1.271     www      4288:     my $topurl=$url;
                   4289:     unless ($nonstandard) {
                   4290: # ------------------------------------------ For standard courses, make top url
                   4291:         my $mapurl=&clutter($url);
1.278     www      4292:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4293:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4294: <map>
                   4295: <resource id="1" type="start"></resource>
                   4296: <resource id="2" src="$mapurl"></resource>
                   4297: <resource id="3" type="finish"></resource>
                   4298: <link index="1" from="1" to="2"></link>
                   4299: <link index="2" from="2" to="3"></link>
                   4300: </map>
                   4301: ENDINITMAP
                   4302:         $topurl=&declutter(
1.638     albertel 4303:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4304:                           );
                   4305:     }
                   4306: # ----------------------------------------------------------- Write preferences
1.84      www      4307:     &writecoursepref($udom.'_'.$uname,
                   4308:                      ('description' => $description,
1.271     www      4309:                       'url'         => $topurl));
1.84      www      4310:     return '/'.$udom.'/'.$uname;
                   4311: }
                   4312: 
1.21      www      4313: # ---------------------------------------------------------- Assign Custom Role
                   4314: 
                   4315: sub assigncustomrole {
1.357     www      4316:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4317:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4318:                        $end,$start,$deleteflag);
1.21      www      4319: }
                   4320: 
                   4321: # ----------------------------------------------------------------- Revoke Role
                   4322: 
                   4323: sub revokerole {
1.357     www      4324:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4325:     my $now=time;
1.357     www      4326:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4327: }
                   4328: 
                   4329: # ---------------------------------------------------------- Revoke Custom Role
                   4330: 
                   4331: sub revokecustomrole {
1.357     www      4332:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4333:     my $now=time;
1.357     www      4334:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4335:            $deleteflag);
1.17      www      4336: }
                   4337: 
1.533     banghart 4338: # ------------------------------------------------------------ Disk usage
1.535     albertel 4339: sub diskusage {
1.533     banghart 4340:     my ($udom,$uname,$directoryRoot)=@_;
                   4341:     $directoryRoot =~ s/\/$//;
1.535     albertel 4342:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4343:     return $listing;
1.512     banghart 4344: }
                   4345: 
1.566     banghart 4346: sub is_locked {
                   4347:     my ($file_name, $domain, $user) = @_;
                   4348:     my @check;
                   4349:     my $is_locked;
                   4350:     push @check, $file_name;
1.613     albertel 4351:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4352: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4353:     my ($tmp)=keys(%locked);
                   4354:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 4355: 
1.566     banghart 4356:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   4357:         $is_locked = 'true';
                   4358:     } else {
                   4359:         $is_locked = 'false';
                   4360:     }
                   4361: }
                   4362: 
1.559     banghart 4363: # ------------------------------------------------------------- Mark as Read Only
                   4364: 
                   4365: sub mark_as_readonly {
                   4366:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4367:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4368:     my ($tmp)=keys(%current_permissions);
                   4369:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4370:     foreach my $file (@{$files}) {
1.561     banghart 4371:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4372:     }
1.613     albertel 4373:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4374:     return;
                   4375: }
                   4376: 
1.572     banghart 4377: # ------------------------------------------------------------Save Selected Files
                   4378: 
                   4379: sub save_selected_files {
                   4380:     my ($user, $path, @files) = @_;
                   4381:     my $filename = $user."savedfiles";
1.573     banghart 4382:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4383:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4384:     foreach my $file (@files) {
1.620     albertel 4385:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4386:     }
                   4387:     foreach my $file (@other_files) {
1.574     banghart 4388:         print (OUT $file."\n");
1.572     banghart 4389:     }
1.574     banghart 4390:     close (OUT);
1.572     banghart 4391:     return 'ok';
                   4392: }
                   4393: 
1.574     banghart 4394: sub clear_selected_files {
                   4395:     my ($user) = @_;
                   4396:     my $filename = $user."savedfiles";
                   4397:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4398:     print (OUT undef);
                   4399:     close (OUT);
                   4400:     return ("ok");    
                   4401: }
                   4402: 
1.572     banghart 4403: sub files_in_path {
                   4404:     my ($user, $path) = @_;
                   4405:     my $filename = $user."savedfiles";
                   4406:     my %return_files;
1.574     banghart 4407:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4408:     while (my $line_in = <IN>) {
1.574     banghart 4409:         chomp ($line_in);
                   4410:         my @paths_and_file = split (m!/!, $line_in);
                   4411:         my $file_part = pop (@paths_and_file);
                   4412:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4413:         $path_part.='/';
                   4414:         my $path_and_file = $path_part.$file_part;
                   4415:         if ($path_part eq $path) {
                   4416:             $return_files{$file_part}= 'selected';
                   4417:         }
                   4418:     }
1.574     banghart 4419:     close (IN);
                   4420:     return (\%return_files);
1.572     banghart 4421: }
                   4422: 
                   4423: # called in portfolio select mode, to show files selected NOT in current directory
                   4424: sub files_not_in_path {
                   4425:     my ($user, $path) = @_;
                   4426:     my $filename = $user."savedfiles";
                   4427:     my @return_files;
                   4428:     my $path_part;
1.574     banghart 4429:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4430:     while (<IN>) {
                   4431:         #ok, I know it's clunky, but I want it to work
                   4432:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4433:         my $file_part = pop (@paths_and_file);
                   4434:         chomp ($file_part);
                   4435:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4436:         $path_part .= '/';
                   4437:         my $path_and_file = $path_part.$file_part;
                   4438:         if ($path_part ne $path) {
1.574     banghart 4439:             push (@return_files, ($path_and_file));
1.572     banghart 4440:         }
                   4441:     }
1.574     banghart 4442:     close (OUT);
                   4443:     return (@return_files);
1.572     banghart 4444: }
                   4445: 
1.561     banghart 4446: #--------------------------------------------------------------Get Marked as Read Only
                   4447: 
1.629     banghart 4448: 
1.561     banghart 4449: sub get_marked_as_readonly {
                   4450:     my ($domain,$user,$what) = @_;
1.613     albertel 4451:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4452:     my ($tmp)=keys(%current_permissions);
                   4453:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.563     banghart 4454:     my @readonly_files;
1.629     banghart 4455:     my $cmp1=$what;
                   4456:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.563     banghart 4457:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 4458:         if (ref($value) eq "ARRAY"){
                   4459:             foreach my $stored_what (@{$value}) {
1.629     banghart 4460:                 my $cmp2=$stored_what;
                   4461:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
                   4462:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4463:                     push(@readonly_files, $file_name);
1.563     banghart 4464:                 } elsif (!defined($what)) {
                   4465:                     push(@readonly_files, $file_name);
1.561     banghart 4466:                 }
                   4467:             }
                   4468:         } 
                   4469:     }
                   4470:     return @readonly_files;
                   4471: }
1.577     banghart 4472: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4473: 
1.577     banghart 4474: sub get_marked_as_readonly_hash {
                   4475:     my ($domain,$user,$what) = @_;
1.613     albertel 4476:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4477:     my ($tmp)=keys(%current_permissions);
                   4478:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4479: 
1.577     banghart 4480:     my %readonly_files;
                   4481:     while (my ($file_name,$value) = each(%current_permissions)) {
                   4482:         if (ref($value) eq "ARRAY"){
                   4483:             foreach my $stored_what (@{$value}) {
                   4484:                 if ($stored_what eq $what) {
                   4485:                     $readonly_files{$file_name} = 'locked';
                   4486:                 } elsif (!defined($what)) {
                   4487:                     $readonly_files{$file_name} = 'locked';
                   4488:                 }
                   4489:             }
                   4490:         } 
                   4491:     }
                   4492:     return %readonly_files;
                   4493: }
1.559     banghart 4494: # ------------------------------------------------------------ Unmark as Read Only
                   4495: 
                   4496: sub unmark_as_readonly {
1.629     banghart 4497:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4498:     # for portfolio submissions, $what contains [$symb,$crsid] 
                   4499:     my ($domain,$user,$what,$file_name) = @_;
1.634     albertel 4500:     my $symb_crs = $what;
                   4501:     if (ref($what)) { $symb_crs=join('',@$what); }
1.613     albertel 4502:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4503:     my ($tmp)=keys(%current_permissions);
                   4504:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4505:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.650     albertel 4506:     foreach my $file (@readonly_files) {
                   4507: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4508: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4509:         my @new_locks;
                   4510:         my @del_keys;
                   4511:         if (ref($current_locks) eq "ARRAY"){
                   4512:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4513:                 my $compare=$locker;
                   4514:                 if (ref($locker)) { $compare=join('',@{$locker}) };
1.650     albertel 4515:                 if ($compare ne $symb_crs) {
                   4516:                     push(@new_locks, $locker);
1.563     banghart 4517:                 }
                   4518:             }
1.650     albertel 4519:             if (scalar(@new_locks) > 0) {
1.563     banghart 4520:                 $current_permissions{$file} = \@new_locks;
                   4521:             } else {
                   4522:                 push(@del_keys, $file);
1.613     albertel 4523:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4524:                 delete($current_permissions{$file});
1.563     banghart 4525:             }
                   4526:         }
1.561     banghart 4527:     }
1.613     albertel 4528:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4529:     return;
                   4530: }
1.512     banghart 4531: 
1.17      www      4532: # ------------------------------------------------------------ Directory lister
                   4533: 
                   4534: sub dirlist {
1.253     stredwic 4535:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4536: 
1.18      www      4537:     $uri=~s/^\///;
                   4538:     $uri=~s/\/$//;
1.253     stredwic 4539:     my ($udom, $uname);
                   4540:     (undef,$udom,$uname)=split(/\//,$uri);
                   4541:     if(defined($userdomain)) {
                   4542:         $udom = $userdomain;
                   4543:     }
                   4544:     if(defined($username)) {
                   4545:         $uname = $username;
                   4546:     }
                   4547: 
                   4548:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4549:     if(defined($alternateDirectoryRoot)) {
                   4550:         $dirRoot = $alternateDirectoryRoot;
                   4551:         $dirRoot =~ s/\/$//;
                   4552:     }
                   4553: 
                   4554:     if($udom) {
                   4555:         if($uname) {
1.605     matthew  4556:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4557:                               homeserver($uname,$udom));
1.605     matthew  4558:             my @listing_results;
                   4559:             if ($listing eq 'unknown_cmd') {
                   4560:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4561:                                homeserver($uname,$udom));
                   4562:                 @listing_results = split(/:/,$listing);
                   4563:             } else {
                   4564:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4565:             }
                   4566:             return @listing_results;
1.253     stredwic 4567:         } elsif(!defined($alternateDirectoryRoot)) {
                   4568:             my $tryserver;
                   4569:             my %allusers=();
                   4570:             foreach $tryserver (keys %libserv) {
                   4571:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  4572:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 4573:                                       $udom, $tryserver);
1.605     matthew  4574:                     my @listing_results;
                   4575:                     if ($listing eq 'unknown_cmd') {
                   4576:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   4577:                                        $udom, $tryserver);
                   4578:                         @listing_results = split(/:/,$listing);
                   4579:                     } else {
                   4580:                         @listing_results =
                   4581:                             map { &unescape($_); } split(/:/,$listing);
                   4582:                     }
                   4583:                     if ($listing_results[0] ne 'no_such_dir' && 
                   4584:                         $listing_results[0] ne 'empty'       &&
                   4585:                         $listing_results[0] ne 'con_lost') {
                   4586:                         foreach (@listing_results) {
1.253     stredwic 4587:                             my ($entry,@stat)=split(/&/,$_);
                   4588:                             $allusers{$entry}=1;
                   4589:                         }
                   4590:                     }
1.191     harris41 4591:                 }
1.253     stredwic 4592:             }
                   4593:             my $alluserstr='';
                   4594:             foreach (sort keys %allusers) {
                   4595:                 $alluserstr.=$_.'&user:';
                   4596:             }
                   4597:             $alluserstr=~s/:$//;
                   4598:             return split(/:/,$alluserstr);
                   4599:         } else {
                   4600:             my @emptyResults = ();
                   4601:             push(@emptyResults, 'missing user name');
                   4602:             return split(':',@emptyResults);
                   4603:         }
                   4604:     } elsif(!defined($alternateDirectoryRoot)) {
                   4605:         my $tryserver;
                   4606:         my %alldom=();
                   4607:         foreach $tryserver (keys %libserv) {
                   4608:             $alldom{$hostdom{$tryserver}}=1;
                   4609:         }
                   4610:         my $alldomstr='';
                   4611:         foreach (sort keys %alldom) {
1.397     albertel 4612:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4613:         }
                   4614:         $alldomstr=~s/:$//;
                   4615:         return split(/:/,$alldomstr);       
                   4616:     } else {
                   4617:         my @emptyResults = ();
                   4618:         push(@emptyResults, 'missing domain');
                   4619:         return split(':',@emptyResults);
1.275     stredwic 4620:     }
                   4621: }
                   4622: 
                   4623: # --------------------------------------------- GetFileTimestamp
                   4624: # This function utilizes dirlist and returns the date stamp for
                   4625: # when it was last modified.  It will also return an error of -1
                   4626: # if an error occurs
                   4627: 
1.410     matthew  4628: ##
                   4629: ## FIXME: This subroutine assumes its caller knows something about the
                   4630: ## directory structure of the home server for the student ($root).
                   4631: ## Not a good assumption to make.  Since this is for looking up files
                   4632: ## in user directories, the full path should be constructed by lond, not
                   4633: ## whatever machine we request data from.
                   4634: ##
1.275     stredwic 4635: sub GetFileTimestamp {
                   4636:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4637:     $studentDomain=~s/\W//g;
                   4638:     $studentName=~s/\W//g;
                   4639:     my $subdir=$studentName.'__';
                   4640:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4641:     my $proname="$studentDomain/$subdir/$studentName";
                   4642:     $proname .= '/'.$filename;
1.375     matthew  4643:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4644:                                               $studentName, $root);
1.275     stredwic 4645:     my @stats = split('&', $fileStat);
                   4646:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4647:         # @stats contains first the filename, then the stat output
                   4648:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4649:     } else {
                   4650:         return -1;
1.253     stredwic 4651:     }
1.26      www      4652: }
                   4653: 
                   4654: # -------------------------------------------------------- Value of a Condition
                   4655: 
1.683.2.19  albertel 4656: # gets the value of a specific preevaluated condition
                   4657: #    stored in the string  $env{user.state.<cid>}
                   4658: # or looks up a condition reference in the bighash and if if hasn't
                   4659: # already been evaluated recurses into docondval to get the value of
                   4660: # the condition, then memoizing it to 
                   4661: #   $env{user.state.<cid>.<condition>}
1.40      www      4662: sub directcondval {
                   4663:     my $number=shift;
1.620     albertel 4664:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4665: 	&Apache::lonuserstate::evalstate();
                   4666:     }
1.683.2.19  albertel 4667:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   4668: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   4669:     } elsif ($number =~ /^_/) {
                   4670: 	my $sub_condition;
                   4671: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   4672: 		&GDBM_READER(),0640)) {
                   4673: 	    $sub_condition=$bighash{'conditions'.$number};
                   4674: 	    untie(%bighash);
                   4675: 	}
                   4676: 	my $value = &docondval($sub_condition);
                   4677: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   4678: 	return $value;
                   4679:     }
1.620     albertel 4680:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4681:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4682:     } else {
                   4683:        return 2;
                   4684:     }
                   4685: }
                   4686: 
1.683.2.19  albertel 4687: # get the collection of conditions for this resource
1.26      www      4688: sub condval {
                   4689:     my $condidx=shift;
1.54      www      4690:     my $allpathcond='';
1.683.2.19  albertel 4691:     foreach my $cond (split(/\|/,$condidx)) {
                   4692: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   4693: 	    $allpathcond.=
                   4694: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   4695: 	}
1.191     harris41 4696:     }
1.54      www      4697:     $allpathcond=~s/\|$//;
1.683.2.19  albertel 4698:     return &docondval($allpathcond);
                   4699: }
                   4700: 
                   4701: #evaluates an expression of conditions
                   4702: sub docondval {
                   4703:     my ($allpathcond) = @_;
                   4704:     my $result=0;
                   4705:     if ($env{'request.course.id'}
                   4706: 	&& defined($allpathcond)) {
                   4707: 	my $operand='|';
                   4708: 	my @stack;
                   4709: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   4710: 	    if ($chunk eq '(') {
                   4711: 		push @stack,($operand,$result);
                   4712: 	    } elsif ($chunk eq ')') {
                   4713: 		my $before=pop @stack;
                   4714: 		if (pop @stack eq '&') {
                   4715: 		    $result=$result>$before?$before:$result;
                   4716: 		} else {
                   4717: 		    $result=$result>$before?$result:$before;
                   4718: 		}
                   4719: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   4720: 		$operand=$chunk;
                   4721: 	    } else {
                   4722: 		my $new=directcondval($chunk);
                   4723: 		if ($operand eq '&') {
                   4724: 		    $result=$result>$new?$new:$result;
                   4725: 		} else {
                   4726: 		    $result=$result>$new?$result:$new;
                   4727: 		}
                   4728: 	    }
                   4729: 	}
1.26      www      4730:     }
                   4731:     return $result;
1.421     albertel 4732: }
                   4733: 
                   4734: # ---------------------------------------------------- Devalidate courseresdata
                   4735: 
                   4736: sub devalidatecourseresdata {
                   4737:     my ($coursenum,$coursedomain)=@_;
                   4738:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4739:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4740: }
                   4741: 
1.200     www      4742: # --------------------------------------------------- Course Resourcedata Query
                   4743: 
1.624     albertel 4744: sub get_courseresdata {
                   4745:     my ($coursenum,$coursedomain)=@_;
1.200     www      4746:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4747:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4748:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 4749:     my %dumpreply;
1.417     albertel 4750:     unless (defined($cached)) {
1.624     albertel 4751: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4752: 	$result=\%dumpreply;
1.251     albertel 4753: 	my ($tmp) = keys(%dumpreply);
                   4754: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4755: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4756: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4757: 	    return $tmp;
1.416     albertel 4758: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4759: 	    $result=undef;
1.599     albertel 4760: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4761: 	}
                   4762:     }
1.624     albertel 4763:     return $result;
                   4764: }
                   4765: 
1.633     albertel 4766: sub devalidateuserresdata {
                   4767:     my ($uname,$udom)=@_;
                   4768:     my $hashid="$udom:$uname";
                   4769:     &devalidate_cache_new('userres',$hashid);
                   4770: }
                   4771: 
1.624     albertel 4772: sub get_userresdata {
                   4773:     my ($uname,$udom)=@_;
                   4774:     #most student don\'t have any data set, check if there is some data
                   4775:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   4776: 
                   4777:     my $hashid="$udom:$uname";
                   4778:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   4779:     if (!defined($cached)) {
                   4780: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   4781: 	$result=\%resourcedata;
                   4782: 	&do_cache_new('userres',$hashid,$result,600);
                   4783:     }
                   4784:     my ($tmp)=keys(%$result);
                   4785:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   4786: 	return $result;
                   4787:     }
                   4788:     #error 2 occurs when the .db doesn't exist
                   4789:     if ($tmp!~/error: 2 /) {
1.672     albertel 4790: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 4791: 		 " Trying to get resource data for ".
                   4792: 		 $uname." at ".$udom.": ".
                   4793: 		 $tmp."</font>");
                   4794:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 4795: 	#&EXT_cache_set($udom,$uname);
                   4796: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 4797: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 4798:     }
                   4799:     return $tmp;
                   4800: }
                   4801: 
                   4802: sub resdata {
                   4803:     my ($name,$domain,$type,@which)=@_;
                   4804:     my $result;
                   4805:     if ($type eq 'course') {
                   4806: 	$result=&get_courseresdata($name,$domain);
                   4807:     } elsif ($type eq 'user') {
                   4808: 	$result=&get_userresdata($name,$domain);
                   4809:     }
                   4810:     if (!ref($result)) { return $result; }    
1.251     albertel 4811:     foreach my $item (@which) {
1.417     albertel 4812: 	if (defined($result->{$item})) {
                   4813: 	    return $result->{$item};
1.251     albertel 4814: 	}
1.250     albertel 4815:     }
1.291     albertel 4816:     return undef;
1.200     www      4817: }
                   4818: 
1.379     matthew  4819: #
                   4820: # EXT resource caching routines
                   4821: #
                   4822: 
                   4823: sub clear_EXT_cache_status {
1.383     albertel 4824:     &delenv('cache.EXT.');
1.379     matthew  4825: }
                   4826: 
                   4827: sub EXT_cache_status {
                   4828:     my ($target_domain,$target_user) = @_;
1.383     albertel 4829:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 4830:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  4831:         # We know already the user has no data
                   4832:         return 1;
                   4833:     } else {
                   4834:         return 0;
                   4835:     }
                   4836: }
                   4837: 
                   4838: sub EXT_cache_set {
                   4839:     my ($target_domain,$target_user) = @_;
1.383     albertel 4840:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 4841:     #&appenv($cachename => time);
1.379     matthew  4842: }
                   4843: 
1.28      www      4844: # --------------------------------------------------------- Value of a Variable
1.58      www      4845: sub EXT {
1.395     albertel 4846:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218     albertel 4847: 
1.68      www      4848:     unless ($varname) { return ''; }
1.218     albertel 4849:     #get real user name/domain, courseid and symb
                   4850:     my $courseid;
1.359     albertel 4851:     my $publicuser;
1.427     www      4852:     if ($symbparm) {
                   4853: 	$symbparm=&get_symb_from_alias($symbparm);
                   4854:     }
1.218     albertel 4855:     if (!($uname && $udom)) {
1.360     albertel 4856:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  4857: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 4858:       if (!$symbparm) {	$symbparm=$cursymb; }
                   4859:     } else {
1.620     albertel 4860: 	$courseid=$env{'request.course.id'};
1.218     albertel 4861:     }
1.48      www      4862:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   4863:     my $rest;
1.320     albertel 4864:     if (defined($therest[0])) {
1.48      www      4865:        $rest=join('.',@therest);
                   4866:     } else {
                   4867:        $rest='';
                   4868:     }
1.320     albertel 4869: 
1.57      www      4870:     my $qualifierrest=$qualifier;
                   4871:     if ($rest) { $qualifierrest.='.'.$rest; }
                   4872:     my $spacequalifierrest=$space;
                   4873:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      4874:     if ($realm eq 'user') {
1.48      www      4875: # --------------------------------------------------------------- user.resource
                   4876: 	if ($space eq 'resource') {
1.651     albertel 4877: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   4878: 		  || defined($Apache::lonhomework::parsing_a_task))
                   4879: 		 &&
                   4880: 		 ($symbparm eq &symbread()) ) {
1.335     albertel 4881: 		return $Apache::lonhomework::history{$qualifierrest};
                   4882: 	    } else {
1.359     albertel 4883: 		my %restored;
1.620     albertel 4884: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 4885: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   4886: 		} else {
                   4887: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   4888: 		}
1.335     albertel 4889: 		return $restored{$qualifierrest};
                   4890: 	    }
1.48      www      4891: # ----------------------------------------------------------------- user.access
                   4892:         } elsif ($space eq 'access') {
1.218     albertel 4893: 	    # FIXME - not supporting calls for a specific user
1.48      www      4894:             return &allowed($qualifier,$rest);
                   4895: # ------------------------------------------ user.preferences, user.environment
                   4896:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 4897: 	    if (($uname eq $env{'user.name'}) &&
                   4898: 		($udom eq $env{'user.domain'})) {
                   4899: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 4900: 	    } else {
1.359     albertel 4901: 		my %returnhash;
                   4902: 		if (!$publicuser) {
                   4903: 		    %returnhash=&userenvironment($udom,$uname,
                   4904: 						 $qualifierrest);
                   4905: 		}
1.218     albertel 4906: 		return $returnhash{$qualifierrest};
                   4907: 	    }
1.48      www      4908: # ----------------------------------------------------------------- user.course
                   4909:         } elsif ($space eq 'course') {
1.218     albertel 4910: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 4911:             return $env{join('.',('request.course',$qualifier))};
1.48      www      4912: # ------------------------------------------------------------------- user.role
                   4913:         } elsif ($space eq 'role') {
1.218     albertel 4914: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 4915:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      4916:             if ($qualifier eq 'value') {
                   4917: 		return $role;
                   4918:             } elsif ($qualifier eq 'extent') {
                   4919:                 return $where;
                   4920:             }
                   4921: # ----------------------------------------------------------------- user.domain
                   4922:         } elsif ($space eq 'domain') {
1.218     albertel 4923:             return $udom;
1.48      www      4924: # ------------------------------------------------------------------- user.name
                   4925:         } elsif ($space eq 'name') {
1.218     albertel 4926:             return $uname;
1.48      www      4927: # ---------------------------------------------------- Any other user namespace
1.29      www      4928:         } else {
1.359     albertel 4929: 	    my %reply;
                   4930: 	    if (!$publicuser) {
                   4931: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   4932: 	    }
                   4933: 	    return $reply{$qualifierrest};
1.48      www      4934:         }
1.236     www      4935:     } elsif ($realm eq 'query') {
                   4936: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 4937:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   4938: 						[$spacequalifierrest]);
1.620     albertel 4939: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      4940:    } elsif ($realm eq 'request') {
1.48      www      4941: # ------------------------------------------------------------- request.browser
                   4942:         if ($space eq 'browser') {
1.430     www      4943: 	    if ($qualifier eq 'textremote') {
1.676     albertel 4944: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      4945: 		    return 1;
                   4946: 		} else {
                   4947: 		    return 0;
                   4948: 		}
                   4949: 	    } else {
1.620     albertel 4950: 		return $env{'browser.'.$qualifier};
1.430     www      4951: 	    }
1.57      www      4952: # ------------------------------------------------------------ request.filename
                   4953:         } else {
1.620     albertel 4954:             return $env{'request.'.$spacequalifierrest};
1.29      www      4955:         }
1.28      www      4956:     } elsif ($realm eq 'course') {
1.48      www      4957: # ---------------------------------------------------------- course.description
1.620     albertel 4958:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      4959:     } elsif ($realm eq 'resource') {
1.165     www      4960: 
1.395     albertel 4961: 	my $section;
1.620     albertel 4962: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 4963: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   4964: 	}
1.593     albertel 4965: 	my ($courselevelm,$courselevel);
1.539     albertel 4966: 	if ($symbparm && defined($courseid) && 
1.620     albertel 4967: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      4968: 
1.218     albertel 4969: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      4970: 
1.60      www      4971: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 4972: 	    my $symbp=$symbparm;
1.683.2.21! albertel 4973: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 4974: 
                   4975: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   4976: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   4977: 
1.620     albertel 4978: 	    if (($env{'user.name'} eq $uname) &&
                   4979: 		($env{'user.domain'} eq $udom)) {
                   4980: 		$section=$env{'request.course.sec'};
1.218     albertel 4981: 	    } else {
1.539     albertel 4982: 		if (! defined($usection)) {
1.551     albertel 4983: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 4984: 		} else {
                   4985: 		    $section = $usection;
                   4986: 		}
1.218     albertel 4987: 	    }
                   4988: 
                   4989: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   4990: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   4991: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   4992: 
1.593     albertel 4993: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 4994: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 4995: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      4996: 
1.60      www      4997: # ----------------------------------------------------------- first, check user
1.624     albertel 4998: 
                   4999: 	    my $userreply=&resdata($uname,$udom,'user',
                   5000: 				       ($courselevelr,$courselevelm,
                   5001: 					$courselevel));
                   5002: 
                   5003: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5004: 
1.594     albertel 5005: # ------------------------------------------------ second, check some of course
1.96      www      5006: 
1.624     albertel 5007: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5008: 				     $env{'course.'.$courseid.'.domain'},
                   5009: 				     'course',
                   5010: 				     ($seclevelr,$seclevelm,$seclevel,
                   5011: 				      $courselevelr));
1.287     albertel 5012: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5013: 
1.60      www      5014: # ------------------------------------------------------ third, check map parms
1.218     albertel 5015: 	    my %parmhash=();
                   5016: 	    my $thisparm='';
                   5017: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5018: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5019: 		    &GDBM_READER(),0640)) {
1.218     albertel 5020: 		$thisparm=$parmhash{$symbparm};
                   5021: 		untie(%parmhash);
                   5022: 	    }
                   5023: 	    if ($thisparm) { return $thisparm; }
                   5024: 	}
1.594     albertel 5025: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5026: 
1.218     albertel 5027: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5028: 	my $filename;
                   5029: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5030: 	if ($symbparm) {
1.409     www      5031: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5032: 	} else {
1.620     albertel 5033: 	    $filename=$env{'request.filename'};
1.282     albertel 5034: 	}
                   5035: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5036: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5037: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5038: 	if (defined($metadata)) { return $metadata; }
1.142     www      5039: 
1.594     albertel 5040: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5041: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5042: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5043: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5044: 				     $env{'course.'.$courseid.'.domain'},
                   5045: 				     'course',
                   5046: 				     ($courselevelm,$courselevel));
1.593     albertel 5047: 	    if (defined($coursereply)) { return $coursereply; }
                   5048: 	}
1.145     www      5049: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5050: 	unless ($space eq '0') {
1.336     albertel 5051: 	    my @parts=split(/_/,$space);
                   5052: 	    my $id=pop(@parts);
                   5053: 	    my $part=join('_',@parts);
                   5054: 	    if ($part eq '') { $part='0'; }
                   5055: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5056: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5057: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5058: 	}
1.395     albertel 5059: 	if ($recurse) { return undef; }
                   5060: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5061: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5062: 
1.48      www      5063: # ---------------------------------------------------- Any other user namespace
                   5064:     } elsif ($realm eq 'environment') {
                   5065: # ----------------------------------------------------------------- environment
1.620     albertel 5066: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5067: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5068: 	} else {
                   5069: 	    my %returnhash=&userenvironment($udom,$uname,
                   5070: 					    $spacequalifierrest);
                   5071: 	    return $returnhash{$spacequalifierrest};
                   5072: 	}
1.28      www      5073:     } elsif ($realm eq 'system') {
1.48      www      5074: # ----------------------------------------------------------------- system.time
                   5075: 	if ($space eq 'time') {
                   5076: 	    return time;
                   5077:         }
1.683.2.8  albertel 5078:     } elsif ($realm eq 'server') {
                   5079: # ----------------------------------------------------------------- system.time
                   5080: 	if ($space eq 'name') {
                   5081: 	    return $ENV{'SERVER_NAME'};
                   5082:         }
1.28      www      5083:     }
1.48      www      5084:     return '';
1.61      www      5085: }
                   5086: 
1.395     albertel 5087: sub packages_tab_default {
                   5088:     my ($uri,$varname)=@_;
                   5089:     my (undef,$part,$name)=split(/\./,$varname);
                   5090:     my $packages=&metadata($uri,'packages');
                   5091:     foreach my $package (split(/,/,$packages)) {
                   5092: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468     albertel 5093: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5094: 	    return $packagetab{"$pack_type&$name&default"};
                   5095: 	}
1.585     albertel 5096: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5097: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5098: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5099: 	}
                   5100:     }
                   5101:     return undef;
                   5102: }
                   5103: 
1.334     albertel 5104: sub add_prefix_and_part {
                   5105:     my ($prefix,$part)=@_;
                   5106:     my $keyroot;
                   5107:     if (defined($prefix) && $prefix !~ /^__/) {
                   5108: 	# prefix that has a part already
                   5109: 	$keyroot=$prefix;
                   5110:     } elsif (defined($prefix)) {
                   5111: 	# prefix that is missing a part
                   5112: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5113:     } else {
                   5114: 	# no prefix at all
                   5115: 	if (defined($part)) { $keyroot='_'.$part; }
                   5116:     }
                   5117:     return $keyroot;
                   5118: }
                   5119: 
1.71      www      5120: # ---------------------------------------------------------------- Get metadata
                   5121: 
1.599     albertel 5122: my %metaentry;
1.71      www      5123: sub metadata {
1.176     www      5124:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5125:     $uri=&declutter($uri);
1.288     albertel 5126:     # if it is a non metadata possible uri return quickly
1.529     albertel 5127:     if (($uri eq '') || 
                   5128: 	(($uri =~ m|^/*adm/|) && 
1.683.2.10  albertel 5129: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5130:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5131: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5132: 	return undef;
1.288     albertel 5133:     }
1.73      www      5134:     my $filename=$uri;
                   5135:     $uri=~s/\.meta$//;
1.172     www      5136: #
                   5137: # Is the metadata already cached?
1.177     www      5138: # Look at timestamp of caching
1.172     www      5139: # Everything is cached by the main uri, libraries are never directly cached
                   5140: #
1.428     albertel 5141:     if (!defined($liburi)) {
1.599     albertel 5142: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5143: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5144:     }
                   5145:     {
1.172     www      5146: #
                   5147: # Is this a recursive call for a library?
                   5148: #
1.599     albertel 5149: #	if (! exists($metacache{$uri})) {
                   5150: #	    $metacache{$uri}={};
                   5151: #	}
1.171     www      5152:         if ($liburi) {
                   5153: 	    $liburi=&declutter($liburi);
                   5154:             $filename=$liburi;
1.401     bowersj2 5155:         } else {
1.599     albertel 5156: 	    &devalidate_cache_new('meta',$uri);
                   5157: 	    undef(%metaentry);
1.401     bowersj2 5158: 	}
1.140     www      5159:         my %metathesekeys=();
1.73      www      5160:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5161: 	my $metastring;
1.609     banghart 5162: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 5163: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5164: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5165: 	    $metastring=&getfile($file);
1.489     albertel 5166: 	}
1.208     albertel 5167:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5168:         my $token;
1.140     www      5169:         undef %metathesekeys;
1.71      www      5170:         while ($token=$parser->get_token) {
1.339     albertel 5171: 	    if ($token->[0] eq 'S') {
                   5172: 		if (defined($token->[2]->{'package'})) {
1.172     www      5173: #
                   5174: # This is a package - get package info
                   5175: #
1.339     albertel 5176: 		    my $package=$token->[2]->{'package'};
                   5177: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5178: 		    if (defined($token->[2]->{'id'})) { 
                   5179: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5180: 		    }
1.599     albertel 5181: 		    if ($metaentry{':packages'}) {
                   5182: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5183: 		    } else {
1.599     albertel 5184: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5185: 		    }
1.613     albertel 5186: 		    foreach (sort keys %packagetab) {
1.432     albertel 5187: 			my $part=$keyroot;
                   5188: 			$part=~s/^\_//;
                   5189: 			if ($_=~/^\Q$package\E\&/ || 
                   5190: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 5191: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 5192: 			    # ignore package.tab specified default values
                   5193:                             # here &package_tab_default() will fetch those
                   5194: 			    if ($subp eq 'default') { next; }
1.339     albertel 5195: 			    my $value=$packagetab{$_};
1.432     albertel 5196: 			    my $unikey;
                   5197: 			    if ($pack =~ /_0$/) {
                   5198: 				$unikey='parameter_0_'.$name;
                   5199: 				$part=0;
                   5200: 			    } else {
                   5201: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5202: 			    }
1.339     albertel 5203: 			    if ($subp eq 'display') {
                   5204: 				$value.=' [Part: '.$part.']';
                   5205: 			    }
1.599     albertel 5206: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5207: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5208: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5209: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5210: 			    }
1.599     albertel 5211: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5212: 				$metaentry{':'.$unikey}=
                   5213: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5214: 			    }
1.339     albertel 5215: 			}
                   5216: 		    }
                   5217: 		} else {
1.172     www      5218: #
                   5219: # This is not a package - some other kind of start tag
1.339     albertel 5220: #
                   5221: 		    my $entry=$token->[1];
                   5222: 		    my $unikey;
                   5223: 		    if ($entry eq 'import') {
                   5224: 			$unikey='';
                   5225: 		    } else {
                   5226: 			$unikey=$entry;
                   5227: 		    }
                   5228: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5229: 
                   5230: 		    if (defined($token->[2]->{'id'})) { 
                   5231: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5232: 		    }
1.175     www      5233: 
1.339     albertel 5234: 		    if ($entry eq 'import') {
1.175     www      5235: #
                   5236: # Importing a library here
1.339     albertel 5237: #
                   5238: 			if ($depthcount<20) {
                   5239: 			    my $location=$parser->get_text('/import');
                   5240: 			    my $dir=$filename;
                   5241: 			    $dir=~s|[^/]*$||;
                   5242: 			    $location=&filelocation($dir,$location);
                   5243: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5244: 							       $location,$unikey,
                   5245: 							       $depthcount+1)))) {
1.599     albertel 5246: 				$metaentry{':'.$_}=$metaentry{':'.$_};
1.339     albertel 5247: 				$metathesekeys{$_}=1;
                   5248: 			    }
                   5249: 			}
                   5250: 		    } else { 
                   5251: 			
                   5252: 			if (defined($token->[2]->{'name'})) { 
                   5253: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5254: 			}
                   5255: 			$metathesekeys{$unikey}=1;
                   5256: 			foreach (@{$token->[3]}) {
1.599     albertel 5257: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 5258: 			}
                   5259: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5260: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5261: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5262: 		 # only ws inside the tag, and not in default, so use default
                   5263: 		 # as value
1.599     albertel 5264: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5265: 			} else {
1.321     albertel 5266: 		  # either something interesting inside the tag or default
                   5267:                   # uninteresting
1.599     albertel 5268: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5269: 			}
1.172     www      5270: # end of not-a-package not-a-library import
1.339     albertel 5271: 		    }
1.172     www      5272: # end of not-a-package start tag
1.339     albertel 5273: 		}
1.172     www      5274: # the next is the end of "start tag"
1.339     albertel 5275: 	    }
                   5276: 	}
1.483     albertel 5277: 	my ($extension) = ($uri =~ /\.(\w+)$/);
                   5278: 	foreach my $key (sort(keys(%packagetab))) {
                   5279: 	    #no specific packages #how's our extension
                   5280: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 5281: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 5282: 					 \%metathesekeys);
                   5283: 	}
1.599     albertel 5284: 	if (!exists($metaentry{':packages'})) {
1.483     albertel 5285: 	    foreach my $key (sort(keys(%packagetab))) {
                   5286: 		#no specific packages well let's get default then
                   5287: 		if ($key!~/^default&/) { next; }
1.488     albertel 5288: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 5289: 					     \%metathesekeys);
                   5290: 	    }
                   5291: 	}
1.338     www      5292: # are there custom rights to evaluate
1.599     albertel 5293: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 5294: 
1.338     www      5295:     #
                   5296:     # Importing a rights file here
1.339     albertel 5297:     #
                   5298: 	    unless ($depthcount) {
1.599     albertel 5299: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 5300: 		my $dir=$filename;
                   5301: 		$dir=~s|[^/]*$||;
                   5302: 		$location=&filelocation($dir,$location);
                   5303: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5304: 						   $location,'_rights',
                   5305: 						   $depthcount+1)))) {
1.599     albertel 5306: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 5307: 		    $metathesekeys{$_}=1;
                   5308: 		}
                   5309: 	    }
                   5310: 	}
1.599     albertel 5311: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
                   5312: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   5313: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.683.2.11  albertel 5314: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      5315: # this is the end of "was not already recently cached
1.71      www      5316:     }
1.599     albertel 5317:     return $metaentry{':'.$what};
1.261     albertel 5318: }
                   5319: 
1.488     albertel 5320: sub metadata_create_package_def {
1.483     albertel 5321:     my ($uri,$key,$package,$metathesekeys)=@_;
                   5322:     my ($pack,$name,$subp)=split(/\&/,$key);
                   5323:     if ($subp eq 'default') { next; }
                   5324:     
1.599     albertel 5325:     if (defined($metaentry{':packages'})) {
                   5326: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 5327:     } else {
1.599     albertel 5328: 	$metaentry{':packages'}=$package;
1.483     albertel 5329:     }
                   5330:     my $value=$packagetab{$key};
                   5331:     my $unikey;
                   5332:     $unikey='parameter_0_'.$name;
1.599     albertel 5333:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 5334:     $$metathesekeys{$unikey}=1;
1.599     albertel 5335:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5336: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 5337:     }
1.599     albertel 5338:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   5339: 	$metaentry{':'.$unikey}=
                   5340: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 5341:     }
                   5342: }
                   5343: 
1.261     albertel 5344: sub metadata_generate_part0 {
                   5345:     my ($metadata,$metacache,$uri) = @_;
                   5346:     my %allnames;
                   5347:     foreach my $metakey (sort keys %$metadata) {
                   5348: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 5349: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   5350: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 5351: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 5352: 	    $allnames{$name}=$part;
                   5353: 	  }
                   5354: 	}
                   5355:     }
                   5356:     foreach my $name (keys(%allnames)) {
                   5357:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 5358:       my $key=":parameter_0_$name";
1.261     albertel 5359:       $$metacache{"$key.part"}='0';
                   5360:       $$metacache{"$key.name"}=$name;
1.428     albertel 5361:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 5362: 					   $allnames{$name}.'_'.$name.
                   5363: 					   '.type'};
1.428     albertel 5364:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 5365: 			     '.display'};
1.644     www      5366:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 5367:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 5368:       $$metacache{"$key.display"}=$olddis;
                   5369:     }
1.71      www      5370: }
                   5371: 
1.301     www      5372: # ------------------------------------------------- Get the title of a resource
                   5373: 
                   5374: sub gettitle {
                   5375:     my $urlsymb=shift;
                   5376:     my $symb=&symbread($urlsymb);
1.534     albertel 5377:     if ($symb) {
1.620     albertel 5378: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 5379: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 5380: 	if (defined($cached)) { 
                   5381: 	    return $result;
                   5382: 	}
1.534     albertel 5383: 	my ($map,$resid,$url)=&decode_symb($symb);
                   5384: 	my $title='';
                   5385: 	my %bighash;
1.620     albertel 5386: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 5387: 		&GDBM_READER(),0640)) {
                   5388: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   5389: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   5390: 	    untie %bighash;
                   5391: 	}
                   5392: 	$title=~s/\&colon\;/\:/gs;
                   5393: 	if ($title) {
1.599     albertel 5394: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 5395: 	}
                   5396: 	$urlsymb=$url;
                   5397:     }
                   5398:     my $title=&metadata($urlsymb,'title');
                   5399:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   5400:     return $title;
1.301     www      5401: }
1.613     albertel 5402: 
1.614     albertel 5403: sub get_slot {
                   5404:     my ($which,$cnum,$cdom)=@_;
                   5405:     if (!$cnum || !$cdom) {
                   5406: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 5407: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   5408: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 5409:     }
1.683.2.13  albertel 5410:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   5411:     my %slotinfo;
                   5412:     if (exists($remembered{$key})) {
                   5413: 	$slotinfo{$which} = $remembered{$key};
                   5414:     } else {
                   5415: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   5416: 	&Apache::lonhomework::showhash(%slotinfo);
                   5417: 	my ($tmp)=keys(%slotinfo);
                   5418: 	if ($tmp=~/^error:/) { return (); }
                   5419: 	$remembered{$key} = $slotinfo{$which};
                   5420:     }
1.616     albertel 5421:     if (ref($slotinfo{$which}) eq 'HASH') {
                   5422: 	return %{$slotinfo{$which}};
                   5423:     }
                   5424:     return $slotinfo{$which};
1.614     albertel 5425: }
1.31      www      5426: # ------------------------------------------------- Update symbolic store links
                   5427: 
                   5428: sub symblist {
                   5429:     my ($mapname,%newhash)=@_;
1.438     www      5430:     $mapname=&deversion(&declutter($mapname));
1.31      www      5431:     my %hash;
1.620     albertel 5432:     if (($env{'request.course.fn'}) && (%newhash)) {
                   5433:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5434:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 5435: 	    foreach (keys %newhash) {
1.601     albertel 5436:                 $hash{declutter($_)}=&encode_symb($mapname,$newhash{$_}->[1],
                   5437: 						  $newhash{$_}->[0]);
1.191     harris41 5438:             }
1.31      www      5439:             if (untie(%hash)) {
                   5440: 		return 'ok';
                   5441:             }
                   5442:         }
                   5443:     }
                   5444:     return 'error';
1.212     www      5445: }
                   5446: 
                   5447: # --------------------------------------------------------------- Verify a symb
                   5448: 
                   5449: sub symbverify {
1.510     www      5450:     my ($symb,$thisurl)=@_;
                   5451:     my $thisfn=$thisurl;
                   5452: # wrapper not part of symbs
                   5453:     $thisfn=~s/^\/adm\/wrapper//;
1.683.2.7  albertel 5454:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      5455:     $thisfn=&declutter($thisfn);
1.215     www      5456: # direct jump to resource in page or to a sequence - will construct own symbs
                   5457:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   5458: # check URL part
1.409     www      5459:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      5460: 
1.431     www      5461:     unless ($url eq $thisfn) { return 0; }
1.213     www      5462: 
1.216     www      5463:     $symb=&symbclean($symb);
1.510     www      5464:     $thisurl=&deversion($thisurl);
1.439     www      5465:     $thisfn=&deversion($thisfn);
1.213     www      5466: 
                   5467:     my %bighash;
                   5468:     my $okay=0;
1.431     www      5469: 
1.620     albertel 5470:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5471:                             &GDBM_READER(),0640)) {
1.510     www      5472:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      5473:         unless ($ids) { 
1.510     www      5474:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      5475:         }
                   5476:         if ($ids) {
                   5477: # ------------------------------------------------------------------- Has ID(s)
                   5478: 	    foreach (split(/\,/,$ids)) {
1.644     www      5479: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      5480:                if (
                   5481:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   5482:    eq $symb) { 
1.620     albertel 5483: 		   if (($env{'request.role.adv'}) ||
                   5484: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 5485: 		       $okay=1; 
                   5486: 		   }
                   5487: 	       }
1.216     www      5488: 	   }
                   5489:         }
1.213     www      5490: 	untie(%bighash);
                   5491:     }
                   5492:     return $okay;
1.31      www      5493: }
                   5494: 
1.210     www      5495: # --------------------------------------------------------------- Clean-up symb
                   5496: 
                   5497: sub symbclean {
                   5498:     my $symb=shift;
1.568     albertel 5499:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      5500: # remove version from map
                   5501:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      5502: 
1.210     www      5503: # remove version from URL
                   5504:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      5505: 
1.507     www      5506: # remove wrapper
                   5507: 
1.510     www      5508:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.683.2.7  albertel 5509:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      5510:     return $symb;
1.409     www      5511: }
                   5512: 
                   5513: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 5514: 
                   5515: sub encode_symb {
                   5516:     my ($map,$resid,$url)=@_;
                   5517:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   5518: }
1.409     www      5519: 
                   5520: sub decode_symb {
1.568     albertel 5521:     my $symb=shift;
                   5522:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   5523:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      5524:     return (&fixversion($map),$resid,&fixversion($url));
                   5525: }
                   5526: 
                   5527: sub fixversion {
                   5528:     my $fn=shift;
1.609     banghart 5529:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      5530:     my %bighash;
                   5531:     my $uri=&clutter($fn);
1.620     albertel 5532:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      5533: # is this cached?
1.599     albertel 5534:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      5535:     if (defined($cached)) { return $result; }
                   5536: # unfortunately not cached, or expired
1.620     albertel 5537:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      5538: 	    &GDBM_READER(),0640)) {
                   5539:  	if ($bighash{'version_'.$uri}) {
                   5540:  	    my $version=$bighash{'version_'.$uri};
1.444     www      5541:  	    unless (($version eq 'mostrecent') || 
                   5542: 		    ($version==&getversion($uri))) {
1.440     www      5543:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   5544:  	    }
                   5545:  	}
                   5546:  	untie %bighash;
1.413     www      5547:     }
1.599     albertel 5548:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      5549: }
                   5550: 
                   5551: sub deversion {
                   5552:     my $url=shift;
                   5553:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   5554:     return $url;
1.210     www      5555: }
                   5556: 
1.31      www      5557: # ------------------------------------------------------ Return symb list entry
                   5558: 
                   5559: sub symbread {
1.249     www      5560:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 5561:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 5562:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      5563: # no filename provided? try from environment
1.44      www      5564:     unless ($thisfn) {
1.620     albertel 5565:         if ($env{'request.symb'}) {
                   5566: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 5567: 	}
1.620     albertel 5568: 	$thisfn=$env{'request.filename'};
1.44      www      5569:     }
1.569     albertel 5570:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      5571: # is that filename actually a symb? Verify, clean, and return
                   5572:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 5573: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 5574: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 5575: 	}
1.242     www      5576:     }
1.44      www      5577:     $thisfn=declutter($thisfn);
1.31      www      5578:     my %hash;
1.37      www      5579:     my %bighash;
                   5580:     my $syval='';
1.620     albertel 5581:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  5582:         my $targetfn = $thisfn;
1.609     banghart 5583:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  5584:             $targetfn = 'adm/wrapper/'.$thisfn;
                   5585:         }
1.683.2.3  albertel 5586: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   5587: 	    $targetfn=$1;
                   5588: 	}
1.620     albertel 5589:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5590:                       &GDBM_READER(),0640)) {
1.481     raeburn  5591: 	    $syval=$hash{$targetfn};
1.37      www      5592:             untie(%hash);
                   5593:         }
                   5594: # ---------------------------------------------------------- There was an entry
                   5595:         if ($syval) {
1.601     albertel 5596: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 5597: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 5598: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 5599: 		    #return $env{$cache_str}='';
1.601     albertel 5600: 		#}    
                   5601: 		#$syval.=$1;
                   5602: 	    #}
1.37      www      5603:         } else {
                   5604: # ------------------------------------------------------- Was not in symb table
1.620     albertel 5605:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5606:                             &GDBM_READER(),0640)) {
1.37      www      5607: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      5608:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      5609:               unless ($ids) { 
                   5610:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      5611:               }
                   5612:               unless ($ids) {
                   5613: # alias?
                   5614: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      5615:               }
1.37      www      5616:               if ($ids) {
                   5617: # ------------------------------------------------------------------- Has ID(s)
                   5618:                  my @possibilities=split(/\,/,$ids);
1.39      www      5619:                  if ($#possibilities==0) {
                   5620: # ----------------------------------------------- There is only one possibility
1.37      www      5621: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 5622: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5623: 						    $resid,$thisfn);
1.249     www      5624:                  } elsif (!$donotrecurse) {
1.39      www      5625: # ------------------------------------------ There is more than one possibility
                   5626:                      my $realpossible=0;
1.191     harris41 5627:                      foreach (@possibilities) {
1.39      www      5628: 			 my $file=$bighash{'src_'.$_};
                   5629:                          if (&allowed('bre',$file)) {
                   5630:          		    my ($mapid,$resid)=split(/\./,$_);
                   5631:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   5632: 				$realpossible++;
1.626     albertel 5633:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5634: 						    $resid,$thisfn);
1.39      www      5635:                             }
                   5636: 			 }
1.191     harris41 5637:                      }
1.39      www      5638: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      5639:                  } else {
                   5640:                      $syval='';
1.37      www      5641:                  }
                   5642: 	      }
                   5643:               untie(%bighash)
1.481     raeburn  5644:            }
1.31      www      5645:         }
1.62      www      5646:         if ($syval) {
1.620     albertel 5647: 	    return $env{$cache_str}=$syval;
1.62      www      5648:         }
1.31      www      5649:     }
1.44      www      5650:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 5651:     return $env{$cache_str}='';
1.31      www      5652: }
                   5653: 
                   5654: # ---------------------------------------------------------- Return random seed
                   5655: 
1.32      www      5656: sub numval {
                   5657:     my $txt=shift;
                   5658:     $txt=~tr/A-J/0-9/;
                   5659:     $txt=~tr/a-j/0-9/;
                   5660:     $txt=~tr/K-T/0-9/;
                   5661:     $txt=~tr/k-t/0-9/;
                   5662:     $txt=~tr/U-Z/0-5/;
                   5663:     $txt=~tr/u-z/0-5/;
                   5664:     $txt=~s/\D//g;
1.564     albertel 5665:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      5666:     return int($txt);
1.368     albertel 5667: }
                   5668: 
1.484     albertel 5669: sub numval2 {
                   5670:     my $txt=shift;
                   5671:     $txt=~tr/A-J/0-9/;
                   5672:     $txt=~tr/a-j/0-9/;
                   5673:     $txt=~tr/K-T/0-9/;
                   5674:     $txt=~tr/k-t/0-9/;
                   5675:     $txt=~tr/U-Z/0-5/;
                   5676:     $txt=~tr/u-z/0-5/;
                   5677:     $txt=~s/\D//g;
                   5678:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5679:     my $total;
                   5680:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 5681:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 5682:     return int($total);
                   5683: }
                   5684: 
1.575     albertel 5685: sub numval3 {
                   5686:     use integer;
                   5687:     my $txt=shift;
                   5688:     $txt=~tr/A-J/0-9/;
                   5689:     $txt=~tr/a-j/0-9/;
                   5690:     $txt=~tr/K-T/0-9/;
                   5691:     $txt=~tr/k-t/0-9/;
                   5692:     $txt=~tr/U-Z/0-5/;
                   5693:     $txt=~tr/u-z/0-5/;
                   5694:     $txt=~s/\D//g;
                   5695:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5696:     my $total;
                   5697:     foreach my $val (@txts) { $total+=$val; }
                   5698:     if ($_64bit) { $total=(($total<<32)>>32); }
                   5699:     return $total;
                   5700: }
                   5701: 
1.675     albertel 5702: sub digest {
                   5703:     my ($data)=@_;
                   5704:     my $digest=&Digest::MD5::md5($data);
                   5705:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   5706:     my ($e,$f);
                   5707:     {
                   5708:         use integer;
                   5709:         $e=($a+$b);
                   5710:         $f=($c+$d);
                   5711:         if ($_64bit) {
                   5712:             $e=(($e<<32)>>32);
                   5713:             $f=(($f<<32)>>32);
                   5714:         }
                   5715:     }
                   5716:     if (wantarray) {
                   5717: 	return ($e,$f);
                   5718:     } else {
                   5719: 	my $g;
                   5720: 	{
                   5721: 	    use integer;
                   5722: 	    $g=($e+$f);
                   5723: 	    if ($_64bit) {
                   5724: 		$g=(($g<<32)>>32);
                   5725: 	    }
                   5726: 	}
                   5727: 	return $g;
                   5728:     }
                   5729: }
                   5730: 
1.368     albertel 5731: sub latest_rnd_algorithm_id {
1.675     albertel 5732:     return '64bit5';
1.366     albertel 5733: }
1.32      www      5734: 
1.503     albertel 5735: sub get_rand_alg {
                   5736:     my ($courseid)=@_;
                   5737:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   5738:     if ($courseid) {
1.620     albertel 5739: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 5740:     }
                   5741:     return &latest_rnd_algorithm_id();
                   5742: }
                   5743: 
1.562     albertel 5744: sub validCODE {
                   5745:     my ($CODE)=@_;
                   5746:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   5747:     return 0;
                   5748: }
                   5749: 
1.491     albertel 5750: sub getCODE {
1.620     albertel 5751:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 5752:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   5753: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   5754: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 5755: 	return $Apache::lonhomework::history{'resource.CODE'};
                   5756:     }
                   5757:     return undef;
                   5758: }
                   5759: 
1.31      www      5760: sub rndseed {
1.155     albertel 5761:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 5762: 
                   5763:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 5764:     if (!$symb) {
1.366     albertel 5765: 	unless ($symb=$wsymb) { return time; }
                   5766:     }
                   5767:     if (!$courseid) { $courseid=$wcourseid; }
                   5768:     if (!$domain) { $domain=$wdomain; }
                   5769:     if (!$username) { $username=$wusername }
1.503     albertel 5770:     my $which=&get_rand_alg();
1.491     albertel 5771:     if (defined(&getCODE())) {
1.675     albertel 5772: 	if ($which eq '64bit5') {
                   5773: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   5774: 	} elsif ($which eq '64bit4') {
1.575     albertel 5775: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   5776: 	} else {
                   5777: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   5778: 	}
1.675     albertel 5779:     } elsif ($which eq '64bit5') {
                   5780: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 5781:     } elsif ($which eq '64bit4') {
                   5782: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 5783:     } elsif ($which eq '64bit3') {
                   5784: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 5785:     } elsif ($which eq '64bit2') {
                   5786: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 5787:     } elsif ($which eq '64bit') {
                   5788: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   5789:     }
                   5790:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   5791: }
                   5792: 
                   5793: sub rndseed_32bit {
                   5794:     my ($symb,$courseid,$domain,$username)=@_;
                   5795:     {
                   5796: 	use integer;
                   5797: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   5798: 	my $symbseed=numval($symb) << 22;
                   5799: 	my $namechck=unpack("%32C*",$username) << 17;
                   5800: 	my $nameseed=numval($username) << 12;
                   5801: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   5802: 	my $courseseed=unpack("%32C*",$courseid);
                   5803: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   5804: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5805: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5806: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 5807: 	return $num;
                   5808:     }
                   5809: }
                   5810: 
                   5811: sub rndseed_64bit {
                   5812:     my ($symb,$courseid,$domain,$username)=@_;
                   5813:     {
                   5814: 	use integer;
                   5815: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   5816: 	my $symbseed=numval($symb) << 10;
                   5817: 	my $namechck=unpack("%32S*",$username);
                   5818: 	
                   5819: 	my $nameseed=numval($username) << 21;
                   5820: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   5821: 	my $courseseed=unpack("%32S*",$courseid);
                   5822: 	
                   5823: 	my $num1=$symbchck+$symbseed+$namechck;
                   5824: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5825: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5826: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5827: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5828: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 5829: 	return "$num1,$num2";
1.155     albertel 5830:     }
1.366     albertel 5831: }
                   5832: 
1.443     albertel 5833: sub rndseed_64bit2 {
                   5834:     my ($symb,$courseid,$domain,$username)=@_;
                   5835:     {
                   5836: 	use integer;
                   5837: 	# strings need to be an even # of cahracters long, it it is odd the
                   5838:         # last characters gets thrown away
                   5839: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5840: 	my $symbseed=numval($symb) << 10;
                   5841: 	my $namechck=unpack("%32S*",$username.' ');
                   5842: 	
                   5843: 	my $nameseed=numval($username) << 21;
1.501     albertel 5844: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5845: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5846: 	
                   5847: 	my $num1=$symbchck+$symbseed+$namechck;
                   5848: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5849: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5850: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   5851: 	return "$num1,$num2";
                   5852:     }
                   5853: }
                   5854: 
                   5855: sub rndseed_64bit3 {
                   5856:     my ($symb,$courseid,$domain,$username)=@_;
                   5857:     {
                   5858: 	use integer;
                   5859: 	# strings need to be an even # of cahracters long, it it is odd the
                   5860:         # last characters gets thrown away
                   5861: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5862: 	my $symbseed=numval2($symb) << 10;
                   5863: 	my $namechck=unpack("%32S*",$username.' ');
                   5864: 	
                   5865: 	my $nameseed=numval2($username) << 21;
1.443     albertel 5866: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5867: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5868: 	
                   5869: 	my $num1=$symbchck+$symbseed+$namechck;
                   5870: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5871: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 5872: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5873: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5874: 	
1.503     albertel 5875: 	return "$num1:$num2";
1.443     albertel 5876:     }
                   5877: }
                   5878: 
1.575     albertel 5879: sub rndseed_64bit4 {
                   5880:     my ($symb,$courseid,$domain,$username)=@_;
                   5881:     {
                   5882: 	use integer;
                   5883: 	# strings need to be an even # of cahracters long, it it is odd the
                   5884:         # last characters gets thrown away
                   5885: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5886: 	my $symbseed=numval3($symb) << 10;
                   5887: 	my $namechck=unpack("%32S*",$username.' ');
                   5888: 	
                   5889: 	my $nameseed=numval3($username) << 21;
                   5890: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5891: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5892: 	
                   5893: 	my $num1=$symbchck+$symbseed+$namechck;
                   5894: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5895: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5896: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5897: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5898: 	
                   5899: 	return "$num1:$num2";
                   5900:     }
                   5901: }
                   5902: 
1.675     albertel 5903: sub rndseed_64bit5 {
                   5904:     my ($symb,$courseid,$domain,$username)=@_;
                   5905:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   5906:     return "$num1:$num2";
                   5907: }
                   5908: 
1.366     albertel 5909: sub rndseed_CODE_64bit {
                   5910:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 5911:     {
1.366     albertel 5912: 	use integer;
1.443     albertel 5913: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 5914: 	my $symbseed=numval2($symb);
1.491     albertel 5915: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5916: 	my $CODEseed=numval(&getCODE());
1.443     albertel 5917: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 5918: 	my $num1=$symbseed+$CODEchck;
                   5919: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5920: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 5921: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 5922: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5923: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 5924: 	return "$num1:$num2";
1.366     albertel 5925:     }
                   5926: }
                   5927: 
1.575     albertel 5928: sub rndseed_CODE_64bit4 {
                   5929:     my ($symb,$courseid,$domain,$username)=@_;
                   5930:     {
                   5931: 	use integer;
                   5932: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   5933: 	my $symbseed=numval3($symb);
                   5934: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5935: 	my $CODEseed=numval3(&getCODE());
                   5936: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5937: 	my $num1=$symbseed+$CODEchck;
                   5938: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5939: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   5940: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   5941: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5942: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   5943: 	return "$num1:$num2";
                   5944:     }
                   5945: }
                   5946: 
1.675     albertel 5947: sub rndseed_CODE_64bit5 {
                   5948:     my ($symb,$courseid,$domain,$username)=@_;
                   5949:     my $code = &getCODE();
                   5950:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   5951:     return "$num1:$num2";
                   5952: }
                   5953: 
1.366     albertel 5954: sub setup_random_from_rndseed {
                   5955:     my ($rndseed)=@_;
1.503     albertel 5956:     if ($rndseed =~/([,:])/) {
                   5957: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 5958: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   5959:     } else {
                   5960: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 5961:     }
1.36      albertel 5962: }
                   5963: 
1.474     albertel 5964: sub latest_receipt_algorithm_id {
                   5965:     return 'receipt2';
                   5966: }
                   5967: 
1.480     www      5968: sub recunique {
                   5969:     my $fucourseid=shift;
                   5970:     my $unique;
1.620     albertel 5971:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5972: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      5973:     } else {
                   5974: 	$unique=$perlvar{'lonReceipt'};
                   5975:     }
                   5976:     return unpack("%32C*",$unique);
                   5977: }
                   5978: 
                   5979: sub recprefix {
                   5980:     my $fucourseid=shift;
                   5981:     my $prefix;
1.620     albertel 5982:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5983: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      5984:     } else {
                   5985: 	$prefix=$perlvar{'lonHostID'};
                   5986:     }
                   5987:     return unpack("%32C*",$prefix);
                   5988: }
                   5989: 
1.76      www      5990: sub ireceipt {
1.474     albertel 5991:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      5992:     my $cuname=unpack("%32C*",$funame);
                   5993:     my $cudom=unpack("%32C*",$fudom);
                   5994:     my $cucourseid=unpack("%32C*",$fucourseid);
                   5995:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      5996:     my $cunique=&recunique($fucourseid);
1.474     albertel 5997:     my $cpart=unpack("%32S*",$part);
1.480     www      5998:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 5999:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6000: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6001: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6002: 			       " and ".($cpart%$cudom));
                   6003: 			       
                   6004: 	$return.= ($cunique%$cuname+
                   6005: 		   $cunique%$cudom+
                   6006: 		   $cusymb%$cuname+
                   6007: 		   $cusymb%$cudom+
                   6008: 		   $cucourseid%$cuname+
                   6009: 		   $cucourseid%$cudom+
                   6010: 		   $cpart%$cuname+
                   6011: 		   $cpart%$cudom);
                   6012:     } else {
                   6013: 	$return.= ($cunique%$cuname+
                   6014: 		   $cunique%$cudom+
                   6015: 		   $cusymb%$cuname+
                   6016: 		   $cusymb%$cudom+
                   6017: 		   $cucourseid%$cuname+
                   6018: 		   $cucourseid%$cudom);
                   6019:     }
                   6020:     return $return;
1.76      www      6021: }
                   6022: 
                   6023: sub receipt {
1.474     albertel 6024:     my ($part)=@_;
                   6025:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6026:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6027: }
1.260     ng       6028: 
1.36      albertel 6029: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6030: # returns either the contents of the file or 
                   6031: # -1 if the file doesn't exist
1.481     raeburn  6032: #
                   6033: # if the target is a file that was uploaded via DOCS, 
                   6034: # a check will be made to see if a current copy exists on the local server,
                   6035: # if it does this will be served, otherwise a copy will be retrieved from
                   6036: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6037: # the local server.   
1.472     albertel 6038: 
1.36      albertel 6039: sub getfile {
1.538     albertel 6040:     my ($file) = @_;
1.609     banghart 6041:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6042:     &repcopy($file);
                   6043:     return &readfile($file);
                   6044: }
                   6045: 
                   6046: sub repcopy_userfile {
                   6047:     my ($file)=@_;
1.609     banghart 6048:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6049:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6050:     my ($cdom,$cnum,$filename) = 
                   6051: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6052:     my ($info,$rtncode);
                   6053:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6054:     if (-e "$file") {
                   6055: 	my @fileinfo = stat($file);
                   6056: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6057: 	if ($lwpresp ne 'ok') {
                   6058: 	    if ($rtncode eq '404') {
1.538     albertel 6059: 		unlink($file);
1.482     albertel 6060: 	    }
1.517     albertel 6061: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6062: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6063: 	    #my $response=$ua->request($request);
                   6064: 	    #if ($response->is_success()) {
                   6065: 	#	return $response->content;
                   6066: 	#    } else {
                   6067: 	#	return -1;
                   6068: 	#    }
1.482     albertel 6069: 	    return -1;
                   6070: 	}
                   6071: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6072: 	    return 'ok';
1.482     albertel 6073: 	}
                   6074: 	$info = '';
1.538     albertel 6075: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6076: 	if ($lwpresp ne 'ok') {
                   6077: 	    return -1;
                   6078: 	}
                   6079:     } else {
1.538     albertel 6080: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6081: 	if ($lwpresp ne 'ok') {
1.517     albertel 6082: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6083: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6084: 	    my $response=$ua->request($request);
                   6085: 	    if ($response->is_success()) {
1.538     albertel 6086: 		$info=$response->content;
1.517     albertel 6087: 	    } else {
                   6088: 		return -1;
                   6089: 	    }
1.482     albertel 6090: 	}
                   6091: 	my @parts = ($cdom,$cnum); 
                   6092: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6093: 	    push @parts, split(/\//,$1);
1.518     albertel 6094: 	}
1.538     albertel 6095: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6096: 	foreach my $part (@parts) {
                   6097: 	    $path .= '/'.$part;
                   6098: 	    if (!-e $path) {
                   6099: 		mkdir($path,0770);
                   6100: 	    }
                   6101: 	}
                   6102:     }
1.538     albertel 6103:     open(FILE,">$file");
1.482     albertel 6104:     print FILE $info;
                   6105:     close(FILE);
1.607     raeburn  6106:     return 'ok';
1.481     raeburn  6107: }
                   6108: 
1.517     albertel 6109: sub tokenwrapper {
                   6110:     my $uri=shift;
1.552     albertel 6111:     $uri=~s|^http\://([^/]+)||;
                   6112:     $uri=~s|^/||;
1.620     albertel 6113:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6114:     my $token=$1;
1.552     albertel 6115:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6116:     if ($udom && $uname && $file) {
                   6117: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6118:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6119:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6120:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6121:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6122:     } else {
                   6123:         return '/adm/notfound.html';
                   6124:     }
                   6125: }
                   6126: 
1.481     raeburn  6127: sub getuploaded {
                   6128:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6129:     $uri=~s/^\///;
                   6130:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6131:     my $ua=new LWP::UserAgent;
                   6132:     my $request=new HTTP::Request($reqtype,$uri);
                   6133:     my $response=$ua->request($request);
                   6134:     $$rtncode = $response->code;
1.482     albertel 6135:     if (! $response->is_success()) {
                   6136: 	return 'failed';
                   6137:     }      
                   6138:     if ($reqtype eq 'HEAD') {
1.486     www      6139: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6140:     } elsif ($reqtype eq 'GET') {
                   6141: 	$$info = $response->content;
1.472     albertel 6142:     }
1.482     albertel 6143:     return 'ok';
1.36      albertel 6144: }
                   6145: 
1.481     raeburn  6146: sub readfile {
                   6147:     my $file = shift;
                   6148:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6149:     my $fh;
                   6150:     open($fh,"<$file");
                   6151:     my $a='';
                   6152:     while (<$fh>) { $a .=$_; }
                   6153:     return $a;
                   6154: }
                   6155: 
1.36      albertel 6156: sub filelocation {
1.590     banghart 6157:     my ($dir,$file) = @_;
                   6158:     my $location;
                   6159:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.683.2.11  albertel 6160: 
                   6161:     if ($file =~ m-^/adm/-) {
                   6162: 	$file=~s-^/adm/wrapper/-/-;
                   6163: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6164:     }
1.590     banghart 6165:     if ($file=~m:^/~:) { # is a contruction space reference
                   6166:         $location = $file;
                   6167:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6168:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6169: 	# is a correct contruction space reference
                   6170:         $location = $file;
1.609     banghart 6171:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6172:         my ($udom,$uname,$filename)=
1.609     banghart 6173:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6174:         my $home=&homeserver($uname,$udom);
                   6175:         my $is_me=0;
                   6176:         my @ids=&current_machine_ids();
                   6177:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6178:         if ($is_me) {
                   6179:   	    $location=&Apache::loncommon::propath($udom,$uname).
                   6180:   	      '/userfiles/'.$filename;
                   6181:         } else {
                   6182:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6183:   	      $udom.'/'.$uname.'/'.$filename;
                   6184:         }
                   6185:     } else {
                   6186:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6187:         $file=~s:^/res/:/:;
                   6188:         if ( !( $file =~ m:^/:) ) {
                   6189:             $location = $dir. '/'.$file;
                   6190:         } else {
                   6191:             $location = '/home/httpd/html/res'.$file;
                   6192:         }
1.59      albertel 6193:     }
1.590     banghart 6194:     $location=~s://+:/:g; # remove duplicate /
                   6195:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6196:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6197:     return $location;
1.46      www      6198: }
1.36      albertel 6199: 
1.46      www      6200: sub hreflocation {
                   6201:     my ($dir,$file)=@_;
1.460     albertel 6202:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6203: 	$file=filelocation($dir,$file);
1.683.2.11  albertel 6204:     } elsif ($file=~m-^/adm/-) {
                   6205: 	$file=~s-^/adm/wrapper/-/-;
                   6206: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6207:     }
                   6208:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6209: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6210:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6211: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6212:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6213: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6214: 	    -/uploaded/$1/$2/-x;
1.46      www      6215:     }
1.462     albertel 6216:     return $file;
1.465     albertel 6217: }
                   6218: 
                   6219: sub current_machine_domains {
                   6220:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6221:     my @domains;
                   6222:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6223: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6224: 	if ($hostname eq $name) {
                   6225: 	    push(@domains,$hostdom{$id});
                   6226: 	}
                   6227:     }
                   6228:     return @domains;
                   6229: }
                   6230: 
                   6231: sub current_machine_ids {
                   6232:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6233:     my @ids;
                   6234:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6235: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6236: 	if ($hostname eq $name) {
                   6237: 	    push(@ids,$id);
                   6238: 	}
                   6239:     }
                   6240:     return @ids;
1.31      www      6241: }
                   6242: 
                   6243: # ------------------------------------------------------------- Declutters URLs
                   6244: 
                   6245: sub declutter {
                   6246:     my $thisfn=shift;
1.569     albertel 6247:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6248:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6249:     $thisfn=~s/^\///;
1.683.2.7  albertel 6250:     $thisfn=~s|^adm/wrapper/||;
                   6251:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.683.2.9  albertel 6252:     $thisfn=~s/^res\///;
                   6253:     $thisfn=~s/\?.+$//;
1.268     www      6254:     return $thisfn;
                   6255: }
                   6256: 
                   6257: # ------------------------------------------------------------- Clutter up URLs
                   6258: 
                   6259: sub clutter {
                   6260:     my $thisfn='/'.&declutter(shift);
1.609     banghart 6261:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      6262:        $thisfn='/res'.$thisfn; 
                   6263:     }
1.683.2.7  albertel 6264:     if ($thisfn !~m|/adm|) {
                   6265: 	if ($thisfn =~ m|/ext/|) {
                   6266: 	    $thisfn='/adm/wrapper'.$thisfn;
                   6267: 	} else {
                   6268: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   6269: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.683.2.10  albertel 6270: 	    if ($embstyle eq 'ssi'
                   6271: 		|| ($embstyle eq 'hdn')
                   6272: 		|| ($embstyle eq 'rat')
                   6273: 		|| ($embstyle eq 'prv')
                   6274: 		|| ($embstyle eq 'ign')) {
                   6275: 		#do nothing with these
                   6276: 	    } elsif (($embstyle eq 'img') 
1.683.2.7  albertel 6277: 		|| ($embstyle eq 'emb')
                   6278: 		|| ($embstyle eq 'wrp')) {
                   6279: 		$thisfn='/adm/wrapper'.$thisfn;
1.683.2.10  albertel 6280: 	    } elsif ($embstyle eq 'unk'
                   6281: 		     && $thisfn!~/\.(sequence|page)$/) {
1.683.2.7  albertel 6282: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.683.2.10  albertel 6283: 	    } else {
1.683.2.12  albertel 6284: 		#&logthis("Got a blank emb style");
1.683.2.7  albertel 6285: 	    }
                   6286: 	}
                   6287:     }
1.31      www      6288:     return $thisfn;
1.12      www      6289: }
                   6290: 
1.557     albertel 6291: sub freeze_escape {
                   6292:     my ($value)=@_;
                   6293:     if (ref($value)) {
                   6294: 	$value=&nfreeze($value);
                   6295: 	return '__FROZEN__'.&escape($value);
                   6296:     }
                   6297:     return &escape($value);
                   6298: }
                   6299: 
1.12      www      6300: # -------------------------------------------------------- Escape Special Chars
                   6301: 
                   6302: sub escape {
                   6303:     my $str=shift;
                   6304:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   6305:     return $str;
                   6306: }
                   6307: 
                   6308: # ----------------------------------------------------- Un-Escape Special Chars
                   6309: 
                   6310: sub unescape {
                   6311:     my $str=shift;
                   6312:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   6313:     return $str;
                   6314: }
1.11      www      6315: 
1.557     albertel 6316: sub thaw_unescape {
                   6317:     my ($value)=@_;
                   6318:     if ($value =~ /^__FROZEN__/) {
                   6319: 	substr($value,0,10,undef);
                   6320: 	$value=&unescape($value);
                   6321: 	return &thaw($value);
                   6322:     }
                   6323:     return &unescape($value);
                   6324: }
                   6325: 
1.436     albertel 6326: sub correct_line_ends {
                   6327:     my ($result)=@_;
                   6328:     $$result =~s/\r\n/\n/mg;
                   6329:     $$result =~s/\r/\n/mg;
1.415     albertel 6330: }
1.1       albertel 6331: # ================================================================ Main Program
                   6332: 
1.184     www      6333: sub goodbye {
1.204     albertel 6334:    &logthis("Starting Shut down");
1.443     albertel 6335: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 6336:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 6337: #converted
1.599     albertel 6338: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   6339:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   6340: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   6341: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 6342: #1.1 only
1.599     albertel 6343: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   6344: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   6345: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   6346: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   6347:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   6348:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   6349:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      6350:    &flushcourselogs();
                   6351:    &logthis("Shutting down");
1.362     albertel 6352:    return DONE;
1.184     www      6353: }
                   6354: 
1.179     www      6355: BEGIN {
1.228     harris41 6356: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      6357:     unless ($readit) {
1.217     harris41 6358: {
1.581     matthew  6359:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 6360:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 6361: 
                   6362:     while (my $configline=<$config>) {
1.484     albertel 6363:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 6364: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      6365:            chomp($varvalue);
1.1       albertel 6366:            $perlvar{$varname}=$varvalue;
                   6367:         }
                   6368:     }
1.448     albertel 6369:     close($config);
1.1       albertel 6370: }
1.227     harris41 6371: {
1.448     albertel 6372:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 6373: 
                   6374:     while (my $configline=<$config>) {
                   6375:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   6376: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   6377:            chomp($varvalue);
                   6378:            $perlvar{$varname}=$varvalue;
                   6379:         }
                   6380:     }
1.448     albertel 6381:     close($config);
1.227     harris41 6382: }
1.1       albertel 6383: 
1.327     albertel 6384: # ------------------------------------------------------------ Read domain file
                   6385: {
                   6386:     %domaindescription = ();
                   6387:     %domain_auth_def = ();
                   6388:     %domain_auth_arg_def = ();
1.448     albertel 6389:     my $fh;
                   6390:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 6391:        while (<$fh>) {
1.390     matthew  6392:            next if (/^(\#|\s*$)/);
                   6393: #           next if /^\#/;
1.327     albertel 6394:            chomp;
1.403     www      6395:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.683.2.2  albertel 6396: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      6397: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 6398:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      6399: 	   $domaindescription{$domain}=$domain_description;
                   6400: 	   $domain_lang_def{$domain}=$def_lang;
                   6401: 	   $domain_city{$domain}=$city;
                   6402: 	   $domain_longi{$domain}=$longi;
                   6403: 	   $domain_lati{$domain}=$lati;
1.683.2.2  albertel 6404:            $domain_primary{$domain}=$primary;
1.403     www      6405: 
1.448     albertel 6406:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 6407: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 6408: 	}
1.327     albertel 6409:     }
1.448     albertel 6410:     close ($fh);
1.327     albertel 6411: }
                   6412: 
                   6413: 
1.1       albertel 6414: # ------------------------------------------------------------- Read hosts file
                   6415: {
1.448     albertel 6416:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 6417: 
                   6418:     while (my $configline=<$config>) {
1.303     matthew  6419:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      6420:        chomp($configline);
1.595     albertel 6421:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 6422:        $name=~s/\s//g;
1.595     albertel 6423:        if ($id && $domain && $role && $name) {
1.252     albertel 6424: 	 $hostname{$id}=$name;
                   6425: 	 $hostdom{$id}=$domain;
                   6426: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      6427:        }
1.1       albertel 6428:     }
1.448     albertel 6429:     close($config);
1.619     albertel 6430:     # FIXME: dev server don't want this, production servers _do_ want this
1.683.2.1  albertel 6431:     &get_iphost();
1.1       albertel 6432: }
                   6433: 
1.598     albertel 6434: sub get_iphost {
                   6435:     if (%iphost) { return %iphost; }
1.653     albertel 6436:     my %name_to_ip;
1.598     albertel 6437:     foreach my $id (keys(%hostname)) {
                   6438: 	my $name=$hostname{$id};
1.653     albertel 6439: 	my $ip;
                   6440: 	if (!exists($name_to_ip{$name})) {
                   6441: 	    $ip = gethostbyname($name);
                   6442: 	    if (!$ip || length($ip) ne 4) {
                   6443: 		&logthis("Skipping host $id name $name no IP found\n");
                   6444: 		next;
                   6445: 	    }
                   6446: 	    $ip=inet_ntoa($ip);
                   6447: 	    $name_to_ip{$name} = $ip;
                   6448: 	} else {
                   6449: 	    $ip = $name_to_ip{$name};
1.598     albertel 6450: 	}
                   6451: 	push(@{$iphost{$ip}},$id);
                   6452:     }
                   6453:     return %iphost;
                   6454: }
                   6455: 
1.1       albertel 6456: # ------------------------------------------------------ Read spare server file
                   6457: {
1.448     albertel 6458:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 6459: 
                   6460:     while (my $configline=<$config>) {
                   6461:        chomp($configline);
1.284     matthew  6462:        if ($configline) {
1.1       albertel 6463:           $spareid{$configline}=1;
                   6464:        }
                   6465:     }
1.448     albertel 6466:     close($config);
1.1       albertel 6467: }
1.11      www      6468: # ------------------------------------------------------------ Read permissions
                   6469: {
1.448     albertel 6470:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      6471: 
                   6472:     while (my $configline=<$config>) {
1.448     albertel 6473: 	chomp($configline);
                   6474: 	if ($configline) {
                   6475: 	    my ($role,$perm)=split(/ /,$configline);
                   6476: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   6477: 	}
1.11      www      6478:     }
1.448     albertel 6479:     close($config);
1.11      www      6480: }
                   6481: 
                   6482: # -------------------------------------------- Read plain texts for permissions
                   6483: {
1.448     albertel 6484:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      6485: 
                   6486:     while (my $configline=<$config>) {
1.448     albertel 6487: 	chomp($configline);
                   6488: 	if ($configline) {
                   6489: 	    my ($short,$plain)=split(/:/,$configline);
                   6490: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   6491: 	}
1.135     www      6492:     }
1.448     albertel 6493:     close($config);
1.135     www      6494: }
                   6495: 
                   6496: # ---------------------------------------------------------- Read package table
                   6497: {
1.448     albertel 6498:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      6499: 
                   6500:     while (my $configline=<$config>) {
1.483     albertel 6501: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 6502: 	chomp($configline);
                   6503: 	my ($short,$plain)=split(/:/,$configline);
                   6504: 	my ($pack,$name)=split(/\&/,$short);
                   6505: 	if ($plain ne '') {
                   6506: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   6507: 	    $packagetab{$short}=$plain; 
                   6508: 	}
1.11      www      6509:     }
1.448     albertel 6510:     close($config);
1.329     matthew  6511: }
                   6512: 
                   6513: # ------------- set up temporary directory
                   6514: {
                   6515:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   6516: 
1.11      www      6517: }
                   6518: 
1.599     albertel 6519: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      6520: 
1.281     www      6521: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      6522: $dumpcount=0;
1.22      www      6523: 
1.163     harris41 6524: &logtouch();
1.672     albertel 6525: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      6526: $readit=1;
1.564     albertel 6527:     {
                   6528: 	use integer;
                   6529: 	my $test=(2**32)+1;
1.568     albertel 6530: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 6531: 	&logthis(" Detected 64bit platform ($_64bit)");
                   6532:     }
1.195     www      6533: }
1.1       albertel 6534: }
1.179     www      6535: 
1.1       albertel 6536: 1;
1.191     harris41 6537: __END__
                   6538: 
1.243     albertel 6539: =pod
                   6540: 
1.191     harris41 6541: =head1 NAME
                   6542: 
1.243     albertel 6543: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 6544: 
                   6545: =head1 SYNOPSIS
                   6546: 
1.243     albertel 6547: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 6548: 
                   6549:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   6550: 
1.243     albertel 6551: Common parameters:
                   6552: 
                   6553: =over 4
                   6554: 
                   6555: =item *
                   6556: 
                   6557: $uname : an internal username (if $cname expecting a course Id specifically)
                   6558: 
                   6559: =item *
                   6560: 
                   6561: $udom : a domain (if $cdom expecting a course's domain specifically)
                   6562: 
                   6563: =item *
                   6564: 
                   6565: $symb : a resource instance identifier
                   6566: 
                   6567: =item *
                   6568: 
                   6569: $namespace : the name of a .db file that contains the data needed or
                   6570: being set.
                   6571: 
                   6572: =back
                   6573: 
1.394     bowersj2 6574: =head1 OVERVIEW
1.191     harris41 6575: 
1.394     bowersj2 6576: lonnet provides subroutines which interact with the
                   6577: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   6578: about classes, users, and resources.
1.243     albertel 6579: 
                   6580: For many of these objects you can also use this to store data about
                   6581: them or modify them in various ways.
1.191     harris41 6582: 
1.394     bowersj2 6583: =head2 Symbs
1.191     harris41 6584: 
1.394     bowersj2 6585: To identify a specific instance of a resource, LON-CAPA uses symbols
                   6586: or "symbs"X<symb>. These identifiers are built from the URL of the
                   6587: map, the resource number of the resource in the map, and the URL of
                   6588: the resource itself. The latter is somewhat redundant, but might help
                   6589: if maps change.
                   6590: 
                   6591: An example is
                   6592: 
                   6593:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   6594: 
                   6595: The respective map entry is
                   6596: 
                   6597:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   6598:   title="Problem 2">
                   6599:  </resource>
                   6600: 
                   6601: Symbs are used by the random number generator, as well as to store and
                   6602: restore data specific to a certain instance of for example a problem.
                   6603: 
                   6604: =head2 Storing And Retrieving Data
                   6605: 
                   6606: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   6607: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   6608: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   6609: is is the non-critical message twin of cstore. These functions are for
                   6610: handlers to store a perl hash to a user's permanent data space in an
                   6611: easy manner, and to retrieve it again on another call. It is expected
                   6612: that a handler would use this once at the beginning to retrieve data,
                   6613: and then again once at the end to send only the new data back.
                   6614: 
                   6615: The data is stored in the user's data directory on the user's
                   6616: homeserver under the ID of the course.
                   6617: 
                   6618: The hash that is returned by restore will have all of the previous
                   6619: value for all of the elements of the hash.
                   6620: 
                   6621: Example:
                   6622: 
                   6623:  #creating a hash
                   6624:  my %hash;
                   6625:  $hash{'foo'}='bar';
                   6626: 
                   6627:  #storing it
                   6628:  &Apache::lonnet::cstore(\%hash);
                   6629: 
                   6630:  #changing a value
                   6631:  $hash{'foo'}='notbar';
                   6632: 
                   6633:  #adding a new value
                   6634:  $hash{'bar'}='foo';
                   6635:  &Apache::lonnet::cstore(\%hash);
                   6636: 
                   6637:  #retrieving the hash
                   6638:  my %history=&Apache::lonnet::restore();
                   6639: 
                   6640:  #print the hash
                   6641:  foreach my $key (sort(keys(%history))) {
                   6642:    print("\%history{$key} = $history{$key}");
                   6643:  }
                   6644: 
                   6645: Will print out:
1.191     harris41 6646: 
1.394     bowersj2 6647:  %history{1:foo} = bar
                   6648:  %history{1:keys} = foo:timestamp
                   6649:  %history{1:timestamp} = 990455579
                   6650:  %history{2:bar} = foo
                   6651:  %history{2:foo} = notbar
                   6652:  %history{2:keys} = foo:bar:timestamp
                   6653:  %history{2:timestamp} = 990455580
                   6654:  %history{bar} = foo
                   6655:  %history{foo} = notbar
                   6656:  %history{timestamp} = 990455580
                   6657:  %history{version} = 2
                   6658: 
                   6659: Note that the special hash entries C<keys>, C<version> and
                   6660: C<timestamp> were added to the hash. C<version> will be equal to the
                   6661: total number of versions of the data that have been stored. The
                   6662: C<timestamp> attribute will be the UNIX time the hash was
                   6663: stored. C<keys> is available in every historical section to list which
                   6664: keys were added or changed at a specific historical revision of a
                   6665: hash.
                   6666: 
                   6667: B<Warning>: do not store the hash that restore returns directly. This
                   6668: will cause a mess since it will restore the historical keys as if the
                   6669: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 6670: 
1.394     bowersj2 6671: Calling convention:
1.191     harris41 6672: 
1.394     bowersj2 6673:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   6674:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 6675: 
1.394     bowersj2 6676: For more detailed information, see lonnet specific documentation.
1.191     harris41 6677: 
1.394     bowersj2 6678: =head1 RETURN MESSAGES
1.191     harris41 6679: 
1.394     bowersj2 6680: =over 4
1.191     harris41 6681: 
1.394     bowersj2 6682: =item * B<con_lost>: unable to contact remote host
1.191     harris41 6683: 
1.394     bowersj2 6684: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   6685: when the connection is brought back up
1.191     harris41 6686: 
1.394     bowersj2 6687: =item * B<con_failed>: unable to contact remote host and unable to save message
                   6688: for later delivery
1.191     harris41 6689: 
1.394     bowersj2 6690: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 6691: 
1.394     bowersj2 6692: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 6693: that was requested
1.191     harris41 6694: 
1.243     albertel 6695: =back
1.191     harris41 6696: 
1.243     albertel 6697: =head1 PUBLIC SUBROUTINES
1.191     harris41 6698: 
1.243     albertel 6699: =head2 Session Environment Functions
1.191     harris41 6700: 
1.243     albertel 6701: =over 4
1.191     harris41 6702: 
1.394     bowersj2 6703: =item * 
                   6704: X<appenv()>
                   6705: B<appenv(%hash)>: the value of %hash is written to
                   6706: the user envirnoment file, and will be restored for each access this
1.620     albertel 6707: user makes during this session, also modifies the %env for the current
1.394     bowersj2 6708: process
1.191     harris41 6709: 
                   6710: =item *
1.394     bowersj2 6711: X<delenv()>
                   6712: B<delenv($regexp)>: removes all items from the session
                   6713: environment file that matches the regular expression in $regexp. The
1.620     albertel 6714: values are also delted from the current processes %env.
1.191     harris41 6715: 
1.243     albertel 6716: =back
                   6717: 
                   6718: =head2 User Information
1.191     harris41 6719: 
1.243     albertel 6720: =over 4
1.191     harris41 6721: 
                   6722: =item *
1.394     bowersj2 6723: X<queryauthenticate()>
                   6724: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 6725: authentication scheme
                   6726: 
                   6727: =item *
1.394     bowersj2 6728: X<authenticate()>
                   6729: B<authenticate($uname,$upass,$udom)>: try to
                   6730: authenticate user from domain's lib servers (first use the current
                   6731: one). C<$upass> should be the users password.
1.191     harris41 6732: 
                   6733: =item *
1.394     bowersj2 6734: X<homeserver()>
                   6735: B<homeserver($uname,$udom)>: find the server which has
                   6736: the user's directory and files (there must be only one), this caches
                   6737: the answer, and also caches if there is a borken connection.
1.191     harris41 6738: 
                   6739: =item *
1.394     bowersj2 6740: X<idget()>
                   6741: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   6742: (IDs are a unique resource in a domain, there must be only 1 ID per
                   6743: username, and only 1 username per ID in a specific domain) (returns
                   6744: hash: id=>name,id=>name)
1.191     harris41 6745: 
                   6746: =item *
1.394     bowersj2 6747: X<idrget()>
                   6748: B<idrget($udom,@unames)>: find the IDs behind a list of
                   6749: usernames (returns hash: name=>id,name=>id)
1.191     harris41 6750: 
                   6751: =item *
1.394     bowersj2 6752: X<idput()>
                   6753: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 6754: 
                   6755: =item *
1.394     bowersj2 6756: X<rolesinit()>
                   6757: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 6758: 
                   6759: =item *
1.551     albertel 6760: X<getsection()>
                   6761: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 6762: course $cname, return section name/number or '' for "not in course"
                   6763: and '-1' for "no section"
                   6764: 
                   6765: =item *
1.394     bowersj2 6766: X<userenvironment()>
                   6767: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 6768: passed in @what from the requested user's environment, returns a hash
                   6769: 
                   6770: =back
                   6771: 
                   6772: =head2 User Roles
                   6773: 
                   6774: =over 4
                   6775: 
                   6776: =item *
                   6777: 
                   6778: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   6779: actions
                   6780:  F: full access
                   6781:  U,I,K: authentication modes (cxx only)
                   6782:  '': forbidden
                   6783:  1: user needs to choose course
                   6784:  2: browse allowed
                   6785: 
                   6786: =item *
                   6787: 
                   6788: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   6789: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   6790: and course level
                   6791: 
                   6792: =item *
                   6793: 
                   6794: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   6795: explanation of a user role term
                   6796: 
                   6797: =back
                   6798: 
                   6799: =head2 User Modification
                   6800: 
                   6801: =over 4
                   6802: 
                   6803: =item *
                   6804: 
                   6805: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   6806: user for the level given by URL.  Optional start and end dates (leave empty
                   6807: string or zero for "no date")
1.191     harris41 6808: 
                   6809: =item *
                   6810: 
1.243     albertel 6811: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   6812: change a users, password, possible return values are: ok,
                   6813: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   6814: refused
1.191     harris41 6815: 
                   6816: =item *
                   6817: 
1.243     albertel 6818: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 6819: 
                   6820: =item *
                   6821: 
1.243     albertel 6822: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   6823: modify user
1.191     harris41 6824: 
                   6825: =item *
                   6826: 
1.286     matthew  6827: modifystudent
                   6828: 
                   6829: modify a students enrollment and identification information.
                   6830: The course id is resolved based on the current users environment.  
                   6831: This means the envoking user must be a course coordinator or otherwise
                   6832: associated with a course.
                   6833: 
1.297     matthew  6834: This call is essentially a wrapper for lonnet::modifyuser and
                   6835: lonnet::modify_student_enrollment
1.286     matthew  6836: 
                   6837: Inputs: 
                   6838: 
                   6839: =over 4
                   6840: 
                   6841: =item B<$udom> Students loncapa domain
                   6842: 
                   6843: =item B<$uname> Students loncapa login name
                   6844: 
                   6845: =item B<$uid> Students id/student number
                   6846: 
                   6847: =item B<$umode> Students authentication mode
                   6848: 
                   6849: =item B<$upass> Students password
                   6850: 
                   6851: =item B<$first> Students first name
                   6852: 
                   6853: =item B<$middle> Students middle name
                   6854: 
                   6855: =item B<$last> Students last name
                   6856: 
                   6857: =item B<$gene> Students generation
                   6858: 
                   6859: =item B<$usec> Students section in course
                   6860: 
                   6861: =item B<$end> Unix time of the roles expiration
                   6862: 
                   6863: =item B<$start> Unix time of the roles start date
                   6864: 
                   6865: =item B<$forceid> If defined, allow $uid to be changed
                   6866: 
                   6867: =item B<$desiredhome> server to use as home server for student
                   6868: 
                   6869: =back
1.297     matthew  6870: 
                   6871: =item *
                   6872: 
                   6873: modify_student_enrollment
                   6874: 
                   6875: Change a students enrollment status in a class.  The environment variable
                   6876: 'role.request.course' must be defined for this function to proceed.
                   6877: 
                   6878: Inputs:
                   6879: 
                   6880: =over 4
                   6881: 
                   6882: =item $udom, students domain
                   6883: 
                   6884: =item $uname, students name
                   6885: 
                   6886: =item $uid, students user id
                   6887: 
                   6888: =item $first, students first name
                   6889: 
                   6890: =item $middle
                   6891: 
                   6892: =item $last
                   6893: 
                   6894: =item $gene
                   6895: 
                   6896: =item $usec
                   6897: 
                   6898: =item $end
                   6899: 
                   6900: =item $start
                   6901: 
                   6902: =back
                   6903: 
1.191     harris41 6904: 
                   6905: =item *
                   6906: 
1.243     albertel 6907: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   6908: custom role; give a custom role to a user for the level given by URL.  Specify
                   6909: name and domain of role author, and role name
1.191     harris41 6910: 
                   6911: =item *
                   6912: 
1.243     albertel 6913: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 6914: 
                   6915: =item *
                   6916: 
1.243     albertel 6917: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   6918: 
                   6919: =back
                   6920: 
                   6921: =head2 Course Infomation
                   6922: 
                   6923: =over 4
1.191     harris41 6924: 
                   6925: =item *
                   6926: 
1.631     albertel 6927: coursedescription($courseid) : returns a hash of information about the
                   6928: specified course id, including all environment settings for the
                   6929: course, the description of the course will be in the hash under the
                   6930: key 'description'
1.191     harris41 6931: 
                   6932: =item *
                   6933: 
1.624     albertel 6934: resdata($name,$domain,$type,@which) : request for current parameter
                   6935: setting for a specific $type, where $type is either 'course' or 'user',
                   6936: @what should be a list of parameters to ask about. This routine caches
                   6937: answers for 5 minutes.
1.243     albertel 6938: 
                   6939: =back
                   6940: 
                   6941: =head2 Course Modification
                   6942: 
                   6943: =over 4
1.191     harris41 6944: 
                   6945: =item *
                   6946: 
1.243     albertel 6947: writecoursepref($courseid,%prefs) : write preferences (environment
                   6948: database) for a course
1.191     harris41 6949: 
                   6950: =item *
                   6951: 
1.243     albertel 6952: createcourse($udom,$description,$url) : make/modify course
                   6953: 
                   6954: =back
                   6955: 
                   6956: =head2 Resource Subroutines
                   6957: 
                   6958: =over 4
1.191     harris41 6959: 
                   6960: =item *
                   6961: 
1.243     albertel 6962: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 6963: 
                   6964: =item *
                   6965: 
1.243     albertel 6966: repcopy($filename) : subscribes to the requested file, and attempts to
                   6967: replicate from the owning library server, Might return
1.607     raeburn  6968: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   6969: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 6970: resource. Expects the local filesystem pathname
                   6971: (/home/httpd/html/res/....)
                   6972: 
                   6973: =back
                   6974: 
                   6975: =head2 Resource Information
                   6976: 
                   6977: =over 4
1.191     harris41 6978: 
                   6979: =item *
                   6980: 
1.243     albertel 6981: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   6982: a vairety of different possible values, $varname should be a request
                   6983: string, and the other parameters can be used to specify who and what
                   6984: one is asking about.
                   6985: 
                   6986: Possible values for $varname are environment.lastname (or other item
                   6987: from the envirnment hash), user.name (or someother aspect about the
                   6988: user), resource.0.maxtries (or some other part and parameter of a
                   6989: resource)
1.204     albertel 6990: 
                   6991: =item *
                   6992: 
1.243     albertel 6993: directcondval($number) : get current value of a condition; reads from a state
                   6994: string
1.204     albertel 6995: 
                   6996: =item *
                   6997: 
1.243     albertel 6998: condval($condidx) : value of condition index based on state
1.204     albertel 6999: 
                   7000: =item *
                   7001: 
1.243     albertel 7002: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7003: resource's metadata, $what should be either a specific key, or either
                   7004: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7005: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7006: 
                   7007: this function automatically caches all requests
1.191     harris41 7008: 
                   7009: =item *
                   7010: 
1.243     albertel 7011: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7012: network of library servers; returns file handle of where SQL and regex results
                   7013: will be stored for query
1.191     harris41 7014: 
                   7015: =item *
                   7016: 
1.243     albertel 7017: symbread($filename) : return symbolic list entry (filename argument optional);
                   7018: returns the data handle
1.191     harris41 7019: 
                   7020: =item *
                   7021: 
1.243     albertel 7022: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7023: a possible symb for the URL in $thisfn, and if is an encryypted
                   7024: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7025: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7026: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7027: 
1.191     harris41 7028: 
                   7029: =item *
                   7030: 
1.243     albertel 7031: symbclean($symb) : removes versions numbers from a symb, returns the
                   7032: cleaned symb
1.191     harris41 7033: 
                   7034: =item *
                   7035: 
1.243     albertel 7036: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7037: course map, user must be in a course for it to work.
1.191     harris41 7038: 
                   7039: =item *
                   7040: 
1.243     albertel 7041: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7042: 
                   7043: =item *
                   7044: 
1.243     albertel 7045: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7046: a random seed, all arguments are optional, if they aren't sent it uses the
                   7047: environment to derive them. Note: if symb isn't sent and it can't get one
                   7048: from &symbread it will use the current time as its return value
1.191     harris41 7049: 
                   7050: =item *
                   7051: 
1.243     albertel 7052: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7053: unfakeable, receipt
1.191     harris41 7054: 
                   7055: =item *
                   7056: 
1.620     albertel 7057: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7058: 
                   7059: =item *
                   7060: 
1.243     albertel 7061: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7062: 
                   7063: =item *
                   7064: 
1.243     albertel 7065: 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 7066: 
                   7067: =item *
                   7068: 
1.243     albertel 7069: 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 7070: 
                   7071: =item *
                   7072: 
1.243     albertel 7073: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7074: 
                   7075: =item *
                   7076: 
1.243     albertel 7077: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7078: forcing spreadsheet to reevaluate the resource scores next time.
                   7079: 
                   7080: =back
                   7081: 
                   7082: =head2 Storing/Retreiving Data
                   7083: 
                   7084: =over 4
1.191     harris41 7085: 
                   7086: =item *
                   7087: 
1.243     albertel 7088: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7089: for this url; hashref needs to be given and should be a \%hashname; the
                   7090: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7091: be derived from the env
1.191     harris41 7092: 
                   7093: =item *
                   7094: 
1.243     albertel 7095: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7096: uses critical subroutine
1.191     harris41 7097: 
                   7098: =item *
                   7099: 
1.243     albertel 7100: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7101: all args are optional
1.191     harris41 7102: 
                   7103: =item *
                   7104: 
1.243     albertel 7105: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7106: works very similar to store/cstore, but all data is stored in a
                   7107: temporary location and can be reset using tmpreset, $storehash should
                   7108: be a hash reference, returns nothing on success
1.191     harris41 7109: 
                   7110: =item *
                   7111: 
1.243     albertel 7112: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7113: similar to restore, but all data is stored in a temporary location and
                   7114: can be reset using tmpreset. Returns a hash of values on success,
                   7115: error string otherwise.
1.191     harris41 7116: 
                   7117: =item *
                   7118: 
1.243     albertel 7119: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7120: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7121: 
                   7122: =item *
                   7123: 
1.243     albertel 7124: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7125: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7126: 
                   7127: =item *
                   7128: 
1.243     albertel 7129: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7130: namesp ($udom and $uname are optional)
1.191     harris41 7131: 
                   7132: =item *
                   7133: 
1.243     albertel 7134: dump($namespace,$udom,$uname,$regexp) : 
                   7135: dumps the complete (or key matching regexp) namespace into a hash
                   7136: ($udom, $uname and $regexp are optional)
1.449     matthew  7137: 
                   7138: =item *
                   7139: 
                   7140: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7141: $store can be a scalar, an array reference, or if the amount to be 
                   7142: incremented is > 1, a hash reference.
                   7143: 
                   7144: ($udom and $uname are optional)
1.191     harris41 7145: 
                   7146: =item *
                   7147: 
1.243     albertel 7148: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7149: ($udom and $uname are optional)
1.191     harris41 7150: 
                   7151: =item *
                   7152: 
1.524     raeburn  7153: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
                   7154: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
                   7155: used in records written by &store and retrieved by &restore.  This function 
                   7156: was created for use in editing discussion posts, without incrementing the
                   7157: version number included in the key for a particular post. The colon 
                   7158: separated list of attribute names (e.g., the value associated with the key 
                   7159: 1:keys:$symb) is also generated and passed in the ampersand separated 
                   7160: items sent to lonnet::reply().  
                   7161: 
                   7162: =item *
                   7163: 
1.243     albertel 7164: cput($namespace,$storehash,$udom,$uname) : critical put
                   7165: ($udom and $uname are optional)
1.191     harris41 7166: 
                   7167: =item *
                   7168: 
1.243     albertel 7169: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7170: reference filled in from namesp (encrypts the return communication)
                   7171: ($udom and $uname are optional)
1.191     harris41 7172: 
                   7173: =item *
                   7174: 
1.243     albertel 7175: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7176: critical subroutine
                   7177: 
                   7178: =back
                   7179: 
                   7180: =head2 Network Status Functions
                   7181: 
                   7182: =over 4
1.191     harris41 7183: 
                   7184: =item *
                   7185: 
                   7186: dirlist($uri) : return directory list based on URI
                   7187: 
                   7188: =item *
                   7189: 
1.243     albertel 7190: spareserver() : find server with least workload from spare.tab
                   7191: 
                   7192: =back
                   7193: 
                   7194: =head2 Apache Request
                   7195: 
                   7196: =over 4
1.191     harris41 7197: 
                   7198: =item *
                   7199: 
1.243     albertel 7200: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7201: localhost, posts hash
                   7202: 
                   7203: =back
                   7204: 
                   7205: =head2 Data to String to Data
                   7206: 
                   7207: =over 4
1.191     harris41 7208: 
                   7209: =item *
                   7210: 
1.243     albertel 7211: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7212: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7213: 
                   7214: =item *
                   7215: 
1.243     albertel 7216: hashref2str($hashref) : convert a hashref into a string complete with
                   7217: escaping and '=' and '&' separators, supports elements that are
                   7218: arrayrefs and hashrefs
1.191     harris41 7219: 
                   7220: =item *
                   7221: 
1.243     albertel 7222: arrayref2str($arrayref) : convert an arrayref into a string complete
                   7223: with escaping and '&' separators, supports elements that are arrayrefs
                   7224: and hashrefs
1.191     harris41 7225: 
                   7226: =item *
                   7227: 
1.243     albertel 7228: str2hash($string) : convert string to hash using unescaping and
                   7229: splitting on '=' and '&', supports elements that are arrayrefs and
                   7230: hashrefs
1.191     harris41 7231: 
                   7232: =item *
                   7233: 
1.243     albertel 7234: str2array($string) : convert string to hash using unescaping and
                   7235: splitting on '&', supports elements that are arrayrefs and hashrefs
                   7236: 
                   7237: =back
                   7238: 
                   7239: =head2 Logging Routines
                   7240: 
                   7241: =over 4
                   7242: 
                   7243: These routines allow one to make log messages in the lonnet.log and
                   7244: lonnet.perm logfiles.
1.191     harris41 7245: 
                   7246: =item *
                   7247: 
1.243     albertel 7248: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 7249: 
                   7250: =item *
                   7251: 
1.243     albertel 7252: logthis() : append message to the normal lonnet.log file, it gets
                   7253: preiodically rolled over and deleted.
1.191     harris41 7254: 
                   7255: =item *
                   7256: 
1.243     albertel 7257: logperm() : append a permanent message to lonnet.perm.log, this log
                   7258: file never gets deleted by any automated portion of the system, only
                   7259: messages of critical importance should go in here.
                   7260: 
                   7261: =back
                   7262: 
                   7263: =head2 General File Helper Routines
                   7264: 
                   7265: =over 4
1.191     harris41 7266: 
                   7267: =item *
                   7268: 
1.481     raeburn  7269: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   7270: (a) files in /uploaded
                   7271:   (i) If a local copy of the file exists - 
                   7272:       compares modification date of local copy with last-modified date for 
                   7273:       definitive version stored on home server for course. If local copy is 
                   7274:       stale, requests a new version from the home server and stores it. 
                   7275:       If the original has been removed from the home server, then local copy 
                   7276:       is unlinked.
                   7277:   (ii) If local copy does not exist -
                   7278:       requests the file from the home server and stores it. 
                   7279:   
                   7280:   If $caller is 'uploadrep':  
                   7281:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   7282:     for request for files originally uploaded via DOCS. 
                   7283:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   7284:   
                   7285:   Otherwise:
                   7286:      This indicates a call from the content generation phase of the request.
                   7287:      -  returns the entire contents of the file or -1.
                   7288:      
                   7289: (b) files in /res
                   7290:    - returns the entire contents of a file or -1; 
                   7291:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 7292: 
                   7293: =item *
                   7294: 
1.243     albertel 7295: filelocation($dir,$file) : returns file system location of a file
                   7296: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   7297: directory that relative $file lookups are to looked in ($dir of /a/dir
                   7298: and a file of ../bob will become /a/bob)
1.191     harris41 7299: 
                   7300: =item *
                   7301: 
                   7302: hreflocation($dir,$file) : returns file system location or a URL; same as
                   7303: filelocation except for hrefs
                   7304: 
                   7305: =item *
                   7306: 
                   7307: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   7308: 
1.243     albertel 7309: =back
                   7310: 
1.608     albertel 7311: =head2 Usererfile file routines (/uploaded*)
                   7312: 
                   7313: =over 4
                   7314: 
                   7315: =item *
                   7316: 
                   7317: userfileupload(): main rotine for putting a file in a user or course's
                   7318:                   filespace, arguments are,
                   7319: 
1.620     albertel 7320:  formname - required - this is the name of the element in $env where the
1.608     albertel 7321:            filename, and the contents of the file to create/modifed exist
1.620     albertel 7322:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   7323:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 7324:  coursedoc - if true, store the file in the course of the active role
                   7325:              of the current user
                   7326:  subdir - required - subdirectory to put the file in under ../userfiles/
                   7327:          if undefined, it will be placed in "unknown"
                   7328: 
                   7329:  (This routine calls clean_filename() to remove any dangerous
                   7330:  characters from the filename, and then calls finuserfileupload() to
                   7331:  complete the transaction)
                   7332: 
                   7333:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7334:  and /adm/notfound.html if unsuccessful
                   7335: 
                   7336: =item *
                   7337: 
                   7338: clean_filename(): routine for cleaing a filename up for storage in
                   7339:                  userfile space, argument is:
                   7340: 
                   7341:  filename - proposed filename
                   7342: 
                   7343: returns: the new clean filename
                   7344: 
                   7345: =item *
                   7346: 
                   7347: finishuserfileupload(): routine that creaes and sends the file to
                   7348: userspace, probably shouldn't be called directly
                   7349: 
                   7350:   docuname: username or courseid of destination for the file
                   7351:   docudom: domain of user/course of destination for the file
                   7352:   formname: same as for userfileupload()
                   7353:   fname: filename (inculding subdirectories) for the file
                   7354: 
                   7355:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7356:  and /adm/notfound.html if unsuccessful
                   7357: 
                   7358: =item *
                   7359: 
                   7360: renameuserfile(): renames an existing userfile to a new name
                   7361: 
                   7362:   Args:
                   7363:    docuname: username or courseid of destination for the file
                   7364:    docudom: domain of user/course of destination for the file
                   7365:    old: current file name (including any subdirs under userfiles)
                   7366:    new: desired file name (including any subdirs under userfiles)
                   7367: 
                   7368: =item *
                   7369: 
                   7370: mkdiruserfile(): creates a directory is a userfiles dir
                   7371: 
                   7372:   Args:
                   7373:    docuname: username or courseid of destination for the file
                   7374:    docudom: domain of user/course of destination for the file
                   7375:    dir: dir to create (including any subdirs under userfiles)
                   7376: 
                   7377: =item *
                   7378: 
                   7379: removeuserfile(): removes a file that exists in userfiles
                   7380: 
                   7381:   Args:
                   7382:    docuname: username or courseid of destination for the file
                   7383:    docudom: domain of user/course of destination for the file
                   7384:    fname: filname to delete (including any subdirs under userfiles)
                   7385: 
                   7386: =item *
                   7387: 
                   7388: removeuploadedurl(): convience function for removeuserfile()
                   7389: 
                   7390:   Args:
                   7391:    url:  a full /uploaded/... url to delete
                   7392: 
                   7393: =back
                   7394: 
1.243     albertel 7395: =head2 HTTP Helper Routines
                   7396: 
                   7397: =over 4
                   7398: 
1.191     harris41 7399: =item *
                   7400: 
                   7401: escape() : unpack non-word characters into CGI-compatible hex codes
                   7402: 
                   7403: =item *
                   7404: 
                   7405: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   7406: 
1.243     albertel 7407: =back
                   7408: 
                   7409: =head1 PRIVATE SUBROUTINES
                   7410: 
                   7411: =head2 Underlying communication routines (Shouldn't call)
                   7412: 
                   7413: =over 4
                   7414: 
                   7415: =item *
                   7416: 
                   7417: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   7418: 
                   7419: =item *
                   7420: 
                   7421: reply() : uses subreply to send a message to remote machine, logs all failures
                   7422: 
                   7423: =item *
                   7424: 
                   7425: critical() : passes a critical message to another server; if cannot
                   7426: get through then place message in connection buffer directory and
                   7427: returns con_delayed, if incapable of saving message, returns
                   7428: con_failed
                   7429: 
                   7430: =item *
                   7431: 
                   7432: reconlonc() : tries to reconnect lonc client processes.
                   7433: 
                   7434: =back
                   7435: 
                   7436: =head2 Resource Access Logging
                   7437: 
                   7438: =over 4
                   7439: 
                   7440: =item *
                   7441: 
                   7442: flushcourselogs() : flush (save) buffer logs and access logs
                   7443: 
                   7444: =item *
                   7445: 
                   7446: courselog($what) : save message for course in hash
                   7447: 
                   7448: =item *
                   7449: 
                   7450: courseacclog($what) : save message for course using &courselog().  Perform
                   7451: special processing for specific resource types (problems, exams, quizzes, etc).
                   7452: 
1.191     harris41 7453: =item *
                   7454: 
                   7455: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   7456: as a PerlChildExitHandler
1.243     albertel 7457: 
                   7458: =back
                   7459: 
                   7460: =head2 Other
                   7461: 
                   7462: =over 4
                   7463: 
                   7464: =item *
                   7465: 
                   7466: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 7467: 
                   7468: =back
                   7469: 
                   7470: =cut

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