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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.37! raeburn     4: # $Id: lonnet.pm,v 1.1056.4.36 2012/01/08 23:34:38 raeburn 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.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1056.4.33  raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1056.4.13  raeburn    99: use File::Copy;
1.676     albertel  100: 
1.195     www       101: my $readit;
1.550     foxr      102: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    154: 	print $fh $logstring;
1.448     albertel  155: 	close($fh);
                    156:     }
1.1       albertel  157:     return 1;
                    158: }
                    159: 
                    160: sub logperm {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.448     albertel  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    166: 	print $fh "$now:$message:$local\n";
                    167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
1.850     albertel  172: sub create_connection {
1.853     albertel  173:     my ($hostname,$lonid) = @_;
1.851     albertel  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  175: 				     Type    => SOCK_STREAM,
                    176: 				     Timeout => 10);
                    177:     return 0 if (!$client);
1.890     albertel  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  179:     my $result = <$client>;
                    180:     chomp($result);
                    181:     return 1 if ($result eq 'done');
                    182:     return 0;
                    183: }
                    184: 
1.983     raeburn   185: sub get_server_timezone {
                    186:     my ($cnum,$cdom) = @_;
                    187:     my $home=&homeserver($cnum,$cdom);
                    188:     if ($home ne 'no_host') {
                    189:         my $cachetime = 24*3600;
                    190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    191:         if (defined($cached)) {
                    192:             return $timezone;
                    193:         } else {
                    194:             my $timezone = &reply('servertimezone',$home);
                    195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    196:         }
                    197:     }
                    198: }
1.850     albertel  199: 
1.1056.4.25  raeburn   200: sub get_server_distarch {
                    201:     my ($lonhost,$ignore_cache) = @_;
                    202:     if (defined($lonhost)) {
                    203:         if (!defined(&hostname($lonhost))) {
                    204:             return;
                    205:         }
                    206:         my $cachetime = 12*3600;
                    207:         if (!$ignore_cache) {
                    208:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    209:             if (defined($cached)) {
                    210:                 return $distarch;
                    211:             }
                    212:         }
                    213:         my $rep = &reply('serverdistarch',$lonhost);
                    214:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    215:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    216:                 $rep eq '') {
                    217:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    218:         }
                    219:     }
                    220:     return;
                    221: }
                    222: 
1.993     raeburn   223: sub get_server_loncaparev {
1.1056.4.3  raeburn   224:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   225:     if (defined($lonhost)) {
                    226:         if (!defined(&hostname($lonhost))) {
                    227:             undef($lonhost);
                    228:         }
                    229:     }
                    230:     if (!defined($lonhost)) {
                    231:         if (defined(&domain($dom,'primary'))) {
                    232:             $lonhost=&domain($dom,'primary');
                    233:             if ($lonhost eq 'no_host') {
                    234:                 undef($lonhost);
                    235:             }
                    236:         }
                    237:     }
                    238:     if (defined($lonhost)) {
1.1056.4.3  raeburn   239:         my $cachetime = 12*3600;
                    240:         if (!$ignore_cache) {
                    241:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    242:             if (defined($cached)) {
                    243:                 return $loncaparev;
                    244:             }
                    245:         }
                    246:         my ($answer,$loncaparev);
                    247:         my @ids=&current_machine_ids();
                    248:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    249:             $answer = $perlvar{'lonVersion'};
1.1056.4.7  raeburn   250:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   251:                 $loncaparev = $1;
                    252:             }
                    253:         } else {
                    254:             $answer = &reply('serverloncaparev',$lonhost);
                    255:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    256:                 if ($caller eq 'loncron') {
                    257:                     my $ua=new LWP::UserAgent;
1.1056.4.8  raeburn   258:                     $ua->timeout(4);
1.1056.4.3  raeburn   259:                     my $protocol = $protocol{$lonhost};
                    260:                     $protocol = 'http' if ($protocol ne 'https');
                    261:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    262:                     my $request=new HTTP::Request('GET',$url);
                    263:                     my $response=$ua->request($request);
                    264:                     unless ($response->is_error()) {
                    265:                         my $content = $response->content;
1.1056.4.7  raeburn   266:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3  raeburn   267:                             $loncaparev = $1;
                    268:                         }
                    269:                     }
                    270:                 } else {
                    271:                     $loncaparev = $loncaparevs{$lonhost};
                    272:                 }
1.1056.4.7  raeburn   273:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   274:                 $loncaparev = $1;
                    275:             }
                    276:         }
                    277:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    278:     }
                    279: }
                    280: 
                    281: sub get_server_homeID {
                    282:     my ($hostname,$ignore_cache,$caller) = @_;
                    283:     unless ($ignore_cache) {
                    284:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993     raeburn   285:         if (defined($cached)) {
1.1056.4.3  raeburn   286:             return $serverhomeID;
                    287:         }
                    288:     }
                    289:     my $cachetime = 12*3600;
                    290:     my $serverhomeID;
                    291:     if ($caller eq 'loncron') {
                    292:         my @machine_ids = &machine_ids($hostname);
                    293:         foreach my $id (@machine_ids) {
                    294:             my $response = &reply('serverhomeID',$id);
                    295:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    296:                 $serverhomeID = $response;
                    297:                 last;
                    298:             }
1.993     raeburn   299:         }
1.1056.4.3  raeburn   300:         if ($serverhomeID eq '') {
                    301:             $serverhomeID = $machine_ids[-1];
                    302:         }
                    303:     } else {
                    304:         $serverhomeID = $serverhomeIDs{$hostname};
1.993     raeburn   305:     }
1.1056.4.3  raeburn   306:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993     raeburn   307: }
                    308: 
1.1       albertel  309: # -------------------------------------------------- Non-critical communication
                    310: sub subreply {
                    311:     my ($cmd,$server)=@_;
1.838     albertel  312:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      313:     #
                    314:     #  With loncnew process trimming, there's a timing hole between lonc server
                    315:     #  process exit and the master server picking up the listen on the AF_UNIX
                    316:     #  socket.  In that time interval, a lock file will exist:
                    317: 
                    318:     my $lockfile=$peerfile.".lock";
                    319:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    320: 	sleep(1);
                    321:     }
                    322:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      323:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      324:     #
1.550     foxr      325:     #   We'll give the connection a few tries before abandoning it.  If
                    326:     #   connection is not possible, we'll con_lost back to the client.
                    327:     #   
                    328:     my $client;
                    329:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    330: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    331: 				      Type    => SOCK_STREAM,
                    332: 				      Timeout => 10);
1.869     albertel  333: 	if ($client) {
1.550     foxr      334: 	    last;		# Connected!
1.850     albertel  335: 	} else {
1.853     albertel  336: 	    &create_connection(&hostname($server),$server);
1.550     foxr      337: 	}
1.850     albertel  338:         sleep(1);		# Try again later if failed connection.
1.550     foxr      339:     }
                    340:     my $answer;
                    341:     if ($client) {
1.704     albertel  342: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      343: 	$answer=<$client>;
                    344: 	if (!$answer) { $answer="con_lost"; }
                    345: 	chomp($answer);
                    346:     } else {
                    347: 	$answer = 'con_lost';	# Failed connection.
                    348:     }
1.1       albertel  349:     return $answer;
                    350: }
                    351: 
                    352: sub reply {
                    353:     my ($cmd,$server)=@_;
1.838     albertel  354:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  355:     my $answer=subreply($cmd,$server);
1.65      www       356:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  357:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       358:                 " $cmd to $server returned $answer</font>");
                    359:     }
1.1       albertel  360:     return $answer;
                    361: }
                    362: 
                    363: # ----------------------------------------------------------- Send USR1 to lonc
                    364: 
                    365: sub reconlonc {
1.891     albertel  366:     my ($lonid) = @_;
                    367:     my $hostname = &hostname($lonid);
                    368:     if ($lonid) {
                    369: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    370: 	if ($hostname && -e $peerfile) {
                    371: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    372: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    373: 					     Type    => SOCK_STREAM,
                    374: 					     Timeout => 10);
                    375: 	    if ($client) {
                    376: 		print $client ("reset_retries\n");
                    377: 		my $answer=<$client>;
                    378: 		#reset just this one.
                    379: 	    }
                    380: 	}
                    381: 	return;
                    382:     }
                    383: 
1.836     www       384:     &logthis("Trying to reconnect lonc");
1.1       albertel  385:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  386:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  387: 	my $loncpid=<$fh>;
                    388:         chomp($loncpid);
                    389:         if (kill 0 => $loncpid) {
                    390: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    391:             kill USR1 => $loncpid;
                    392:             sleep 1;
1.836     www       393:          } else {
1.12      www       394: 	    &logthis(
1.672     albertel  395:                "<font color=\"blue\">WARNING:".
1.12      www       396:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  397:         }
                    398:     } else {
1.836     www       399: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  400:     }
                    401: }
                    402: 
                    403: # ------------------------------------------------------ Critical communication
1.12      www       404: 
1.1       albertel  405: sub critical {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (&hostname($server)) {
1.672     albertel  408:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       409:                " Critical message to unknown server ($server)</font>");
                    410:         return 'no_such_host';
                    411:     }
1.1       albertel  412:     my $answer=reply($cmd,$server);
                    413:     if ($answer eq 'con_lost') {
                    414: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  415: 	my $answer=reply($cmd,$server);
1.1       albertel  416:         if ($answer eq 'con_lost') {
                    417:             my $now=time;
                    418:             my $middlename=$cmd;
1.5       www       419:             $middlename=substr($middlename,0,16);
1.1       albertel  420:             $middlename=~s/\W//g;
                    421:             my $dfilename=
1.305     www       422:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    423:             $dumpcount++;
1.1       albertel  424:             {
1.448     albertel  425: 		my $dfh;
                    426: 		if (open($dfh,">$dfilename")) {
                    427: 		    print $dfh "$cmd\n"; 
                    428: 		    close($dfh);
                    429: 		}
1.1       albertel  430:             }
                    431:             sleep 2;
                    432:             my $wcmd='';
                    433:             {
1.448     albertel  434: 		my $dfh;
                    435: 		if (open($dfh,"<$dfilename")) {
                    436: 		    $wcmd=<$dfh>; 
                    437: 		    close($dfh);
                    438: 		}
1.1       albertel  439:             }
                    440:             chomp($wcmd);
1.7       www       441:             if ($wcmd eq $cmd) {
1.672     albertel  442: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       443:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  444:                 &logperm("D:$server:$cmd");
                    445: 	        return 'con_delayed';
                    446:             } else {
1.672     albertel  447:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       448:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  449:                 &logperm("F:$server:$cmd");
                    450:                 return 'con_failed';
                    451:             }
                    452:         }
                    453:     }
                    454:     return $answer;
1.405     albertel  455: }
                    456: 
1.755     albertel  457: # ------------------------------------------- check if return value is an error
                    458: 
                    459: sub error {
                    460:     my ($result) = @_;
1.756     albertel  461:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  462: 	if ($2 == 2) { return undef; }
                    463: 	return $1;
                    464:     }
                    465:     return undef;
                    466: }
                    467: 
1.783     albertel  468: sub convert_and_load_session_env {
                    469:     my ($lonidsdir,$handle)=@_;
                    470:     my @profile;
                    471:     {
1.917     albertel  472: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    473: 	if (!$opened) {
1.915     albertel  474: 	    return 0;
                    475: 	}
1.783     albertel  476: 	flock($idf,LOCK_SH);
                    477: 	@profile=<$idf>;
                    478: 	close($idf);
                    479:     }
                    480:     my %temp_env;
                    481:     foreach my $line (@profile) {
1.786     albertel  482: 	if ($line !~ m/=/) {
                    483: 	    return 0;
                    484: 	}
1.783     albertel  485: 	chomp($line);
                    486: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    487: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    488:     }
                    489:     unlink("$lonidsdir/$handle.id");
                    490:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    491: 	    0640)) {
                    492: 	%disk_env = %temp_env;
                    493: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    494: 	untie(%disk_env);
                    495:     }
1.786     albertel  496:     return 1;
1.783     albertel  497: }
                    498: 
1.374     www       499: # ------------------------------------------- Transfer profile into environment
1.780     albertel  500: my $env_loaded;
                    501: sub transfer_profile_to_env {
1.788     albertel  502:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    503:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       504: 
1.720     albertel  505:     if (!defined($lonidsdir)) {
                    506: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    507:     }
                    508:     if (!defined($handle)) {
                    509:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    510:     }
                    511: 
1.786     albertel  512:     my $convert;
                    513:     {
1.917     albertel  514:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    515: 	if (!$opened) {
1.915     albertel  516: 	    return;
                    517: 	}
1.786     albertel  518: 	flock($idf,LOCK_SH);
                    519: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    520: 		&GDBM_READER(),0640)) {
                    521: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    522: 	    untie(%disk_env);
                    523: 	} else {
                    524: 	    $convert = 1;
                    525: 	}
                    526:     }
                    527:     if ($convert) {
                    528: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    529: 	    &logthis("Failed to load session, or convert session.");
                    530: 	}
1.374     www       531:     }
1.783     albertel  532: 
1.786     albertel  533:     my %remove;
1.783     albertel  534:     while ( my $envname = each(%env) ) {
1.433     matthew   535:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    536:             if ($time < time-300) {
1.783     albertel  537:                 $remove{$key}++;
1.433     matthew   538:             }
                    539:         }
                    540:     }
1.783     albertel  541: 
1.619     albertel  542:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  543:     $env_loaded=1;
1.783     albertel  544:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   545:         &delenv($expired_key);
1.374     www       546:     }
1.1       albertel  547: }
                    548: 
1.916     albertel  549: # ---------------------------------------------------- Check for valid session 
                    550: sub check_for_valid_session {
                    551:     my ($r) = @_;
                    552:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    553:     my $lonid=$cookies{'lonID'};
                    554:     return undef if (!$lonid);
                    555: 
                    556:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    557:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    558:     return undef if (!-e "$lonidsdir/$handle.id");
                    559: 
1.917     albertel  560:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    561:     return undef if (!$opened);
1.916     albertel  562: 
                    563:     flock($idf,LOCK_SH);
                    564:     my %disk_env;
                    565:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    566: 	    &GDBM_READER(),0640)) {
                    567: 	return undef;	
                    568:     }
                    569: 
                    570:     if (!defined($disk_env{'user.name'})
                    571: 	|| !defined($disk_env{'user.domain'})) {
                    572: 	return undef;
                    573:     }
                    574:     return $handle;
                    575: }
                    576: 
1.830     albertel  577: sub timed_flock {
                    578:     my ($file,$lock_type) = @_;
                    579:     my $failed=0;
                    580:     eval {
                    581: 	local $SIG{__DIE__}='DEFAULT';
                    582: 	local $SIG{ALRM}=sub {
                    583: 	    $failed=1;
                    584: 	    die("failed lock");
                    585: 	};
                    586: 	alarm(13);
                    587: 	flock($file,$lock_type);
                    588: 	alarm(0);
                    589:     };
                    590:     if ($failed) {
                    591: 	return undef;
                    592:     } else {
                    593: 	return 1;
                    594:     }
                    595: }
                    596: 
1.5       www       597: # ---------------------------------------------------------- Append Environment
                    598: 
                    599: sub appenv {
1.949     raeburn   600:     my ($newenv,$roles) = @_;
                    601:     if (ref($newenv) eq 'HASH') {
                    602:         foreach my $key (keys(%{$newenv})) {
                    603:             my $refused = 0;
                    604: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    605:                 $refused = 1;
                    606:                 if (ref($roles) eq 'ARRAY') {
                    607:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    608:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    609:                         $refused = 0;
                    610:                     }
                    611:                 }
                    612:             }
                    613:             if ($refused) {
                    614:                 &logthis("<font color=\"blue\">WARNING: ".
                    615:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    616:                          .'</font>');
                    617: 	        delete($newenv->{$key});
                    618:             } else {
                    619:                 $env{$key}=$newenv->{$key};
                    620:             }
                    621:         }
                    622:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    623:         if ($opened
                    624: 	    && &timed_flock($env_file,LOCK_EX)
                    625: 	    &&
                    626: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    627: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    628: 	    while (my ($key,$value) = each(%{$newenv})) {
                    629: 	        $disk_env{$key} = $value;
                    630: 	    }
                    631: 	    untie(%disk_env);
1.35      www       632:         }
1.191     harris41  633:     }
1.56      www       634:     return 'ok';
                    635: }
                    636: # ----------------------------------------------------- Delete from Environment
                    637: 
                    638: sub delenv {
1.987     raeburn   639:     my ($delthis,$regexp) = @_;
1.56      www       640:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  641:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       642:                 "Attempt to delete from environment ".$delthis);
                    643:         return 'error';
                    644:     }
1.917     albertel  645:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    646:     if ($opened
1.915     albertel  647: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  648: 	&&
                    649: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    650: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  651: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   652: 	    if ($regexp) {
                    653:                 if ($key=~/^$delthis/) {
                    654:                     delete($env{$key});
                    655:                     delete($disk_env{$key});
                    656:                 } 
                    657:             } else {
                    658:                 if ($key=~/^\Q$delthis\E/) {
                    659: 		    delete($env{$key});
                    660: 		    delete($disk_env{$key});
                    661: 	        }
                    662:             }
1.448     albertel  663: 	}
1.783     albertel  664: 	untie(%disk_env);
1.5       www       665:     }
                    666:     return 'ok';
1.369     albertel  667: }
                    668: 
1.790     albertel  669: sub get_env_multiple {
                    670:     my ($name) = @_;
                    671:     my @values;
                    672:     if (defined($env{$name})) {
                    673:         # exists is it an array
                    674:         if (ref($env{$name})) {
                    675:             @values=@{ $env{$name} };
                    676:         } else {
                    677:             $values[0]=$env{$name};
                    678:         }
                    679:     }
                    680:     return(@values);
                    681: }
                    682: 
1.958     www       683: # ------------------------------------------------------------------- Locking
                    684: 
                    685: sub set_lock {
                    686:     my ($text)=@_;
                    687:     $locknum++;
                    688:     my $id=$$.'-'.$locknum;
                    689:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    690:              'session.lock.'.$id => $text});
                    691:     return $id;
                    692: }
                    693: 
                    694: sub get_locks {
                    695:     my $num=0;
                    696:     my %texts=();
                    697:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    698:        if ($lock=~/\w/) {
                    699:           $num++;
                    700:           $texts{$lock}=$env{'session.lock.'.$lock};
                    701:        }
                    702:    }
                    703:    return ($num,%texts);
                    704: }
                    705: 
                    706: sub remove_lock {
                    707:     my ($id)=@_;
                    708:     my $newlocks='';
                    709:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    710:        if (($lock=~/\w/) && ($lock ne $id)) {
                    711:           $newlocks.=','.$lock;
                    712:        }
                    713:     }
                    714:     &appenv({'session.locks' => $newlocks});
                    715:     &delenv('session.lock.'.$id);
                    716: }
                    717: 
                    718: sub remove_all_locks {
                    719:     my $activelocks=$env{'session.locks'};
                    720:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    721:        if ($lock=~/\w/) {
                    722:           &remove_lock($lock);
                    723:        }
                    724:     }
                    725: }
                    726: 
                    727: 
1.369     albertel  728: # ------------------------------------------ Find out current server userload
                    729: sub userload {
                    730:     my $numusers=0;
                    731:     {
                    732: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    733: 	my $filename;
                    734: 	my $curtime=time;
                    735: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  736: 	    next if ($filename eq '.' || $filename eq '..');
                    737: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  738: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  739: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  740: 	}
                    741: 	closedir(LONIDS);
                    742:     }
                    743:     my $userloadpercent=0;
                    744:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    745:     if ($maxuserload) {
1.371     albertel  746: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  747:     }
1.372     albertel  748:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  749:     return $userloadpercent;
1.283     www       750: }
                    751: 
                    752: # ------------------------------------------ Fight off request when overloaded
                    753: 
                    754: sub overloaderror {
                    755:     my ($r,$checkserver)=@_;
                    756:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    757:     my $loadavg;
                    758:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  759:        open(my $loadfile,'/proc/loadavg');
1.283     www       760:        $loadavg=<$loadfile>;
                    761:        $loadavg =~ s/\s.*//g;
1.285     matthew   762:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  763:        close($loadfile);
1.283     www       764:     } else {
                    765:        $loadavg=&reply('load',$checkserver);
                    766:     }
1.285     matthew   767:     my $overload=$loadavg-100;
1.283     www       768:     if ($overload>0) {
1.285     matthew   769: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       770:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       771:         return 413;
1.283     www       772:     }    
                    773:     return '';
1.5       www       774: }
1.1       albertel  775: 
                    776: # ------------------------------ Find server with least workload from spare.tab
1.11      www       777: 
1.1       albertel  778: sub spareserver {
1.1056.4.23  raeburn   779:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  780:     my $spare_server;
1.370     albertel  781:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  782:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    783:                                                      :  $userloadpercent;
1.1056.4.8  raeburn   784:     my ($uint_dom,$remotesessions);
1.1056.4.23  raeburn   785:     if (($udom ne '') && (&domain($udom) ne '')) {
                    786:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1.1056.4.8  raeburn   787:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.23  raeburn   788:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
1.1056.4.8  raeburn   789:         $remotesessions = $udomdefaults{'remotesessions'};
                    790:     }
1.784     albertel  791:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8  raeburn   792:         if ($uint_dom) {
1.1056.4.23  raeburn   793:             next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    794:                                          $try_server));
1.1056.4.8  raeburn   795:         }
1.784     albertel  796: 	($spare_server, $lowest_load) =
                    797: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    798:     }
                    799: 
                    800:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    801: 
                    802:     if (!$found_server) {
                    803: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8  raeburn   804:             if ($uint_dom) {
1.1056.4.23  raeburn   805:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    806:                                              $try_server));
1.1056.4.8  raeburn   807:             }
1.784     albertel  808: 	    ($spare_server, $lowest_load) =
                    809: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    810: 	}
                    811:     }
                    812: 
                    813:     if (!$want_server_name) {
1.968     raeburn   814:         my $protocol = 'http';
                    815:         if ($protocol{$spare_server} eq 'https') {
                    816:             $protocol = $protocol{$spare_server};
                    817:         }
1.1001    raeburn   818:         if (defined($spare_server)) {
                    819:             my $hostname = &hostname($spare_server);
1.1056.4.8  raeburn   820:             if (defined($hostname)) {
1.1001    raeburn   821: 	        $spare_server = $protocol.'://'.$hostname;
                    822:             }
                    823:         }
1.784     albertel  824:     }
                    825:     return $spare_server;
                    826: }
                    827: 
                    828: sub compare_server_load {
                    829:     my ($try_server, $spare_server, $lowest_load) = @_;
                    830: 
                    831:     my $loadans     = &reply('load',    $try_server);
                    832:     my $userloadans = &reply('userload',$try_server);
                    833: 
                    834:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.29  raeburn   835:         return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  836:     }
                    837: 
                    838:     my $load;
                    839:     if ($loadans =~ /\d/) {
                    840: 	if ($userloadans =~ /\d/) {
                    841: 	    #both are numbers, pick the bigger one
                    842: 	    $load = ($loadans > $userloadans) ? $loadans 
                    843: 		                              : $userloadans;
1.411     albertel  844: 	} else {
1.784     albertel  845: 	    $load = $loadans;
1.411     albertel  846: 	}
1.784     albertel  847:     } else {
                    848: 	$load = $userloadans;
                    849:     }
                    850: 
                    851:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    852: 	$spare_server = $try_server;
                    853: 	$lowest_load  = $load;
1.370     albertel  854:     }
1.784     albertel  855:     return ($spare_server,$lowest_load);
1.202     matthew   856: }
1.914     albertel  857: 
                    858: # --------------------------- ask offload servers if user already has a session
                    859: sub find_existing_session {
                    860:     my ($udom,$uname) = @_;
                    861:     foreach my $try_server (@{ $spareid{'primary'} },
                    862: 			    @{ $spareid{'default'} }) {
                    863: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    864:     }
                    865:     return;
                    866: }
                    867: 
                    868: # -------------------------------- ask if server already has a session for user
                    869: sub has_user_session {
                    870:     my ($lonid,$udom,$uname) = @_;
                    871:     my $result = &reply(join(':','userhassession',
                    872: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    873:     return 1 if ($result eq 'ok');
                    874: 
                    875:     return 0;
                    876: }
                    877: 
1.1056.4.3  raeburn   878: # --------- determine least loaded server in a user's domain which allows login
                    879: 
                    880: sub choose_server {
1.1056.4.31  raeburn   881:     my ($udom,$checkloginvia) = @_;
1.1056.4.3  raeburn   882:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
                    883:     my %servers = &get_servers($udom);
                    884:     my $lowest_load = 30000;
1.1056.4.36  raeburn   885:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1056.4.3  raeburn   886:     foreach my $lonhost (keys(%servers)) {
1.1056.4.31  raeburn   887:         my $loginvia;
                    888:         if ($checkloginvia) {
                    889:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    890:             if ($loginvia) {
                    891:                 my ($server,$path) = split(/:/,$loginvia);
                    892:                 ($login_host, $lowest_load) =
                    893:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    894:                 if ($login_host eq $server) {
                    895:                     $portal_path = $path;
1.1056.4.36  raeburn   896:                     $isredirect = 1;
1.1056.4.31  raeburn   897:                 }
                    898:             } else {
                    899:                 ($login_host, $lowest_load) =
                    900:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    901:                 if ($login_host eq $lonhost) {
                    902:                     $portal_path = '';
1.1056.4.36  raeburn   903:                     $isredirect = '';
1.1056.4.31  raeburn   904:                 }
                    905:             }
                    906:         } else {
1.1056.4.3  raeburn   907:             ($login_host, $lowest_load) =
1.1056.4.31  raeburn   908:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1056.4.3  raeburn   909:         }
                    910:     }
                    911:     if ($login_host ne '') {
1.1056.4.31  raeburn   912:         $hostname = &hostname($login_host);
1.1056.4.3  raeburn   913:     }
1.1056.4.36  raeburn   914:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1056.4.3  raeburn   915: }
                    916: 
1.202     matthew   917: # --------------------------------------------- Try to change a user's password
                    918: 
                    919: sub changepass {
1.799     raeburn   920:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   921:     $currentpass = &escape($currentpass);
                    922:     $newpass     = &escape($newpass);
1.1030    raeburn   923:     my $lonhost = $perlvar{'lonHostID'};
                    924:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   925: 		       $server);
                    926:     if (! $answer) {
                    927: 	&logthis("No reply on password change request to $server ".
                    928: 		 "by $uname in domain $udom.");
                    929:     } elsif ($answer =~ "^ok") {
                    930:         &logthis("$uname in $udom successfully changed their password ".
                    931: 		 "on $server.");
                    932:     } elsif ($answer =~ "^pwchange_failure") {
                    933: 	&logthis("$uname in $udom was unable to change their password ".
                    934: 		 "on $server.  The action was blocked by either lcpasswd ".
                    935: 		 "or pwchange");
                    936:     } elsif ($answer =~ "^non_authorized") {
                    937:         &logthis("$uname in $udom did not get their password correct when ".
                    938: 		 "attempting to change it on $server.");
                    939:     } elsif ($answer =~ "^auth_mode_error") {
                    940:         &logthis("$uname in $udom attempted to change their password despite ".
                    941: 		 "not being locally or internally authenticated on $server.");
                    942:     } elsif ($answer =~ "^unknown_user") {
                    943:         &logthis("$uname in $udom attempted to change their password ".
                    944: 		 "on $server but were unable to because $server is not ".
                    945: 		 "their home server.");
                    946:     } elsif ($answer =~ "^refused") {
                    947: 	&logthis("$server refused to change $uname in $udom password because ".
                    948: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   949:     } elsif ($answer =~ "invalid_client") {
                    950:         &logthis("$server refused to change $uname in $udom password because ".
                    951:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   952:     }
                    953:     return $answer;
1.1       albertel  954: }
                    955: 
1.169     harris41  956: # ----------------------- Try to determine user's current authentication scheme
                    957: 
                    958: sub queryauthenticate {
                    959:     my ($uname,$udom)=@_;
1.456     albertel  960:     my $uhome=&homeserver($uname,$udom);
                    961:     if (!$uhome) {
                    962: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    963: 	return 'no_host';
                    964:     }
                    965:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    966:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    967: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  968:     }
1.456     albertel  969:     return $answer;
1.169     harris41  970: }
                    971: 
1.1       albertel  972: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       973: 
1.1       albertel  974: sub authenticate {
1.1056.4.3  raeburn   975:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  976:     $upass=&escape($upass);
                    977:     $uname= &LONCAPA::clean_username($uname);
1.836     www       978:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   979:     my $newhome;
1.836     www       980:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    981: # Maybe the machine was offline and only re-appeared again recently?
                    982:         &reconlonc();
                    983: # One more
1.952     raeburn   984: 	$uhome=&homeserver($uname,$udom,1);
                    985:         if (($uhome eq 'no_host') && $checkdefauth) {
                    986:             if (defined(&domain($udom,'primary'))) {
                    987:                 $newhome=&domain($udom,'primary');
                    988:             }
                    989:             if ($newhome ne '') {
                    990:                 $uhome = $newhome;
                    991:             }
                    992:         }
1.836     www       993: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    994: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   995: 	    return 'no_host';
                    996:         }
1.1       albertel  997:     }
1.1056.4.3  raeburn   998:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  999:     if ($answer eq 'authorized') {
1.952     raeburn  1000:         if ($newhome) {
                   1001:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1002:             return 'no_account_on_host'; 
                   1003:         } else {
                   1004:             &logthis("User $uname at $udom authorized by $uhome");
                   1005:             return $uhome;
                   1006:         }
1.471     albertel 1007:     }
                   1008:     if ($answer eq 'non_authorized') {
                   1009: 	&logthis("User $uname at $udom rejected by $uhome");
                   1010: 	return 'no_host'; 
1.9       www      1011:     }
1.471     albertel 1012:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1013:     return 'no_host';
                   1014: }
                   1015: 
1.1056.4.3  raeburn  1016: sub can_host_session {
                   1017:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
                   1018:     my $canhost = 1;
                   1019:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
                   1020:     if (ref($remotesessions) eq 'HASH') {
                   1021:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
                   1022:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
                   1023:                 $canhost = 0;
                   1024:             } else {
                   1025:                 $canhost = 1;
                   1026:             }
                   1027:         }
                   1028:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
                   1029:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
                   1030:                 $canhost = 1;
                   1031:             } else {
                   1032:                 $canhost = 0;
                   1033:             }
                   1034:         }
                   1035:         if ($canhost) {
                   1036:             if ($remotesessions->{'version'} ne '') {
                   1037:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1038:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1039:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1040:                         my $major = $1;
                   1041:                         my $minor = $2;
                   1042:                         if (($major < $reqmajor ) ||
                   1043:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1044:                             $canhost = 0;
                   1045:                         }
                   1046:                     } else {
                   1047:                         $canhost = 0;
                   1048:                     }
                   1049:                 }
                   1050:             }
                   1051:         }
                   1052:     }
                   1053:     if ($canhost) {
                   1054:         if (ref($hostedsessions) eq 'HASH') {
1.1056.4.28  raeburn  1055:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1056:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.3  raeburn  1057:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1056.4.28  raeburn  1058:                 if (($uint_dom ne '') && 
                   1059:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1056.4.3  raeburn  1060:                     $canhost = 0;
                   1061:                 } else {
                   1062:                     $canhost = 1;
                   1063:                 }
                   1064:             }
                   1065:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1056.4.28  raeburn  1066:                 if (($uint_dom ne '') && 
                   1067:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1056.4.3  raeburn  1068:                     $canhost = 1;
                   1069:                 } else {
                   1070:                     $canhost = 0;
                   1071:                 }
                   1072:             }
                   1073:         }
                   1074:     }
                   1075:     return $canhost;
                   1076: }
                   1077: 
1.1056.4.8  raeburn  1078: sub spare_can_host {
                   1079:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1080:     my $canhost=1;
                   1081:     my @intdoms;
                   1082:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1083:     if (ref($internet_names) eq 'ARRAY') {
                   1084:         @intdoms = @{$internet_names};
                   1085:     }
                   1086:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1087:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1088:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1089:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1090:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1091:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1092:                                      $remotesessions,
                   1093:                                      $defdomdefaults{'hostedsessions'});
                   1094:     }
                   1095:     return $canhost;
                   1096: }
                   1097: 
1.1       albertel 1098: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1099: 
1.599     albertel 1100: my %homecache;
1.1       albertel 1101: sub homeserver {
1.230     stredwic 1102:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1103:     my $index="$uname:$udom";
1.426     albertel 1104: 
1.599     albertel 1105:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1106: 
                   1107:     my %servers = &get_servers($udom,'library');
                   1108:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1109:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1110: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1111: 
                   1112: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1113: 	if ($answer eq 'found') {
                   1114: 	    delete($badServerCache{$tryserver}); 
                   1115: 	    return $homecache{$index}=$tryserver;
                   1116: 	} elsif ($answer eq 'no_host') {
                   1117: 	    $badServerCache{$tryserver}=1;
                   1118: 	}
1.1       albertel 1119:     }    
                   1120:     return 'no_host';
1.70      www      1121: }
                   1122: 
                   1123: # ------------------------------------- Find the usernames behind a list of IDs
                   1124: 
                   1125: sub idget {
                   1126:     my ($udom,@ids)=@_;
                   1127:     my %returnhash=();
                   1128:     
1.841     albertel 1129:     my %servers = &get_servers($udom,'library');
                   1130:     foreach my $tryserver (keys(%servers)) {
                   1131: 	my $idlist=join('&',@ids);
                   1132: 	$idlist=~tr/A-Z/a-z/; 
                   1133: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1134: 	my @answer=();
                   1135: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1136: 	    @answer=split(/\&/,$reply);
                   1137: 	}                    ;
                   1138: 	my $i;
                   1139: 	for ($i=0;$i<=$#ids;$i++) {
                   1140: 	    if ($answer[$i]) {
                   1141: 		$returnhash{$ids[$i]}=$answer[$i];
                   1142: 	    } 
                   1143: 	}
                   1144:     } 
1.70      www      1145:     return %returnhash;
                   1146: }
                   1147: 
                   1148: # ------------------------------------- Find the IDs behind a list of usernames
                   1149: 
                   1150: sub idrget {
                   1151:     my ($udom,@unames)=@_;
                   1152:     my %returnhash=();
1.800     albertel 1153:     foreach my $uname (@unames) {
                   1154:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1155:     }
1.70      www      1156:     return %returnhash;
                   1157: }
                   1158: 
                   1159: # ------------------------------- Store away a list of names and associated IDs
                   1160: 
                   1161: sub idput {
                   1162:     my ($udom,%ids)=@_;
                   1163:     my %servers=();
1.800     albertel 1164:     foreach my $uname (keys(%ids)) {
                   1165: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1166:         my $uhom=&homeserver($uname,$udom);
1.70      www      1167:         if ($uhom ne 'no_host') {
1.800     albertel 1168:             my $id=&escape($ids{$uname});
1.70      www      1169:             $id=~tr/A-Z/a-z/;
1.800     albertel 1170:             my $esc_unam=&escape($uname);
1.70      www      1171: 	    if ($servers{$uhom}) {
1.800     albertel 1172: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1173:             } else {
1.800     albertel 1174:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1175:             }
                   1176:         }
1.191     harris41 1177:     }
1.800     albertel 1178:     foreach my $server (keys(%servers)) {
                   1179:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1180:     }
1.344     www      1181: }
                   1182: 
1.1023    raeburn  1183: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1184: sub dump_dom {
1.1023    raeburn  1185:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1186:     if (!$udom) {
                   1187:         $udom=$env{'user.domain'};
                   1188:     }
                   1189:     my %returnhash;
1.1023    raeburn  1190:     if ($udom) {
                   1191:         my $uname = &get_domainconfiguser($udom);
                   1192:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1193:     }
                   1194:     return %returnhash;
                   1195: }
                   1196: 
1.1023    raeburn  1197: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1198: 
                   1199: sub get_dom {
1.860     raeburn  1200:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1201:     my $items='';
                   1202:     foreach my $item (@$storearr) {
                   1203:         $items.=&escape($item).'&';
                   1204:     }
                   1205:     $items=~s/\&$//;
1.860     raeburn  1206:     if (!$udom) {
                   1207:         $udom=$env{'user.domain'};
                   1208:         if (defined(&domain($udom,'primary'))) {
                   1209:             $uhome=&domain($udom,'primary');
                   1210:         } else {
1.874     albertel 1211:             undef($uhome);
1.860     raeburn  1212:         }
                   1213:     } else {
                   1214:         if (!$uhome) {
                   1215:             if (defined(&domain($udom,'primary'))) {
                   1216:                 $uhome=&domain($udom,'primary');
                   1217:             }
                   1218:         }
                   1219:     }
                   1220:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1221:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1222:         my %returnhash;
1.875     albertel 1223:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1224:             return %returnhash;
                   1225:         }
1.806     raeburn  1226:         my @pairs=split(/\&/,$rep);
                   1227:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1228:             return @pairs;
                   1229:         }
                   1230:         my $i=0;
                   1231:         foreach my $item (@$storearr) {
                   1232:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1233:             $i++;
                   1234:         }
                   1235:         return %returnhash;
                   1236:     } else {
1.880     banghart 1237:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1238:     }
                   1239: }
                   1240: 
                   1241: # -------------------------------------------- put items in domain db files 
                   1242: 
                   1243: sub put_dom {
1.860     raeburn  1244:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1245:     if (!$udom) {
                   1246:         $udom=$env{'user.domain'};
                   1247:         if (defined(&domain($udom,'primary'))) {
                   1248:             $uhome=&domain($udom,'primary');
                   1249:         } else {
1.874     albertel 1250:             undef($uhome);
1.860     raeburn  1251:         }
                   1252:     } else {
                   1253:         if (!$uhome) {
                   1254:             if (defined(&domain($udom,'primary'))) {
                   1255:                 $uhome=&domain($udom,'primary');
                   1256:             }
                   1257:         }
                   1258:     } 
                   1259:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1260:         my $items='';
                   1261:         foreach my $item (keys(%$storehash)) {
                   1262:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1263:         }
                   1264:         $items=~s/\&$//;
                   1265:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1266:     } else {
1.860     raeburn  1267:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1268:     }
                   1269: }
                   1270: 
1.1023    raeburn  1271: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1272: sub newput_dom {
1.1023    raeburn  1273:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1274:     my $result;
                   1275:     if (!$udom) {
                   1276:         $udom=$env{'user.domain'};
                   1277:     }
1.1023    raeburn  1278:     if ($udom) {
                   1279:         my $uname = &get_domainconfiguser($udom);
                   1280:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1281:     }
                   1282:     return $result;
                   1283: }
                   1284: 
1.1023    raeburn  1285: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1286: sub del_dom {
1.1023    raeburn  1287:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1288:     if (ref($storearr) eq 'ARRAY') {
                   1289:         if (!$udom) {
                   1290:             $udom=$env{'user.domain'};
                   1291:         }
1.1023    raeburn  1292:         if ($udom) {
                   1293:             my $uname = &get_domainconfiguser($udom); 
                   1294:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1295:         }
                   1296:     }
                   1297: }
                   1298: 
1.1023    raeburn  1299: # ----------------------------------construct domainconfig user for a domain 
                   1300: sub get_domainconfiguser {
                   1301:     my ($udom) = @_;
                   1302:     return $udom.'-domainconfig';
                   1303: }
                   1304: 
1.837     raeburn  1305: sub retrieve_inst_usertypes {
                   1306:     my ($udom) = @_;
                   1307:     my (%returnhash,@order);
1.989     raeburn  1308:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1309:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1310:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1311:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1312:         @order = @{$domdefs{'inststatusorder'}};
                   1313:     } else {
                   1314:         if (defined(&domain($udom,'primary'))) {
                   1315:             my $uhome=&domain($udom,'primary');
                   1316:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1317:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1318:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1319:                 return (\%returnhash,\@order);
                   1320:             }
                   1321:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1322:             my @pairs=split(/\&/,$hashitems);
                   1323:             foreach my $item (@pairs) {
                   1324:                 my ($key,$value)=split(/=/,$item,2);
                   1325:                 $key = &unescape($key);
                   1326:                 next if ($key =~ /^error: 2 /);
                   1327:                 $returnhash{$key}=&thaw_unescape($value);
                   1328:             }
                   1329:             my @esc_order = split(/\&/,$orderitems);
                   1330:             foreach my $item (@esc_order) {
                   1331:                 push(@order,&unescape($item));
                   1332:             }
                   1333:         } else {
                   1334:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1335:         }
                   1336:     }
                   1337:     return (\%returnhash,\@order);
                   1338: }
                   1339: 
1.868     raeburn  1340: sub is_domainimage {
                   1341:     my ($url) = @_;
                   1342:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1343:         if (&domain($1) ne '') {
                   1344:             return '1';
                   1345:         }
                   1346:     }
                   1347:     return;
                   1348: }
                   1349: 
1.899     raeburn  1350: sub inst_directory_query {
                   1351:     my ($srch) = @_;
                   1352:     my $udom = $srch->{'srchdomain'};
                   1353:     my %results;
                   1354:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1355:     my $outcome;
1.899     raeburn  1356:     if ($homeserver ne '') {
1.904     albertel 1357: 	my $queryid=&reply("querysend:instdirsearch:".
                   1358: 			   &escape($srch->{'srchby'}).':'.
                   1359: 			   &escape($srch->{'srchterm'}).':'.
                   1360: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1361: 	my $host=&hostname($homeserver);
                   1362: 	if ($queryid !~/^\Q$host\E\_/) {
                   1363: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1364: 	    return;
                   1365: 	}
                   1366: 	my $response = &get_query_reply($queryid);
                   1367: 	my $maxtries = 5;
                   1368: 	my $tries = 1;
                   1369: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1370: 	    $response = &get_query_reply($queryid);
                   1371: 	    $tries ++;
                   1372: 	}
                   1373: 
                   1374:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1375:             if ($response eq 'unavailable') {
                   1376:                 $outcome = $response;
                   1377:             } else {
                   1378:                 $outcome = 'ok';
                   1379:                 my @matches = split(/\n/,$response);
                   1380:                 foreach my $match (@matches) {
                   1381:                     my ($key,$value) = split(/=/,$match);
                   1382:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1383:                 }
1.899     raeburn  1384:             }
                   1385:         }
                   1386:     }
1.909     raeburn  1387:     return ($outcome,%results);
1.899     raeburn  1388: }
                   1389: 
                   1390: sub usersearch {
                   1391:     my ($srch) = @_;
                   1392:     my $dom = $srch->{'srchdomain'};
                   1393:     my %results;
                   1394:     my %libserv = &all_library();
                   1395:     my $query = 'usersearch';
                   1396:     foreach my $tryserver (keys(%libserv)) {
                   1397:         if (&host_domain($tryserver) eq $dom) {
                   1398:             my $host=&hostname($tryserver);
                   1399:             my $queryid=
1.911     raeburn  1400:                 &reply("querysend:".&escape($query).':'.
                   1401:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1402:                        &escape($srch->{'srchtype'}).':'.
                   1403:                        &escape($srch->{'srchterm'}),$tryserver);
                   1404:             if ($queryid !~/^\Q$host\E\_/) {
                   1405:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1406:                 next;
1.899     raeburn  1407:             }
                   1408:             my $reply = &get_query_reply($queryid);
                   1409:             my $maxtries = 1;
                   1410:             my $tries = 1;
                   1411:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1412:                 $reply = &get_query_reply($queryid);
                   1413:                 $tries ++;
                   1414:             }
                   1415:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1416:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1417:             } else {
1.911     raeburn  1418:                 my @matches;
                   1419:                 if ($reply =~ /\n/) {
                   1420:                     @matches = split(/\n/,$reply);
                   1421:                 } else {
                   1422:                     @matches = split(/\&/,$reply);
                   1423:                 }
1.899     raeburn  1424:                 foreach my $match (@matches) {
                   1425:                     my ($uname,$udom,%userhash);
1.911     raeburn  1426:                     foreach my $entry (split(/:/,$match)) {
                   1427:                         my ($key,$value) =
                   1428:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1429:                         $userhash{$key} = $value;
                   1430:                         if ($key eq 'username') {
                   1431:                             $uname = $value;
                   1432:                         } elsif ($key eq 'domain') {
                   1433:                             $udom = $value;
1.911     raeburn  1434:                         }
1.899     raeburn  1435:                     }
                   1436:                     $results{$uname.':'.$udom} = \%userhash;
                   1437:                 }
                   1438:             }
                   1439:         }
                   1440:     }
                   1441:     return %results;
                   1442: }
                   1443: 
1.912     raeburn  1444: sub get_instuser {
                   1445:     my ($udom,$uname,$id) = @_;
                   1446:     my $homeserver = &domain($udom,'primary');
                   1447:     my ($outcome,%results);
                   1448:     if ($homeserver ne '') {
                   1449:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1450:                            &escape($id).':'.&escape($udom),$homeserver);
                   1451:         my $host=&hostname($homeserver);
                   1452:         if ($queryid !~/^\Q$host\E\_/) {
                   1453:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1454:             return;
                   1455:         }
                   1456:         my $response = &get_query_reply($queryid);
                   1457:         my $maxtries = 5;
                   1458:         my $tries = 1;
                   1459:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1460:             $response = &get_query_reply($queryid);
                   1461:             $tries ++;
                   1462:         }
                   1463:         if (!&error($response) && $response ne 'refused') {
                   1464:             if ($response eq 'unavailable') {
                   1465:                 $outcome = $response;
                   1466:             } else {
                   1467:                 $outcome = 'ok';
                   1468:                 my @matches = split(/\n/,$response);
                   1469:                 foreach my $match (@matches) {
                   1470:                     my ($key,$value) = split(/=/,$match);
                   1471:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1472:                 }
                   1473:             }
                   1474:         }
                   1475:     }
                   1476:     my %userinfo;
                   1477:     if (ref($results{$uname}) eq 'HASH') {
                   1478:         %userinfo = %{$results{$uname}};
                   1479:     } 
                   1480:     return ($outcome,%userinfo);
                   1481: }
                   1482: 
                   1483: sub inst_rulecheck {
1.923     raeburn  1484:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1485:     my %returnhash;
                   1486:     if ($udom ne '') {
                   1487:         if (ref($rules) eq 'ARRAY') {
                   1488:             @{$rules} = map {&escape($_);} (@{$rules});
                   1489:             my $rulestr = join(':',@{$rules});
                   1490:             my $homeserver=&domain($udom,'primary');
                   1491:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1492:                 my $response;
                   1493:                 if ($item eq 'username') {                
                   1494:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1495:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1496:                                               $homeserver));
1.923     raeburn  1497:                 } elsif ($item eq 'id') {
                   1498:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1499:                                               ':'.&escape($id).':'.$rulestr,
                   1500:                                               $homeserver));
1.945     raeburn  1501:                 } elsif ($item eq 'selfcreate') {
                   1502:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1503:                                                &escape($udom).':'.&escape($uname).
                   1504:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1505:                 }
1.912     raeburn  1506:                 if ($response ne 'refused') {
                   1507:                     my @pairs=split(/\&/,$response);
                   1508:                     foreach my $item (@pairs) {
                   1509:                         my ($key,$value)=split(/=/,$item,2);
                   1510:                         $key = &unescape($key);
                   1511:                         next if ($key =~ /^error: 2 /);
                   1512:                         $returnhash{$key}=&thaw_unescape($value);
                   1513:                     }
                   1514:                 }
                   1515:             }
                   1516:         }
                   1517:     }
                   1518:     return %returnhash;
                   1519: }
                   1520: 
                   1521: sub inst_userrules {
1.923     raeburn  1522:     my ($udom,$check) = @_;
1.912     raeburn  1523:     my (%ruleshash,@ruleorder);
                   1524:     if ($udom ne '') {
                   1525:         my $homeserver=&domain($udom,'primary');
                   1526:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1527:             my $response;
                   1528:             if ($check eq 'id') {
                   1529:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1530:                                  $homeserver);
1.943     raeburn  1531:             } elsif ($check eq 'email') {
                   1532:                 $response=&reply('instemailrules:'.&escape($udom),
                   1533:                                  $homeserver);
1.923     raeburn  1534:             } else {
                   1535:                 $response=&reply('instuserrules:'.&escape($udom),
                   1536:                                  $homeserver);
                   1537:             }
1.912     raeburn  1538:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1539:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1540:                 ($response ne 'no_such_host')) {
                   1541:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1542:                 my @pairs=split(/\&/,$hashitems);
                   1543:                 foreach my $item (@pairs) {
                   1544:                     my ($key,$value)=split(/=/,$item,2);
                   1545:                     $key = &unescape($key);
                   1546:                     next if ($key =~ /^error: 2 /);
                   1547:                     $ruleshash{$key}=&thaw_unescape($value);
                   1548:                 }
                   1549:                 my @esc_order = split(/\&/,$orderitems);
                   1550:                 foreach my $item (@esc_order) {
                   1551:                     push(@ruleorder,&unescape($item));
                   1552:                 }
                   1553:             }
                   1554:         }
                   1555:     }
                   1556:     return (\%ruleshash,\@ruleorder);
                   1557: }
                   1558: 
1.976     raeburn  1559: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1560: 
                   1561: sub get_domain_defaults {
                   1562:     my ($domain) = @_;
                   1563:     my $cachetime = 60*60*24;
                   1564:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1565:     if (defined($cached)) {
                   1566:         if (ref($result) eq 'HASH') {
                   1567:             return %{$result};
                   1568:         }
                   1569:     }
                   1570:     my %domdefaults;
                   1571:     my %domconfig =
1.989     raeburn  1572:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1573:                                   'requestcourses','inststatus',
1.1056.4.3  raeburn  1574:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1575:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1576:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1577:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1578:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1579:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1580:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1056.4.34  raeburn  1581:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1582:     } else {
                   1583:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1584:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1585:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1586:     }
1.976     raeburn  1587:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1588:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1589:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1590:         } else {
                   1591:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1592:         } 
                   1593:         my @usertools = ('aboutme','blog','portfolio');
                   1594:         foreach my $item (@usertools) {
                   1595:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1596:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1597:             }
                   1598:         }
                   1599:     }
1.985     raeburn  1600:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1601:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1602:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1603:         }
                   1604:     }
1.989     raeburn  1605:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1606:         foreach my $item ('inststatustypes','inststatusorder') {
                   1607:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1608:         }
                   1609:     }
1.1047    raeburn  1610:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1611:         foreach my $item ('canuse_pdfforms') {
                   1612:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1613:         }
                   1614:     }
1.1056.4.3  raeburn  1615:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1616:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1617:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1618:         }
                   1619:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1620:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1621:         }
                   1622:     }
1.943     raeburn  1623:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1624:                                   $cachetime);
                   1625:     return %domdefaults;
                   1626: }
                   1627: 
1.344     www      1628: # --------------------------------------------------- Assign a key to a student
                   1629: 
                   1630: sub assign_access_key {
1.364     www      1631: #
                   1632: # a valid key looks like uname:udom#comments
                   1633: # comments are being appended
                   1634: #
1.498     www      1635:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1636:     $kdom=
1.620     albertel 1637:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1638:     $knum=
1.620     albertel 1639:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1640:     $cdom=
1.620     albertel 1641:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1642:     $cnum=
1.620     albertel 1643:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1644:     $udom=$env{'user.name'} unless (defined($udom));
                   1645:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1646:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1647:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1648:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1649:                                                   # assigned to this person
                   1650:                                                   # - this should not happen,
1.345     www      1651:                                                   # unless something went wrong
                   1652:                                                   # the first time around
                   1653: # ready to assign
1.364     www      1654:         $logentry=$1.'; '.$logentry;
1.496     www      1655:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1656:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1657: # key now belongs to user
1.346     www      1658: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1659:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1660:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1661:                 return 'ok';
                   1662:             } else {
                   1663:                 return 
                   1664:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1665: 	    }
                   1666:         } else {
                   1667:             return 'error: Could not assign key, try again later.';
                   1668:         }
1.364     www      1669:     } elsif (!$existing{$ckey}) {
1.345     www      1670: # the key does not exist
                   1671: 	return 'error: The key does not exist';
                   1672:     } else {
                   1673: # the key is somebody else's
                   1674: 	return 'error: The key is already in use';
                   1675:     }
1.344     www      1676: }
                   1677: 
1.364     www      1678: # ------------------------------------------ put an additional comment on a key
                   1679: 
                   1680: sub comment_access_key {
                   1681: #
                   1682: # a valid key looks like uname:udom#comments
                   1683: # comments are being appended
                   1684: #
                   1685:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1686:     $cdom=
1.620     albertel 1687:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1688:     $cnum=
1.620     albertel 1689:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1690:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1691:     if ($existing{$ckey}) {
                   1692:         $existing{$ckey}.='; '.$logentry;
                   1693: # ready to assign
1.367     www      1694:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1695:                                                  $cdom,$cnum) eq 'ok') {
                   1696: 	    return 'ok';
                   1697:         } else {
                   1698: 	    return 'error: Count not store comment.';
                   1699:         }
                   1700:     } else {
                   1701: # the key does not exist
                   1702: 	return 'error: The key does not exist';
                   1703:     }
                   1704: }
                   1705: 
1.344     www      1706: # ------------------------------------------------------ Generate a set of keys
                   1707: 
                   1708: sub generate_access_keys {
1.364     www      1709:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1710:     $cdom=
1.620     albertel 1711:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1712:     $cnum=
1.620     albertel 1713:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1714:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1715:     unless (($cdom) && ($cnum)) { return 0; }
                   1716:     if ($number>10000) { return 0; }
                   1717:     sleep(2); # make sure don't get same seed twice
                   1718:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1719:     my $total=0;
                   1720:     for (my $i=1;$i<=$number;$i++) {
                   1721:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1722:                   sprintf("%lx",int(100000*rand)).'-'.
                   1723:                   sprintf("%lx",int(100000*rand));
                   1724:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1725:        $newkey=~s/0/h/g; # and also 0 and O
                   1726:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1727:        if ($existing{$newkey}) {
                   1728:            $i--;
                   1729:        } else {
1.364     www      1730: 	  if (&put('accesskeys',
                   1731:               { $newkey => '# generated '.localtime().
1.620     albertel 1732:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1733:                            '; '.$logentry },
                   1734: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1735:               $total++;
                   1736: 	  }
                   1737:        }
                   1738:     }
1.620     albertel 1739:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1740:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1741:     return $total;
                   1742: }
                   1743: 
                   1744: # ------------------------------------------------------- Validate an accesskey
                   1745: 
                   1746: sub validate_access_key {
                   1747:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1748:     $cdom=
1.620     albertel 1749:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1750:     $cnum=
1.620     albertel 1751:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1752:     $udom=$env{'user.domain'} unless (defined($udom));
                   1753:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1754:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1755:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1756: }
                   1757: 
                   1758: # ------------------------------------- Find the section of student in a course
1.652     albertel 1759: sub devalidate_getsection_cache {
                   1760:     my ($udom,$unam,$courseid)=@_;
                   1761:     my $hashid="$udom:$unam:$courseid";
                   1762:     &devalidate_cache_new('getsection',$hashid);
                   1763: }
1.298     matthew  1764: 
1.815     albertel 1765: sub courseid_to_courseurl {
                   1766:     my ($courseid) = @_;
                   1767:     #already url style courseid
                   1768:     return $courseid if ($courseid =~ m{^/});
                   1769: 
                   1770:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1771: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1772: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1773: 	return "/$cdom/$cnum";
                   1774:     }
                   1775: 
                   1776:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1777:     if (exists($courseinfo{'num'})) {
                   1778: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1779:     }
                   1780: 
                   1781:     return undef;
                   1782: }
                   1783: 
1.298     matthew  1784: sub getsection {
                   1785:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1786:     my $cachetime=1800;
1.551     albertel 1787: 
                   1788:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1789:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1790:     if (defined($cached)) { return $result; }
                   1791: 
1.298     matthew  1792:     my %Pending; 
                   1793:     my %Expired;
                   1794:     #
                   1795:     # Each role can either have not started yet (pending), be active, 
                   1796:     #    or have expired.
                   1797:     #
                   1798:     # If there is an active role, we are done.
                   1799:     #
                   1800:     # If there is more than one role which has not started yet, 
                   1801:     #     choose the one which will start sooner
                   1802:     # If there is one role which has not started yet, return it.
                   1803:     #
                   1804:     # If there is more than one expired role, choose the one which ended last.
                   1805:     # If there is a role which has expired, return it.
                   1806:     #
1.815     albertel 1807:     $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  1808:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1809:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1810:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1811:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1812:         my $section=$1;
                   1813:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1814:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1815:         my $now=time;
1.548     albertel 1816:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1817:             $Expired{$end}=$section;
                   1818:             next;
                   1819:         }
1.548     albertel 1820:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1821:             $Pending{$start}=$section;
                   1822:             next;
                   1823:         }
1.599     albertel 1824:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1825:     }
                   1826:     #
                   1827:     # Presumedly there will be few matching roles from the above
                   1828:     # loop and the sorting time will be negligible.
                   1829:     if (scalar(keys(%Pending))) {
                   1830:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1831:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1832:     } 
                   1833:     if (scalar(keys(%Expired))) {
                   1834:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1835:         my $time = pop(@sorted);
1.599     albertel 1836:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1837:     }
1.599     albertel 1838:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1839: }
1.70      www      1840: 
1.599     albertel 1841: sub save_cache {
                   1842:     &purge_remembered();
1.722     albertel 1843:     #&Apache::loncommon::validate_page();
1.620     albertel 1844:     undef(%env);
1.780     albertel 1845:     undef($env_loaded);
1.599     albertel 1846: }
1.452     albertel 1847: 
1.599     albertel 1848: my $to_remember=-1;
                   1849: my %remembered;
                   1850: my %accessed;
                   1851: my $kicks=0;
                   1852: my $hits=0;
1.849     albertel 1853: sub make_key {
                   1854:     my ($name,$id) = @_;
1.872     albertel 1855:     if (length($id) > 65 
                   1856: 	&& length(&escape($id)) > 200) {
                   1857: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1858:     }
1.849     albertel 1859:     return &escape($name.':'.$id);
                   1860: }
                   1861: 
1.599     albertel 1862: sub devalidate_cache_new {
                   1863:     my ($name,$id,$debug) = @_;
                   1864:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1865:     $id=&make_key($name,$id);
1.599     albertel 1866:     $memcache->delete($id);
                   1867:     delete($remembered{$id});
                   1868:     delete($accessed{$id});
                   1869: }
                   1870: 
                   1871: sub is_cached_new {
                   1872:     my ($name,$id,$debug) = @_;
1.849     albertel 1873:     $id=&make_key($name,$id);
1.599     albertel 1874:     if (exists($remembered{$id})) {
                   1875: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1876: 	$accessed{$id}=[&gettimeofday()];
                   1877: 	$hits++;
                   1878: 	return ($remembered{$id},1);
                   1879:     }
                   1880:     my $value = $memcache->get($id);
                   1881:     if (!(defined($value))) {
                   1882: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1883: 	return (undef,undef);
1.416     albertel 1884:     }
1.599     albertel 1885:     if ($value eq '__undef__') {
                   1886: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1887: 	$value=undef;
                   1888:     }
                   1889:     &make_room($id,$value,$debug);
                   1890:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1891:     return ($value,1);
                   1892: }
                   1893: 
                   1894: sub do_cache_new {
                   1895:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1896:     $id=&make_key($name,$id);
1.599     albertel 1897:     my $setvalue=$value;
                   1898:     if (!defined($setvalue)) {
                   1899: 	$setvalue='__undef__';
                   1900:     }
1.623     albertel 1901:     if (!defined($time) ) {
                   1902: 	$time=600;
                   1903:     }
1.599     albertel 1904:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1905:     my $result = $memcache->set($id,$setvalue,$time);
                   1906:     if (! $result) {
1.872     albertel 1907: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1908: 	$memcache->disconnect_all();
1.872     albertel 1909:     }
1.600     albertel 1910:     # need to make a copy of $value
1.919     albertel 1911:     &make_room($id,$value,$debug);
1.599     albertel 1912:     return $value;
                   1913: }
                   1914: 
                   1915: sub make_room {
                   1916:     my ($id,$value,$debug)=@_;
1.919     albertel 1917: 
                   1918:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1919:                                     : $value;
1.599     albertel 1920:     if ($to_remember<0) { return; }
                   1921:     $accessed{$id}=[&gettimeofday()];
                   1922:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1923:     my $to_kick;
                   1924:     my $max_time=0;
                   1925:     foreach my $other (keys(%accessed)) {
                   1926: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1927: 	    $to_kick=$other;
                   1928: 	    $max_time=&tv_interval($accessed{$other});
                   1929: 	}
                   1930:     }
                   1931:     delete($remembered{$to_kick});
                   1932:     delete($accessed{$to_kick});
                   1933:     $kicks++;
                   1934:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1935:     return;
                   1936: }
                   1937: 
1.599     albertel 1938: sub purge_remembered {
1.604     albertel 1939:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1940:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1941:     undef(%remembered);
                   1942:     undef(%accessed);
1.428     albertel 1943: }
1.70      www      1944: # ------------------------------------- Read an entry from a user's environment
                   1945: 
                   1946: sub userenvironment {
                   1947:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1948:     my $items;
                   1949:     foreach my $item (@what) {
                   1950:         $items.=&escape($item).'&';
                   1951:     }
                   1952:     $items=~s/\&$//;
1.70      www      1953:     my %returnhash=();
1.1009    raeburn  1954:     my $uhome = &homeserver($unam,$udom);
                   1955:     unless ($uhome eq 'no_host') {
                   1956:         my @answer=split(/\&/, 
                   1957:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1958:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1959:             return %returnhash;
                   1960:         }
1.1009    raeburn  1961:         my $i;
                   1962:         for ($i=0;$i<=$#what;$i++) {
                   1963: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1964:         }
1.70      www      1965:     }
                   1966:     return %returnhash;
1.1       albertel 1967: }
                   1968: 
1.617     albertel 1969: # ---------------------------------------------------------- Get a studentphoto
                   1970: sub studentphoto {
                   1971:     my ($udom,$unam,$ext) = @_;
                   1972:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1973:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1974:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1975:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1976:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1977:             } else {
                   1978:                 my ($result,$perm_reqd)=
1.707     albertel 1979: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1980:                 if ($result eq 'ok') {
                   1981:                     if (!($perm_reqd eq 'yes')) {
                   1982:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1983:                     }
                   1984:                 }
                   1985:             }
                   1986:         }
                   1987:     } else {
                   1988:         my ($result,$perm_reqd) = 
1.707     albertel 1989: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1990:         if ($result eq 'ok') {
                   1991:             if (!($perm_reqd eq 'yes')) {
                   1992:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1993:             }
                   1994:         }
                   1995:     }
                   1996:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1997: }
                   1998: 
                   1999: sub retrievestudentphoto {
                   2000:     my ($udom,$unam,$ext,$type) = @_;
                   2001:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2002:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2003:     if ($ret eq 'ok') {
                   2004:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2005:         if ($type eq 'thumbnail') {
                   2006:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2007:         }
                   2008:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2009:         return $tokenurl;
                   2010:     } else {
                   2011:         if ($type eq 'thumbnail') {
                   2012:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2013:         } else { 
                   2014:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2015:         }
1.617     albertel 2016:     }
                   2017: }
                   2018: 
1.263     www      2019: # -------------------------------------------------------------------- New chat
                   2020: 
                   2021: sub chatsend {
1.724     raeburn  2022:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2023:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2024:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2025:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2026:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2027: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2028: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2029: }
                   2030: 
                   2031: # ------------------------------------------ Find current version of a resource
                   2032: 
                   2033: sub getversion {
                   2034:     my $fname=&clutter(shift);
                   2035:     unless ($fname=~/^\/res\//) { return -1; }
                   2036:     return &currentversion(&filelocation('',$fname));
                   2037: }
                   2038: 
                   2039: sub currentversion {
                   2040:     my $fname=shift;
1.599     albertel 2041:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      2042:     if (defined($cached)) { return $result; }
1.292     www      2043:     my $author=$fname;
                   2044:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2045:     my ($udom,$uname)=split(/\//,$author);
                   2046:     my $home=homeserver($uname,$udom);
                   2047:     if ($home eq 'no_host') { 
                   2048:         return -1; 
                   2049:     }
                   2050:     my $answer=reply("currentversion:$fname",$home);
                   2051:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2052: 	return -1;
                   2053:     }
1.599     albertel 2054:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      2055: }
                   2056: 
1.1       albertel 2057: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2058: 
1.1       albertel 2059: sub subscribe {
                   2060:     my $fname=shift;
1.761     raeburn  2061:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2062:     $fname=~s/[\n\r]//g;
1.1       albertel 2063:     my $author=$fname;
                   2064:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2065:     my ($udom,$uname)=split(/\//,$author);
                   2066:     my $home=homeserver($uname,$udom);
1.335     albertel 2067:     if ($home eq 'no_host') {
                   2068:         return 'not_found';
1.1       albertel 2069:     }
                   2070:     my $answer=reply("sub:$fname",$home);
1.64      www      2071:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2072: 	$answer.=' by '.$home;
                   2073:     }
1.1       albertel 2074:     return $answer;
                   2075: }
                   2076:     
1.8       www      2077: # -------------------------------------------------------------- Replicate file
                   2078: 
                   2079: sub repcopy {
                   2080:     my $filename=shift;
1.23      www      2081:     $filename=~s/\/+/\//g;
1.607     raeburn  2082:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2083:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2084:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2085: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2086: 	return &repcopy_userfile($filename);
                   2087:     }
1.532     albertel 2088:     $filename=~s/[\n\r]//g;
1.8       www      2089:     my $transname="$filename.in.transfer";
1.828     www      2090: # FIXME: this should flock
1.607     raeburn  2091:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2092:     my $remoteurl=subscribe($filename);
1.64      www      2093:     if ($remoteurl =~ /^con_lost by/) {
                   2094: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2095:            return 'unavailable';
1.8       www      2096:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2097: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2098: 	   return 'not_found';
1.64      www      2099:     } elsif ($remoteurl =~ /^rejected by/) {
                   2100: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2101:            return 'forbidden';
1.20      www      2102:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2103:            return 'ok';
1.8       www      2104:     } else {
1.290     www      2105:         my $author=$filename;
                   2106:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2107:         my ($udom,$uname)=split(/\//,$author);
                   2108:         my $home=homeserver($uname,$udom);
                   2109:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2110:            my @parts=split(/\//,$filename);
                   2111:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2112:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2113:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2114: 	       return 'bad_request';
1.8       www      2115:            }
                   2116:            my $count;
                   2117:            for ($count=5;$count<$#parts;$count++) {
                   2118:                $path.="/$parts[$count]";
                   2119:                if ((-e $path)!=1) {
                   2120: 		   mkdir($path,0777);
                   2121:                }
                   2122:            }
                   2123:            my $ua=new LWP::UserAgent;
                   2124:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2125:            my $response=$ua->request($request,$transname);
                   2126:            if ($response->is_error()) {
                   2127: 	       unlink($transname);
                   2128:                my $message=$response->status_line;
1.672     albertel 2129:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2130:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2131:                return 'unavailable';
1.8       www      2132:            } else {
1.16      www      2133: 	       if ($remoteurl!~/\.meta$/) {
                   2134:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2135:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2136:                   if ($mresponse->is_error()) {
                   2137: 		      unlink($filename.'.meta');
                   2138:                       &logthis(
1.672     albertel 2139:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2140:                   }
                   2141: 	       }
1.8       www      2142:                rename($transname,$filename);
1.607     raeburn  2143:                return 'ok';
1.8       www      2144:            }
1.290     www      2145:        }
1.8       www      2146:     }
1.330     www      2147: }
                   2148: 
                   2149: # ------------------------------------------------ Get server side include body
                   2150: sub ssi_body {
1.381     albertel 2151:     my ($filelink,%form)=@_;
1.606     matthew  2152:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2153:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2154:     }
1.953     www      2155:     my $output='';
                   2156:     my $response;
1.980     raeburn  2157:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2158:        ($output,$response)=&externalssi($filelink);
1.953     www      2159:     } else {
1.1004    droeschl 2160:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2161:        $filelink .= 'inhibitmenu=yes';
1.953     www      2162:        ($output,$response)=&ssi($filelink,%form);
                   2163:     }
1.778     albertel 2164:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2165:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2166:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2167:     if (wantarray) {
                   2168:         return ($output, $response);
                   2169:     } else {
                   2170:         return $output;
                   2171:     }
1.8       www      2172: }
                   2173: 
1.15      www      2174: # --------------------------------------------------------- Server Side Include
                   2175: 
1.782     albertel 2176: sub absolute_url {
                   2177:     my ($host_name) = @_;
                   2178:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2179:     if ($host_name eq '') {
                   2180: 	$host_name = $ENV{'SERVER_NAME'};
                   2181:     }
                   2182:     return $protocol.$host_name;
                   2183: }
                   2184: 
1.942     foxr     2185: #
                   2186: #   Server side include.
                   2187: # Parameters:
                   2188: #  fn     Possibly encrypted resource name/id.
                   2189: #  form   Hash that describes how the rendering should be done
                   2190: #         and other things.
1.944     foxr     2191: # Returns:
1.950     raeburn  2192: #   Scalar context: The content of the response.
                   2193: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2194: #     
1.15      www      2195: sub ssi {
                   2196: 
1.944     foxr     2197:     my ($fn,%form)=@_;
1.15      www      2198:     my $ua=new LWP::UserAgent;
1.23      www      2199:     my $request;
1.711     albertel 2200: 
                   2201:     $form{'no_update_last_known'}=1;
1.895     albertel 2202:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2203:     if (%form) {
1.782     albertel 2204:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2205:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2206:     } else {
1.782     albertel 2207:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2208:     }
                   2209: 
1.15      www      2210:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2211:     my $response=$ua->request($request);
                   2212: 
1.944     foxr     2213:     if (wantarray) {
                   2214: 	return ($response->content, $response);
                   2215:     } else {
                   2216: 	return $response->content;
1.942     foxr     2217:     }
1.324     www      2218: }
                   2219: 
                   2220: sub externalssi {
                   2221:     my ($url)=@_;
                   2222:     my $ua=new LWP::UserAgent;
                   2223:     my $request=new HTTP::Request('GET',$url);
                   2224:     my $response=$ua->request($request);
1.954     raeburn  2225:     if (wantarray) {
                   2226:         return ($response->content, $response);
                   2227:     } else {
                   2228:         return $response->content;
                   2229:     }
1.15      www      2230: }
1.254     www      2231: 
1.492     albertel 2232: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2233: 
                   2234: sub allowuploaded {
                   2235:     my ($srcurl,$url)=@_;
                   2236:     $url=&clutter(&declutter($url));
                   2237:     my $dir=$url;
                   2238:     $dir=~s/\/[^\/]+$//;
                   2239:     my %httpref=();
                   2240:     my $httpurl=&hreflocation('',$url);
                   2241:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2242:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2243: }
1.477     raeburn  2244: 
1.478     albertel 2245: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2246: # input: action, courseID, current domain, intended
1.637     raeburn  2247: #        path to file, source of file, instruction to parse file for objects,
                   2248: #        ref to hash for embedded objects,
                   2249: #        ref to hash for codebase of java objects.
1.1056.4.16  raeburn  2250: #        reference to scalar to accommodate mime type determined
                   2251: #          from File::MMagic if $parser = parse.
1.637     raeburn  2252: #
1.485     raeburn  2253: # output: url to file (if action was uploaddoc), 
                   2254: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2255: #
1.478     albertel 2256: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2257: # course.
1.477     raeburn  2258: #
1.478     albertel 2259: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2260: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2261: #          course's home server.
1.477     raeburn  2262: #
1.478     albertel 2263: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2264: #          be copied from $source (current location) to 
                   2265: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2266: #         and will then be copied to
                   2267: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2268: #         course's home server.
1.485     raeburn  2269: #
1.481     raeburn  2270: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2271: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2272: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2273: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2274: #         in course's home server.
1.637     raeburn  2275: #
1.477     raeburn  2276: 
                   2277: sub process_coursefile {
1.1056.4.16  raeburn  2278:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2279:         $mimetype)=@_;
1.477     raeburn  2280:     my $fetchresult;
1.638     albertel 2281:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2282:     if ($action eq 'propagate') {
1.638     albertel 2283:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2284: 			     $home);
1.481     raeburn  2285:     } else {
1.477     raeburn  2286:         my $fpath = '';
                   2287:         my $fname = $file;
1.478     albertel 2288:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2289:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2290:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2291:         if ($action eq 'copy') {
                   2292:             if ($source eq '') {
                   2293:                 $fetchresult = 'no source file';
                   2294:                 return $fetchresult;
                   2295:             } else {
                   2296:                 my $destination = $filepath.'/'.$fname;
                   2297:                 rename($source,$destination);
                   2298:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2299:                                  $home);
1.481     raeburn  2300:             }
                   2301:         } elsif ($action eq 'uploaddoc') {
                   2302:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2303:             print $fh $env{'form.'.$source};
1.481     raeburn  2304:             close($fh);
1.637     raeburn  2305:             if ($parser eq 'parse') {
1.1024    raeburn  2306:                 my $mm = new File::MMagic;
1.1056.4.16  raeburn  2307:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2308:                 if ($type eq 'text/html') {
1.1024    raeburn  2309:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2310:                     unless ($parse_result eq 'ok') {
                   2311:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2312:                     }
1.637     raeburn  2313:                 }
1.1056.4.16  raeburn  2314:                 if (ref($mimetype)) {
                   2315:                     $$mimetype = $type;
                   2316:                 }
1.637     raeburn  2317:             }
1.477     raeburn  2318:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2319:                                  $home);
1.481     raeburn  2320:             if ($fetchresult eq 'ok') {
                   2321:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2322:             } else {
                   2323:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2324:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2325:                 return '/adm/notfound.html';
                   2326:             }
1.477     raeburn  2327:         }
                   2328:     }
1.485     raeburn  2329:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2330:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2331:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2332:     }
                   2333:     return $fetchresult;
                   2334: }
                   2335: 
1.637     raeburn  2336: sub build_filepath {
                   2337:     my ($fpath) = @_;
                   2338:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2339:     unless ($fpath eq '') {
                   2340:         my @parts=split('/',$fpath);
                   2341:         foreach my $part (@parts) {
                   2342:             $filepath.= '/'.$part;
                   2343:             if ((-e $filepath)!=1) {
                   2344:                 mkdir($filepath,0777);
                   2345:             }
                   2346:         }
                   2347:     }
                   2348:     return $filepath;
                   2349: }
                   2350: 
                   2351: sub store_edited_file {
1.638     albertel 2352:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2353:     my $file = $primary_url;
                   2354:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2355:     my $fpath = '';
                   2356:     my $fname = $file;
                   2357:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2358:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2359:     my $filepath = &build_filepath($fpath);
                   2360:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2361:     print $fh $content;
                   2362:     close($fh);
1.638     albertel 2363:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2364:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2365: 			  $home);
1.637     raeburn  2366:     if ($$fetchresult eq 'ok') {
                   2367:         return '/uploaded/'.$fpath.'/'.$fname;
                   2368:     } else {
1.638     albertel 2369:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2370: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2371:         return '/adm/notfound.html';
                   2372:     }
                   2373: }
                   2374: 
1.531     albertel 2375: sub clean_filename {
1.831     albertel 2376:     my ($fname,$args)=@_;
1.315     www      2377: # Replace Windows backslashes by forward slashes
1.257     www      2378:     $fname=~s/\\/\//g;
1.831     albertel 2379:     if (!$args->{'keep_path'}) {
                   2380:         # Get rid of everything but the actual filename
                   2381: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2382:     }
1.315     www      2383: # Replace spaces by underscores
                   2384:     $fname=~s/\s+/\_/g;
                   2385: # Replace all other weird characters by nothing
1.831     albertel 2386:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2387: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2388: # numbers
                   2389:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2390:     return $fname;
                   2391: }
1.1051    raeburn  2392: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2393: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2394: # image with the same aspect ratio as the original, but with dimensions which do 
                   2395: # not exceed $resizewidth and $resizeheight.
                   2396:  
1.984     neumanie 2397: sub resizeImage {
1.1051    raeburn  2398:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2399:     my $ima = Image::Magick->new;
                   2400:     my $resized;
                   2401:     if (-e $img_path) {
                   2402:         $ima->Read($img_path);
                   2403:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2404:             my $width = $ima->Get('width');
                   2405:             my $height = $ima->Get('height');
                   2406:             if ($width > $resizewidth) {
                   2407: 	        my $factor = $width/$resizewidth;
                   2408:                 my $newheight = $height/$factor;
                   2409:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2410:                 $resized = 1;
                   2411:             }
                   2412:         }
                   2413:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2414:             my $width = $ima->Get('width');
                   2415:             my $height = $ima->Get('height');
                   2416:             if ($height > $resizeheight) {
                   2417:                 my $factor = $height/$resizeheight;
                   2418:                 my $newwidth = $width/$factor;
                   2419:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2420:                 $resized = 1;
                   2421:             }
                   2422:         }
                   2423:         if ($resized) {
                   2424:             $ima->Write($img_path);
                   2425:         }
                   2426:     }
                   2427:     return;
1.977     amueller 2428: }
                   2429: 
1.608     albertel 2430: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2431: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13  raeburn  2432: #                    the desired filename is in $env{"form.$formname.filename"}
                   2433: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2434: #                                    canceloverwrite, or ''.
                   2435: #                   if 'coursedoc': upload to the current course
                   2436: #                   if 'existingfile': write file to tmp/overwrites directory
                   2437: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2438: #                   $context is passed as argument to &finishuserfileupload 
1.686     albertel 2439: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2440: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2441: #        $allfiles - reference to hash for embedded objects
                   2442: #        $codebase - reference to hash for codebase of java objects
                   2443: #        $desuname - username for permanent storage of uploaded file
                   2444: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2445: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2446: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2447: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2448: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1056.4.16  raeburn  2449: #        $mimetype - reference to scalar to accommodate mime type determined
                   2450: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2451: # 
1.686     albertel 2452: # output: url of file in userspace, or error: <message> 
                   2453: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2454: 
1.531     albertel 2455: sub userfileupload {
1.1056.4.13  raeburn  2456:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1056.4.16  raeburn  2457:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2458:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2459:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2460:     $fname=&clean_filename($fname);
1.1056.4.13  raeburn  2461:     # See if there is anything left
1.257     www      2462:     unless ($fname) { return 'error: no uploaded file'; }
1.1056.4.13  raeburn  2463:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2464:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2465:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2466:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2467:         my $now = time;
1.1056.4.13  raeburn  2468:         my $filepath;
                   2469:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
                   2470:              $filepath = 'tmp/helprequests/'.$now;
                   2471:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2472:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2473:                          '_'.$env{'user.domain'}.'/pending';
                   2474:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2475:             my ($docuname,$docudom);
                   2476:             if ($destudom) {
                   2477:                 $docudom = $destudom;
                   2478:             } else {
                   2479:                 $docudom = $env{'user.domain'};
                   2480:             }
                   2481:             if ($destuname) {
                   2482:                 $docuname = $destuname;
                   2483:             } else {
                   2484:                 $docuname = $env{'user.name'};
                   2485:             }
                   2486:             if (exists($env{'form.group'})) {
                   2487:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2488:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2489:             }
                   2490:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2491:             if ($context eq 'canceloverwrite') {
                   2492:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2493:                 if (-e  $tempfile) {
                   2494:                     my @info = stat($tempfile);
                   2495:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2496:                         unlink($tempfile);
                   2497:                     }
                   2498:                 }
                   2499:                 return;
1.523     raeburn  2500:             }
                   2501:         }
1.1056.4.13  raeburn  2502:         # Create the directory if not present
1.741     raeburn  2503:         my @parts=split(/\//,$filepath);
                   2504:         my $fullpath = $perlvar{'lonDaemons'};
                   2505:         for (my $i=0;$i<@parts;$i++) {
                   2506:             $fullpath .= '/'.$parts[$i];
                   2507:             if ((-e $fullpath)!=1) {
                   2508:                 mkdir($fullpath,0777);
                   2509:             }
                   2510:         }
                   2511:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2512:         print $fh $env{'form.'.$formname};
                   2513:         close($fh);
1.1056.4.13  raeburn  2514:         if ($context eq 'existingfile') {
                   2515:             my @info = stat($fullpath.'/'.$fname);
                   2516:             return ($fullpath.'/'.$fname,$info[9]);
                   2517:         } else {
                   2518:             return $fullpath.'/'.$fname;
                   2519:         }
1.523     raeburn  2520:     }
1.995     raeburn  2521:     if ($subdir eq 'scantron') {
                   2522:         $fname = 'scantron_orig_'.$fname;
1.1056.4.14  raeburn  2523:     } else {
1.995     raeburn  2524:         $fname="$subdir/$fname";
                   2525:     }
1.1056.4.13  raeburn  2526:     if ($context eq 'coursedoc') {
1.638     albertel 2527: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2528: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2529:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2530:             return &finishuserfileupload($docuname,$docudom,
                   2531: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2532: 					 $codebase,$thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2533:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2534:         } else {
1.620     albertel 2535:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2536:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2537: 				       $fname,$formname,$parser,
1.1056.4.16  raeburn  2538: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2539:         }
1.719     banghart 2540:     } elsif (defined($destuname)) {
                   2541:         my $docuname=$destuname;
                   2542:         my $docudom=$destudom;
1.860     raeburn  2543: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2544: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2545:                                      $thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2546:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2547:     } else {
1.638     albertel 2548:         my $docuname=$env{'user.name'};
                   2549:         my $docudom=$env{'user.domain'};
1.714     raeburn  2550:         if (exists($env{'form.group'})) {
                   2551:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2552:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2553:         }
1.860     raeburn  2554: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2555: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2556:                                      $thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2557:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2558:     }
1.271     www      2559: }
                   2560: 
                   2561: sub finishuserfileupload {
1.860     raeburn  2562:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.16  raeburn  2563:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2564:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2565:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2566:   
1.860     raeburn  2567:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2568:     $file=$fname;
                   2569:     if ($fname=~m|/|) {
                   2570:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2571: 	$path.=$fnamepath.'/';
                   2572:     }
1.259     www      2573:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2574:     my $count;
                   2575:     for ($count=4;$count<=$#parts;$count++) {
                   2576:         $filepath.="/$parts[$count]";
                   2577:         if ((-e $filepath)!=1) {
                   2578: 	    mkdir($filepath,0777);
                   2579:         }
                   2580:     }
1.984     neumanie 2581: 
1.258     www      2582: # Save the file
                   2583:     {
1.701     albertel 2584: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2585: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2586: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2587: 	    return '/adm/notfound.html';
                   2588: 	}
1.1056.4.13  raeburn  2589:         if ($context eq 'overwrite') {
                   2590:             my $source =  $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
                   2591:             my $target = $filepath.'/'.$file;
                   2592:             if (-e $source) {
                   2593:                 my @info = stat($source);
                   2594:                 if ($info[9] eq $env{'form.timestamp'}) {
                   2595:                     unless (&File::Copy::move($source,$target)) {
                   2596:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2597:                         return "Moving from $source failed";
                   2598:                     }
                   2599:                 } else {
                   2600:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2601:                 }
                   2602:             } else {
                   2603:                 return "Temporary file: $source missing";
                   2604:             }
                   2605: 	} elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2606: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2607: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2608: 	    return '/adm/notfound.html';
                   2609: 	}
1.570     albertel 2610: 	close(FH);
1.1051    raeburn  2611:         if ($resizewidth && $resizeheight) {
                   2612:             my $mm = new File::MMagic;
                   2613:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2614:             if ($mime_type =~ m{^image/}) {
                   2615: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2616:             }  
1.977     amueller 2617: 	}
1.258     www      2618:     }
1.637     raeburn  2619:     if ($parser eq 'parse') {
1.1024    raeburn  2620:         my $mm = new File::MMagic;
1.1056.4.16  raeburn  2621:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2622:         if ($type eq 'text/html') {
1.1024    raeburn  2623:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2624:                                                        $allfiles,$codebase);
                   2625:             unless ($parse_result eq 'ok') {
                   2626:                 &logthis('Failed to parse '.$filepath.$file.
                   2627: 	   	         ' for embedded media: '.$parse_result); 
                   2628:             }
1.637     raeburn  2629:         }
1.1056.4.16  raeburn  2630:         if (ref($mimetype)) {
                   2631:             $$mimetype = $type;
                   2632:         }
1.637     raeburn  2633:     }
1.860     raeburn  2634:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2635:         my $input = $filepath.'/'.$file;
                   2636:         my $output = $filepath.'/'.'tn-'.$file;
                   2637:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2638:         system("convert -sample $thumbsize $input $output");
                   2639:         if (-e $filepath.'/'.'tn-'.$file) {
                   2640:             $fetchthumb  = 1; 
                   2641:         }
                   2642:     }
1.858     raeburn  2643:  
1.259     www      2644: # Notify homeserver to grep it
                   2645: #
1.984     neumanie 2646:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2647:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2648:     if ($fetchresult eq 'ok') {
1.860     raeburn  2649:         if ($fetchthumb) {
                   2650:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2651:             if ($thumbresult ne 'ok') {
                   2652:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2653:                          $docuhome.': '.$thumbresult);
                   2654:             }
                   2655:         }
1.259     www      2656: #
1.258     www      2657: # Return the URL to it
1.494     albertel 2658:         return '/uploaded/'.$path.$file;
1.263     www      2659:     } else {
1.494     albertel 2660:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2661: 		 ': '.$fetchresult);
1.263     www      2662:         return '/adm/notfound.html';
1.858     raeburn  2663:     }
1.493     albertel 2664: }
                   2665: 
1.637     raeburn  2666: sub extract_embedded_items {
1.961     raeburn  2667:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2668:     my @state = ();
                   2669:     my %javafiles = (
                   2670:                       codebase => '',
                   2671:                       code => '',
                   2672:                       archive => ''
                   2673:                     );
                   2674:     my %mediafiles = (
                   2675:                       src => '',
                   2676:                       movie => '',
                   2677:                      );
1.648     raeburn  2678:     my $p;
                   2679:     if ($content) {
                   2680:         $p = HTML::LCParser->new($content);
                   2681:     } else {
1.961     raeburn  2682:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2683:     }
1.641     albertel 2684:     while (my $t=$p->get_token()) {
1.640     albertel 2685: 	if ($t->[0] eq 'S') {
                   2686: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2687: 	    push(@state, $tagname);
1.648     raeburn  2688:             if (lc($tagname) eq 'allow') {
                   2689:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2690:             }
1.640     albertel 2691: 	    if (lc($tagname) eq 'img') {
                   2692: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2693: 	    }
1.886     albertel 2694: 	    if (lc($tagname) eq 'a') {
                   2695: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2696: 	    }
1.645     raeburn  2697:             if (lc($tagname) eq 'script') {
                   2698:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2699:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2700:                 } else {
                   2701:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2702:                 }
                   2703:             }
                   2704:             if (lc($tagname) eq 'link') {
                   2705:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2706:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2707:                 }
                   2708:             }
1.640     albertel 2709: 	    if (lc($tagname) eq 'object' ||
                   2710: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2711: 		foreach my $item (keys(%javafiles)) {
                   2712: 		    $javafiles{$item} = '';
                   2713: 		}
                   2714: 	    }
                   2715: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2716: 		my $name = lc($attr->{'name'});
                   2717: 		foreach my $item (keys(%javafiles)) {
                   2718: 		    if ($name eq $item) {
                   2719: 			$javafiles{$item} = $attr->{'value'};
                   2720: 			last;
                   2721: 		    }
                   2722: 		}
                   2723: 		foreach my $item (keys(%mediafiles)) {
                   2724: 		    if ($name eq $item) {
                   2725: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2726: 			last;
                   2727: 		    }
                   2728: 		}
                   2729: 	    }
                   2730: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2731: 		foreach my $item (keys(%javafiles)) {
                   2732: 		    if ($attr->{$item}) {
                   2733: 			$javafiles{$item} = $attr->{$item};
                   2734: 			last;
                   2735: 		    }
                   2736: 		}
                   2737: 		foreach my $item (keys(%mediafiles)) {
                   2738: 		    if ($attr->{$item}) {
                   2739: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2740: 			last;
                   2741: 		    }
                   2742: 		}
                   2743: 	    }
                   2744: 	} elsif ($t->[0] eq 'E') {
                   2745: 	    my ($tagname) = ($t->[1]);
                   2746: 	    if ($javafiles{'codebase'} ne '') {
                   2747: 		$javafiles{'codebase'} .= '/';
                   2748: 	    }  
                   2749: 	    if (lc($tagname) eq 'applet' ||
                   2750: 		lc($tagname) eq 'object' ||
                   2751: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2752: 		) {
                   2753: 		foreach my $item (keys(%javafiles)) {
                   2754: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2755: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2756: 			&add_filetype($allfiles,$file,$item);
                   2757: 		    }
                   2758: 		}
                   2759: 	    } 
                   2760: 	    pop @state;
                   2761: 	}
                   2762:     }
1.637     raeburn  2763:     return 'ok';
                   2764: }
                   2765: 
1.639     albertel 2766: sub add_filetype {
                   2767:     my ($allfiles,$file,$type)=@_;
                   2768:     if (exists($allfiles->{$file})) {
                   2769: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2770: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2771: 	}
                   2772:     } else {
                   2773: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2774:     }
                   2775: }
                   2776: 
1.493     albertel 2777: sub removeuploadedurl {
1.984     neumanie 2778:     my ($url)=@_;	
                   2779:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2780:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2781: }
                   2782: 
                   2783: sub removeuserfile {
                   2784:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2785:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2786:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2787:     if ($result eq 'ok') {	
1.798     raeburn  2788:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2789:             my $metafile = $fname.'.meta';
                   2790:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2791: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2792:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2793:             my $sqlresult = 
1.823     albertel 2794:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2795:                                         'portfolio_metadata',$group,
                   2796:                                         'delete');
1.798     raeburn  2797:         }
                   2798:     }
                   2799:     return $result;
1.257     www      2800: }
1.15      www      2801: 
1.530     albertel 2802: sub mkdiruserfile {
                   2803:     my ($docuname,$docudom,$dir)=@_;
                   2804:     my $home=&homeserver($docuname,$docudom);
                   2805:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2806: }
                   2807: 
1.531     albertel 2808: sub renameuserfile {
                   2809:     my ($docuname,$docudom,$old,$new)=@_;
                   2810:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2811:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2812:                         &escape("$old").':'.&escape("$new"),$home);
                   2813:     if ($result eq 'ok') {
                   2814:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2815:             my $oldmeta = $old.'.meta';
                   2816:             my $newmeta = $new.'.meta';
                   2817:             my $metaresult = 
                   2818:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2819: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2820:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2821:             my $sqlresult = 
1.823     albertel 2822:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2823:                                         'portfolio_metadata',$group,
                   2824:                                         'delete');
1.798     raeburn  2825:         }
                   2826:     }
                   2827:     return $result;
1.531     albertel 2828: }
                   2829: 
1.14      www      2830: # ------------------------------------------------------------------------- Log
                   2831: 
                   2832: sub log {
                   2833:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2834:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2835: }
                   2836: 
                   2837: # ------------------------------------------------------------------ Course Log
1.352     www      2838: #
                   2839: # This routine flushes several buffers of non-mission-critical nature
                   2840: #
1.157     www      2841: 
                   2842: sub flushcourselogs {
1.352     www      2843:     &logthis('Flushing log buffers');
                   2844: #
                   2845: # course logs
                   2846: # This is a log of all transactions in a course, which can be used
                   2847: # for data mining purposes
                   2848: #
                   2849: # It also collects the courseid database, which lists last transaction
                   2850: # times and course titles for all courseids
                   2851: #
                   2852:     my %courseidbuffer=();
1.921     raeburn  2853:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2854:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2855: 		          &escape($courselogs{$crsid}),
                   2856: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2857: 	    delete $courselogs{$crsid};
                   2858:         } else {
                   2859:             &logthis('Failed to flush log buffer for '.$crsid);
                   2860:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2861:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2862:                         " exceeded maximum size, deleting.</font>");
                   2863:                delete $courselogs{$crsid};
                   2864:             }
1.352     www      2865:         }
1.920     raeburn  2866:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2867:             'description' => $coursedescrbuf{$crsid},
                   2868:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2869:             'type'        => $coursetypebuf{$crsid},
                   2870:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2871:         };
1.191     harris41 2872:     }
1.352     www      2873: #
                   2874: # Write course id database (reverse lookup) to homeserver of courses 
                   2875: # Is used in pickcourse
                   2876: #
1.840     albertel 2877:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2878:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2879:                                     $courseidbuffer{$crs_home},
                   2880:                                     $crs_home,'timeonly');
1.352     www      2881:     }
                   2882: #
                   2883: # File accesses
                   2884: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2885: #
1.449     matthew  2886:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2887:         if ($entry =~ /___count$/) {
                   2888:             my ($dom,$name);
1.807     albertel 2889:             ($dom,$name,undef)=
1.811     albertel 2890: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2891:             if (! defined($dom) || $dom eq '' || 
                   2892:                 ! defined($name) || $name eq '') {
1.620     albertel 2893:                 my $cid = $env{'request.course.id'};
                   2894:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2895:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2896:             }
1.450     matthew  2897:             my $value = $accesshash{$entry};
                   2898:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2899:             my %temphash=($url => $value);
1.449     matthew  2900:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2901:             if ($result eq 'ok') {
                   2902:                 delete $accesshash{$entry};
                   2903:             } elsif ($result eq 'unknown_cmd') {
                   2904:                 # Target server has old code running on it.
1.450     matthew  2905:                 my %temphash=($entry => $value);
1.449     matthew  2906:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2907:                     delete $accesshash{$entry};
                   2908:                 }
                   2909:             }
                   2910:         } else {
1.811     albertel 2911:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2912:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2913:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2914:                 delete $accesshash{$entry};
                   2915:             }
1.185     www      2916:         }
1.191     harris41 2917:     }
1.352     www      2918: #
                   2919: # Roles
                   2920: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2921: #
1.800     albertel 2922:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2923:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2924: 	    split(/\:/,$entry);
                   2925:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2926:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2927:                 $rudom,$runame) eq 'ok') {
                   2928: 	    delete $userrolehash{$entry};
                   2929:         }
                   2930:     }
1.662     raeburn  2931: #
                   2932: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2933: #
                   2934:     my %domrolebuffer = ();
1.1000    raeburn  2935:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2936:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2937:         if ($domrolebuffer{$rudom}) {
                   2938:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2939:                       '='.&escape($domainrolehash{$entry});
                   2940:         } else {
                   2941:             $domrolebuffer{$rudom}.=&escape($entry).
                   2942:                       '='.&escape($domainrolehash{$entry});
                   2943:         }
                   2944:         delete $domainrolehash{$entry};
                   2945:     }
                   2946:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2947: 	my %servers = &get_servers($dom,'library');
                   2948: 	foreach my $tryserver (keys(%servers)) {
                   2949: 	    unless (&reply('domroleput:'.$dom.':'.
                   2950: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2951: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2952: 	    }
1.662     raeburn  2953:         }
                   2954:     }
1.186     www      2955:     $dumpcount++;
1.157     www      2956: }
                   2957: 
                   2958: sub courselog {
                   2959:     my $what=shift;
1.158     www      2960:     $what=time.':'.$what;
1.620     albertel 2961:     unless ($env{'request.course.id'}) { return ''; }
                   2962:     $coursedombuf{$env{'request.course.id'}}=
                   2963:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2964:     $coursenumbuf{$env{'request.course.id'}}=
                   2965:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2966:     $coursehombuf{$env{'request.course.id'}}=
                   2967:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2968:     $coursedescrbuf{$env{'request.course.id'}}=
                   2969:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2970:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2971:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2972:     $courseownerbuf{$env{'request.course.id'}}=
                   2973:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2974:     $coursetypebuf{$env{'request.course.id'}}=
                   2975:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2976:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2977: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2978:     } else {
1.620     albertel 2979: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2980:     }
1.620     albertel 2981:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2982: 	&flushcourselogs();
                   2983:     }
1.158     www      2984: }
                   2985: 
                   2986: sub courseacclog {
                   2987:     my $fnsymb=shift;
1.620     albertel 2988:     unless ($env{'request.course.id'}) { return ''; }
                   2989:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2990:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2991:         $what.=':POST';
1.583     matthew  2992:         # FIXME: Probably ought to escape things....
1.800     albertel 2993: 	foreach my $key (keys(%env)) {
                   2994:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2995:                 my $formitem = $1;
                   2996:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2997:                     $what.=':'.$formitem.'='.$env{$key};
                   2998:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2999:                     $what.=':'.$formitem.'='.$env{$key};
                   3000:                 }
1.158     www      3001:             }
1.191     harris41 3002:         }
1.583     matthew  3003:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3004:         # FIXME: We should not be depending on a form parameter that someone
                   3005:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3006:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3007:             $what.= ':POST';
                   3008:             # FIXME: Probably ought to escape things....
                   3009:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3010:                                  'crsdiscuss') {
1.620     albertel 3011:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3012:             }
                   3013:         }
1.158     www      3014:     }
                   3015:     &courselog($what);
1.149     www      3016: }
                   3017: 
1.185     www      3018: sub countacc {
                   3019:     my $url=&declutter(shift);
1.458     matthew  3020:     return if (! defined($url) || $url eq '');
1.620     albertel 3021:     unless ($env{'request.course.id'}) { return ''; }
                   3022:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3023:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3024:     $accesshash{$key}++;
1.185     www      3025: }
1.349     www      3026: 
1.361     www      3027: sub linklog {
                   3028:     my ($from,$to)=@_;
                   3029:     $from=&declutter($from);
                   3030:     $to=&declutter($to);
                   3031:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3032:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3033: }
                   3034:   
1.349     www      3035: sub userrolelog {
                   3036:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3037:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3038:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3039:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3040:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3041:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3042:        $userrolehash
                   3043:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3044:                     =$tend.':'.$tstart;
1.662     raeburn  3045:     }
1.898     albertel 3046:     if (($env{'request.role'} =~ /dc\./) &&
                   3047: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3048: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3049: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3050:          ($trole=~/^co/))) {
1.898     albertel 3051:        $userrolehash
                   3052:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3053:                     =$tend.':'.$tstart;
                   3054:     }
1.662     raeburn  3055:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3056:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3057:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3058:         ($trole=~/^sc/)) {
                   3059:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3060:        $domainrolehash
                   3061:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3062:                     = $tend.':'.$tstart;
                   3063:     }
1.351     www      3064: }
                   3065: 
1.957     raeburn  3066: sub courserolelog {
                   3067:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3068:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3069:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3070:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3071:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3072:         ($trole eq 'co')) {
1.957     raeburn  3073:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3074:             my $cdom = $1;
                   3075:             my $cnum = $2;
                   3076:             my $sec = $3;
                   3077:             my $namespace = 'rolelog';
                   3078:             my %storehash = (
                   3079:                                role    => $trole,
                   3080:                                start   => $tstart,
                   3081:                                end     => $tend,
                   3082:                                selfenroll => $selfenroll,
                   3083:                                context    => $context,
                   3084:                             );
                   3085:             if ($trole eq 'gr') {
                   3086:                 $namespace = 'groupslog';
                   3087:                 $storehash{'group'} = $sec;
                   3088:             } else {
                   3089:                 $storehash{'section'} = $sec;
                   3090:             }
                   3091:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3092:             if (($trole ne 'st') || ($sec ne '')) {
                   3093:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3094:             }
1.957     raeburn  3095:         }
                   3096:     }
                   3097:     return;
                   3098: }
                   3099: 
1.351     www      3100: sub get_course_adv_roles {
1.948     raeburn  3101:     my ($cid,$codes) = @_;
1.620     albertel 3102:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3103:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3104:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3105:     my %nothide=();
1.800     albertel 3106:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3107:         if ($user !~ /:/) {
                   3108: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3109:         } else {
                   3110:             $nothide{$user}=1;
                   3111:         }
1.470     www      3112:     }
1.351     www      3113:     my %returnhash=();
                   3114:     my %dumphash=
                   3115:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3116:     my $now=time;
1.997     raeburn  3117:     my %privileged;
1.1000    raeburn  3118:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3119: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3120:         if (($tstart) && ($tstart<0)) { next; }
                   3121:         if (($tend) && ($tend<$now)) { next; }
                   3122:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3123:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3124: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3125:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3126:             my %dompersonnel =
1.998     raeburn  3127:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3128:             $privileged{$domain} = {};
                   3129:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3130:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3131:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3132:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3133:                         $privileged{$udom}{$uname} = 1;
                   3134:                     }
                   3135:                 }
                   3136:             }
                   3137:         }
                   3138:         if ((exists($privileged{$domain}{$username})) && 
                   3139:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3140: 	if ($role eq 'cr') { next; }
1.948     raeburn  3141:         if ($codes) {
                   3142:             if ($section) { $role .= ':'.$section; }
                   3143:             if ($returnhash{$role}) {
                   3144:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3145:             } else {
                   3146:                 $returnhash{$role}=$username.':'.$domain;
                   3147:             }
1.351     www      3148:         } else {
1.988     raeburn  3149:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3150:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3151:             if ($returnhash{$key}) {
                   3152: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3153:             } else {
                   3154:                 $returnhash{$key}=$username.':'.$domain;
                   3155:             }
1.351     www      3156:         }
1.948     raeburn  3157:     }
1.400     www      3158:     return %returnhash;
                   3159: }
                   3160: 
                   3161: sub get_my_roles {
1.937     raeburn  3162:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3163:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3164:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3165:     my (%dumphash,%nothide);
1.858     raeburn  3166:     if ($context eq 'userroles') { 
1.1056.4.10  raeburn  3167:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3168:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3169:     } else {
                   3170:         %dumphash=
1.400     www      3171:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3172:         if ($hidepriv) {
                   3173:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3174:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3175:                 if ($user !~ /:/) {
                   3176:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3177:                 } else {
                   3178:                     $nothide{$user} = 1;
                   3179:                 }
                   3180:             }
                   3181:         }
1.858     raeburn  3182:     }
1.400     www      3183:     my %returnhash=();
                   3184:     my $now=time;
1.999     raeburn  3185:     my %privileged;
1.800     albertel 3186:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3187:         my ($role,$tend,$tstart);
                   3188:         if ($context eq 'userroles') {
                   3189: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3190:         } else {
                   3191:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3192:         }
1.400     www      3193:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3194:         my $status = 'active';
1.939     raeburn  3195:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3196:             $status = 'previous';
                   3197:         } 
                   3198:         if (($tstart) && ($now<$tstart)) {
                   3199:             $status = 'future';
                   3200:         }
                   3201:         if (ref($types) eq 'ARRAY') {
                   3202:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3203:                 next;
                   3204:             } 
                   3205:         } else {
                   3206:             if ($status ne 'active') {
                   3207:                 next;
                   3208:             }
                   3209:         }
1.867     raeburn  3210:         my ($rolecode,$username,$domain,$section,$area);
                   3211:         if ($context eq 'userroles') {
                   3212:             ($area,$rolecode) = split(/_/,$entry);
                   3213:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3214:         } else {
                   3215:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3216:         }
1.832     raeburn  3217:         if (ref($roledoms) eq 'ARRAY') {
                   3218:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3219:                 next;
                   3220:             }
                   3221:         }
                   3222:         if (ref($roles) eq 'ARRAY') {
                   3223:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3224:                 if ($role =~ /^cr\//) {
                   3225:                     if (!grep(/^cr$/,@{$roles})) {
                   3226:                         next;
                   3227:                     }
                   3228:                 } else {
                   3229:                     next;
                   3230:                 }
1.832     raeburn  3231:             }
1.867     raeburn  3232:         }
1.937     raeburn  3233:         if ($hidepriv) {
1.999     raeburn  3234:             if ($context eq 'userroles') {
                   3235:                 if ((&privileged($username,$domain)) &&
                   3236:                     (!$nothide{$username.':'.$domain})) {
                   3237:                     next;
                   3238:                 }
                   3239:             } else {
                   3240:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3241:                     my %dompersonnel =
                   3242:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3243:                     $privileged{$domain} = {};
                   3244:                     if (keys(%dompersonnel)) {
                   3245:                         foreach my $server (keys(%dompersonnel)) {
                   3246:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3247:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3248:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3249:                                     $privileged{$udom}{$uname} = $trole;
                   3250:                                 }
                   3251:                             }
                   3252:                         }
                   3253:                     }
                   3254:                 }
                   3255:                 if (exists($privileged{$domain}{$username})) {
                   3256:                     if (!$nothide{$username.':'.$domain}) {
                   3257:                         next;
                   3258:                     }
                   3259:                 }
1.937     raeburn  3260:             }
                   3261:         }
1.933     raeburn  3262:         if ($withsec) {
                   3263:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3264:                 $tstart.':'.$tend;
                   3265:         } else {
                   3266:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3267:         }
1.832     raeburn  3268:     }
1.373     www      3269:     return %returnhash;
1.399     www      3270: }
                   3271: 
                   3272: # ----------------------------------------------------- Frontpage Announcements
                   3273: #
                   3274: #
                   3275: 
                   3276: sub postannounce {
                   3277:     my ($server,$text)=@_;
1.844     albertel 3278:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3279:     unless ($text=~/\w/) { $text=''; }
                   3280:     return &reply('setannounce:'.&escape($text),$server);
                   3281: }
                   3282: 
                   3283: sub getannounce {
1.448     albertel 3284: 
                   3285:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3286: 	my $announcement='';
1.800     albertel 3287: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3288: 	close($fh);
1.399     www      3289: 	if ($announcement=~/\w/) { 
                   3290: 	    return 
                   3291:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3292:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3293: 	} else {
                   3294: 	    return '';
                   3295: 	}
                   3296:     } else {
                   3297: 	return '';
                   3298:     }
1.351     www      3299: }
1.353     www      3300: 
                   3301: # ---------------------------------------------------------- Course ID routines
                   3302: # Deal with domain's nohist_courseid.db files
                   3303: #
                   3304: 
                   3305: sub courseidput {
1.921     raeburn  3306:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3307:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3308:     my $outcome;
                   3309:     if ($caller eq 'timeonly') {
                   3310:         my $cids = '';
                   3311:         foreach my $item (keys(%$storehash)) {
                   3312:             $cids.=&escape($item).'&';
                   3313:         }
                   3314:         $cids=~s/\&$//;
                   3315:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3316:                           $coursehome);       
                   3317:     } else {
                   3318:         my $items = '';
                   3319:         foreach my $item (keys(%$storehash)) {
                   3320:             $items.= &escape($item).'='.
                   3321:                      &freeze_escape($$storehash{$item}).'&';
                   3322:         }
                   3323:         $items=~s/\&$//;
                   3324:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3325:                           $coursehome);
1.918     raeburn  3326:     }
                   3327:     if ($outcome eq 'unknown_cmd') {
                   3328:         my $what;
                   3329:         foreach my $cid (keys(%$storehash)) {
                   3330:             $what .= &escape($cid).'=';
1.921     raeburn  3331:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3332:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3333:             }
                   3334:             $what =~ s/\:$/&/;
                   3335:         }
                   3336:         $what =~ s/\&$//;  
                   3337:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3338:     } else {
                   3339:         return $outcome;
                   3340:     }
1.353     www      3341: }
                   3342: 
                   3343: sub courseiddump {
1.921     raeburn  3344:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3345:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3346:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3347:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3348:     my $as_hash = 1;
                   3349:     my %returnhash;
                   3350:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3351:     my %libserv = &all_library();
                   3352:     foreach my $tryserver (keys(%libserv)) {
                   3353:         if ( (  $hostidflag == 1 
                   3354: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3355: 	     || (!defined($hostidflag)) ) {
                   3356: 
1.918     raeburn  3357: 	    if (($domfilter eq '') ||
                   3358: 		(&host_domain($tryserver) eq $domfilter)) {
                   3359:                 my $rep = 
                   3360:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3361:                          $sincefilter.':'.&escape($descfilter).':'.
                   3362:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3363:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3364:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3365:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3366:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3367:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3368:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3369:                          &escape($creationcontext).':'.$domcloner,
                   3370:                          $tryserver);
1.918     raeburn  3371:                 my @pairs=split(/\&/,$rep);
                   3372:                 foreach my $item (@pairs) {
                   3373:                     my ($key,$value)=split(/\=/,$item,2);
                   3374:                     $key = &unescape($key);
                   3375:                     next if ($key =~ /^error: 2 /);
                   3376:                     my $result = &thaw_unescape($value);
                   3377:                     if (ref($result) eq 'HASH') {
                   3378:                         $returnhash{$key}=$result;
                   3379:                     } else {
1.921     raeburn  3380:                         my @responses = split(/:/,$value);
                   3381:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3382:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3383:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3384:                         }
1.1008    raeburn  3385:                     }
1.353     www      3386:                 }
                   3387:             }
                   3388:         }
                   3389:     }
                   3390:     return %returnhash;
                   3391: }
                   3392: 
1.1055    raeburn  3393: sub courselastaccess {
                   3394:     my ($cdom,$cnum,$hostidref) = @_;
                   3395:     my %returnhash;
                   3396:     if ($cdom && $cnum) {
                   3397:         my $chome = &homeserver($cnum,$cdom);
                   3398:         if ($chome ne 'no_host') {
                   3399:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3400:             &extract_lastaccess(\%returnhash,$rep);
                   3401:         }
                   3402:     } else {
                   3403:         if (!$cdom) { $cdom=''; }
                   3404:         my %libserv = &all_library();
                   3405:         foreach my $tryserver (keys(%libserv)) {
                   3406:             if (ref($hostidref) eq 'ARRAY') {
                   3407:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3408:             } 
                   3409:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3410:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3411:                 &extract_lastaccess(\%returnhash,$rep);
                   3412:             }
                   3413:         }
                   3414:     }
                   3415:     return %returnhash;
                   3416: }
                   3417: 
                   3418: sub extract_lastaccess {
                   3419:     my ($returnhash,$rep) = @_;
                   3420:     if (ref($returnhash) eq 'HASH') {
                   3421:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3422:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3423:                  $rep eq '') {
                   3424:             my @pairs=split(/\&/,$rep);
                   3425:             foreach my $item (@pairs) {
                   3426:                 my ($key,$value)=split(/\=/,$item,2);
                   3427:                 $key = &unescape($key);
                   3428:                 next if ($key =~ /^error: 2 /);
                   3429:                 $returnhash->{$key} = &thaw_unescape($value);
                   3430:             }
                   3431:         }
                   3432:     }
                   3433:     return;
                   3434: }
                   3435: 
1.658     raeburn  3436: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3437: 
                   3438: sub dcmailput {
1.685     raeburn  3439:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3440:     my $status = &Apache::lonnet::critical(
1.740     www      3441:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3442:        &escape($message),$server);
1.662     raeburn  3443:     return $status;
                   3444: }
                   3445: 
1.658     raeburn  3446: sub dcmaildump {
                   3447:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3448:     my %returnhash=();
1.846     albertel 3449: 
                   3450:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3451:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3452:                                                          &escape($enddate).':';
                   3453: 	my @esc_senders=map { &escape($_)} @$senders;
                   3454: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3455: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3456:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3457:             if (($key) && ($value)) {
                   3458:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3459:             }
                   3460:         }
                   3461:     }
                   3462:     return %returnhash;
                   3463: }
1.662     raeburn  3464: # ---------------------------------------------------------- Domain roles
                   3465: 
                   3466: sub get_domain_roles {
                   3467:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3468:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3469:         $startdate = '.';
                   3470:     }
1.1018    raeburn  3471:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3472:         $enddate = '.';
                   3473:     }
1.922     raeburn  3474:     my $rolelist;
                   3475:     if (ref($roles) eq 'ARRAY') {
                   3476:         $rolelist = join(':',@{$roles});
                   3477:     }
1.662     raeburn  3478:     my %personnel = ();
1.841     albertel 3479: 
                   3480:     my %servers = &get_servers($dom,'library');
                   3481:     foreach my $tryserver (keys(%servers)) {
                   3482: 	%{$personnel{$tryserver}}=();
                   3483: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3484: 					    &escape($startdate).':'.
                   3485: 					    &escape($enddate).':'.
                   3486: 					    &escape($rolelist), $tryserver))) {
                   3487: 	    my ($key,$value) = split(/\=/,$line,2);
                   3488: 	    if (($key) && ($value)) {
                   3489: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3490: 	    }
                   3491: 	}
1.662     raeburn  3492:     }
                   3493:     return %personnel;
                   3494: }
1.658     raeburn  3495: 
1.149     www      3496: # ----------------------------------------------------------- Check out an item
                   3497: 
1.504     albertel 3498: sub get_first_access {
                   3499:     my ($type,$argsymb)=@_;
1.790     albertel 3500:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3501:     if ($argsymb) { $symb=$argsymb; }
                   3502:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3503:     if ($type eq 'course') {
                   3504: 	$res='course';
                   3505:     } elsif ($type eq 'map') {
1.588     albertel 3506: 	$res=&symbread($map);
                   3507:     } else {
                   3508: 	$res=$symb;
                   3509:     }
                   3510:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3511:     return $times{"$courseid\0$res"};
1.504     albertel 3512: }
                   3513: 
                   3514: sub set_first_access {
                   3515:     my ($type)=@_;
1.790     albertel 3516:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3517:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3518:     if ($type eq 'course') {
                   3519: 	$res='course';
                   3520:     } elsif ($type eq 'map') {
1.588     albertel 3521: 	$res=&symbread($map);
                   3522:     } else {
                   3523: 	$res=$symb;
                   3524:     }
                   3525:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3526:     if (!$firstaccess) {
1.588     albertel 3527: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3528:     }
                   3529:     return 'already_set';
1.504     albertel 3530: }
                   3531: 
1.149     www      3532: sub checkout {
                   3533:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3534:     my $now=time;
                   3535:     my $lonhost=$perlvar{'lonHostID'};
                   3536:     my $infostr=&escape(
1.234     www      3537:                  'CHECKOUTTOKEN&'.
1.149     www      3538:                  $tuname.'&'.
                   3539:                  $tudom.'&'.
                   3540:                  $tcrsid.'&'.
                   3541:                  $symb.'&'.
                   3542: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3543:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3544:     if ($token=~/^error\:/) { 
1.672     albertel 3545:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3546:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3547:                  "</font>");
                   3548:         return ''; 
                   3549:     }
                   3550: 
1.149     www      3551:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3552:     $token=~tr/a-z/A-Z/;
                   3553: 
1.153     www      3554:     my %infohash=('resource.0.outtoken' => $token,
                   3555:                   'resource.0.checkouttime' => $now,
                   3556:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3557: 
                   3558:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3559:        return '';
1.151     www      3560:     } else {
1.672     albertel 3561:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3562:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3563:                  "</font>");
1.149     www      3564:     }    
                   3565: 
                   3566:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3567:                          &escape('Checkout '.$infostr.' - '.
                   3568:                                                  $token)) ne 'ok') {
                   3569: 	return '';
1.151     www      3570:     } else {
1.672     albertel 3571:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3572:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3573:                  "</font>");
1.149     www      3574:     }
1.151     www      3575:     return $token;
1.149     www      3576: }
                   3577: 
                   3578: # ------------------------------------------------------------ Check in an item
                   3579: 
                   3580: sub checkin {
                   3581:     my $token=shift;
1.150     www      3582:     my $now=time;
                   3583:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3584:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3585:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3586:     $dtoken=~s/\W/\_/g;
1.234     www      3587:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3588:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3589: 
1.154     www      3590:     unless (($tuname) && ($tudom)) {
                   3591:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3592:         return '';
                   3593:     }
                   3594:     
                   3595:     unless (&allowed('mgr',$tcrsid)) {
                   3596:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3597:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3598:         return '';
                   3599:     }
                   3600: 
1.153     www      3601:     my %infohash=('resource.0.intoken' => $token,
                   3602:                   'resource.0.checkintime' => $now,
                   3603:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3604: 
                   3605:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3606:        return '';
                   3607:     }    
                   3608: 
                   3609:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3610:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3611: 	return '';
                   3612:     }
                   3613: 
                   3614:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3615: }
                   3616: 
                   3617: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3618: 
                   3619: sub expirespread {
                   3620:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3621:     my $cid=$env{'request.course.id'}; 
1.110     www      3622:     if ($cid) {
                   3623:        my $now=time;
                   3624:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3625:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3626:                             $env{'course.'.$cid.'.num'}.
1.110     www      3627: 	        	    ':nohist_expirationdates:'.
                   3628:                             &escape($key).'='.$now,
1.620     albertel 3629:                             $env{'course.'.$cid.'.home'})
1.110     www      3630:     }
                   3631:     return 'ok';
1.14      www      3632: }
                   3633: 
1.109     www      3634: # ----------------------------------------------------- Devalidate Spreadsheets
                   3635: 
                   3636: sub devalidate {
1.325     www      3637:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3638:     my $cid=$env{'request.course.id'}; 
1.109     www      3639:     if ($cid) {
1.391     matthew  3640:         # delete the stored spreadsheets for
                   3641:         # - the student level sheet of this user in course's homespace
                   3642:         # - the assessment level sheet for this resource 
                   3643:         #   for this user in user's homespace
1.553     albertel 3644: 	# - current conditional state info
1.325     www      3645: 	my $key=$uname.':'.$udom.':';
1.109     www      3646:         my $status=
1.299     matthew  3647: 	    &del('nohist_calculatedsheets',
1.391     matthew  3648: 		 [$key.'studentcalc:'],
1.620     albertel 3649: 		 $env{'course.'.$cid.'.domain'},
                   3650: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3651: 		.' '.
                   3652: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3653: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3654:         unless ($status eq 'ok ok') {
                   3655:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3656:                     $uname.' at '.$udom.' for '.
1.109     www      3657: 		    $symb.': '.$status);
1.133     albertel 3658:         }
1.553     albertel 3659: 	&delenv('user.state.'.$cid);
1.109     www      3660:     }
                   3661: }
                   3662: 
1.265     albertel 3663: sub get_scalar {
                   3664:     my ($string,$end) = @_;
                   3665:     my $value;
                   3666:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3667: 	$value = $1;
                   3668:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3669: 	$value = $1;
                   3670:     }
                   3671:     return &unescape($value);
                   3672: }
                   3673: 
                   3674: sub array2str {
                   3675:   my (@array) = @_;
                   3676:   my $result=&arrayref2str(\@array);
                   3677:   $result=~s/^__ARRAY_REF__//;
                   3678:   $result=~s/__END_ARRAY_REF__$//;
                   3679:   return $result;
                   3680: }
                   3681: 
1.204     albertel 3682: sub arrayref2str {
                   3683:   my ($arrayref) = @_;
1.265     albertel 3684:   my $result='__ARRAY_REF__';
1.204     albertel 3685:   foreach my $elem (@$arrayref) {
1.265     albertel 3686:     if(ref($elem) eq 'ARRAY') {
                   3687:       $result.=&arrayref2str($elem).'&';
                   3688:     } elsif(ref($elem) eq 'HASH') {
                   3689:       $result.=&hashref2str($elem).'&';
                   3690:     } elsif(ref($elem)) {
                   3691:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3692:     } else {
                   3693:       $result.=&escape($elem).'&';
                   3694:     }
                   3695:   }
                   3696:   $result=~s/\&$//;
1.265     albertel 3697:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3698:   return $result;
                   3699: }
                   3700: 
1.168     albertel 3701: sub hash2str {
1.204     albertel 3702:   my (%hash) = @_;
                   3703:   my $result=&hashref2str(\%hash);
1.265     albertel 3704:   $result=~s/^__HASH_REF__//;
                   3705:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3706:   return $result;
                   3707: }
                   3708: 
                   3709: sub hashref2str {
                   3710:   my ($hashref)=@_;
1.265     albertel 3711:   my $result='__HASH_REF__';
1.800     albertel 3712:   foreach my $key (sort(keys(%$hashref))) {
                   3713:     if (ref($key) eq 'ARRAY') {
                   3714:       $result.=&arrayref2str($key).'=';
                   3715:     } elsif (ref($key) eq 'HASH') {
                   3716:       $result.=&hashref2str($key).'=';
                   3717:     } elsif (ref($key)) {
1.265     albertel 3718:       $result.='=';
1.800     albertel 3719:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3720:     } else {
1.1056.4.32  raeburn  3721:         if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3722:     }
                   3723: 
1.800     albertel 3724:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3725:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3726:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3727:       $result.=&hashref2str($hashref->{$key}).'&';
                   3728:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3729:        $result.='&';
1.800     albertel 3730:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3731:     } else {
1.800     albertel 3732:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3733:     }
                   3734:   }
1.168     albertel 3735:   $result=~s/\&$//;
1.265     albertel 3736:   $result .= '__END_HASH_REF__';
1.168     albertel 3737:   return $result;
                   3738: }
                   3739: 
                   3740: sub str2hash {
1.265     albertel 3741:     my ($string)=@_;
                   3742:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3743:     return %$hash;
                   3744: }
                   3745: 
                   3746: sub str2hashref {
1.168     albertel 3747:   my ($string) = @_;
1.265     albertel 3748: 
                   3749:   my %hash;
                   3750: 
                   3751:   if($string !~ /^__HASH_REF__/) {
                   3752:       if (! ($string eq '' || !defined($string))) {
                   3753: 	  $hash{'error'}='Not hash reference';
                   3754:       }
                   3755:       return (\%hash, $string);
                   3756:   }
                   3757: 
                   3758:   $string =~ s/^__HASH_REF__//;
                   3759: 
                   3760:   while($string !~ /^__END_HASH_REF__/) {
                   3761:       #key
                   3762:       my $key='';
                   3763:       if($string =~ /^__HASH_REF__/) {
                   3764:           ($key, $string)=&str2hashref($string);
                   3765:           if(defined($key->{'error'})) {
                   3766:               $hash{'error'}='Bad data';
                   3767:               return (\%hash, $string);
                   3768:           }
                   3769:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3770:           ($key, $string)=&str2arrayref($string);
                   3771:           if($key->[0] eq 'Array reference error') {
                   3772:               $hash{'error'}='Bad data';
                   3773:               return (\%hash, $string);
                   3774:           }
                   3775:       } else {
                   3776:           $string =~ s/^(.*?)=//;
1.267     albertel 3777: 	  $key=&unescape($1);
1.265     albertel 3778:       }
                   3779:       $string =~ s/^=//;
                   3780: 
                   3781:       #value
                   3782:       my $value='';
                   3783:       if($string =~ /^__HASH_REF__/) {
                   3784:           ($value, $string)=&str2hashref($string);
                   3785:           if(defined($value->{'error'})) {
                   3786:               $hash{'error'}='Bad data';
                   3787:               return (\%hash, $string);
                   3788:           }
                   3789:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3790:           ($value, $string)=&str2arrayref($string);
                   3791:           if($value->[0] eq 'Array reference error') {
                   3792:               $hash{'error'}='Bad data';
                   3793:               return (\%hash, $string);
                   3794:           }
                   3795:       } else {
                   3796: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3797:       }
                   3798:       $string =~ s/^&//;
                   3799: 
                   3800:       $hash{$key}=$value;
1.204     albertel 3801:   }
1.265     albertel 3802: 
                   3803:   $string =~ s/^__END_HASH_REF__//;
                   3804: 
                   3805:   return (\%hash, $string);
1.204     albertel 3806: }
                   3807: 
                   3808: sub str2array {
1.265     albertel 3809:     my ($string)=@_;
                   3810:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3811:     return @$array;
                   3812: }
                   3813: 
                   3814: sub str2arrayref {
1.204     albertel 3815:   my ($string) = @_;
1.265     albertel 3816:   my @array;
                   3817: 
                   3818:   if($string !~ /^__ARRAY_REF__/) {
                   3819:       if (! ($string eq '' || !defined($string))) {
                   3820: 	  $array[0]='Array reference error';
                   3821:       }
                   3822:       return (\@array, $string);
                   3823:   }
                   3824: 
                   3825:   $string =~ s/^__ARRAY_REF__//;
                   3826: 
                   3827:   while($string !~ /^__END_ARRAY_REF__/) {
                   3828:       my $value='';
                   3829:       if($string =~ /^__HASH_REF__/) {
                   3830:           ($value, $string)=&str2hashref($string);
                   3831:           if(defined($value->{'error'})) {
                   3832:               $array[0] ='Array reference error';
                   3833:               return (\@array, $string);
                   3834:           }
                   3835:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3836:           ($value, $string)=&str2arrayref($string);
                   3837:           if($value->[0] eq 'Array reference error') {
                   3838:               $array[0] ='Array reference error';
                   3839:               return (\@array, $string);
                   3840:           }
                   3841:       } else {
                   3842: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3843:       }
                   3844:       $string =~ s/^&//;
                   3845: 
                   3846:       push(@array, $value);
1.191     harris41 3847:   }
1.265     albertel 3848: 
                   3849:   $string =~ s/^__END_ARRAY_REF__//;
                   3850: 
                   3851:   return (\@array, $string);
1.168     albertel 3852: }
                   3853: 
1.167     albertel 3854: # -------------------------------------------------------------------Temp Store
                   3855: 
1.168     albertel 3856: sub tmpreset {
                   3857:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3858:   if (!$symb) {
                   3859:     $symb=&symbread();
1.620     albertel 3860:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3861:   }
                   3862:   $symb=escape($symb);
                   3863: 
1.620     albertel 3864:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3865:   $namespace=~s/\//\_/g;
                   3866:   $namespace=~s/\W//g;
                   3867: 
1.620     albertel 3868:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3869:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3870:   if ($domain eq 'public' && $stuname eq 'public') {
                   3871:       $stuname=$ENV{'REMOTE_ADDR'};
                   3872:   }
1.168     albertel 3873:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3874:   my %hash;
                   3875:   if (tie(%hash,'GDBM_File',
                   3876: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3877: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3878:     foreach my $key (keys(%hash)) {
1.180     albertel 3879:       if ($key=~ /:$symb/) {
1.168     albertel 3880: 	delete($hash{$key});
                   3881:       }
                   3882:     }
                   3883:   }
                   3884: }
                   3885: 
1.167     albertel 3886: sub tmpstore {
1.168     albertel 3887:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3888: 
                   3889:   if (!$symb) {
                   3890:     $symb=&symbread();
1.620     albertel 3891:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3892:   }
                   3893:   $symb=escape($symb);
                   3894: 
                   3895:   if (!$namespace) {
                   3896:     # I don't think we would ever want to store this for a course.
                   3897:     # it seems this will only be used if we don't have a course.
1.620     albertel 3898:     #$namespace=$env{'request.course.id'};
1.168     albertel 3899:     #if (!$namespace) {
1.620     albertel 3900:       $namespace=$env{'request.state'};
1.168     albertel 3901:     #}
                   3902:   }
                   3903:   $namespace=~s/\//\_/g;
                   3904:   $namespace=~s/\W//g;
1.620     albertel 3905:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3906:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3907:   if ($domain eq 'public' && $stuname eq 'public') {
                   3908:       $stuname=$ENV{'REMOTE_ADDR'};
                   3909:   }
1.168     albertel 3910:   my $now=time;
                   3911:   my %hash;
                   3912:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3913:   if (tie(%hash,'GDBM_File',
                   3914: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3915: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3916:     $hash{"version:$symb"}++;
                   3917:     my $version=$hash{"version:$symb"};
                   3918:     my $allkeys=''; 
                   3919:     foreach my $key (keys(%$storehash)) {
                   3920:       $allkeys.=$key.':';
1.591     albertel 3921:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3922:     }
                   3923:     $hash{"$version:$symb:timestamp"}=$now;
                   3924:     $allkeys.='timestamp';
                   3925:     $hash{"$version:keys:$symb"}=$allkeys;
                   3926:     if (untie(%hash)) {
                   3927:       return 'ok';
                   3928:     } else {
                   3929:       return "error:$!";
                   3930:     }
                   3931:   } else {
                   3932:     return "error:$!";
                   3933:   }
                   3934: }
1.167     albertel 3935: 
1.168     albertel 3936: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3937: 
1.168     albertel 3938: sub tmprestore {
                   3939:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3940: 
1.168     albertel 3941:   if (!$symb) {
                   3942:     $symb=&symbread();
1.620     albertel 3943:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3944:   }
                   3945:   $symb=escape($symb);
                   3946: 
1.620     albertel 3947:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3948: 
1.620     albertel 3949:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3950:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3951:   if ($domain eq 'public' && $stuname eq 'public') {
                   3952:       $stuname=$ENV{'REMOTE_ADDR'};
                   3953:   }
1.168     albertel 3954:   my %returnhash;
                   3955:   $namespace=~s/\//\_/g;
                   3956:   $namespace=~s/\W//g;
                   3957:   my %hash;
                   3958:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3959:   if (tie(%hash,'GDBM_File',
                   3960: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3961: 	  &GDBM_READER(),0640)) {
1.168     albertel 3962:     my $version=$hash{"version:$symb"};
                   3963:     $returnhash{'version'}=$version;
                   3964:     my $scope;
                   3965:     for ($scope=1;$scope<=$version;$scope++) {
                   3966:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3967:       my @keys=split(/:/,$vkeys);
                   3968:       my $key;
                   3969:       $returnhash{"$scope:keys"}=$vkeys;
                   3970:       foreach $key (@keys) {
1.591     albertel 3971: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3972: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3973:       }
                   3974:     }
1.168     albertel 3975:     if (!(untie(%hash))) {
                   3976:       return "error:$!";
                   3977:     }
                   3978:   } else {
                   3979:     return "error:$!";
                   3980:   }
                   3981:   return %returnhash;
1.167     albertel 3982: }
                   3983: 
1.9       www      3984: # ----------------------------------------------------------------------- Store
                   3985: 
                   3986: sub store {
1.124     www      3987:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3988:     my $home='';
                   3989: 
1.168     albertel 3990:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3991: 
1.213     www      3992:     $symb=&symbclean($symb);
1.122     albertel 3993:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3994: 
1.620     albertel 3995:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3996:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3997: 
                   3998:     &devalidate($symb,$stuname,$domain);
1.109     www      3999: 
                   4000:     $symb=escape($symb);
1.187     www      4001:     if (!$namespace) { 
1.620     albertel 4002:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4003:           return ''; 
                   4004:        } 
                   4005:     }
1.620     albertel 4006:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4007: 
                   4008:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4009:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4010: 
1.12      www      4011:     my $namevalue='';
1.800     albertel 4012:     foreach my $key (keys(%$storehash)) {
                   4013:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4014:     }
1.12      www      4015:     $namevalue=~s/\&$//;
1.187     www      4016:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4017:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4018: }
                   4019: 
1.47      www      4020: # -------------------------------------------------------------- Critical Store
                   4021: 
                   4022: sub cstore {
1.124     www      4023:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4024:     my $home='';
                   4025: 
1.168     albertel 4026:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4027: 
1.213     www      4028:     $symb=&symbclean($symb);
1.122     albertel 4029:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4030: 
1.620     albertel 4031:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4032:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4033: 
                   4034:     &devalidate($symb,$stuname,$domain);
1.109     www      4035: 
                   4036:     $symb=escape($symb);
1.187     www      4037:     if (!$namespace) { 
1.620     albertel 4038:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4039:           return ''; 
                   4040:        } 
                   4041:     }
1.620     albertel 4042:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4043: 
                   4044:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4045:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4046: 
1.47      www      4047:     my $namevalue='';
1.800     albertel 4048:     foreach my $key (keys(%$storehash)) {
                   4049:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4050:     }
1.47      www      4051:     $namevalue=~s/\&$//;
1.187     www      4052:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4053:     return critical
                   4054:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4055: }
                   4056: 
1.9       www      4057: # --------------------------------------------------------------------- Restore
                   4058: 
                   4059: sub restore {
1.124     www      4060:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4061:     my $home='';
                   4062: 
1.168     albertel 4063:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4064: 
1.122     albertel 4065:     if (!$symb) {
1.1056.4.37! raeburn  4066:         return if ($namespace eq 'courserequests');
        !          4067:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4068:     } else {
1.1056.4.37! raeburn  4069:         unless ($namespace eq 'courserequests') {
        !          4070:             $symb=&escape(&symbclean($symb));
        !          4071:         }
1.122     albertel 4072:     }
1.188     www      4073:     if (!$namespace) { 
1.620     albertel 4074:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4075:           return ''; 
                   4076:        } 
                   4077:     }
1.620     albertel 4078:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4079:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4080:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4081:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4082: 
1.12      www      4083:     my %returnhash=();
1.800     albertel 4084:     foreach my $line (split(/\&/,$answer)) {
                   4085: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4086:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4087:     }
1.75      www      4088:     my $version;
                   4089:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4090:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4091:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4092:        }
1.75      www      4093:     }
1.13      www      4094:     return %returnhash;
1.34      www      4095: }
                   4096: 
                   4097: # ---------------------------------------------------------- Course Description
                   4098: 
                   4099: sub coursedescription {
1.731     albertel 4100:     my ($courseid,$args)=@_;
1.34      www      4101:     $courseid=~s/^\///;
1.49      www      4102:     $courseid=~s/\_/\//g;
1.34      www      4103:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4104:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4105:     my $normalid=$cdomain.'_'.$cnum;
                   4106:     # need to always cache even if we get errors otherwise we keep 
                   4107:     # trying and trying and trying to get the course description.
                   4108:     my %envhash=();
                   4109:     my %returnhash=();
1.731     albertel 4110:     
                   4111:     my $expiretime=600;
                   4112:     if ($env{'request.course.id'} eq $normalid) {
                   4113: 	$expiretime=120;
                   4114:     }
                   4115: 
                   4116:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4117:     if (!$args->{'freshen_cache'}
                   4118: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4119: 	foreach my $key (keys(%env)) {
                   4120: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4121: 	    my ($setting) = $1;
                   4122: 	    $returnhash{$setting} = $env{$key};
                   4123: 	}
                   4124: 	return %returnhash;
                   4125:     }
                   4126: 
                   4127:     # get the data agin
                   4128:     if (!$args->{'one_time'}) {
                   4129: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4130:     }
1.811     albertel 4131: 
1.34      www      4132:     if ($chome ne 'no_host') {
1.302     albertel 4133:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4134:        if (!exists($returnhash{'con_lost'})) {
                   4135:            $returnhash{'home'}= $chome;
                   4136: 	   $returnhash{'domain'} = $cdomain;
                   4137: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4138:            if (!defined($returnhash{'type'})) {
                   4139:                $returnhash{'type'} = 'Course';
                   4140:            }
1.130     albertel 4141:            while (my ($name,$value) = each %returnhash) {
1.53      www      4142:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4143:            }
1.270     www      4144:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4145:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4146: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4147:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4148:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4149:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4150:        }
                   4151:     }
1.731     albertel 4152:     if (!$args->{'one_time'}) {
1.949     raeburn  4153: 	&appenv(\%envhash);
1.731     albertel 4154:     }
1.302     albertel 4155:     return %returnhash;
1.461     www      4156: }
                   4157: 
1.1056.4.5  raeburn  4158: sub update_released_required {
                   4159:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4160:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4161:         $cid = $env{'request.course.id'};
                   4162:         $cdom = $env{'course.'.$cid.'.domain'};
                   4163:         $cnum = $env{'course.'.$cid.'.num'};
                   4164:         $chome = $env{'course.'.$cid.'.home'};
                   4165:     }
                   4166:     if ($needsrelease) {
                   4167:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4168:         my $needsupdate;
                   4169:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4170:             $needsupdate = 1;
                   4171:         } else {
                   4172:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4173:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4174:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4175:                 $needsupdate = 1;
                   4176:             }
                   4177:         }
                   4178:         if ($needsupdate) {
                   4179:             my %needshash = (
                   4180:                              'internal.releaserequired' => $needsrelease,
                   4181:                             );
                   4182:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4183:             if ($putresult eq 'ok') {
                   4184:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4185:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4186:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4187:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4188:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4189:                 }
                   4190:             }
                   4191:         }
                   4192:     }
                   4193:     return;
                   4194: }
                   4195: 
1.461     www      4196: # -------------------------------------------------See if a user is privileged
                   4197: 
                   4198: sub privileged {
                   4199:     my ($username,$domain)=@_;
                   4200:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4201: 			&homeserver($username,$domain));
1.1033    raeburn  4202:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4203:         ($rolesdump =~ /^error:/)) {
                   4204:         return 0;
                   4205:     }
1.461     www      4206:     my $now=time;
                   4207:     if ($rolesdump ne '') {
1.800     albertel 4208:         foreach my $entry (split(/&/,$rolesdump)) {
                   4209: 	    if ($entry!~/^rolesdef_/) {
                   4210: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4211: 		$area=~s/\_\w\w$//;
                   4212: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4213: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4214: 		    my $active=1;
                   4215: 		    if ($tend) {
                   4216: 			if ($tend<$now) { $active=0; }
                   4217: 		    }
                   4218: 		    if ($tstart) {
                   4219: 			if ($tstart>$now) { $active=0; }
                   4220: 		    }
                   4221: 		    if ($active) { return 1; }
                   4222: 		}
                   4223: 	    }
                   4224: 	}
                   4225:     }
                   4226:     return 0;
1.9       www      4227: }
1.1       albertel 4228: 
1.103     harris41 4229: # -------------------------------------------------------- Get user privileges
1.11      www      4230: 
                   4231: sub rolesinit {
                   4232:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4233:     my $now=time;
                   4234:     my %userroles = ('user.login.time' => $now);
1.1056.4.10  raeburn  4235:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3  raeburn  4236:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4237:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4238:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4239:         return \%userroles;
                   4240:     }
1.11      www      4241:     my %allroles=();
1.678     raeburn  4242:     my %allgroups=();   
                   4243:     my $group_privs;
1.11      www      4244: 
                   4245:     if ($rolesdump ne '') {
1.800     albertel 4246:         foreach my $entry (split(/&/,$rolesdump)) {
                   4247: 	  if ($entry!~/^rolesdef_/) {
                   4248:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4249: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4250:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4251: 	    if ($role=~/^cr/) { 
1.807     albertel 4252: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4253: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4254: 		    ($tend,$tstart)=split('_',$trest);
                   4255: 		} else {
                   4256: 		    $trole=$role;
                   4257: 		}
1.678     raeburn  4258:             } elsif ($role =~ m|^gr/|) {
                   4259:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4260:                 ($trole,$group_privs) = split(/\//,$trole);
                   4261:                 $group_privs = &unescape($group_privs);
1.587     albertel 4262: 	    } else {
                   4263: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4264: 	    }
1.743     albertel 4265: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4266: 					 $username);
                   4267: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4268:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4269:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4270:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4271: 		my $spec=$trole.'.'.$area;
                   4272: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4273: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4274:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4275:                 } elsif ($trole eq 'gr') {
                   4276:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4277: 		} else {
1.567     raeburn  4278:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4279: 		}
1.12      www      4280:             }
1.662     raeburn  4281:           }
1.191     harris41 4282:         }
1.743     albertel 4283:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4284:         $userroles{'user.adv'}    = $adv;
                   4285: 	$userroles{'user.author'} = $author;
1.620     albertel 4286:         $env{'user.adv'}=$adv;
1.11      www      4287:     }
1.743     albertel 4288:     return \%userroles;  
1.11      www      4289: }
                   4290: 
1.567     raeburn  4291: sub set_arearole {
                   4292:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4293: # log the associated role with the area
                   4294:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4295:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4296: }
                   4297: 
                   4298: sub custom_roleprivs {
                   4299:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4300:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4301:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4302:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4303:         my ($rdummy,$roledef)=
                   4304:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4305:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4306:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4307:             if (defined($syspriv)) {
1.1043    raeburn  4308:                 if ($trest =~ /^$match_community$/) {
                   4309:                     $syspriv =~ s/bre\&S//; 
                   4310:                 }
1.567     raeburn  4311:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4312:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4313:             }
                   4314:             if ($tdomain ne '') {
                   4315:                 if (defined($dompriv)) {
                   4316:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4317:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4318:                 }
                   4319:                 if (($trest ne '') && (defined($coursepriv))) {
                   4320:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4321:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4322:                 }
                   4323:             }
                   4324:         }
                   4325:     }
                   4326: }
                   4327: 
1.678     raeburn  4328: sub group_roleprivs {
                   4329:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4330:     my $access = 1;
                   4331:     my $now = time;
                   4332:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4333:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4334:     if ($access) {
1.811     albertel 4335:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4336:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4337:     }
                   4338: }
1.567     raeburn  4339: 
                   4340: sub standard_roleprivs {
                   4341:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4342:     if (defined($pr{$trole.':s'})) {
                   4343:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4344:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4345:     }
                   4346:     if ($tdomain ne '') {
                   4347:         if (defined($pr{$trole.':d'})) {
                   4348:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4349:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4350:         }
                   4351:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4352:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4353:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4354:         }
                   4355:     }
                   4356: }
                   4357: 
                   4358: sub set_userprivs {
1.1056.4.2  raeburn  4359:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4360:     my $author=0;
                   4361:     my $adv=0;
1.678     raeburn  4362:     my %grouproles = ();
                   4363:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4364:         my @groupkeys;
1.1000    raeburn  4365:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4366:             push(@groupkeys,$role);
                   4367:         }
                   4368:         if (ref($groups_roles) eq 'HASH') {
                   4369:             foreach my $key (keys(%{$groups_roles})) {
                   4370:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4371:                     push(@groupkeys,$key);
                   4372:                 }
                   4373:             }
                   4374:         }
                   4375:         if (@groupkeys > 0) {
                   4376:             foreach my $role (@groupkeys) {
                   4377:                 my ($trole,$area,$sec,$extendedarea);
                   4378:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4379:                     $trole = $1;
                   4380:                     $area = $2;
                   4381:                     $sec = $3;
                   4382:                     $extendedarea = $area.$sec;
                   4383:                     if (exists($$allgroups{$area})) {
                   4384:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4385:                             my $spec = $trole.'.'.$extendedarea;
                   4386:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4387:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4388:                         }
1.678     raeburn  4389:                     }
                   4390:                 }
                   4391:             }
                   4392:         }
                   4393:     }
1.800     albertel 4394:     foreach my $group (keys(%grouproles)) {
                   4395:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4396:     }
1.800     albertel 4397:     foreach my $role (keys(%{$allroles})) {
                   4398:         my %thesepriv;
1.941     raeburn  4399:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4400:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4401:             if ($item ne '') {
                   4402:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4403:                 if ($restrictions eq '') {
                   4404:                     $thesepriv{$privilege}='F';
                   4405:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4406:                     $thesepriv{$privilege}.=$restrictions;
                   4407:                 }
                   4408:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4409:             }
                   4410:         }
                   4411:         my $thesestr='';
1.800     albertel 4412:         foreach my $priv (keys(%thesepriv)) {
                   4413: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4414: 	}
                   4415:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4416:     }
                   4417:     return ($author,$adv);
                   4418: }
                   4419: 
1.994     raeburn  4420: sub role_status {
1.1002    raeburn  4421:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4422:     my @pwhere = ();
                   4423:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4424:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4425:         unless (!defined($$role) || $$role eq '') {
                   4426:             $$where=join('.',@pwhere);
                   4427:             $$trolecode=$$role.'.'.$$where;
                   4428:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4429:             $$tstatus='is';
                   4430:             if ($$tstart && $$tstart>$then) {
                   4431:                 $$tstatus='future';
1.1034    raeburn  4432:                 if ($$tstart<$now) {
                   4433:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4434:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4435:                             my (%allroles,%allgroups,$group_privs,
                   4436:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4437:                             my %userroles = (
                   4438:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4439:                             );
1.1056.4.2  raeburn  4440:                             @rolecodes = ('cm');
1.1002    raeburn  4441:                             my $spec=$$role.'.'.$$where;
                   4442:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4443:                             if ($$role =~ /^cr\//) {
                   4444:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4445:                                 push(@rolecodes,'cr');
1.1002    raeburn  4446:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4447:                                 push(@rolecodes,$$role);
1.1002    raeburn  4448:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4449:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4450:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4451:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4452:                                 $group_privs = &unescape($group_privs);
                   4453:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4454:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4455:                                 if (keys(%course_roles) > 0) {
                   4456:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4457:                                     if ($tdomain ne '' && $tnum ne '') {
                   4458:                                         foreach my $key (keys(%course_roles)) {
                   4459:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4460:                                                 my $crsrole = $1;
                   4461:                                                 my $crssec = $2;
                   4462:                                                 if ($crsrole =~ /^cr/) {
                   4463:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4464:                                                         push(@rolecodes,'cr');
                   4465:                                                     }
                   4466:                                                 } else {
                   4467:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4468:                                                         push(@rolecodes,$crsrole);
                   4469:                                                     }
                   4470:                                                 }
                   4471:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4472:                                                 if ($crssec ne '') {
                   4473:                                                     $rolekey .= '/'.$crssec;
                   4474:                                                 }
                   4475:                                                 $rolekey .= './';
                   4476:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4477:                                             }
                   4478:                                         }
                   4479:                                     }
                   4480:                                 }
1.1002    raeburn  4481:                             } else {
1.1056.4.2  raeburn  4482:                                 push(@rolecodes,$$role);
1.1002    raeburn  4483:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4484:                             }
1.1056.4.2  raeburn  4485:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4486:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4487:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4488:                         }
                   4489:                     }
1.1034    raeburn  4490:                     $$tstatus = 'is';
1.1002    raeburn  4491:                 }
1.994     raeburn  4492:             }
                   4493:             if ($$tend) {
                   4494:                 if ($$tend<$then) {
                   4495:                     $$tstatus='expired';
                   4496:                 } elsif ($$tend<$now) {
                   4497:                     $$tstatus='will_not';
                   4498:                 }
                   4499:             }
                   4500:         }
                   4501:     }
                   4502: }
                   4503: 
                   4504: sub check_adhoc_privs {
1.1056.4.12  raeburn  4505:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4506:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4507:     if ($env{$cckey}) {
                   4508:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4509:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4510:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12  raeburn  4511:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4512:         }
                   4513:     } else {
1.1056.4.12  raeburn  4514:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4515:     }
                   4516: }
                   4517: 
                   4518: sub set_adhoc_privileges {
                   4519: # role can be cc or ca
1.1056.4.12  raeburn  4520:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4521:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4522:     my $spec = $role.'.'.$area;
                   4523:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4524:                                   $env{'user.name'});
                   4525:     my %ccrole = ();
                   4526:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4527:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4528:     &appenv(\%userroles,[$role,'cm']);
                   4529:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12  raeburn  4530:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4531:         &appenv( {'request.role'        => $spec,
                   4532:                   'request.role.domain' => $dcdom,
                   4533:                   'request.course.sec'  => ''
                   4534:                  }
                   4535:                );
                   4536:         my $tadv=0;
                   4537:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4538:         &appenv({'request.role.adv'    => $tadv});
                   4539:     }
1.994     raeburn  4540: }
                   4541: 
1.12      www      4542: # --------------------------------------------------------------- get interface
                   4543: 
                   4544: sub get {
1.131     albertel 4545:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4546:    my $items='';
1.800     albertel 4547:    foreach my $item (@$storearr) {
                   4548:        $items.=&escape($item).'&';
1.191     harris41 4549:    }
1.12      www      4550:    $items=~s/\&$//;
1.620     albertel 4551:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4552:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4553:    my $uhome=&homeserver($uname,$udomain);
                   4554: 
1.133     albertel 4555:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4556:    my @pairs=split(/\&/,$rep);
1.273     albertel 4557:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4558:      return @pairs;
                   4559:    }
1.15      www      4560:    my %returnhash=();
1.42      www      4561:    my $i=0;
1.800     albertel 4562:    foreach my $item (@$storearr) {
                   4563:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4564:       $i++;
1.191     harris41 4565:    }
1.15      www      4566:    return %returnhash;
1.27      www      4567: }
                   4568: 
                   4569: # --------------------------------------------------------------- del interface
                   4570: 
                   4571: sub del {
1.133     albertel 4572:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4573:    my $items='';
1.800     albertel 4574:    foreach my $item (@$storearr) {
                   4575:        $items.=&escape($item).'&';
1.191     harris41 4576:    }
1.984     neumanie 4577: 
1.27      www      4578:    $items=~s/\&$//;
1.620     albertel 4579:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4580:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4581:    my $uhome=&homeserver($uname,$udomain);
                   4582:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4583: }
                   4584: 
                   4585: # -------------------------------------------------------------- dump interface
                   4586: 
                   4587: sub dump {
1.1056.4.10  raeburn  4588:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4589:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4590:     if (!$uname) { $uname=$env{'user.name'}; }
                   4591:     my $uhome=&homeserver($uname,$udomain);
                   4592:     if ($regexp) {
                   4593: 	$regexp=&escape($regexp);
                   4594:     } else {
                   4595: 	$regexp='.';
                   4596:     }
1.1056.4.10  raeburn  4597:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4598:     my @pairs=split(/\&/,$rep);
                   4599:     my %returnhash=();
                   4600:     foreach my $item (@pairs) {
                   4601: 	my ($key,$value)=split(/=/,$item,2);
                   4602: 	$key = &unescape($key);
                   4603: 	next if ($key =~ /^error: 2 /);
                   4604: 	$returnhash{$key}=&thaw_unescape($value);
                   4605:     }
                   4606:     return %returnhash;
1.407     www      4607: }
                   4608: 
1.717     albertel 4609: # --------------------------------------------------------- dumpstore interface
                   4610: 
                   4611: sub dumpstore {
                   4612:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4613:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4614:    if (!$uname) { $uname=$env{'user.name'}; }
                   4615:    my $uhome=&homeserver($uname,$udomain);
                   4616:    if ($regexp) {
                   4617:        $regexp=&escape($regexp);
                   4618:    } else {
                   4619:        $regexp='.';
                   4620:    }
                   4621:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4622:    my @pairs=split(/\&/,$rep);
                   4623:    my %returnhash=();
                   4624:    foreach my $item (@pairs) {
                   4625:        my ($key,$value)=split(/=/,$item,2);
                   4626:        next if ($key =~ /^error: 2 /);
                   4627:        $returnhash{$key}=&thaw_unescape($value);
                   4628:    }
                   4629:    return %returnhash;
1.717     albertel 4630: }
                   4631: 
1.407     www      4632: # -------------------------------------------------------------- keys interface
                   4633: 
                   4634: sub getkeys {
                   4635:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4636:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4637:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4638:    my $uhome=&homeserver($uname,$udomain);
                   4639:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4640:    my @keyarray=();
1.800     albertel 4641:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4642:       next if ($key =~ /^error: 2 /);
1.800     albertel 4643:       push(@keyarray,&unescape($key));
1.407     www      4644:    }
                   4645:    return @keyarray;
1.318     matthew  4646: }
                   4647: 
1.319     matthew  4648: # --------------------------------------------------------------- currentdump
                   4649: sub currentdump {
1.328     matthew  4650:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4651:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4652:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4653:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4654:    my $uhome = &homeserver($sname,$sdom);
                   4655:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4656:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4657:    #
1.318     matthew  4658:    my %returnhash=();
1.319     matthew  4659:    #
                   4660:    if ($rep eq "unknown_cmd") { 
                   4661:        # an old lond will not know currentdump
                   4662:        # Do a dump and make it look like a currentdump
1.822     albertel 4663:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4664:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4665:        my %hash = @tmp;
                   4666:        @tmp=();
1.424     matthew  4667:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4668:    } else {
                   4669:        my @pairs=split(/\&/,$rep);
1.800     albertel 4670:        foreach my $pair (@pairs) {
                   4671:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4672:            my ($symb,$param) = split(/:/,$key);
                   4673:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4674:                                                         &thaw_unescape($value);
1.319     matthew  4675:        }
1.191     harris41 4676:    }
1.12      www      4677:    return %returnhash;
1.424     matthew  4678: }
                   4679: 
                   4680: sub convert_dump_to_currentdump{
                   4681:     my %hash = %{shift()};
                   4682:     my %returnhash;
                   4683:     # Code ripped from lond, essentially.  The only difference
                   4684:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4685:     # we might run in to problems with parameter names =~ /^v\./
                   4686:     while (my ($key,$value) = each(%hash)) {
                   4687:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4688: 	$symb  = &unescape($symb);
                   4689: 	$param = &unescape($param);
1.424     matthew  4690:         next if ($v eq 'version' || $symb eq 'keys');
                   4691:         next if (exists($returnhash{$symb}) &&
                   4692:                  exists($returnhash{$symb}->{$param}) &&
                   4693:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4694:         $returnhash{$symb}->{$param}=$value;
                   4695:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4696:     }
                   4697:     #
                   4698:     # Remove all of the keys in the hashes which keep track of
                   4699:     # the version of the parameter.
                   4700:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4701:         # use a foreach because we are going to delete from the hash.
                   4702:         foreach my $key (keys(%$param_hash)) {
                   4703:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4704:         }
                   4705:     }
                   4706:     return \%returnhash;
1.12      www      4707: }
                   4708: 
1.627     albertel 4709: # ------------------------------------------------------ critical inc interface
                   4710: 
                   4711: sub cinc {
                   4712:     return &inc(@_,'critical');
                   4713: }
                   4714: 
1.449     matthew  4715: # --------------------------------------------------------------- inc interface
                   4716: 
                   4717: sub inc {
1.627     albertel 4718:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4719:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4720:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4721:     my $uhome=&homeserver($uname,$udomain);
                   4722:     my $items='';
                   4723:     if (! ref($store)) {
                   4724:         # got a single value, so use that instead
                   4725:         $items = &escape($store).'=&';
                   4726:     } elsif (ref($store) eq 'SCALAR') {
                   4727:         $items = &escape($$store).'=&';        
                   4728:     } elsif (ref($store) eq 'ARRAY') {
                   4729:         $items = join('=&',map {&escape($_);} @{$store});
                   4730:     } elsif (ref($store) eq 'HASH') {
                   4731:         while (my($key,$value) = each(%{$store})) {
                   4732:             $items.= &escape($key).'='.&escape($value).'&';
                   4733:         }
                   4734:     }
                   4735:     $items=~s/\&$//;
1.627     albertel 4736:     if ($critical) {
                   4737: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4738:     } else {
                   4739: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4740:     }
1.449     matthew  4741: }
                   4742: 
1.12      www      4743: # --------------------------------------------------------------- put interface
                   4744: 
                   4745: sub put {
1.134     albertel 4746:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4747:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4748:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4749:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4750:    my $items='';
1.800     albertel 4751:    foreach my $item (keys(%$storehash)) {
                   4752:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4753:    }
1.12      www      4754:    $items=~s/\&$//;
1.134     albertel 4755:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4756: }
                   4757: 
1.631     albertel 4758: # ------------------------------------------------------------ newput interface
                   4759: 
                   4760: sub newput {
                   4761:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4762:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4763:    if (!$uname) { $uname=$env{'user.name'}; }
                   4764:    my $uhome=&homeserver($uname,$udomain);
                   4765:    my $items='';
                   4766:    foreach my $key (keys(%$storehash)) {
                   4767:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4768:    }
                   4769:    $items=~s/\&$//;
                   4770:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4771: }
                   4772: 
                   4773: # ---------------------------------------------------------  putstore interface
                   4774: 
1.524     raeburn  4775: sub putstore {
1.715     albertel 4776:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4777:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4778:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4779:    my $uhome=&homeserver($uname,$udomain);
                   4780:    my $items='';
1.715     albertel 4781:    foreach my $key (keys(%$storehash)) {
                   4782:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4783:    }
1.715     albertel 4784:    $items=~s/\&$//;
1.716     albertel 4785:    my $esc_symb=&escape($symb);
                   4786:    my $esc_v=&escape($version);
1.715     albertel 4787:    my $reply =
1.716     albertel 4788:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4789: 	      $uhome);
                   4790:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4791:        # gfall back to way things use to be done
1.715     albertel 4792:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4793: 			    $uname);
1.524     raeburn  4794:    }
1.715     albertel 4795:    return $reply;
                   4796: }
                   4797: 
                   4798: sub old_putstore {
1.716     albertel 4799:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4800:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4801:     if (!$uname) { $uname=$env{'user.name'}; }
                   4802:     my $uhome=&homeserver($uname,$udomain);
                   4803:     my %newstorehash;
1.800     albertel 4804:     foreach my $item (keys(%$storehash)) {
                   4805: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4806: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4807:     }
                   4808:     my $items='';
                   4809:     my %allitems = ();
1.800     albertel 4810:     foreach my $item (keys(%newstorehash)) {
                   4811: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4812: 	    my $key = $1.':keys:'.$2;
                   4813: 	    $allitems{$key} .= $3.':';
                   4814: 	}
1.800     albertel 4815: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4816:     }
1.800     albertel 4817:     foreach my $item (keys(%allitems)) {
                   4818: 	$allitems{$item} =~ s/\:$//;
                   4819: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4820:     }
                   4821:     $items=~s/\&$//;
                   4822:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4823: }
                   4824: 
1.47      www      4825: # ------------------------------------------------------ critical put interface
                   4826: 
                   4827: sub cput {
1.134     albertel 4828:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4829:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4830:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4831:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4832:    my $items='';
1.800     albertel 4833:    foreach my $item (keys(%$storehash)) {
                   4834:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4835:    }
1.47      www      4836:    $items=~s/\&$//;
1.134     albertel 4837:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4838: }
                   4839: 
                   4840: # -------------------------------------------------------------- eget interface
                   4841: 
                   4842: sub eget {
1.133     albertel 4843:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4844:    my $items='';
1.800     albertel 4845:    foreach my $item (@$storearr) {
                   4846:        $items.=&escape($item).'&';
1.191     harris41 4847:    }
1.12      www      4848:    $items=~s/\&$//;
1.620     albertel 4849:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4850:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4851:    my $uhome=&homeserver($uname,$udomain);
                   4852:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4853:    my @pairs=split(/\&/,$rep);
                   4854:    my %returnhash=();
1.42      www      4855:    my $i=0;
1.800     albertel 4856:    foreach my $item (@$storearr) {
                   4857:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4858:       $i++;
1.191     harris41 4859:    }
1.12      www      4860:    return %returnhash;
                   4861: }
                   4862: 
1.667     albertel 4863: # ------------------------------------------------------------ tmpput interface
                   4864: sub tmpput {
1.802     raeburn  4865:     my ($storehash,$server,$context)=@_;
1.667     albertel 4866:     my $items='';
1.800     albertel 4867:     foreach my $item (keys(%$storehash)) {
                   4868: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4869:     }
                   4870:     $items=~s/\&$//;
1.802     raeburn  4871:     if (defined($context)) {
                   4872:         $items .= ':'.&escape($context);
                   4873:     }
1.667     albertel 4874:     return &reply("tmpput:$items",$server);
                   4875: }
                   4876: 
                   4877: # ------------------------------------------------------------ tmpget interface
                   4878: sub tmpget {
1.688     albertel 4879:     my ($token,$server)=@_;
                   4880:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4881:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4882:     my %returnhash;
                   4883:     foreach my $item (split(/\&/,$rep)) {
                   4884: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4885:         next if ($key =~ /^error: 2 /);
1.667     albertel 4886: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4887:     }
                   4888:     return %returnhash;
                   4889: }
                   4890: 
1.688     albertel 4891: # ------------------------------------------------------------ tmpget interface
                   4892: sub tmpdel {
                   4893:     my ($token,$server)=@_;
                   4894:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4895:     return &reply("tmpdel:$token",$server);
                   4896: }
                   4897: 
1.765     albertel 4898: # -------------------------------------------------- portfolio access checking
                   4899: 
                   4900: sub portfolio_access {
1.766     albertel 4901:     my ($requrl) = @_;
1.765     albertel 4902:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4903:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4904:     if ($result) {
                   4905:         my %setters;
                   4906:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4907:             my ($startblock,$endblock) =
                   4908:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4909:             if ($startblock && $endblock) {
                   4910:                 return 'B';
                   4911:             }
                   4912:         } else {
                   4913:             my ($startblock,$endblock) =
                   4914:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4915:             if ($startblock && $endblock) {
                   4916:                 return 'B';
                   4917:             }
                   4918:         }
                   4919:     }
1.765     albertel 4920:     if ($result eq 'ok') {
1.766     albertel 4921:        return 'F';
1.765     albertel 4922:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4923:        return 'A';
1.765     albertel 4924:     }
1.766     albertel 4925:     return '';
1.765     albertel 4926: }
                   4927: 
                   4928: sub get_portfolio_access {
1.767     albertel 4929:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4930: 
                   4931:     if (!ref($access_hash)) {
                   4932: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4933: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4934: 						   $file_name);
                   4935: 	$access_hash = $access_controls{$file_name};
                   4936:     }
                   4937: 
1.765     albertel 4938:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4939:     my $now = time;
                   4940:     if (ref($access_hash) eq 'HASH') {
                   4941:         foreach my $key (keys(%{$access_hash})) {
                   4942:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4943:             if ($start > $now) {
                   4944:                 next;
                   4945:             }
                   4946:             if ($end && $end<$now) {
                   4947:                 next;
                   4948:             }
                   4949:             if ($scope eq 'public') {
                   4950:                 $public = $key;
                   4951:                 last;
                   4952:             } elsif ($scope eq 'guest') {
                   4953:                 $guest = $key;
                   4954:             } elsif ($scope eq 'domains') {
                   4955:                 push(@domains,$key);
                   4956:             } elsif ($scope eq 'users') {
                   4957:                 push(@users,$key);
                   4958:             } elsif ($scope eq 'course') {
                   4959:                 push(@courses,$key);
                   4960:             } elsif ($scope eq 'group') {
                   4961:                 push(@groups,$key);
                   4962:             }
                   4963:         }
                   4964:         if ($public) {
                   4965:             return 'ok';
                   4966:         }
                   4967:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4968:             if ($guest) {
                   4969:                 return $guest;
                   4970:             }
                   4971:         } else {
                   4972:             if (@domains > 0) {
                   4973:                 foreach my $domkey (@domains) {
                   4974:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4975:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4976:                             return 'ok';
                   4977:                         }
                   4978:                     }
                   4979:                 }
                   4980:             }
                   4981:             if (@users > 0) {
                   4982:                 foreach my $userkey (@users) {
1.865     raeburn  4983:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4984:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4985:                             if (ref($item) eq 'HASH') {
                   4986:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4987:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4988:                                     return 'ok';
                   4989:                                 }
                   4990:                             }
                   4991:                         }
                   4992:                     } 
1.765     albertel 4993:                 }
                   4994:             }
                   4995:             my %roleshash;
                   4996:             my @courses_and_groups = @courses;
                   4997:             push(@courses_and_groups,@groups); 
                   4998:             if (@courses_and_groups > 0) {
                   4999:                 my (%allgroups,%allroles); 
                   5000:                 my ($start,$end,$role,$sec,$group);
                   5001:                 foreach my $envkey (%env) {
1.1056.4.1  raeburn  5002:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5003:                         my $cid = $2.'_'.$3; 
                   5004:                         if ($1 eq 'gr') {
                   5005:                             $group = $4;
                   5006:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5007:                         } else {
                   5008:                             if ($4 eq '') {
                   5009:                                 $sec = 'none';
                   5010:                             } else {
                   5011:                                 $sec = $4;
                   5012:                             }
                   5013:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5014:                         }
1.811     albertel 5015:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5016:                         my $cid = $2.'_'.$3;
                   5017:                         if ($4 eq '') {
                   5018:                             $sec = 'none';
                   5019:                         } else {
                   5020:                             $sec = $4;
                   5021:                         }
                   5022:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5023:                     }
                   5024:                 }
                   5025:                 if (keys(%allroles) == 0) {
                   5026:                     return;
                   5027:                 }
                   5028:                 foreach my $key (@courses_and_groups) {
                   5029:                     my %content = %{$$access_hash{$key}};
                   5030:                     my $cnum = $content{'number'};
                   5031:                     my $cdom = $content{'domain'};
                   5032:                     my $cid = $cdom.'_'.$cnum;
                   5033:                     if (!exists($allroles{$cid})) {
                   5034:                         next;
                   5035:                     }    
                   5036:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5037:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5038:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5039:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5040:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5041:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5042:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5043:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5044:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5045:                                         if (grep/^all$/,@sections) {
                   5046:                                             return 'ok';
                   5047:                                         } else {
                   5048:                                             if (grep/^$sec$/,@sections) {
                   5049:                                                 return 'ok';
                   5050:                                             }
                   5051:                                         }
                   5052:                                     }
                   5053:                                 }
                   5054:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5055:                                     if (grep/^none$/,@groups) {
                   5056:                                         return 'ok';
                   5057:                                     }
                   5058:                                 } else {
                   5059:                                     if (grep/^all$/,@groups) {
                   5060:                                         return 'ok';
                   5061:                                     } 
                   5062:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5063:                                         if (grep/^$group$/,@groups) {
                   5064:                                             return 'ok';
                   5065:                                         }
                   5066:                                     }
                   5067:                                 } 
                   5068:                             }
                   5069:                         }
                   5070:                     }
                   5071:                 }
                   5072:             }
                   5073:             if ($guest) {
                   5074:                 return $guest;
                   5075:             }
                   5076:         }
                   5077:     }
                   5078:     return;
                   5079: }
                   5080: 
                   5081: sub course_group_datechecker {
                   5082:     my ($dates,$now,$status) = @_;
                   5083:     my ($start,$end) = split(/\./,$dates);
                   5084:     if (!$start && !$end) {
                   5085:         return 'ok';
                   5086:     }
                   5087:     if (grep/^active$/,@{$status}) {
                   5088:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5089:             return 'ok';
                   5090:         }
                   5091:     }
                   5092:     if (grep/^previous$/,@{$status}) {
                   5093:         if ($end > $now ) {
                   5094:             return 'ok';
                   5095:         }
                   5096:     }
                   5097:     if (grep/^future$/,@{$status}) {
                   5098:         if ($start > $now) {
                   5099:             return 'ok';
                   5100:         }
                   5101:     }
                   5102:     return; 
                   5103: }
                   5104: 
                   5105: sub parse_portfolio_url {
                   5106:     my ($url) = @_;
                   5107: 
                   5108:     my ($type,$udom,$unum,$group,$file_name);
                   5109:     
1.823     albertel 5110:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5111: 	$type = 1;
                   5112:         $udom = $1;
                   5113:         $unum = $2;
                   5114:         $file_name = $3;
1.823     albertel 5115:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5116: 	$type = 2;
                   5117:         $udom = $1;
                   5118:         $unum = $2;
                   5119:         $group = $3;
                   5120:         $file_name = $3.'/'.$4;
                   5121:     }
                   5122:     if (wantarray) {
                   5123: 	return ($type,$udom,$unum,$file_name,$group);
                   5124:     }
                   5125:     return $type;
                   5126: }
                   5127: 
                   5128: sub is_portfolio_url {
                   5129:     my ($url) = @_;
                   5130:     return scalar(&parse_portfolio_url($url));
                   5131: }
                   5132: 
1.798     raeburn  5133: sub is_portfolio_file {
                   5134:     my ($file) = @_;
1.820     raeburn  5135:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5136:         return 1;
                   5137:     }
                   5138:     return;
                   5139: }
                   5140: 
1.976     raeburn  5141: sub usertools_access {
1.1056.4.9  raeburn  5142:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985     raeburn  5143:     my ($access,%tools);
                   5144:     if ($context eq '') {
                   5145:         $context = 'tools';
                   5146:     }
                   5147:     if ($context eq 'requestcourses') {
                   5148:         %tools = (
                   5149:                       official   => 1,
                   5150:                       unofficial => 1,
1.1006    raeburn  5151:                       community  => 1,
1.985     raeburn  5152:                  );
                   5153:     } else {
                   5154:         %tools = (
                   5155:                       aboutme   => 1,
                   5156:                       blog      => 1,
                   5157:                       portfolio => 1,
                   5158:                  );
                   5159:     }
1.976     raeburn  5160:     return if (!defined($tools{$tool}));
                   5161: 
                   5162:     if ((!defined($udom)) || (!defined($uname))) {
                   5163:         $udom = $env{'user.domain'};
                   5164:         $uname = $env{'user.name'};
                   5165:     }
                   5166: 
1.978     raeburn  5167:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5168:         if ($action ne 'reload') {
1.985     raeburn  5169:             if ($context eq 'requestcourses') {
                   5170:                 return $env{'environment.canrequest.'.$tool};
                   5171:             } else {
                   5172:                 return $env{'environment.availabletools.'.$tool};
                   5173:             }
                   5174:         }
1.976     raeburn  5175:     }
                   5176: 
                   5177:     my ($toolstatus,$inststatus);
                   5178: 
1.985     raeburn  5179:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5180:          ($action ne 'reload')) {
                   5181:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5182:         $inststatus = $env{'environment.inststatus'};
                   5183:     } else {
1.1056.4.9  raeburn  5184:         if (ref($userenvref) eq 'HASH') {
                   5185:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5186:             $inststatus = $userenvref->{'inststatus'};
                   5187:         } else {
                   5188:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5189:             $toolstatus = $userenv{$context.'.'.$tool};
                   5190:             $inststatus = $userenv{'inststatus'};
                   5191:         }
1.976     raeburn  5192:     }
                   5193: 
                   5194:     if ($toolstatus ne '') {
                   5195:         if ($toolstatus) {
                   5196:             $access = 1;
                   5197:         } else {
                   5198:             $access = 0;
                   5199:         }
                   5200:         return $access;
                   5201:     }
                   5202: 
1.1056.4.9  raeburn  5203:     my ($is_adv,%domdef);
                   5204:     if (ref($is_advref) eq 'HASH') {
                   5205:         $is_adv = $is_advref->{'is_adv'};
                   5206:     } else {
                   5207:         $is_adv = &is_advanced_user($udom,$uname);
                   5208:     }
                   5209:     if (ref($domdefref) eq 'HASH') {
                   5210:         %domdef = %{$domdefref};
                   5211:     } else {
                   5212:         %domdef = &get_domain_defaults($udom);
                   5213:     }
1.976     raeburn  5214:     if (ref($domdef{$tool}) eq 'HASH') {
                   5215:         if ($is_adv) {
                   5216:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5217:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5218:                     $access = 1;
                   5219:                 } else {
                   5220:                     $access = 0;
                   5221:                 }
                   5222:                 return $access;
                   5223:             }
                   5224:         }
                   5225:         if ($inststatus ne '') {
                   5226:             my ($hasaccess,$hasnoaccess);
                   5227:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5228:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5229:                     if ($domdef{$tool}{$affiliation}) {
                   5230:                         $hasaccess = 1;
                   5231:                     } else {
                   5232:                         $hasnoaccess = 1;
                   5233:                     }
                   5234:                 }
                   5235:             }
                   5236:             if ($hasaccess || $hasnoaccess) {
                   5237:                 if ($hasaccess) {
                   5238:                     $access = 1;
                   5239:                 } elsif ($hasnoaccess) {
                   5240:                     $access = 0; 
                   5241:                 }
                   5242:                 return $access;
                   5243:             }
                   5244:         } else {
                   5245:             if ($domdef{$tool}{'default'} ne '') {
                   5246:                 if ($domdef{$tool}{'default'}) {
                   5247:                     $access = 1;
                   5248:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5249:                     $access = 0;
                   5250:                 }
                   5251:                 return $access;
                   5252:             }
                   5253:         }
                   5254:     } else {
1.985     raeburn  5255:         if ($context eq 'tools') {
                   5256:             $access = 1;
                   5257:         } else {
                   5258:             $access = 0;
                   5259:         }
1.976     raeburn  5260:         return $access;
                   5261:     }
                   5262: }
                   5263: 
1.1050    raeburn  5264: sub is_course_owner {
                   5265:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5266:     if (($udom eq '') || ($uname eq '')) {
                   5267:         $udom = $env{'user.domain'};
                   5268:         $uname = $env{'user.name'};
                   5269:     }
                   5270:     unless (($udom eq '') || ($uname eq '')) {
                   5271:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5272:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5273:                 return 1;
                   5274:             } else {
                   5275:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5276:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5277:                     return 1;
                   5278:                 }
                   5279:             }
                   5280:         }
                   5281:     }
                   5282:     return;
                   5283: }
                   5284: 
1.976     raeburn  5285: sub is_advanced_user {
                   5286:     my ($udom,$uname) = @_;
1.1056.4.10  raeburn  5287:     if ($udom ne '' && $uname ne '') {
                   5288:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5289:             return $env{'user.adv'};
                   5290:         }
                   5291:     }
1.976     raeburn  5292:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5293:     my %allroles;
                   5294:     my $is_adv;
                   5295:     foreach my $role (keys(%roleshash)) {
                   5296:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5297:         my $area = '/'.$tdomain.'/'.$trest;
                   5298:         if ($sec ne '') {
                   5299:             $area .= '/'.$sec;
                   5300:         }
                   5301:         if (($area ne '') && ($trole ne '')) {
                   5302:             my $spec=$trole.'.'.$area;
                   5303:             if ($trole =~ /^cr\//) {
                   5304:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5305:             } elsif ($trole ne 'gr') {
                   5306:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5307:             }
                   5308:         }
                   5309:     }
                   5310:     foreach my $role (keys(%allroles)) {
                   5311:         last if ($is_adv);
                   5312:         foreach my $item (split(/:/,$allroles{$role})) {
                   5313:             if ($item ne '') {
                   5314:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5315:                 if ($privilege eq 'adv') {
                   5316:                     $is_adv = 1;
                   5317:                     last;
                   5318:                 }
                   5319:             }
                   5320:         }
                   5321:     }
                   5322:     return $is_adv;
                   5323: }
1.798     raeburn  5324: 
1.1035    raeburn  5325: sub check_can_request {
1.1036    raeburn  5326:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5327:     my $canreq = 0;
                   5328:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5329:     my @options = ('approval','validate','autolimit');
                   5330:     my $optregex = join('|',@options);
                   5331:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5332:         foreach my $type (@{$types}) {
                   5333:             if (&usertools_access($env{'user.name'},
                   5334:                                   $env{'user.domain'},
                   5335:                                   $type,undef,'requestcourses')) {
                   5336:                 $canreq ++;
1.1036    raeburn  5337:                 if (ref($request_domains) eq 'HASH') {
                   5338:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5339:                 }
1.1035    raeburn  5340:                 if ($dom eq $env{'user.domain'}) {
                   5341:                     $can_request->{$type} = 1;
                   5342:                 }
                   5343:             }
                   5344:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5345:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5346:                 if (@curr > 0) {
1.1036    raeburn  5347:                     foreach my $item (@curr) {
                   5348:                         if (ref($request_domains) eq 'HASH') {
                   5349:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5350:                             if ($otherdom ne '') {
                   5351:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5352:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5353:                                         push(@{$request_domains->{$type}},$otherdom);
                   5354:                                     }
                   5355:                                 } else {
                   5356:                                     push(@{$request_domains->{$type}},$otherdom);
                   5357:                                 }
                   5358:                             }
                   5359:                         }
                   5360:                     }
                   5361:                     unless($dom eq $env{'user.domain'}) {
                   5362:                         $canreq ++;
1.1035    raeburn  5363:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5364:                             $can_request->{$type} = 1;
                   5365:                         }
                   5366:                     }
                   5367:                 }
                   5368:             }
                   5369:         }
                   5370:     }
                   5371:     return $canreq;
                   5372: }
                   5373: 
1.341     www      5374: # ---------------------------------------------- Custom access rule evaluation
                   5375: 
                   5376: sub customaccess {
                   5377:     my ($priv,$uri)=@_;
1.807     albertel 5378:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5379:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5380:     $udom = &LONCAPA::clean_domain($udom);
                   5381:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5382:     my $access=0;
1.800     albertel 5383:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5384: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5385: 	if ($type eq 'user') {
                   5386: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5387: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5388: 		if ($tdom) {
                   5389: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5390: 		}
1.896     albertel 5391: 		if ($tuname) {
                   5392: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5393: 		}
                   5394: 		$access=($effect eq 'allow');
                   5395: 		last;
                   5396: 	    }
                   5397: 	} else {
                   5398: 	    if ($role) {
                   5399: 		if ($role ne $urole) { next; }
                   5400: 	    }
                   5401: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5402: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5403: 		if ($tdom) {
                   5404: 		    if ($tdom ne $udom) { next; }
                   5405: 		}
                   5406: 		if ($tcrs) {
                   5407: 		    if ($tcrs ne $ucrs) { next; }
                   5408: 		}
                   5409: 		if ($tsec) {
                   5410: 		    if ($tsec ne $usec) { next; }
                   5411: 		}
                   5412: 		$access=($effect eq 'allow');
                   5413: 		last;
                   5414: 	    }
                   5415: 	    if ($realm eq '' && $role eq '') {
                   5416: 		$access=($effect eq 'allow');
                   5417: 	    }
1.402     bowersj2 5418: 	}
1.341     www      5419:     }
                   5420:     return $access;
                   5421: }
                   5422: 
1.103     harris41 5423: # ------------------------------------------------- Check for a user privilege
1.12      www      5424: 
                   5425: sub allowed {
1.810     raeburn  5426:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5427:     my $ver_orguri=$uri;
1.439     www      5428:     $uri=&deversion($uri);
1.152     www      5429:     my $orguri=$uri;
1.52      www      5430:     $uri=&declutter($uri);
1.809     raeburn  5431: 
1.810     raeburn  5432:     if ($priv eq 'evb') {
                   5433: # Evade communication block restrictions for specified role in a course
                   5434:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5435:             return $1;
                   5436:         } else {
                   5437:             return;
                   5438:         }
                   5439:     }
                   5440: 
1.620     albertel 5441:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5442: # Free bre access to adm and meta resources
1.775     albertel 5443:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5444: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5445: 	&& ($priv eq 'bre')) {
1.14      www      5446: 	return 'F';
1.159     www      5447:     }
                   5448: 
1.545     banghart 5449: # Free bre access to user's own portfolio contents
1.714     raeburn  5450:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5451:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5452: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5453:         my %setters;
                   5454:         my ($startblock,$endblock) = 
                   5455:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5456:         if ($startblock && $endblock) {
                   5457:             return 'B';
                   5458:         } else {
                   5459:             return 'F';
                   5460:         }
1.545     banghart 5461:     }
                   5462: 
1.762     raeburn  5463: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5464:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5465:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5466:         if (exists($env{'request.course.id'})) {
                   5467:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5468:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5469:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5470:                 my $courseprivid=$env{'request.course.id'};
                   5471:                 $courseprivid=~s/\_/\//;
                   5472:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5473:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5474:                     return $1; 
1.762     raeburn  5475:                 } else {
                   5476:                     if ($env{'request.course.sec'}) {
                   5477:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5478:                     }
                   5479:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5480:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5481:                         return $2;
                   5482:                     }
1.714     raeburn  5483:                 }
                   5484:             }
                   5485:         }
                   5486:     }
                   5487: 
1.159     www      5488: # Free bre to public access
                   5489: 
                   5490:     if ($priv eq 'bre') {
1.238     www      5491:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5492: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5493:            return 'F'; 
                   5494:         }
1.238     www      5495:         if ($copyright eq 'priv') {
                   5496:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5497: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5498: 		return '';
                   5499:             }
                   5500:         }
                   5501:         if ($copyright eq 'domain') {
                   5502:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5503: 	    unless (($env{'user.domain'} eq $1) ||
                   5504:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5505: 		return '';
                   5506:             }
1.262     matthew  5507:         }
1.620     albertel 5508:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5509:             # Library role, so allow browsing of resources in this domain.
                   5510:             return 'F';
1.238     www      5511:         }
1.341     www      5512:         if ($copyright eq 'custom') {
                   5513: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5514:         }
1.14      www      5515:     }
1.264     matthew  5516:     # Domain coordinator is trying to create a course
1.620     albertel 5517:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5518:         # uri is the requested domain in this case.
                   5519:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5520:         # a role of dc for the domain in question.
1.620     albertel 5521:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5522:     }
1.29      www      5523: 
1.52      www      5524:     my $thisallowed='';
                   5525:     my $statecond=0;
                   5526:     my $courseprivid='';
                   5527: 
1.1039    raeburn  5528:     my $ownaccess;
1.1043    raeburn  5529:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5530:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5531:         if ($uri eq '') {
                   5532:             $ownaccess = 1;
                   5533:         } else {
                   5534:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5535:                 my $udom = $env{'user.domain'};
                   5536:                 my $uname = $env{'user.name'};
                   5537:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5538:                     $ownaccess = 1;
1.1040    raeburn  5539:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5540:                     unless ($uri =~ m{\.\./}) {
                   5541:                         $ownaccess = 1;
                   5542:                     }
                   5543:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5544:                     my $now = time;
                   5545:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5546:                         my $adom = $1;
                   5547:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5548:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5549:                                 my ($start,$end) = split('.',$env{$key});
                   5550:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5551:                                     $ownaccess = 1;
                   5552:                                     last;
                   5553:                                 }
                   5554:                             }
                   5555:                         }
                   5556:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5557:                         my $adom = $1;
                   5558:                         my $aname = $2;
1.1042    raeburn  5559:                         foreach my $role ('ca','aa') { 
                   5560:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5561:                                 my ($start,$end) =
                   5562:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5563:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5564:                                     $ownaccess = 1;
                   5565:                                     last;
                   5566:                                 }
1.1039    raeburn  5567:                             }
                   5568:                         }
                   5569:                     }
                   5570:                 }
                   5571:             }
                   5572:         }
                   5573:     }
                   5574: 
1.52      www      5575: # Course
                   5576: 
1.620     albertel 5577:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5578:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5579:             $thisallowed.=$1;
                   5580:         }
1.52      www      5581:     }
1.29      www      5582: 
1.52      www      5583: # Domain
                   5584: 
1.620     albertel 5585:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5586:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5587:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5588:             $thisallowed.=$1;
                   5589:         }
1.12      www      5590:     }
1.52      www      5591: 
                   5592: # Course: uri itself is a course
1.66      www      5593:     my $courseuri=$uri;
                   5594:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5595:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5596: 
1.620     albertel 5597:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5598:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5599:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5600:             $thisallowed.=$1;
                   5601:         }
1.12      www      5602:     }
1.29      www      5603: 
1.665     albertel 5604: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5605: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5606:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5607: 	$thisallowed='';
1.671     raeburn  5608:         my ($match)=&is_on_map($uri);
                   5609:         if ($match) {
                   5610:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5611:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5612:                 $thisallowed.=$1;
                   5613:             }
                   5614:         } else {
1.705     albertel 5615:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5616:             if ($refuri) {
                   5617:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5618:                     $thisallowed='F';
1.671     raeburn  5619:                 } else {
                   5620:                     $refuri=&declutter($refuri);
                   5621:                     my ($match) = &is_on_map($refuri);
                   5622:                     if ($match) {
                   5623:                         $thisallowed='F';
                   5624:                     }
1.669     raeburn  5625:                 }
1.671     raeburn  5626:             }
                   5627:         }
1.314     www      5628:     }
1.492     albertel 5629: 
1.766     albertel 5630:     if ($priv eq 'bre'
                   5631: 	&& $thisallowed ne 'F' 
                   5632: 	&& $thisallowed ne '2'
                   5633: 	&& &is_portfolio_url($uri)) {
                   5634: 	$thisallowed = &portfolio_access($uri);
                   5635:     }
                   5636:     
1.52      www      5637: # Full access at system, domain or course-wide level? Exit.
1.29      www      5638:     if ($thisallowed=~/F/) {
                   5639: 	return 'F';
                   5640:     }
                   5641: 
1.52      www      5642: # If this is generating or modifying users, exit with special codes
1.29      www      5643: 
1.643     www      5644:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5645: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5646: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5647: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5648: 	    unless ($auname) { return $thisallowed; }
                   5649: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5650: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5651: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5652: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5653: 	}
1.52      www      5654: 	return $thisallowed;
                   5655:     }
                   5656: #
1.103     harris41 5657: # Gathered so far: system, domain and course wide privileges
1.52      www      5658: #
                   5659: # Course: See if uri or referer is an individual resource that is part of 
                   5660: # the course
                   5661: 
1.620     albertel 5662:     if ($env{'request.course.id'}) {
1.232     www      5663: 
1.620     albertel 5664:        $courseprivid=$env{'request.course.id'};
                   5665:        if ($env{'request.course.sec'}) {
                   5666:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5667:        }
                   5668:        $courseprivid=~s/\_/\//;
                   5669:        my $checkreferer=1;
1.232     www      5670:        my ($match,$cond)=&is_on_map($uri);
                   5671:        if ($match) {
                   5672:            $statecond=$cond;
1.620     albertel 5673:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5674:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5675:                $thisallowed.=$1;
                   5676:                $checkreferer=0;
                   5677:            }
1.29      www      5678:        }
1.83      www      5679:        
1.148     www      5680:        if ($checkreferer) {
1.620     albertel 5681: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5682:             unless ($refuri) {
1.800     albertel 5683:                 foreach my $key (keys(%env)) {
                   5684: 		    if ($key=~/^httpref\..*\*/) {
                   5685: 			my $pattern=$key;
1.156     www      5686:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5687:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5688:                         $pattern=~s/\//\\\//g;
1.152     www      5689:                         if ($orguri=~/$pattern/) {
1.800     albertel 5690: 			    $refuri=$env{$key};
1.148     www      5691:                         }
                   5692:                     }
1.191     harris41 5693:                 }
1.148     www      5694:             }
1.232     www      5695: 
1.148     www      5696:          if ($refuri) { 
1.152     www      5697: 	  $refuri=&declutter($refuri);
1.232     www      5698:           my ($match,$cond)=&is_on_map($refuri);
                   5699:             if ($match) {
                   5700:               my $refstatecond=$cond;
1.620     albertel 5701:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5702:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5703:                   $thisallowed.=$1;
1.53      www      5704:                   $uri=$refuri;
                   5705:                   $statecond=$refstatecond;
1.52      www      5706:               }
                   5707:           }
1.148     www      5708:         }
1.29      www      5709:        }
1.52      www      5710:    }
1.29      www      5711: 
1.52      www      5712: #
1.103     harris41 5713: # Gathered now: all privileges that could apply, and condition number
1.52      www      5714: # 
                   5715: #
                   5716: # Full or no access?
                   5717: #
1.29      www      5718: 
1.52      www      5719:     if ($thisallowed=~/F/) {
                   5720: 	return 'F';
                   5721:     }
1.29      www      5722: 
1.52      www      5723:     unless ($thisallowed) {
                   5724:         return '';
                   5725:     }
1.29      www      5726: 
1.52      www      5727: # Restrictions exist, deal with them
                   5728: #
                   5729: #   C:according to course preferences
                   5730: #   R:according to resource settings
                   5731: #   L:unless locked
                   5732: #   X:according to user session state
                   5733: #
                   5734: 
                   5735: # Possibly locked functionality, check all courses
1.54      www      5736: # Locks might take effect only after 10 minutes cache expiration for other
                   5737: # courses, and 2 minutes for current course
1.52      www      5738: 
                   5739:     my $envkey;
                   5740:     if ($thisallowed=~/L/) {
1.1000    raeburn  5741:         foreach $envkey (keys(%env)) {
1.54      www      5742:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5743:                my $courseid=$2;
                   5744:                my $roleid=$1.'.'.$2;
1.92      www      5745:                $courseid=~s/^\///;
1.54      www      5746:                my $expiretime=600;
1.620     albertel 5747:                if ($env{'request.role'} eq $roleid) {
1.54      www      5748: 		  $expiretime=120;
                   5749:                }
                   5750: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5751:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5752:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5753: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5754:                }
1.620     albertel 5755:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5756:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5757: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5758:                        &log($env{'user.domain'},$env{'user.name'},
                   5759:                             $env{'user.home'},
1.57      www      5760:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5761:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5762:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5763: 		       return '';
                   5764:                    }
                   5765:                }
1.620     albertel 5766:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5767:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5768: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5769:                        &log($env{'user.domain'},$env{'user.name'},
                   5770:                             $env{'user.home'},
1.57      www      5771:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5772:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5773:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5774: 		       return '';
                   5775:                    }
                   5776:                }
                   5777: 	   }
1.29      www      5778:        }
1.52      www      5779:     }
                   5780:    
                   5781: #
                   5782: # Rest of the restrictions depend on selected course
                   5783: #
                   5784: 
1.620     albertel 5785:     unless ($env{'request.course.id'}) {
1.766     albertel 5786: 	if ($thisallowed eq 'A') {
                   5787: 	    return 'A';
1.814     raeburn  5788:         } elsif ($thisallowed eq 'B') {
                   5789:             return 'B';
1.766     albertel 5790: 	} else {
                   5791: 	    return '1';
                   5792: 	}
1.52      www      5793:     }
1.29      www      5794: 
1.52      www      5795: #
                   5796: # Now user is definitely in a course
                   5797: #
1.53      www      5798: 
                   5799: 
                   5800: # Course preferences
                   5801: 
                   5802:    if ($thisallowed=~/C/) {
1.620     albertel 5803:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5804:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5805:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5806: 	   =~/\Q$rolecode\E/) {
1.1056.4.22  raeburn  5807:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5808: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5809: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5810: 			$env{'request.course.id'});
                   5811: 	   }
1.237     www      5812:            return '';
                   5813:        }
                   5814: 
1.620     albertel 5815:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5816: 	   =~/\Q$unamedom\E/) {
1.1056.4.22  raeburn  5817:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5818: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5819: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5820: 			$env{'request.course.id'});
                   5821: 	   }
1.54      www      5822:            return '';
                   5823:        }
1.53      www      5824:    }
                   5825: 
                   5826: # Resource preferences
                   5827: 
                   5828:    if ($thisallowed=~/R/) {
1.620     albertel 5829:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5830:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1056.4.22  raeburn  5831:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5832: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5833: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5834: 	   }
                   5835: 	   return '';
1.54      www      5836:        }
1.53      www      5837:    }
1.30      www      5838: 
1.246     www      5839: # Restricted by state or randomout?
1.30      www      5840: 
1.52      www      5841:    if ($thisallowed=~/X/) {
1.620     albertel 5842:       if ($env{'acc.randomout'}) {
1.579     albertel 5843: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5844:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5845:             return ''; 
                   5846:          }
1.247     www      5847:       }
                   5848:       if (&condval($statecond)) {
1.52      www      5849: 	 return '2';
                   5850:       } else {
                   5851:          return '';
                   5852:       }
                   5853:    }
1.30      www      5854: 
1.766     albertel 5855:     if ($thisallowed eq 'A') {
                   5856: 	return 'A';
1.814     raeburn  5857:     } elsif ($thisallowed eq 'B') {
                   5858:         return 'B';
1.766     albertel 5859:     }
1.52      www      5860:    return 'F';
1.232     www      5861: }
                   5862: 
1.710     albertel 5863: sub split_uri_for_cond {
                   5864:     my $uri=&deversion(&declutter(shift));
                   5865:     my @uriparts=split(/\//,$uri);
                   5866:     my $filename=pop(@uriparts);
                   5867:     my $pathname=join('/',@uriparts);
                   5868:     return ($pathname,$filename);
                   5869: }
1.232     www      5870: # --------------------------------------------------- Is a resource on the map?
                   5871: 
                   5872: sub is_on_map {
1.710     albertel 5873:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5874:     #Trying to find the conditional for the file
1.620     albertel 5875:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5876: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5877:     if ($match) {
1.289     bowersj2 5878: 	return (1,$1);
                   5879:     } else {
1.434     www      5880: 	return (0,0);
1.289     bowersj2 5881:     }
1.12      www      5882: }
                   5883: 
1.427     www      5884: # --------------------------------------------------------- Get symb from alias
                   5885: 
                   5886: sub get_symb_from_alias {
                   5887:     my $symb=shift;
                   5888:     my ($map,$resid,$url)=&decode_symb($symb);
                   5889: # Already is a symb
                   5890:     if ($url) { return $symb; }
                   5891: # Must be an alias
                   5892:     my $aliassymb='';
                   5893:     my %bighash;
1.620     albertel 5894:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5895:                             &GDBM_READER(),0640)) {
                   5896:         my $rid=$bighash{'mapalias_'.$symb};
                   5897: 	if ($rid) {
                   5898: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5899: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5900: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5901: 	}
                   5902:         untie %bighash;
                   5903:     }
                   5904:     return $aliassymb;
                   5905: }
                   5906: 
1.12      www      5907: # ----------------------------------------------------------------- Define Role
                   5908: 
                   5909: sub definerole {
                   5910:   if (allowed('mcr','/')) {
                   5911:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5912:     foreach my $role (split(':',$sysrole)) {
                   5913: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5914:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5915:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5916: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5917:                return "refused:s:$crole&$cqual"; 
                   5918:             }
                   5919:         }
1.191     harris41 5920:     }
1.800     albertel 5921:     foreach my $role (split(':',$domrole)) {
                   5922: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5923:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5924:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5925: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5926:                return "refused:d:$crole&$cqual"; 
                   5927:             }
                   5928:         }
1.191     harris41 5929:     }
1.800     albertel 5930:     foreach my $role (split(':',$courole)) {
                   5931: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5932:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5933:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5934: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5935:                return "refused:c:$crole&$cqual"; 
                   5936:             }
                   5937:         }
1.191     harris41 5938:     }
1.620     albertel 5939:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5940:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5941: 	        "rolesdef_$rolename=".
                   5942:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5943:     return reply($command,$env{'user.home'});
1.12      www      5944:   } else {
                   5945:     return 'refused';
                   5946:   }
1.105     harris41 5947: }
                   5948: 
                   5949: # ---------------- Make a metadata query against the network of library servers
                   5950: 
                   5951: sub metadata_query {
1.244     matthew  5952:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5953:     my %rhash;
1.845     albertel 5954:     my %libserv = &all_library();
1.244     matthew  5955:     my @server_list = (defined($server_array) ? @$server_array
                   5956:                                               : keys(%libserv) );
                   5957:     for my $server (@server_list) {
1.118     harris41 5958: 	unless ($custom or $customshow) {
                   5959: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5960: 	    $rhash{$server}=$reply;
                   5961: 	}
                   5962: 	else {
                   5963: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5964: 			     &escape($custom).':'.&escape($customshow),
                   5965: 			     $server);
                   5966: 	    $rhash{$server}=$reply;
                   5967: 	}
1.112     harris41 5968:     }
1.118     harris41 5969:     return \%rhash;
1.240     www      5970: }
                   5971: 
                   5972: # ----------------------------------------- Send log queries and wait for reply
                   5973: 
                   5974: sub log_query {
                   5975:     my ($uname,$udom,$query,%filters)=@_;
                   5976:     my $uhome=&homeserver($uname,$udom);
                   5977:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5978:     my $uhost=&hostname($uhome);
1.800     albertel 5979:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5980:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5981:                        $uhome);
1.479     albertel 5982:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5983:     return get_query_reply($queryid);
                   5984: }
                   5985: 
1.818     raeburn  5986: # -------------------------- Update MySQL table for portfolio file
                   5987: 
                   5988: sub update_portfolio_table {
1.821     raeburn  5989:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5990:     if ($group ne '') {
                   5991:         $file_name =~s /^\Q$group\E//;
                   5992:     }
1.818     raeburn  5993:     my $homeserver = &homeserver($uname,$udom);
                   5994:     my $queryid=
1.821     raeburn  5995:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5996:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5997:     my $reply = &get_query_reply($queryid);
                   5998:     return $reply;
                   5999: }
                   6000: 
1.899     raeburn  6001: # -------------------------- Update MySQL allusers table
                   6002: 
                   6003: sub update_allusers_table {
                   6004:     my ($uname,$udom,$names) = @_;
                   6005:     my $homeserver = &homeserver($uname,$udom);
                   6006:     my $queryid=
                   6007:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6008:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6009:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6010:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6011:                'generation='.&escape($names->{'generation'}).'%%'.
                   6012:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6013:                'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4  raeburn  6014:     return;
1.899     raeburn  6015: }
                   6016: 
1.508     raeburn  6017: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6018: 
                   6019: sub fetch_enrollment_query {
1.511     raeburn  6020:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6021:     my $homeserver;
1.547     raeburn  6022:     my $maxtries = 1;
1.508     raeburn  6023:     if ($context eq 'automated') {
                   6024:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6025:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6026:     } else {
                   6027:         $homeserver = &homeserver($cnum,$dom);
                   6028:     }
1.838     albertel 6029:     my $host=&hostname($homeserver);
1.506     raeburn  6030:     my $cmd = '';
1.1000    raeburn  6031:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6032:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6033:     }
                   6034:     $cmd =~ s/%%$//;
                   6035:     $cmd = &escape($cmd);
                   6036:     my $query = 'fetchenrollment';
1.620     albertel 6037:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6038:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6039:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6040:         return 'error: '.$queryid;
                   6041:     }
1.506     raeburn  6042:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6043:     my $tries = 1;
                   6044:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6045:         $reply = &get_query_reply($queryid);
                   6046:         $tries ++;
                   6047:     }
1.526     raeburn  6048:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6049:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6050:     } else {
1.901     albertel 6051:         my @responses = split(/:/,$reply);
1.515     raeburn  6052:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6053:             foreach my $line (@responses) {
                   6054:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6055:                 $$replyref{$key} = $value;
                   6056:             }
                   6057:         } else {
1.506     raeburn  6058:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 6059:             foreach my $line (@responses) {
                   6060:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6061:                 $$replyref{$key} = $value;
                   6062:                 if ($value > 0) {
1.800     albertel 6063:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6064:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6065:                         my $destname = $pathname.'/'.$filename;
                   6066:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6067:                         if ($xml_classlist =~ /^error/) {
                   6068:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6069:                         } else {
1.506     raeburn  6070:                             if ( open(FILE,">$destname") ) {
                   6071:                                 print FILE &unescape($xml_classlist);
                   6072:                                 close(FILE);
1.526     raeburn  6073:                             } else {
                   6074:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6075:                             }
                   6076:                         }
                   6077:                     }
                   6078:                 }
                   6079:             }
                   6080:         }
                   6081:         return 'ok';
                   6082:     }
                   6083:     return 'error';
                   6084: }
                   6085: 
1.242     www      6086: sub get_query_reply {
                   6087:     my $queryid=shift;
1.240     www      6088:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   6089:     my $reply='';
                   6090:     for (1..100) {
                   6091: 	sleep 2;
                   6092:         if (-e $replyfile.'.end') {
1.448     albertel 6093: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6094: 		$reply = join('',<$fh>);
                   6095: 		close($fh);
1.240     www      6096: 	   } else { return 'error: reply_file_error'; }
1.242     www      6097:            return &unescape($reply);
                   6098: 	}
1.240     www      6099:     }
1.242     www      6100:     return 'timeout:'.$queryid;
1.240     www      6101: }
                   6102: 
                   6103: sub courselog_query {
1.241     www      6104: #
                   6105: # possible filters:
                   6106: # url: url or symb
                   6107: # username
                   6108: # domain
                   6109: # action: view, submit, grade
                   6110: # start: timestamp
                   6111: # end: timestamp
                   6112: #
1.240     www      6113:     my (%filters)=@_;
1.620     albertel 6114:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6115:     if ($filters{'url'}) {
                   6116: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6117:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6118:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6119:     }
1.620     albertel 6120:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6121:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6122:     return &log_query($cname,$cdom,'courselog',%filters);
                   6123: }
                   6124: 
                   6125: sub userlog_query {
1.858     raeburn  6126: #
                   6127: # possible filters:
                   6128: # action: log check role
                   6129: # start: timestamp
                   6130: # end: timestamp
                   6131: #
1.240     www      6132:     my ($uname,$udom,%filters)=@_;
                   6133:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6134: }
                   6135: 
1.506     raeburn  6136: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6137: 
                   6138: sub auto_run {
1.508     raeburn  6139:     my ($cnum,$cdom) = @_;
1.876     raeburn  6140:     my $response = 0;
                   6141:     my $settings;
                   6142:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6143:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6144:         $settings = $domconfig{'autoenroll'};
                   6145:         if ($settings->{'run'} eq '1') {
                   6146:             $response = 1;
                   6147:         }
                   6148:     } else {
1.934     raeburn  6149:         my $homeserver;
                   6150:         if (&is_course($cdom,$cnum)) {
                   6151:             $homeserver = &homeserver($cnum,$cdom);
                   6152:         } else {
                   6153:             $homeserver = &domain($cdom,'primary');
                   6154:         }
                   6155:         if ($homeserver ne 'no_host') {
                   6156:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6157:         }
1.876     raeburn  6158:     }
1.506     raeburn  6159:     return $response;
                   6160: }
1.776     albertel 6161: 
1.506     raeburn  6162: sub auto_get_sections {
1.508     raeburn  6163:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6164:     my $homeserver;
                   6165:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6166:         $homeserver = &homeserver($cnum,$cdom);
                   6167:     }
                   6168:     if (!defined($homeserver)) { 
                   6169:         if ($cdom =~ /^$match_domain$/) {
                   6170:             $homeserver = &domain($cdom,'primary');
                   6171:         }
                   6172:     }
                   6173:     my @secs;
                   6174:     if (defined($homeserver)) {
                   6175:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6176:         unless ($response eq 'refused') {
                   6177:             @secs = split(/:/,$response);
                   6178:         }
1.506     raeburn  6179:     }
                   6180:     return @secs;
                   6181: }
1.776     albertel 6182: 
1.506     raeburn  6183: sub auto_new_course {
1.1056.4.19  raeburn  6184:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6185:     my $homeserver = &homeserver($cnum,$cdom);
1.1056.4.19  raeburn  6186:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6187:     return $response;
                   6188: }
1.776     albertel 6189: 
1.506     raeburn  6190: sub auto_validate_courseID {
1.508     raeburn  6191:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6192:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6193:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6194:     return $response;
                   6195: }
1.776     albertel 6196: 
1.1007    raeburn  6197: sub auto_validate_instcode {
1.1020    raeburn  6198:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6199:     my ($homeserver,$response);
                   6200:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6201:         $homeserver = &homeserver($cnum,$cdom);
                   6202:     }
                   6203:     if (!defined($homeserver)) {
                   6204:         if ($cdom =~ /^$match_domain$/) {
                   6205:             $homeserver = &domain($cdom,'primary');
                   6206:         }
                   6207:     }
1.1056.4.2  raeburn  6208:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6209:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6210:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6211:     return ($outcome,$description);
1.1007    raeburn  6212: }
                   6213: 
1.506     raeburn  6214: sub auto_create_password {
1.873     raeburn  6215:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6216:     my ($homeserver,$response);
1.506     raeburn  6217:     my $create_passwd = 0;
                   6218:     my $authchk = '';
1.873     raeburn  6219:     if ($udom =~ /^$match_domain$/) {
                   6220:         $homeserver = &domain($udom,'primary');
                   6221:     }
                   6222:     if ($homeserver eq '') {
                   6223:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6224:             $homeserver = &homeserver($cnum,$cdom);
                   6225:         }
                   6226:     }
                   6227:     if ($homeserver eq '') {
                   6228:         $authchk = 'nodomain';
1.506     raeburn  6229:     } else {
1.873     raeburn  6230:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6231:         if ($response eq 'refused') {
                   6232:             $authchk = 'refused';
                   6233:         } else {
1.901     albertel 6234:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6235:         }
1.506     raeburn  6236:     }
                   6237:     return ($authparam,$create_passwd,$authchk);
                   6238: }
                   6239: 
1.706     raeburn  6240: sub auto_photo_permission {
                   6241:     my ($cnum,$cdom,$students) = @_;
                   6242:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6243:     my ($outcome,$perm_reqd,$conditions) = 
                   6244: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6245:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6246: 	return (undef,undef);
                   6247:     }
1.706     raeburn  6248:     return ($outcome,$perm_reqd,$conditions);
                   6249: }
                   6250: 
                   6251: sub auto_checkphotos {
                   6252:     my ($uname,$udom,$pid) = @_;
                   6253:     my $homeserver = &homeserver($uname,$udom);
                   6254:     my ($result,$resulttype);
                   6255:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6256: 				   &escape($uname).':'.&escape($pid),
                   6257: 				   $homeserver));
1.709     albertel 6258:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6259: 	return (undef,undef);
                   6260:     }
1.706     raeburn  6261:     if ($outcome) {
                   6262:         ($result,$resulttype) = split(/:/,$outcome);
                   6263:     } 
                   6264:     return ($result,$resulttype);
                   6265: }
                   6266: 
                   6267: sub auto_photochoice {
                   6268:     my ($cnum,$cdom) = @_;
                   6269:     my $homeserver = &homeserver($cnum,$cdom);
                   6270:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6271: 						       &escape($cdom),
                   6272: 						       $homeserver)));
1.709     albertel 6273:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6274: 	return (undef,undef);
                   6275:     }
1.706     raeburn  6276:     return ($update,$comment);
                   6277: }
                   6278: 
                   6279: sub auto_photoupdate {
                   6280:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6281:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6282:     my $host=&hostname($homeserver);
1.706     raeburn  6283:     my $cmd = '';
                   6284:     my $maxtries = 1;
1.800     albertel 6285:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6286:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6287:     }
                   6288:     $cmd =~ s/%%$//;
                   6289:     $cmd = &escape($cmd);
                   6290:     my $query = 'institutionalphotos';
                   6291:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6292:     unless ($queryid=~/^\Q$host\E\_/) {
                   6293:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6294:         return 'error: '.$queryid;
                   6295:     }
                   6296:     my $reply = &get_query_reply($queryid);
                   6297:     my $tries = 1;
                   6298:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6299:         $reply = &get_query_reply($queryid);
                   6300:         $tries ++;
                   6301:     }
                   6302:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6303:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6304:     } else {
                   6305:         my @responses = split(/:/,$reply);
                   6306:         my $outcome = shift(@responses); 
                   6307:         foreach my $item (@responses) {
                   6308:             my ($key,$value) = split(/=/,$item);
                   6309:             $$photo{$key} = $value;
                   6310:         }
                   6311:         return $outcome;
                   6312:     }
                   6313:     return 'error';
                   6314: }
                   6315: 
1.521     raeburn  6316: sub auto_instcode_format {
1.793     albertel 6317:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6318: 	$cat_order) = @_;
1.521     raeburn  6319:     my $courses = '';
1.772     raeburn  6320:     my @homeservers;
1.521     raeburn  6321:     if ($caller eq 'global') {
1.841     albertel 6322: 	my %servers = &get_servers($codedom,'library');
                   6323: 	foreach my $tryserver (keys(%servers)) {
                   6324: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6325: 		push(@homeservers,$tryserver);
                   6326: 	    }
1.584     raeburn  6327:         }
1.1022    raeburn  6328:     } elsif ($caller eq 'requests') {
                   6329:         if ($codedom =~ /^$match_domain$/) {
                   6330:             my $chome = &domain($codedom,'primary');
                   6331:             unless ($chome eq 'no_host') {
                   6332:                 push(@homeservers,$chome);
                   6333:             }
                   6334:         }
1.521     raeburn  6335:     } else {
1.772     raeburn  6336:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6337:     }
1.793     albertel 6338:     foreach my $code (keys(%{$instcodes})) {
                   6339:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6340:     }
                   6341:     chop($courses);
1.772     raeburn  6342:     my $ok_response = 0;
                   6343:     my $response;
                   6344:     while (@homeservers > 0 && $ok_response == 0) {
                   6345:         my $server = shift(@homeservers); 
                   6346:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6347:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6348:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6349: 		split(/:/,$response);
1.772     raeburn  6350:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6351:             push(@{$codetitles},&str2array($codetitles_str));
                   6352:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6353:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6354:             $ok_response = 1;
                   6355:         }
                   6356:     }
                   6357:     if ($ok_response) {
1.521     raeburn  6358:         return 'ok';
1.772     raeburn  6359:     } else {
                   6360:         return $response;
1.521     raeburn  6361:     }
                   6362: }
                   6363: 
1.792     raeburn  6364: sub auto_instcode_defaults {
                   6365:     my ($domain,$returnhash,$code_order) = @_;
                   6366:     my @homeservers;
1.841     albertel 6367: 
                   6368:     my %servers = &get_servers($domain,'library');
                   6369:     foreach my $tryserver (keys(%servers)) {
                   6370: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6371: 	    push(@homeservers,$tryserver);
                   6372: 	}
1.792     raeburn  6373:     }
1.841     albertel 6374: 
1.792     raeburn  6375:     my $response;
1.841     albertel 6376:     foreach my $server (@homeservers) {
1.792     raeburn  6377:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6378:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6379: 	
                   6380: 	foreach my $pair (split(/\&/,$response)) {
                   6381: 	    my ($name,$value)=split(/\=/,$pair);
                   6382: 	    if ($name eq 'code_order') {
                   6383: 		@{$code_order} = split(/\&/,&unescape($value));
                   6384: 	    } else {
                   6385: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6386: 	    }
                   6387: 	}
                   6388: 	return 'ok';
1.792     raeburn  6389:     }
1.841     albertel 6390: 
                   6391:     return $response;
1.1003    raeburn  6392: }
                   6393: 
                   6394: sub auto_possible_instcodes {
1.1007    raeburn  6395:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6396:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6397:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6398:         return;
                   6399:     }
1.1003    raeburn  6400:     my (@homeservers,$uhome);
                   6401:     if (defined(&domain($domain,'primary'))) {
                   6402:         $uhome=&domain($domain,'primary');
                   6403:         push(@homeservers,&domain($domain,'primary'));
                   6404:     } else {
                   6405:         my %servers = &get_servers($domain,'library');
                   6406:         foreach my $tryserver (keys(%servers)) {
                   6407:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6408:                 push(@homeservers,$tryserver);
                   6409:             }
                   6410:         }
                   6411:     }
                   6412:     my $response;
                   6413:     foreach my $server (@homeservers) {
                   6414:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6415:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6416:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6417:             split(':',$response);
                   6418:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6419:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6420:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6421:             my ($name,$value)=split('=',$item);
                   6422:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6423:         }
                   6424:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6425:             my ($name,$value)=split('=',$item);
                   6426:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6427:         }
                   6428:         return 'ok';
                   6429:     }
                   6430:     return $response;
                   6431: }
1.792     raeburn  6432: 
1.1010    raeburn  6433: sub auto_courserequest_checks {
                   6434:     my ($dom) = @_;
1.1020    raeburn  6435:     my ($homeserver,%validations);
                   6436:     if ($dom =~ /^$match_domain$/) {
                   6437:         $homeserver = &domain($dom,'primary');
                   6438:     }
                   6439:     unless ($homeserver eq 'no_host') {
                   6440:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6441:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6442:             my @items = split(/&/,$response);
                   6443:             foreach my $item (@items) {
                   6444:                 my ($key,$value) = split('=',$item);
                   6445:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6446:             }
                   6447:         }
                   6448:     }
1.1010    raeburn  6449:     return %validations; 
                   6450: }
                   6451: 
1.1020    raeburn  6452: sub auto_courserequest_validation {
                   6453:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6454:     my ($homeserver,$response);
                   6455:     if ($dom =~ /^$match_domain$/) {
                   6456:         $homeserver = &domain($dom,'primary');
                   6457:     }
                   6458:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6459:           
1.1020    raeburn  6460:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6461:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6462:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6463:                                     $homeserver));
                   6464:     }
                   6465:     return $response;
                   6466: }
                   6467: 
1.777     albertel 6468: sub auto_validate_class_sec {
1.918     raeburn  6469:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6470:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6471:     my $ownerlist;
                   6472:     if (ref($owners) eq 'ARRAY') {
                   6473:         $ownerlist = join(',',@{$owners});
                   6474:     } else {
                   6475:         $ownerlist = $owners;
                   6476:     }
1.773     raeburn  6477:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6478:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6479:     return $response;
                   6480: }
                   6481: 
1.679     raeburn  6482: # ------------------------------------------------------- Course Group routines
                   6483: 
                   6484: sub get_coursegroups {
1.809     raeburn  6485:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6486:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6487: }
                   6488: 
1.679     raeburn  6489: sub modify_coursegroup {
                   6490:     my ($cdom,$cnum,$groupsettings) = @_;
                   6491:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6492: }
                   6493: 
1.809     raeburn  6494: sub toggle_coursegroup_status {
                   6495:     my ($cdom,$cnum,$group,$action) = @_;
                   6496:     my ($from_namespace,$to_namespace);
                   6497:     if ($action eq 'delete') {
                   6498:         $from_namespace = 'coursegroups';
                   6499:         $to_namespace = 'deleted_groups';
                   6500:     } else {
                   6501:         $from_namespace = 'deleted_groups';
                   6502:         $to_namespace = 'coursegroups';
                   6503:     }
                   6504:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6505:     if (my $tmp = &error(%curr_group)) {
                   6506:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6507:         return ('read error',$tmp);
                   6508:     } else {
                   6509:         my %savedsettings = %curr_group; 
1.809     raeburn  6510:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6511:         my $deloutcome;
                   6512:         if ($result eq 'ok') {
1.809     raeburn  6513:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6514:         } else {
                   6515:             return ('write error',$result);
                   6516:         }
                   6517:         if ($deloutcome eq 'ok') {
                   6518:             return 'ok';
                   6519:         } else {
                   6520:             return ('delete error',$deloutcome);
                   6521:         }
                   6522:     }
                   6523: }
                   6524: 
1.679     raeburn  6525: sub modify_group_roles {
1.957     raeburn  6526:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6527:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6528:     my $role = 'gr/'.&escape($userprivs);
                   6529:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6530:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6531:     if ($result eq 'ok') {
                   6532:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6533:     }
1.679     raeburn  6534:     return $result;
                   6535: }
                   6536: 
                   6537: sub modify_coursegroup_membership {
                   6538:     my ($cdom,$cnum,$membership) = @_;
                   6539:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6540:     return $result;
                   6541: }
                   6542: 
1.682     raeburn  6543: sub get_active_groups {
                   6544:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6545:     my $now = time;
                   6546:     my %groups = ();
                   6547:     foreach my $key (keys(%env)) {
1.811     albertel 6548:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6549:             my ($start,$end) = split(/\./,$env{$key});
                   6550:             if (($end!=0) && ($end<$now)) { next; }
                   6551:             if (($start!=0) && ($start>$now)) { next; }
                   6552:             if ($1 eq $cdom && $2 eq $cnum) {
                   6553:                 $groups{$3} = $env{$key} ;
                   6554:             }
                   6555:         }
                   6556:     }
                   6557:     return %groups;
                   6558: }
                   6559: 
1.683     raeburn  6560: sub get_group_membership {
                   6561:     my ($cdom,$cnum,$group) = @_;
                   6562:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6563: }
                   6564: 
                   6565: sub get_users_groups {
                   6566:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6567:     my @usersgroups;
1.683     raeburn  6568:     my $cachetime=1800;
                   6569: 
                   6570:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6571:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6572:     if (defined($cached)) {
1.734     albertel 6573:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6574:     } else {  
                   6575:         $grouplist = '';
1.816     raeburn  6576:         my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  6577:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6578:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6579:         my $access_end = $env{'course.'.$courseid.
                   6580:                               '.default_enrollment_end_date'};
                   6581:         my $now = time;
                   6582:         foreach my $key (keys(%roleshash)) {
                   6583:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6584:                 my $group = $1;
                   6585:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6586:                     my $start = $2;
                   6587:                     my $end = $1;
                   6588:                     if ($start == -1) { next; } # deleted from group
                   6589:                     if (($start!=0) && ($start>$now)) { next; }
                   6590:                     if (($end!=0) && ($end<$now)) {
                   6591:                         if ($access_end && $access_end < $now) {
                   6592:                             if ($access_end - $end < 86400) {
                   6593:                                 push(@usersgroups,$group);
1.733     raeburn  6594:                             }
                   6595:                         }
1.817     raeburn  6596:                         next;
1.733     raeburn  6597:                     }
1.817     raeburn  6598:                     push(@usersgroups,$group);
1.683     raeburn  6599:                 }
                   6600:             }
                   6601:         }
1.817     raeburn  6602:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6603:         $grouplist = join(':',@usersgroups);
                   6604:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6605:     }
1.733     raeburn  6606:     return @usersgroups;
1.683     raeburn  6607: }
                   6608: 
                   6609: sub devalidate_getgroups_cache {
                   6610:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6611:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6612: 
1.683     raeburn  6613:     my $hashid="$udom:$uname:$courseid";
                   6614:     &devalidate_cache_new('getgroups',$hashid);
                   6615: }
                   6616: 
1.12      www      6617: # ------------------------------------------------------------------ Plain Text
                   6618: 
                   6619: sub plaintext {
1.988     raeburn  6620:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6621:     if ($short =~ m{^cr/}) {
1.758     albertel 6622: 	return (split('/',$short))[-1];
                   6623:     }
1.742     raeburn  6624:     if (!defined($cid)) {
                   6625:         $cid = $env{'request.course.id'};
                   6626:     }
                   6627:     my %rolenames = (
1.1008    raeburn  6628:                       Course    => 'std',
                   6629:                       Community => 'alt1',
1.742     raeburn  6630:                     );
1.1037    raeburn  6631:     if ($cid ne '') {
                   6632:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6633:             unless ($forcedefault) {
                   6634:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6635:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6636:                 return &Apache::lonlocal::mt($roletext);
                   6637:             }
                   6638:         }
                   6639:     }
                   6640:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6641:         (defined($rolenames{$type})) && 
                   6642:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6643:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6644:     } elsif ($cid ne '') {
                   6645:         my $crstype = $env{'course.'.$cid.'.type'};
                   6646:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6647:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6648:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6649:         }
1.742     raeburn  6650:     }
1.1037    raeburn  6651:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6652: }
                   6653: 
                   6654: # ----------------------------------------------------------------- Assign Role
                   6655: 
                   6656: sub assignrole {
1.957     raeburn  6657:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6658:         $context)=@_;
1.21      www      6659:     my $mrole;
                   6660:     if ($role =~ /^cr\//) {
1.393     www      6661:         my $cwosec=$url;
1.811     albertel 6662:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6663: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6664:            my $refused = 1;
                   6665:            if ($context eq 'requestcourses') {
                   6666:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6667:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6668:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6669:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6670:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6671:                            if ($crsenv{'internal.courseowner'} eq
                   6672:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6673:                                $refused = '';
                   6674:                            }
                   6675:                        }
                   6676:                    }
                   6677:                }
                   6678:            }
                   6679:            if ($refused) {
                   6680:                &logthis('Refused custom assignrole: '.
                   6681:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6682:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6683:                return 'refused';
                   6684:            }
1.104     www      6685:         }
1.21      www      6686:         $mrole='cr';
1.678     raeburn  6687:     } elsif ($role =~ /^gr\//) {
                   6688:         my $cwogrp=$url;
1.811     albertel 6689:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6690:         unless (&allowed('mdg',$cwogrp)) {
                   6691:             &logthis('Refused group assignrole: '.
                   6692:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6693:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6694:             return 'refused';
                   6695:         }
                   6696:         $mrole='gr';
1.21      www      6697:     } else {
1.82      www      6698:         my $cwosec=$url;
1.811     albertel 6699:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6700:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6701:             my $refused;
                   6702:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6703:                 if (!(&allowed('c'.$role,$url))) {
                   6704:                     $refused = 1;
                   6705:                 }
                   6706:             } else {
                   6707:                 $refused = 1;
                   6708:             }
1.947     raeburn  6709:             if ($refused) {
1.1045    raeburn  6710:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6711:                 if (!$selfenroll && $context eq 'course') {
                   6712:                     my %crsenv;
                   6713:                     if ($role eq 'cc' || $role eq 'co') {
                   6714:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6715:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6716:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6717:                                 if ($crsenv{'internal.courseowner'} eq 
                   6718:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6719:                                     $refused = '';
                   6720:                                 }
                   6721:                             }
                   6722:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6723:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6724:                                 if ($crsenv{'internal.courseowner'} eq 
                   6725:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6726:                                     $refused = '';
                   6727:                                 }
                   6728:                             }
                   6729:                         }
                   6730:                     }
                   6731:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6732:                     $refused = '';
1.1017    raeburn  6733:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6734:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6735:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6736:                         my $wrongcc;
                   6737:                         if ($cnum =~ /^$match_community$/) {
                   6738:                             $wrongcc = 1 if ($role eq 'cc');
                   6739:                         } else {
                   6740:                             $wrongcc = 1 if ($role eq 'co');
                   6741:                         }
                   6742:                         unless ($wrongcc) {
                   6743:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6744:                             if ($crsenv{'internal.courseowner'} eq 
                   6745:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6746:                                 $refused = '';
                   6747:                             }
1.1017    raeburn  6748:                         }
                   6749:                     }
                   6750:                 }
                   6751:                 if ($refused) {
1.947     raeburn  6752:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6753:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6754: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6755:                     return 'refused';
                   6756:                 }
1.932     raeburn  6757:             }
1.1056.4.30  raeburn  6758:         } elsif ($role eq 'au') {
                   6759:             if ($url ne '/'.$udom.'/') {
                   6760:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   6761:                          ' to assign author role for '.$uname.':'.$udom.
                   6762:                          ' in domain: '.$url.' refused (wrong domain).');
                   6763:                 return 'refused';
                   6764:             }
1.104     www      6765:         }
1.21      www      6766:         $mrole=$role;
                   6767:     }
1.620     albertel 6768:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6769:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6770:     if ($end) { $command.='_'.$end; }
1.21      www      6771:     if ($start) {
                   6772: 	if ($end) { 
1.81      www      6773:            $command.='_'.$start; 
1.21      www      6774:         } else {
1.81      www      6775:            $command.='_0_'.$start;
1.21      www      6776:         }
                   6777:     }
1.739     raeburn  6778:     my $origstart = $start;
                   6779:     my $origend = $end;
1.957     raeburn  6780:     my $delflag;
1.357     www      6781: # actually delete
                   6782:     if ($deleteflag) {
1.373     www      6783: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6784: # modify command to delete the role
1.620     albertel 6785:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6786:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6787: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6788: # set start and finish to negative values for userrolelog
                   6789:            $start=-1;
                   6790:            $end=-1;
1.957     raeburn  6791:            $delflag = 1;
1.357     www      6792:         }
                   6793:     }
                   6794: # send command
1.349     www      6795:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6796: # log new user role if status is ok
1.349     www      6797:     if ($answer eq 'ok') {
1.663     raeburn  6798: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6799: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6800:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6801:         unless ($role =~ /^gr/) {
                   6802:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6803:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6804:         }
1.1053    raeburn  6805:         if ($role eq 'cc') {
                   6806:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6807:         }
1.349     www      6808:     }
                   6809:     return $answer;
1.169     harris41 6810: }
                   6811: 
1.1053    raeburn  6812: sub autoupdate_coowners {
                   6813:     my ($url,$end,$start,$uname,$udom) = @_;
                   6814:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6815:     if (($cdom ne '') && ($cnum ne '')) {
                   6816:         my $now = time;
                   6817:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6818:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6819:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6820:             my $instcode = $coursehash{'internal.coursecode'};
                   6821:             if ($instcode ne '') {
1.1056    raeburn  6822:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6823:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6824:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6825:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6826:                         if ($result eq 'valid') {
                   6827:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6828:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6829:                                     push(@newcoowners,$coowner);
                   6830:                                 }
                   6831:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6832:                                     push(@newcoowners,$uname.':'.$udom);
                   6833:                                 }
                   6834:                                 @newcoowners = sort(@newcoowners);
                   6835:                             } else {
                   6836:                                 push(@newcoowners,$uname.':'.$udom);
                   6837:                             }
                   6838:                         } else {
                   6839:                             if ($coursehash{'internal.co-owners'}) {
                   6840:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6841:                                     unless ($coowner eq $uname.':'.$udom) {
                   6842:                                         push(@newcoowners,$coowner);
                   6843:                                     }
                   6844:                                 }
                   6845:                                 unless (@newcoowners > 0) {
                   6846:                                     $delcoowners = 1;
                   6847:                                     $coowners = '';
                   6848:                                 }
                   6849:                             }
                   6850:                         }
                   6851:                         if (@newcoowners || $delcoowners) {
                   6852:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6853:                                             $delcoowners,@newcoowners);
                   6854:                         }
                   6855:                     }
                   6856:                 }
                   6857:             }
                   6858:         }
                   6859:     }
                   6860: }
                   6861: 
                   6862: sub store_coowners {
                   6863:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6864:     my $cid = $cdom.'_'.$cnum;
                   6865:     my ($coowners,$delresult,$putresult);
                   6866:     if (@newcoowners) {
                   6867:         $coowners = join(',',@newcoowners);
                   6868:         my %coownershash = (
                   6869:                             'internal.co-owners' => $coowners,
                   6870:                            );
                   6871:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6872:         if ($putresult eq 'ok') {
                   6873:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6874:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6875:             }
                   6876:         }
                   6877:     }
                   6878:     if ($delcoowners) {
                   6879:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6880:         if ($delresult eq 'ok') {
                   6881:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6882:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6883:             }
                   6884:         }
                   6885:     }
                   6886:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6887:         my %crsinfo =
                   6888:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6889:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6890:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6891:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6892:         }
                   6893:     }
                   6894: }
                   6895: 
1.169     harris41 6896: # -------------------------------------------------- Modify user authentication
1.197     www      6897: # Overrides without validation
                   6898: 
1.169     harris41 6899: sub modifyuserauth {
                   6900:     my ($udom,$uname,$umode,$upass)=@_;
                   6901:     my $uhome=&homeserver($uname,$udom);
1.197     www      6902:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6903:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6904:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6905:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6906:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6907: 		     &escape($upass),$uhome);
1.620     albertel 6908:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6909:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6910:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6911:     &log($udom,,$uname,$uhome,
1.620     albertel 6912:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6913:                                      $env{'user.name'}.', '.$umode.
1.197     www      6914:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6915:     unless ($reply eq 'ok') {
1.197     www      6916:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6917: 	return 'error: '.$reply;
                   6918:     }   
1.170     harris41 6919:     return 'ok';
1.80      www      6920: }
                   6921: 
1.81      www      6922: # --------------------------------------------------------------- Modify a user
1.80      www      6923: 
1.81      www      6924: sub modifyuser {
1.206     matthew  6925:     my ($udom,    $uname, $uid,
                   6926:         $umode,   $upass, $first,
                   6927:         $middle,  $last,  $gene,
1.1056.4.1  raeburn  6928:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6929:     $udom= &LONCAPA::clean_domain($udom);
                   6930:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  raeburn  6931:     my $showcandelete = 'none';
                   6932:     if (ref($candelete) eq 'ARRAY') {
                   6933:         if (@{$candelete} > 0) {
                   6934:             $showcandelete = join(', ',@{$candelete});
                   6935:         }
                   6936:     }
1.81      www      6937:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6938:              $umode.', '.$first.', '.$middle.', '.
1.1056.4.1  raeburn  6939:              $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6940:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6941:                                      ' desiredhome not specified'). 
1.620     albertel 6942:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6943:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6944:     my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4  raeburn  6945:     my $newuser;
                   6946:     if ($uhome eq 'no_host') {
                   6947:         $newuser = 1;
                   6948:     }
1.80      www      6949: # ----------------------------------------------------------------- Create User
1.406     albertel 6950:     if (($uhome eq 'no_host') && 
                   6951: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6952:         my $unhome='';
1.844     albertel 6953:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6954:             $unhome = $desiredhome;
1.620     albertel 6955: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6956: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6957:         } else { # load balancing routine for determining $unhome
1.81      www      6958:             my $loadm=10000000;
1.841     albertel 6959: 	    my %servers = &get_servers($udom,'library');
                   6960: 	    foreach my $tryserver (keys(%servers)) {
                   6961: 		my $answer=reply('load',$tryserver);
                   6962: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6963: 		    $loadm=$answer;
                   6964: 		    $unhome=$tryserver;
                   6965: 		}
1.80      www      6966: 	    }
                   6967:         }
                   6968:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6969: 	    return 'error: unable to find a home server for '.$uname.
                   6970:                    ' in domain '.$udom;
1.80      www      6971:         }
                   6972:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6973:                          &escape($upass),$unhome);
                   6974: 	unless ($reply eq 'ok') {
                   6975:             return 'error: '.$reply;
                   6976:         }   
1.230     stredwic 6977:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6978:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6979: 	    return 'error: unable verify users home machine.';
1.80      www      6980:         }
1.209     matthew  6981:     }   # End of creation of new user
1.80      www      6982: # ---------------------------------------------------------------------- Add ID
                   6983:     if ($uid) {
                   6984:        $uid=~tr/A-Z/a-z/;
                   6985:        my %uidhash=&idrget($udom,$uname);
1.196     www      6986:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6987:          && (!$forceid)) {
1.80      www      6988: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6989: 	      return 'error: user id "'.$uid.'" does not match '.
                   6990:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6991:           }
                   6992:        } else {
                   6993: 	  &idput($udom,($uname => $uid));
                   6994:        }
                   6995:     }
                   6996: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6997:     my @tmp=&get('environment',
1.899     raeburn  6998: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6999:                     'permanentemail','inststatus'],
1.134     albertel 7000: 		   $udom,$uname);
1.1056.4.4  raeburn  7001:     my (%names,%oldnames);
1.313     matthew  7002:     if ($tmp[0] =~ m/^error:.*/) { 
                   7003:         %names=(); 
                   7004:     } else {
                   7005:         %names = @tmp;
1.1056.4.4  raeburn  7006:         %oldnames = %names;
1.313     matthew  7007:     }
1.1056.4.6  raeburn  7008: #
1.1056.4.1  raeburn  7009: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7010: # of users did not contain them), do not overwrite existing values
                   7011: # unless field is in $candelete array ref.  
                   7012: #
                   7013: 
                   7014:     my @fields = ('firstname','middlename','lastname','generation',
                   7015:                   'permanentemail','id');
                   7016:     my %newvalues;
                   7017:     if (ref($candelete) eq 'ARRAY') {
                   7018:         foreach my $field (@fields) {
                   7019:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7020:                 if ($field eq 'firstname') {
                   7021:                     $names{$field} = $first;
                   7022:                 } elsif ($field eq 'middlename') {
                   7023:                     $names{$field} = $middle;
                   7024:                 } elsif ($field eq 'lastname') {
                   7025:                     $names{$field} = $last;
                   7026:                 } elsif ($field eq 'generation') { 
                   7027:                     $names{$field} = $gene;
                   7028:                 } elsif ($field eq 'permanentemail') {
                   7029:                     $names{$field} = $email;
                   7030:                 } elsif ($field eq 'id') {
                   7031:                     $names{$field}  = $uid;
                   7032:                 }
                   7033:             }
                   7034:         }
                   7035:     }
1.388     www      7036:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7037:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7038:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7039:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7040:     if ($email) {
                   7041:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7042:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7043:     }
1.899     raeburn  7044:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7045:     if (defined($inststatus)) {
                   7046:         $names{'inststatus'} = '';
                   7047:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7048:         if (ref($usertypes) eq 'HASH') {
                   7049:             my @okstatuses; 
                   7050:             foreach my $item (split(/:/,$inststatus)) {
                   7051:                 if (defined($usertypes->{$item})) {
                   7052:                     push(@okstatuses,$item);  
                   7053:                 }
                   7054:             }
                   7055:             if (@okstatuses) {
                   7056:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7057:             }
                   7058:         }
                   7059:     }
1.1056.4.4  raeburn  7060:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7061:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  raeburn  7062:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7063:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7064:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7065:     } else {
                   7066:         $logmsg .= ' during self creation';
                   7067:     }
1.1056.4.4  raeburn  7068:     my $changed;
                   7069:     if ($newuser) {
                   7070:         $changed = 1;
                   7071:     } else {
                   7072:         foreach my $field (@fields) {
                   7073:             if ($names{$field} ne $oldnames{$field}) {
                   7074:                 $changed = 1;
                   7075:                 last;
                   7076:             }
                   7077:         }
                   7078:     }
                   7079:     unless ($changed) {
                   7080:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7081:         &logthis($logmsg);
                   7082:         return 'ok';
                   7083:     }
                   7084:     my $reply = &put('environment', \%names, $udom,$uname);
                   7085:     if ($reply ne 'ok') {
                   7086:         return 'error: '.$reply;
                   7087:     }
1.1056.4.11  raeburn  7088:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7089:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7090:     }
1.1056.4.4  raeburn  7091:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7092:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7093:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7094:     &logthis($logmsg);
1.134     albertel 7095:     return 'ok';
1.80      www      7096: }
                   7097: 
1.81      www      7098: # -------------------------------------------------------------- Modify student
1.80      www      7099: 
1.81      www      7100: sub modifystudent {
                   7101:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7102:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7103:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7104:     if (!$cid) {
1.620     albertel 7105: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7106: 	    return 'not_in_class';
                   7107: 	}
1.80      www      7108:     }
                   7109: # --------------------------------------------------------------- Make the user
1.81      www      7110:     my $reply=&modifyuser
1.209     matthew  7111: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7112:          $desiredhome,$email,$inststatus);
1.80      www      7113:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7114:     # This will cause &modify_student_enrollment to get the uid from the
                   7115:     # students environment
                   7116:     $uid = undef if (!$forceid);
1.455     albertel 7117:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7118: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7119:     return $reply;
                   7120: }
                   7121: 
                   7122: sub modify_student_enrollment {
1.957     raeburn  7123:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7124:     my ($cdom,$cnum,$chome);
                   7125:     if (!$cid) {
1.620     albertel 7126: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7127: 	    return 'not_in_class';
                   7128: 	}
1.620     albertel 7129: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7130: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7131:     } else {
                   7132: 	($cdom,$cnum)=split(/_/,$cid);
                   7133:     }
1.620     albertel 7134:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7135:     if (!$chome) {
1.457     raeburn  7136: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7137:     }
1.455     albertel 7138:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7139:     # Make sure the user exists
1.81      www      7140:     my $uhome=&homeserver($uname,$udom);
                   7141:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7142: 	return 'error: no such user';
                   7143:     }
1.297     matthew  7144:     # Get student data if we were not given enough information
                   7145:     if (!defined($first)  || $first  eq '' || 
                   7146:         !defined($last)   || $last   eq '' || 
                   7147:         !defined($uid)    || $uid    eq '' || 
                   7148:         !defined($middle) || $middle eq '' || 
                   7149:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7150:         # They did not supply us with enough data to enroll the student, so
                   7151:         # we need to pick up more information.
1.297     matthew  7152:         my %tmp = &get('environment',
1.294     matthew  7153:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7154:                        ,$udom,$uname);
                   7155: 
1.800     albertel 7156:         #foreach my $key (keys(%tmp)) {
                   7157:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7158:         #}
1.294     matthew  7159:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7160:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7161:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7162:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7163:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7164:     }
1.556     albertel 7165:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7166:     my $reply=cput('classlist',
                   7167: 		   {"$uname:$udom" => 
1.515     raeburn  7168: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7169: 		   $cdom,$cnum);
1.81      www      7170:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7171: 	return 'error: '.$reply;
1.652     albertel 7172:     } else {
                   7173: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7174:     }
1.297     matthew  7175:     # Add student role to user
1.83      www      7176:     my $uurl='/'.$cid;
1.81      www      7177:     $uurl=~s/\_/\//g;
                   7178:     if ($usec) {
                   7179: 	$uurl.='/'.$usec;
                   7180:     }
1.957     raeburn  7181:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7182: }
                   7183: 
1.556     albertel 7184: sub format_name {
                   7185:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7186:     my $name;
                   7187:     if ($first ne 'lastname') {
                   7188: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7189:     } else {
                   7190: 	if ($lastname=~/\S/) {
                   7191: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7192: 	    $name=~s/\s+,/,/;
                   7193: 	} else {
                   7194: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7195: 	}
                   7196:     }
                   7197:     $name=~s/^\s+//;
                   7198:     $name=~s/\s+$//;
                   7199:     $name=~s/\s+/ /g;
                   7200:     return $name;
                   7201: }
                   7202: 
1.84      www      7203: # ------------------------------------------------- Write to course preferences
                   7204: 
                   7205: sub writecoursepref {
                   7206:     my ($courseid,%prefs)=@_;
                   7207:     $courseid=~s/^\///;
                   7208:     $courseid=~s/\_/\//g;
                   7209:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7210:     my $chome=homeserver($cnum,$cdomain);
                   7211:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7212: 	return 'error: no such course';
                   7213:     }
                   7214:     my $cstring='';
1.800     albertel 7215:     foreach my $pref (keys(%prefs)) {
                   7216: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7217:     }
1.84      www      7218:     $cstring=~s/\&$//;
                   7219:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7220: }
                   7221: 
                   7222: # ---------------------------------------------------------- Make/modify course
                   7223: 
                   7224: sub createcourse {
1.741     raeburn  7225:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7226:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7227:     $url=&declutter($url);
                   7228:     my $cid='';
1.1028    raeburn  7229:     if ($context eq 'requestcourses') {
                   7230:         my $can_create = 0;
                   7231:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7232:         if ($udom eq $ownerdom) {
                   7233:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7234:                                   $context)) {
                   7235:                 $can_create = 1;
                   7236:             }
                   7237:         } else {
                   7238:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7239:                                            $category);
                   7240:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7241:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7242:                 if (@curr > 0) {
                   7243:                     my @options = qw(approval validate autolimit);
                   7244:                     my $optregex = join('|',@options);
                   7245:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7246:                         $can_create = 1;
                   7247:                     }
                   7248:                 }
                   7249:             }
                   7250:         }
                   7251:         if ($can_create) {
                   7252:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7253:                 unless (&allowed('ccc',$udom)) {
                   7254:                     return 'refused'; 
                   7255:                 }
1.1017    raeburn  7256:             }
                   7257:         } else {
                   7258:             return 'refused';
                   7259:         }
1.1028    raeburn  7260:     } elsif (!&allowed('ccc',$udom)) {
                   7261:         return 'refused';
1.84      www      7262:     }
1.1011    raeburn  7263: # --------------------------------------------------------------- Get Unique ID
                   7264:     my $uname;
                   7265:     if ($cnum =~ /^$match_courseid$/) {
                   7266:         my $chome=&homeserver($cnum,$udom,'true');
                   7267:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7268:             $uname = $cnum;
                   7269:         } else {
1.1038    raeburn  7270:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7271:         }
                   7272:     } else {
1.1038    raeburn  7273:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7274:     }
                   7275:     return $uname if ($uname =~ /^error/);
                   7276: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7277:     if (!defined($course_server)) {
                   7278:         if (defined(&domain($udom,'primary'))) {
                   7279:             $course_server = &domain($udom,'primary');
                   7280:         } else {
                   7281:             $course_server = $env{'user.home'}; 
                   7282:         }
                   7283:     }
                   7284:     my %host_servers =
                   7285:         &Apache::lonnet::get_servers($udom,'library');
                   7286:     unless ($host_servers{$course_server}) {
                   7287:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7288:     }
1.84      www      7289: # ------------------------------------------------------------- Make the course
                   7290:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7291:                       $course_server);
1.84      www      7292:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7293:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7294:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7295: 	return 'error: no such course';
                   7296:     }
1.271     www      7297: # ----------------------------------------------------------------- Course made
1.516     raeburn  7298: # log existence
1.1029    raeburn  7299:     my $now = time;
1.918     raeburn  7300:     my $newcourse = {
                   7301:                     $udom.'_'.$uname => {
1.921     raeburn  7302:                                      description => $description,
                   7303:                                      inst_code   => $inst_code,
                   7304:                                      owner       => $course_owner,
                   7305:                                      type        => $crstype,
1.1029    raeburn  7306:                                      creator     => $env{'user.name'}.':'.
                   7307:                                                     $env{'user.domain'},
                   7308:                                      created     => $now,
                   7309:                                      context     => $context,
1.918     raeburn  7310:                                                 },
                   7311:                     };
1.921     raeburn  7312:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7313: # set toplevel url
1.271     www      7314:     my $topurl=$url;
                   7315:     unless ($nonstandard) {
                   7316: # ------------------------------------------ For standard courses, make top url
                   7317:         my $mapurl=&clutter($url);
1.278     www      7318:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7319:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7320: <map>
                   7321: <resource id="1" type="start"></resource>
                   7322: <resource id="2" src="$mapurl"></resource>
                   7323: <resource id="3" type="finish"></resource>
                   7324: <link index="1" from="1" to="2"></link>
                   7325: <link index="2" from="2" to="3"></link>
                   7326: </map>
                   7327: ENDINITMAP
                   7328:         $topurl=&declutter(
1.638     albertel 7329:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7330:                           );
                   7331:     }
                   7332: # ----------------------------------------------------------- Write preferences
1.84      www      7333:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7334:                      ('description'              => $description,
                   7335:                       'url'                      => $topurl,
                   7336:                       'internal.creator'         => $env{'user.name'}.':'.
                   7337:                                                     $env{'user.domain'},
                   7338:                       'internal.created'         => $now,
                   7339:                       'internal.creationcontext' => $context)
                   7340:                     );
1.84      www      7341:     return '/'.$udom.'/'.$uname;
                   7342: }
                   7343: 
1.1011    raeburn  7344: # ------------------------------------------------------------------- Create ID
                   7345: sub generate_coursenum {
1.1038    raeburn  7346:     my ($udom,$crstype) = @_;
1.1011    raeburn  7347:     my $domdesc = &domain($udom);
                   7348:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7349:     my $first;
                   7350:     if ($crstype eq 'Community') {
                   7351:         $first = '0';
                   7352:     } else {
                   7353:         $first = int(1+rand(9)); 
                   7354:     } 
                   7355:     my $uname=$first.
1.1011    raeburn  7356:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7357:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7358:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7359: # ----------------------------------------------- Make sure that does not exist
                   7360:     my $uhome=&homeserver($uname,$udom,'true');
                   7361:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7362:         if ($crstype eq 'Community') {
                   7363:             $first = '0';
                   7364:         } else {
                   7365:             $first = int(1+rand(9));
                   7366:         }
                   7367:         $uname=$first.
1.1011    raeburn  7368:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7369:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7370:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7371:         $uhome=&homeserver($uname,$udom,'true');
                   7372:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7373:             return 'error: unable to generate unique course-ID';
                   7374:         }
                   7375:     }
                   7376:     return $uname;
                   7377: }
                   7378: 
1.813     albertel 7379: sub is_course {
                   7380:     my ($cdom,$cnum) = @_;
                   7381:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7382: 				undef,'.');
1.813     albertel 7383:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7384:         return 1;
                   7385:     }
                   7386:     return 0;
                   7387: }
                   7388: 
1.1015    raeburn  7389: sub store_userdata {
                   7390:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7391:     my $result;
1.1016    raeburn  7392:     if ($datakey ne '') {
1.1013    raeburn  7393:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7394:             if ($udom eq '' || $uname eq '') {
                   7395:                 $udom = $env{'user.domain'};
                   7396:                 $uname = $env{'user.name'};
                   7397:             }
                   7398:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7399:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7400:                 $result = 'error: no_host';
                   7401:             } else {
                   7402:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7403:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7404: 
                   7405:                 my $namevalue='';
                   7406:                 foreach my $key (keys(%{$storehash})) {
                   7407:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7408:                 }
                   7409:                 $namevalue=~s/\&$//;
1.1056.4.37! raeburn  7410:                 unless ($namespace eq 'courserequests') {
        !          7411:                     $datakey = &escape($datakey);
        !          7412:                 }
1.1056.4.24  raeburn  7413:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7414:                                   $namevalue,$uhome);
1.1013    raeburn  7415:             }
                   7416:         } else {
                   7417:             $result = 'error: data to store was not a hash reference'; 
                   7418:         }
                   7419:     } else {
                   7420:         $result= 'error: invalid requestkey'; 
                   7421:     }
                   7422:     return $result;
                   7423: }
                   7424: 
1.21      www      7425: # ---------------------------------------------------------- Assign Custom Role
                   7426: 
                   7427: sub assigncustomrole {
1.957     raeburn  7428:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7429:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7430:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7431: }
                   7432: 
                   7433: # ----------------------------------------------------------------- Revoke Role
                   7434: 
                   7435: sub revokerole {
1.957     raeburn  7436:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7437:     my $now=time;
1.965     raeburn  7438:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7439: }
                   7440: 
                   7441: # ---------------------------------------------------------- Revoke Custom Role
                   7442: 
                   7443: sub revokecustomrole {
1.957     raeburn  7444:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7445:     my $now=time;
1.357     www      7446:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7447:            $deleteflag,$selfenroll,$context);
1.17      www      7448: }
                   7449: 
1.533     banghart 7450: # ------------------------------------------------------------ Disk usage
1.535     albertel 7451: sub diskusage {
1.955     raeburn  7452:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7453:     $directorypath =~ s/\/$//;
                   7454:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7455:                        .&escape($getpropath).':'.&escape($uname).':'
                   7456:                        .&escape($udom),homeserver($uname,$udom));
                   7457:     if ($listing eq 'unknown_cmd') {
                   7458:         if ($getpropath) {
                   7459:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7460:         }
                   7461:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7462:     }
1.514     albertel 7463:     return $listing;
1.512     banghart 7464: }
                   7465: 
1.566     banghart 7466: sub is_locked {
1.1056.4.17  raeburn  7467:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7468:     my @check;
                   7469:     my $is_locked;
1.1056.4.14  raeburn  7470:     push(@check,$file_name);
1.613     albertel 7471:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7472: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7473:     my ($tmp)=keys(%locked);
                   7474:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7475:     
1.566     banghart 7476:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7477:         $is_locked = 'false';
                   7478:         foreach my $entry (@{$locked{$file_name}}) {
1.1056.4.17  raeburn  7479:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7480:                $is_locked = 'true';
1.1056.4.17  raeburn  7481:                if (ref($which) eq 'ARRAY') {
                   7482:                    push(@{$which},$entry);
                   7483:                } else {
                   7484:                    last;
                   7485:                }
1.745     raeburn  7486:            }
                   7487:        }
1.566     banghart 7488:     } else {
                   7489:         $is_locked = 'false';
                   7490:     }
1.1056.4.14  raeburn  7491:     return $is_locked;
1.566     banghart 7492: }
                   7493: 
1.759     albertel 7494: sub declutter_portfile {
                   7495:     my ($file) = @_;
1.833     albertel 7496:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7497:     return $file;
                   7498: }
                   7499: 
1.559     banghart 7500: # ------------------------------------------------------------- Mark as Read Only
                   7501: 
                   7502: sub mark_as_readonly {
                   7503:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7504:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7505:     my ($tmp)=keys(%current_permissions);
                   7506:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7507:     foreach my $file (@{$files}) {
1.759     albertel 7508: 	$file = &declutter_portfile($file);
1.561     banghart 7509:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7510:     }
1.613     albertel 7511:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7512:     return;
                   7513: }
                   7514: 
1.572     banghart 7515: # ------------------------------------------------------------Save Selected Files
                   7516: 
                   7517: sub save_selected_files {
                   7518:     my ($user, $path, @files) = @_;
                   7519:     my $filename = $user."savedfiles";
1.573     banghart 7520:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7521:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7522:     foreach my $file (@files) {
1.620     albertel 7523:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7524:     }
                   7525:     foreach my $file (@other_files) {
1.574     banghart 7526:         print (OUT $file."\n");
1.572     banghart 7527:     }
1.574     banghart 7528:     close (OUT);
1.572     banghart 7529:     return 'ok';
                   7530: }
                   7531: 
1.574     banghart 7532: sub clear_selected_files {
                   7533:     my ($user) = @_;
                   7534:     my $filename = $user."savedfiles";
                   7535:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7536:     print (OUT undef);
                   7537:     close (OUT);
                   7538:     return ("ok");    
                   7539: }
                   7540: 
1.572     banghart 7541: sub files_in_path {
                   7542:     my ($user, $path) = @_;
                   7543:     my $filename = $user."savedfiles";
                   7544:     my %return_files;
1.574     banghart 7545:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7546:     while (my $line_in = <IN>) {
1.574     banghart 7547:         chomp ($line_in);
                   7548:         my @paths_and_file = split (m!/!, $line_in);
                   7549:         my $file_part = pop (@paths_and_file);
                   7550:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7551:         $path_part.='/';
                   7552:         my $path_and_file = $path_part.$file_part;
                   7553:         if ($path_part eq $path) {
                   7554:             $return_files{$file_part}= 'selected';
                   7555:         }
                   7556:     }
1.574     banghart 7557:     close (IN);
                   7558:     return (\%return_files);
1.572     banghart 7559: }
                   7560: 
                   7561: # called in portfolio select mode, to show files selected NOT in current directory
                   7562: sub files_not_in_path {
                   7563:     my ($user, $path) = @_;
                   7564:     my $filename = $user."savedfiles";
                   7565:     my @return_files;
                   7566:     my $path_part;
1.800     albertel 7567:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7568:     while (my $line = <IN>) {
1.572     banghart 7569:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7570:         my @paths_and_file = split(m|/|, $line);
                   7571:         my $file_part = pop(@paths_and_file);
                   7572:         chomp($file_part);
                   7573:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7574:         $path_part .= '/';
                   7575:         my $path_and_file = $path_part.$file_part;
                   7576:         if ($path_part ne $path) {
1.800     albertel 7577:             push(@return_files, ($path_and_file));
1.572     banghart 7578:         }
                   7579:     }
1.800     albertel 7580:     close(OUT);
1.574     banghart 7581:     return (@return_files);
1.572     banghart 7582: }
                   7583: 
1.745     raeburn  7584: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7585: 
1.745     raeburn  7586: sub get_portfile_permissions {
                   7587:     my ($domain,$user) = @_;
1.613     albertel 7588:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7589:     my ($tmp)=keys(%current_permissions);
                   7590:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7591:     return \%current_permissions;
                   7592: }
                   7593: 
                   7594: #---------------------------------------------Get portfolio file access controls
                   7595: 
1.749     raeburn  7596: sub get_access_controls {
1.745     raeburn  7597:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7598:     my %access;
                   7599:     my $real_file = $file;
                   7600:     $file =~ s/\.meta$//;
1.745     raeburn  7601:     if (defined($file)) {
1.749     raeburn  7602:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7603:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7604:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7605:             }
                   7606:         }
1.745     raeburn  7607:     } else {
1.749     raeburn  7608:         foreach my $key (keys(%{$current_permissions})) {
                   7609:             if ($key =~ /\0accesscontrol$/) {
                   7610:                 if (defined($group)) {
                   7611:                     if ($key !~ m-^\Q$group\E/-) {
                   7612:                         next;
                   7613:                     }
                   7614:                 }
                   7615:                 my ($fullpath) = split(/\0/,$key);
                   7616:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7617:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7618:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7619:                     }
                   7620:                 }
                   7621:             }
                   7622:         }
                   7623:     }
                   7624:     return %access;
                   7625: }
                   7626: 
                   7627: sub modify_access_controls {
                   7628:     my ($file_name,$changes,$domain,$user)=@_;
                   7629:     my ($outcome,$deloutcome);
                   7630:     my %store_permissions;
                   7631:     my %new_values;
                   7632:     my %new_control;
                   7633:     my %translation;
                   7634:     my @deletions = ();
                   7635:     my $now = time;
                   7636:     if (exists($$changes{'activate'})) {
                   7637:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7638:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7639:             my $numnew = scalar(@newitems);
                   7640:             for (my $i=0; $i<$numnew; $i++) {
                   7641:                 my $newkey = $newitems[$i];
                   7642:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7643:                 if ($newkey =~ /^\d+:/) { 
                   7644:                     $newkey =~ s/^(\d+)/$newid/;
                   7645:                     $translation{$1} = $newid;
                   7646:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7647:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7648:                     $translation{$1} = $newid;
                   7649:                 }
1.749     raeburn  7650:                 $new_values{$file_name."\0".$newkey} = 
                   7651:                                           $$changes{'activate'}{$newitems[$i]};
                   7652:                 $new_control{$newkey} = $now;
                   7653:             }
                   7654:         }
                   7655:     }
                   7656:     my %todelete;
                   7657:     my %changed_items;
                   7658:     foreach my $action ('delete','update') {
                   7659:         if (exists($$changes{$action})) {
                   7660:             if (ref($$changes{$action}) eq 'HASH') {
                   7661:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7662:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7663:                     if ($action eq 'delete') { 
                   7664:                         $todelete{$itemnum} = 1;
                   7665:                     } else {
                   7666:                         $changed_items{$itemnum} = $key;
                   7667:                     }
                   7668:                 }
1.745     raeburn  7669:             }
                   7670:         }
1.749     raeburn  7671:     }
                   7672:     # get lock on access controls for file.
                   7673:     my $lockhash = {
                   7674:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7675:                                                        ':'.$env{'user.domain'},
                   7676:                    }; 
                   7677:     my $tries = 0;
                   7678:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7679:    
                   7680:     while (($gotlock ne 'ok') && $tries <3) {
                   7681:         $tries ++;
                   7682:         sleep 1;
                   7683:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7684:     }
                   7685:     if ($gotlock eq 'ok') {
                   7686:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7687:         my ($tmp)=keys(%curr_permissions);
                   7688:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7689:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7690:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7691:             if (ref($curr_controls) eq 'HASH') {
                   7692:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7693:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7694:                     if (defined($todelete{$itemnum})) {
                   7695:                         push(@deletions,$file_name."\0".$control_item);
                   7696:                     } else {
                   7697:                         if (defined($changed_items{$itemnum})) {
                   7698:                             $new_control{$changed_items{$itemnum}} = $now;
                   7699:                             push(@deletions,$file_name."\0".$control_item);
                   7700:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7701:                         } else {
                   7702:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7703:                         }
                   7704:                     }
1.745     raeburn  7705:                 }
                   7706:             }
                   7707:         }
1.970     raeburn  7708:         my ($group);
                   7709:         if (&is_course($domain,$user)) {
                   7710:             ($group,my $file) = split(/\//,$file_name,2);
                   7711:         }
1.749     raeburn  7712:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7713:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7714:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7715:         #  remove lock
                   7716:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7717:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7718:         my $sqlresult =
1.970     raeburn  7719:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7720:                                     $group);
1.749     raeburn  7721:     } else {
                   7722:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7723:     }
1.749     raeburn  7724:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7725: }
                   7726: 
1.827     raeburn  7727: sub make_public_indefinitely {
                   7728:     my ($requrl) = @_;
                   7729:     my $now = time;
                   7730:     my $action = 'activate';
                   7731:     my $aclnum = 0;
                   7732:     if (&is_portfolio_url($requrl)) {
                   7733:         my (undef,$udom,$unum,$file_name,$group) =
                   7734:             &parse_portfolio_url($requrl);
                   7735:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7736:         my %access_controls = &get_access_controls($current_perms,
                   7737:                                                    $group,$file_name);
                   7738:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7739:             my ($num,$scope,$end,$start) = 
                   7740:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7741:             if ($scope eq 'public') {
                   7742:                 if ($start <= $now && $end == 0) {
                   7743:                     $action = 'none';
                   7744:                 } else {
                   7745:                     $action = 'update';
                   7746:                     $aclnum = $num;
                   7747:                 }
                   7748:                 last;
                   7749:             }
                   7750:         }
                   7751:         if ($action eq 'none') {
                   7752:              return 'ok';
                   7753:         } else {
                   7754:             my %changes;
                   7755:             my $newend = 0;
                   7756:             my $newstart = $now;
                   7757:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7758:             $changes{$action}{$newkey} = {
                   7759:                 type => 'public',
                   7760:                 time => {
                   7761:                     start => $newstart,
                   7762:                     end   => $newend,
                   7763:                 },
                   7764:             };
                   7765:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7766:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7767:             return $outcome;
                   7768:         }
                   7769:     } else {
                   7770:         return 'invalid';
                   7771:     }
                   7772: }
                   7773: 
1.745     raeburn  7774: #------------------------------------------------------Get Marked as Read Only
                   7775: 
                   7776: sub get_marked_as_readonly {
                   7777:     my ($domain,$user,$what,$group) = @_;
                   7778:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7779:     my @readonly_files;
1.629     banghart 7780:     my $cmp1=$what;
                   7781:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7782:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7783:         if (defined($group)) {
                   7784:             if ($file_name !~ m-^\Q$group\E/-) {
                   7785:                 next;
                   7786:             }
                   7787:         }
1.561     banghart 7788:         if (ref($value) eq "ARRAY"){
                   7789:             foreach my $stored_what (@{$value}) {
1.629     banghart 7790:                 my $cmp2=$stored_what;
1.759     albertel 7791:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7792:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7793:                 }
1.629     banghart 7794:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7795:                     push(@readonly_files, $file_name);
1.745     raeburn  7796:                     last;
1.563     banghart 7797:                 } elsif (!defined($what)) {
                   7798:                     push(@readonly_files, $file_name);
1.745     raeburn  7799:                     last;
1.561     banghart 7800:                 }
                   7801:             }
1.745     raeburn  7802:         }
1.561     banghart 7803:     }
                   7804:     return @readonly_files;
                   7805: }
1.577     banghart 7806: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7807: 
1.577     banghart 7808: sub get_marked_as_readonly_hash {
1.745     raeburn  7809:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7810:     my %readonly_files;
1.745     raeburn  7811:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7812:         if (defined($group)) {
                   7813:             if ($file_name !~ m-^\Q$group\E/-) {
                   7814:                 next;
                   7815:             }
                   7816:         }
1.577     banghart 7817:         if (ref($value) eq "ARRAY"){
                   7818:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7819:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7820:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7821:                         if ($lock_descriptor eq 'graded') {
                   7822:                             $readonly_files{$file_name} = 'graded';
                   7823:                         } elsif ($lock_descriptor eq 'handback') {
                   7824:                             $readonly_files{$file_name} = 'handback';
                   7825:                         } else {
                   7826:                             if (!exists($readonly_files{$file_name})) {
                   7827:                                 $readonly_files{$file_name} = 'locked';
                   7828:                             }
                   7829:                         }
1.745     raeburn  7830:                     }
1.750     banghart 7831:                 } 
1.577     banghart 7832:             }
                   7833:         } 
                   7834:     }
                   7835:     return %readonly_files;
                   7836: }
1.559     banghart 7837: # ------------------------------------------------------------ Unmark as Read Only
                   7838: 
                   7839: sub unmark_as_readonly {
1.629     banghart 7840:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7841:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7842:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7843:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7844:     my $symb_crs = $what;
                   7845:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7846:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7847:     my ($tmp)=keys(%current_permissions);
                   7848:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7849:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7850:     foreach my $file (@readonly_files) {
1.759     albertel 7851: 	my $clean_file = &declutter_portfile($file);
                   7852: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7853: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7854:         my @new_locks;
                   7855:         my @del_keys;
                   7856:         if (ref($current_locks) eq "ARRAY"){
                   7857:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7858:                 my $compare=$locker;
1.749     raeburn  7859:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7860:                     $compare=join('',@{$locker});
1.746     raeburn  7861:                     if ($compare ne $symb_crs) {
                   7862:                         push(@new_locks, $locker);
                   7863:                     }
1.563     banghart 7864:                 }
                   7865:             }
1.650     albertel 7866:             if (scalar(@new_locks) > 0) {
1.563     banghart 7867:                 $current_permissions{$file} = \@new_locks;
                   7868:             } else {
                   7869:                 push(@del_keys, $file);
1.613     albertel 7870:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7871:                 delete($current_permissions{$file});
1.563     banghart 7872:             }
                   7873:         }
1.561     banghart 7874:     }
1.613     albertel 7875:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7876:     return;
                   7877: }
1.512     banghart 7878: 
1.17      www      7879: # ------------------------------------------------------------ Directory lister
                   7880: 
                   7881: sub dirlist {
1.955     raeburn  7882:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7883:     $uri=~s/^\///;
                   7884:     $uri=~s/\/$//;
1.253     stredwic 7885:     my ($udom, $uname);
1.955     raeburn  7886:     if ($getuserdir) {
1.253     stredwic 7887:         $udom = $userdomain;
                   7888:         $uname = $username;
1.955     raeburn  7889:     } else {
                   7890:         (undef,$udom,$uname)=split(/\//,$uri);
                   7891:         if(defined($userdomain)) {
                   7892:             $udom = $userdomain;
                   7893:         }
                   7894:         if(defined($username)) {
                   7895:             $uname = $username;
                   7896:         }
1.253     stredwic 7897:     }
1.955     raeburn  7898:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7899: 
1.955     raeburn  7900:     $dirRoot = $perlvar{'lonDocRoot'};
                   7901:     if (defined($getpropath)) {
                   7902:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7903:         $dirRoot =~ s/\/$//;
1.955     raeburn  7904:     } elsif (defined($getuserdir)) {
                   7905:         my $subdir=$uname.'__';
                   7906:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7907:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7908:                    ."/$udom/$subdir/$uname";
                   7909:     } elsif (defined($alternateRoot)) {
                   7910:         $dirRoot = $alternateRoot;
1.751     banghart 7911:     }
1.253     stredwic 7912: 
                   7913:     if($udom) {
                   7914:         if($uname) {
1.955     raeburn  7915:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7916:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7917:                               .':'.&escape($uname).':'.&escape($udom),
                   7918:                               &homeserver($uname,$udom));
                   7919:             if ($listing eq 'unknown_cmd') {
                   7920:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7921:                                   &homeserver($uname,$udom));
                   7922:             } else {
                   7923:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7924:             }
1.605     matthew  7925:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7926:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7927: 				  &homeserver($uname,$udom));
1.605     matthew  7928:                 @listing_results = split(/:/,$listing);
                   7929:             } else {
                   7930:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7931:             }
                   7932:             return @listing_results;
1.955     raeburn  7933:         } elsif(!$alternateRoot) {
1.800     albertel 7934:             my %allusers;
1.841     albertel 7935: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7936:  	    foreach my $tryserver (keys(%servers)) {
                   7937:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7938:                                   &escape($udom),$tryserver);
                   7939:                 if ($listing eq 'unknown_cmd') {
                   7940: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7941: 				      $udom, $tryserver);
                   7942:                 } else {
                   7943:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7944:                 }
1.841     albertel 7945: 		if ($listing eq 'unknown_cmd') {
                   7946: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7947: 				      $udom, $tryserver);
                   7948: 		    @listing_results = split(/:/,$listing);
                   7949: 		} else {
                   7950: 		    @listing_results =
                   7951: 			map { &unescape($_); } split(/:/,$listing);
                   7952: 		}
                   7953: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7954: 		    $listing_results[0] ne 'empty'       &&
                   7955: 		    $listing_results[0] ne 'con_lost') {
                   7956: 		    foreach my $line (@listing_results) {
                   7957: 			my ($entry) = split(/&/,$line,2);
                   7958: 			$allusers{$entry} = 1;
                   7959: 		    }
                   7960: 		}
1.253     stredwic 7961:             }
                   7962:             my $alluserstr='';
1.800     albertel 7963:             foreach my $user (sort(keys(%allusers))) {
                   7964:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7965:             }
                   7966:             $alluserstr=~s/:$//;
                   7967:             return split(/:/,$alluserstr);
                   7968:         } else {
1.800     albertel 7969:             return ('missing user name');
1.253     stredwic 7970:         }
1.955     raeburn  7971:     } elsif(!defined($getpropath)) {
1.841     albertel 7972:         my @all_domains = sort(&all_domains());
1.955     raeburn  7973:         foreach my $domain (@all_domains) {
                   7974:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7975:         }
                   7976:         return @all_domains;
                   7977:     } else {
1.800     albertel 7978:         return ('missing domain');
1.275     stredwic 7979:     }
                   7980: }
                   7981: 
                   7982: # --------------------------------------------- GetFileTimestamp
                   7983: # This function utilizes dirlist and returns the date stamp for
                   7984: # when it was last modified.  It will also return an error of -1
                   7985: # if an error occurs
                   7986: 
                   7987: sub GetFileTimestamp {
1.955     raeburn  7988:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7989:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7990:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7991:     my ($fileStat) = 
                   7992:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7993:                                  undef,$getuserdir);
1.275     stredwic 7994:     my @stats = split('&', $fileStat);
                   7995:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7996:         # @stats contains first the filename, then the stat output
                   7997:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7998:     } else {
                   7999:         return -1;
1.253     stredwic 8000:     }
1.26      www      8001: }
                   8002: 
1.712     albertel 8003: sub stat_file {
                   8004:     my ($uri) = @_;
1.787     albertel 8005:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8006: 
1.955     raeburn  8007:     my ($udom,$uname,$file);
1.712     albertel 8008:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8009: 	($udom,$uname,$file) =
1.811     albertel 8010: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8011: 	$file = 'userfiles/'.$file;
                   8012:     }
                   8013:     if ($uri =~ m-^/res/-) {
                   8014: 	($udom,$uname) = 
1.807     albertel 8015: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8016: 	$file = $uri;
                   8017:     }
                   8018: 
                   8019:     if (!$udom || !$uname || !$file) {
                   8020: 	# unable to handle the uri
                   8021: 	return ();
                   8022:     }
1.956     raeburn  8023:     my $getpropath;
                   8024:     if ($file =~ /^userfiles\//) {
                   8025:         $getpropath = 1;
                   8026:     }
1.955     raeburn  8027:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 8028:     my @stats = split('&', $result);
1.721     banghart 8029:     
1.712     albertel 8030:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   8031: 	shift(@stats); #filename is first
                   8032: 	return @stats;
                   8033:     }
                   8034:     return ();
                   8035: }
                   8036: 
1.26      www      8037: # -------------------------------------------------------- Value of a Condition
                   8038: 
1.713     albertel 8039: # gets the value of a specific preevaluated condition
                   8040: #    stored in the string  $env{user.state.<cid>}
                   8041: # or looks up a condition reference in the bighash and if if hasn't
                   8042: # already been evaluated recurses into docondval to get the value of
                   8043: # the condition, then memoizing it to 
                   8044: #   $env{user.state.<cid>.<condition>}
1.40      www      8045: sub directcondval {
                   8046:     my $number=shift;
1.620     albertel 8047:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8048: 	&Apache::lonuserstate::evalstate();
                   8049:     }
1.713     albertel 8050:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8051: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8052:     } elsif ($number =~ /^_/) {
                   8053: 	my $sub_condition;
                   8054: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8055: 		&GDBM_READER(),0640)) {
                   8056: 	    $sub_condition=$bighash{'conditions'.$number};
                   8057: 	    untie(%bighash);
                   8058: 	}
                   8059: 	my $value = &docondval($sub_condition);
1.949     raeburn  8060: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8061: 	return $value;
                   8062:     }
1.620     albertel 8063:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8064:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8065:     } else {
                   8066:        return 2;
                   8067:     }
                   8068: }
                   8069: 
1.713     albertel 8070: # get the collection of conditions for this resource
1.26      www      8071: sub condval {
                   8072:     my $condidx=shift;
1.54      www      8073:     my $allpathcond='';
1.713     albertel 8074:     foreach my $cond (split(/\|/,$condidx)) {
                   8075: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8076: 	    $allpathcond.=
                   8077: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8078: 	}
1.191     harris41 8079:     }
1.54      www      8080:     $allpathcond=~s/\|$//;
1.713     albertel 8081:     return &docondval($allpathcond);
                   8082: }
                   8083: 
                   8084: #evaluates an expression of conditions
                   8085: sub docondval {
                   8086:     my ($allpathcond) = @_;
                   8087:     my $result=0;
                   8088:     if ($env{'request.course.id'}
                   8089: 	&& defined($allpathcond)) {
                   8090: 	my $operand='|';
                   8091: 	my @stack;
                   8092: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8093: 	    if ($chunk eq '(') {
                   8094: 		push @stack,($operand,$result);
                   8095: 	    } elsif ($chunk eq ')') {
                   8096: 		my $before=pop @stack;
                   8097: 		if (pop @stack eq '&') {
                   8098: 		    $result=$result>$before?$before:$result;
                   8099: 		} else {
                   8100: 		    $result=$result>$before?$result:$before;
                   8101: 		}
                   8102: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8103: 		$operand=$chunk;
                   8104: 	    } else {
                   8105: 		my $new=directcondval($chunk);
                   8106: 		if ($operand eq '&') {
                   8107: 		    $result=$result>$new?$new:$result;
                   8108: 		} else {
                   8109: 		    $result=$result>$new?$result:$new;
                   8110: 		}
                   8111: 	    }
                   8112: 	}
1.26      www      8113:     }
                   8114:     return $result;
1.421     albertel 8115: }
                   8116: 
                   8117: # ---------------------------------------------------- Devalidate courseresdata
                   8118: 
                   8119: sub devalidatecourseresdata {
                   8120:     my ($coursenum,$coursedomain)=@_;
                   8121:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8122:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8123: }
                   8124: 
1.763     www      8125: 
1.200     www      8126: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8127: #
                   8128: #  Parameters:
                   8129: #      $coursenum    - Number of the course.
                   8130: #      $coursedomain - Domain at which the course was created.
                   8131: #  Returns:
                   8132: #     A hash of the course parameters along (I think) with timestamps
                   8133: #     and version info.
1.877     foxr     8134: 
1.624     albertel 8135: sub get_courseresdata {
                   8136:     my ($coursenum,$coursedomain)=@_;
1.200     www      8137:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8138:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8139:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8140:     my %dumpreply;
1.417     albertel 8141:     unless (defined($cached)) {
1.624     albertel 8142: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8143: 	$result=\%dumpreply;
1.251     albertel 8144: 	my ($tmp) = keys(%dumpreply);
                   8145: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8146: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8147: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8148: 	    return $tmp;
1.416     albertel 8149: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8150: 	    $result=undef;
1.599     albertel 8151: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8152: 	}
                   8153:     }
1.624     albertel 8154:     return $result;
                   8155: }
                   8156: 
1.633     albertel 8157: sub devalidateuserresdata {
                   8158:     my ($uname,$udom)=@_;
                   8159:     my $hashid="$udom:$uname";
                   8160:     &devalidate_cache_new('userres',$hashid);
                   8161: }
                   8162: 
1.624     albertel 8163: sub get_userresdata {
                   8164:     my ($uname,$udom)=@_;
                   8165:     #most student don\'t have any data set, check if there is some data
                   8166:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8167: 
                   8168:     my $hashid="$udom:$uname";
                   8169:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8170:     if (!defined($cached)) {
                   8171: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8172: 	$result=\%resourcedata;
                   8173: 	&do_cache_new('userres',$hashid,$result,600);
                   8174:     }
                   8175:     my ($tmp)=keys(%$result);
                   8176:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8177: 	return $result;
                   8178:     }
                   8179:     #error 2 occurs when the .db doesn't exist
                   8180:     if ($tmp!~/error: 2 /) {
1.672     albertel 8181: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8182: 		 " Trying to get resource data for ".
                   8183: 		 $uname." at ".$udom.": ".
                   8184: 		 $tmp."</font>");
                   8185:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8186: 	#&EXT_cache_set($udom,$uname);
                   8187: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8188: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8189:     }
                   8190:     return $tmp;
                   8191: }
1.879     foxr     8192: #----------------------------------------------- resdata - return resource data
                   8193: #  Purpose:
                   8194: #    Return resource data for either users or for a course.
                   8195: #  Parameters:
                   8196: #     $name      - Course/user name.
                   8197: #     $domain    - Name of the domain the user/course is registered on.
                   8198: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8199: #     @which     - Array of names of resources desired.
                   8200: #  Returns:
                   8201: #     The value of the first reasource in @which that is found in the
                   8202: #     resource hash.
                   8203: #  Exceptional Conditions:
                   8204: #     If the $type passed in is not valid (not the string 'course' or 
                   8205: #     'user', an undefined  reference is returned.
                   8206: #     If none of the resources are found, an undef is returned
1.624     albertel 8207: sub resdata {
                   8208:     my ($name,$domain,$type,@which)=@_;
                   8209:     my $result;
                   8210:     if ($type eq 'course') {
                   8211: 	$result=&get_courseresdata($name,$domain);
                   8212:     } elsif ($type eq 'user') {
                   8213: 	$result=&get_userresdata($name,$domain);
                   8214:     }
                   8215:     if (!ref($result)) { return $result; }    
1.251     albertel 8216:     foreach my $item (@which) {
1.927     albertel 8217: 	if (defined($result->{$item->[0]})) {
                   8218: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8219: 	}
1.250     albertel 8220:     }
1.291     albertel 8221:     return undef;
1.200     www      8222: }
                   8223: 
1.379     matthew  8224: #
                   8225: # EXT resource caching routines
                   8226: #
                   8227: 
                   8228: sub clear_EXT_cache_status {
1.383     albertel 8229:     &delenv('cache.EXT.');
1.379     matthew  8230: }
                   8231: 
                   8232: sub EXT_cache_status {
                   8233:     my ($target_domain,$target_user) = @_;
1.383     albertel 8234:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8235:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8236:         # We know already the user has no data
                   8237:         return 1;
                   8238:     } else {
                   8239:         return 0;
                   8240:     }
                   8241: }
                   8242: 
                   8243: sub EXT_cache_set {
                   8244:     my ($target_domain,$target_user) = @_;
1.383     albertel 8245:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8246:     #&appenv({$cachename => time});
1.379     matthew  8247: }
                   8248: 
1.28      www      8249: # --------------------------------------------------------- Value of a Variable
1.58      www      8250: sub EXT {
1.715     albertel 8251: 
1.395     albertel 8252:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8253:     unless ($varname) { return ''; }
1.218     albertel 8254:     #get real user name/domain, courseid and symb
                   8255:     my $courseid;
1.359     albertel 8256:     my $publicuser;
1.427     www      8257:     if ($symbparm) {
                   8258: 	$symbparm=&get_symb_from_alias($symbparm);
                   8259:     }
1.218     albertel 8260:     if (!($uname && $udom)) {
1.790     albertel 8261:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8262:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8263:     } else {
1.620     albertel 8264: 	$courseid=$env{'request.course.id'};
1.218     albertel 8265:     }
1.48      www      8266:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8267:     my $rest;
1.320     albertel 8268:     if (defined($therest[0])) {
1.48      www      8269:        $rest=join('.',@therest);
                   8270:     } else {
                   8271:        $rest='';
                   8272:     }
1.320     albertel 8273: 
1.57      www      8274:     my $qualifierrest=$qualifier;
                   8275:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8276:     my $spacequalifierrest=$space;
                   8277:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8278:     if ($realm eq 'user') {
1.48      www      8279: # --------------------------------------------------------------- user.resource
                   8280: 	if ($space eq 'resource') {
1.651     albertel 8281: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8282: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8283: 		 &&
1.744     albertel 8284: 		 ($symbparm eq &symbread()) ) {	
                   8285: 		# if we are in the middle of processing the resource the
                   8286: 		# get the value we are planning on committing
                   8287:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8288:                     return $Apache::lonhomework::results{$qualifierrest};
                   8289:                 } else {
                   8290:                     return $Apache::lonhomework::history{$qualifierrest};
                   8291:                 }
1.335     albertel 8292: 	    } else {
1.359     albertel 8293: 		my %restored;
1.620     albertel 8294: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8295: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8296: 		} else {
                   8297: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8298: 		}
1.335     albertel 8299: 		return $restored{$qualifierrest};
                   8300: 	    }
1.48      www      8301: # ----------------------------------------------------------------- user.access
                   8302:         } elsif ($space eq 'access') {
1.218     albertel 8303: 	    # FIXME - not supporting calls for a specific user
1.48      www      8304:             return &allowed($qualifier,$rest);
                   8305: # ------------------------------------------ user.preferences, user.environment
                   8306:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8307: 	    if (($uname eq $env{'user.name'}) &&
                   8308: 		($udom eq $env{'user.domain'})) {
                   8309: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8310: 	    } else {
1.359     albertel 8311: 		my %returnhash;
                   8312: 		if (!$publicuser) {
                   8313: 		    %returnhash=&userenvironment($udom,$uname,
                   8314: 						 $qualifierrest);
                   8315: 		}
1.218     albertel 8316: 		return $returnhash{$qualifierrest};
                   8317: 	    }
1.48      www      8318: # ----------------------------------------------------------------- user.course
                   8319:         } elsif ($space eq 'course') {
1.218     albertel 8320: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8321:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8322: # ------------------------------------------------------------------- user.role
                   8323:         } elsif ($space eq 'role') {
1.218     albertel 8324: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8325:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8326:             if ($qualifier eq 'value') {
                   8327: 		return $role;
                   8328:             } elsif ($qualifier eq 'extent') {
                   8329:                 return $where;
                   8330:             }
                   8331: # ----------------------------------------------------------------- user.domain
                   8332:         } elsif ($space eq 'domain') {
1.218     albertel 8333:             return $udom;
1.48      www      8334: # ------------------------------------------------------------------- user.name
                   8335:         } elsif ($space eq 'name') {
1.218     albertel 8336:             return $uname;
1.48      www      8337: # ---------------------------------------------------- Any other user namespace
1.29      www      8338:         } else {
1.359     albertel 8339: 	    my %reply;
                   8340: 	    if (!$publicuser) {
                   8341: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8342: 	    }
                   8343: 	    return $reply{$qualifierrest};
1.48      www      8344:         }
1.236     www      8345:     } elsif ($realm eq 'query') {
                   8346: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8347:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8348: 						[$spacequalifierrest]);
1.620     albertel 8349: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8350:    } elsif ($realm eq 'request') {
1.48      www      8351: # ------------------------------------------------------------- request.browser
                   8352:         if ($space eq 'browser') {
1.430     www      8353: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8354: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8355: 		    return 1;
                   8356: 		} else {
                   8357: 		    return 0;
                   8358: 		}
                   8359: 	    } else {
1.620     albertel 8360: 		return $env{'browser.'.$qualifier};
1.430     www      8361: 	    }
1.57      www      8362: # ------------------------------------------------------------ request.filename
                   8363:         } else {
1.620     albertel 8364:             return $env{'request.'.$spacequalifierrest};
1.29      www      8365:         }
1.28      www      8366:     } elsif ($realm eq 'course') {
1.48      www      8367: # ---------------------------------------------------------- course.description
1.620     albertel 8368:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8369:     } elsif ($realm eq 'resource') {
1.165     www      8370: 
1.620     albertel 8371: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8372: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8373: 	}
1.693     albertel 8374: 
                   8375: 	if ($space eq 'title') {
                   8376: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8377: 	    return &gettitle($symbparm);
                   8378: 	}
                   8379: 	
                   8380: 	if ($space eq 'map') {
                   8381: 	    my ($map) = &decode_symb($symbparm);
                   8382: 	    return &symbread($map);
                   8383: 	}
1.905     albertel 8384: 	if ($space eq 'filename') {
                   8385: 	    if ($symbparm) {
                   8386: 		return &clutter((&decode_symb($symbparm))[2]);
                   8387: 	    }
                   8388: 	    return &hreflocation('',$env{'request.filename'});
                   8389: 	}
1.693     albertel 8390: 
                   8391: 	my ($section, $group, @groups);
1.593     albertel 8392: 	my ($courselevelm,$courselevel);
1.539     albertel 8393: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8394: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8395: 
1.218     albertel 8396: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8397: 
1.60      www      8398: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8399: 	    my $symbp=$symbparm;
1.735     albertel 8400: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8401: 
                   8402: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8403: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8404: 
1.620     albertel 8405: 	    if (($env{'user.name'} eq $uname) &&
                   8406: 		($env{'user.domain'} eq $udom)) {
                   8407: 		$section=$env{'request.course.sec'};
1.733     raeburn  8408:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8409:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8410: 	    } else {
1.539     albertel 8411: 		if (! defined($usection)) {
1.551     albertel 8412: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8413: 		} else {
                   8414: 		    $section = $usection;
                   8415: 		}
1.733     raeburn  8416:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8417: 	    }
                   8418: 
                   8419: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8420: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8421: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8422: 
1.593     albertel 8423: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8424: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8425: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8426: 
1.60      www      8427: # ----------------------------------------------------------- first, check user
1.624     albertel 8428: 
                   8429: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8430: 				       ([$courselevelr,'resource'],
                   8431: 					[$courselevelm,'map'     ],
                   8432: 					[$courselevel, 'course'  ]));
1.931     albertel 8433: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8434: 
1.594     albertel 8435: # ------------------------------------------------ second, check some of course
1.684     raeburn  8436:             my $coursereply;
1.691     raeburn  8437:             if (@groups > 0) {
                   8438:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8439:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8440:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8441:             }
1.96      www      8442: 
1.684     raeburn  8443: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8444: 				  $env{'course.'.$courseid.'.domain'},
                   8445: 				  'course',
                   8446: 				  ([$seclevelr,   'resource'],
                   8447: 				   [$seclevelm,   'map'     ],
                   8448: 				   [$seclevel,    'course'  ],
                   8449: 				   [$courselevelr,'resource']));
                   8450: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8451: 
1.60      www      8452: # ------------------------------------------------------ third, check map parms
1.218     albertel 8453: 	    my %parmhash=();
                   8454: 	    my $thisparm='';
                   8455: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8456: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8457: 		    &GDBM_READER(),0640)) {
1.218     albertel 8458: 		$thisparm=$parmhash{$symbparm};
                   8459: 		untie(%parmhash);
                   8460: 	    }
1.927     albertel 8461: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8462: 	}
1.594     albertel 8463: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8464: 
1.218     albertel 8465: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8466: 	my $filename;
                   8467: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8468: 	if ($symbparm) {
1.409     www      8469: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8470: 	} else {
1.620     albertel 8471: 	    $filename=$env{'request.filename'};
1.282     albertel 8472: 	}
                   8473: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8474: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8475: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8476: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8477: 
1.927     albertel 8478: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8479: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8480: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8481: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8482: 				     $env{'course.'.$courseid.'.domain'},
                   8483: 				     'course',
1.927     albertel 8484: 				     ([$courselevelm,'map'   ],
                   8485: 				      [$courselevel, 'course']));
                   8486: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8487: 	}
1.145     www      8488: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8489: 	unless ($space eq '0') {
1.336     albertel 8490: 	    my @parts=split(/_/,$space);
                   8491: 	    my $id=pop(@parts);
                   8492: 	    my $part=join('_',@parts);
                   8493: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8494: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8495: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8496: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8497: 	}
1.395     albertel 8498: 	if ($recurse) { return undef; }
                   8499: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8500: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8501: # ---------------------------------------------------- Any other user namespace
                   8502:     } elsif ($realm eq 'environment') {
                   8503: # ----------------------------------------------------------------- environment
1.620     albertel 8504: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8505: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8506: 	} else {
1.770     albertel 8507: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8508: 		return '';
                   8509: 	    }
1.219     albertel 8510: 	    my %returnhash=&userenvironment($udom,$uname,
                   8511: 					    $spacequalifierrest);
                   8512: 	    return $returnhash{$spacequalifierrest};
                   8513: 	}
1.28      www      8514:     } elsif ($realm eq 'system') {
1.48      www      8515: # ----------------------------------------------------------------- system.time
                   8516: 	if ($space eq 'time') {
                   8517: 	    return time;
                   8518:         }
1.696     albertel 8519:     } elsif ($realm eq 'server') {
                   8520: # ----------------------------------------------------------------- system.time
                   8521: 	if ($space eq 'name') {
                   8522: 	    return $ENV{'SERVER_NAME'};
                   8523:         }
1.28      www      8524:     }
1.48      www      8525:     return '';
1.61      www      8526: }
                   8527: 
1.927     albertel 8528: sub get_reply {
                   8529:     my ($reply_value) = @_;
1.940     raeburn  8530:     if (ref($reply_value) eq 'ARRAY') {
                   8531:         if (wantarray) {
                   8532: 	    return @$reply_value;
                   8533:         }
                   8534:         return $reply_value->[0];
                   8535:     } else {
                   8536:         return $reply_value;
1.927     albertel 8537:     }
                   8538: }
                   8539: 
1.691     raeburn  8540: sub check_group_parms {
                   8541:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8542:     my @groupitems = ();
                   8543:     my $resultitem;
1.927     albertel 8544:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8545:     foreach my $group (@{$groups}) {
                   8546:         foreach my $level (@levels) {
1.927     albertel 8547:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8548:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8549:         }
                   8550:     }
                   8551:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8552:                             $env{'course.'.$courseid.'.domain'},
                   8553:                                      'course',@groupitems);
                   8554:     return $coursereply;
                   8555: }
                   8556: 
                   8557: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8558:     my ($courseid,@groups) = @_;
                   8559:     @groups = sort(@groups);
1.691     raeburn  8560:     return @groups;
                   8561: }
                   8562: 
1.395     albertel 8563: sub packages_tab_default {
                   8564:     my ($uri,$varname)=@_;
                   8565:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8566: 
                   8567:     my (@extension,@specifics,$do_default);
                   8568:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8569: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8570: 	if ($pack_type eq 'default') {
                   8571: 	    $do_default=1;
                   8572: 	} elsif ($pack_type eq 'extension') {
                   8573: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8574: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8575: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8576: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8577: 	}
                   8578:     }
                   8579:     # first look for a package that matches the requested part id
                   8580:     foreach my $package (@specifics) {
                   8581: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8582: 	next if ($pack_part ne $part);
                   8583: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8584: 	    return $packagetab{"$pack_type&$name&default"};
                   8585: 	}
                   8586:     }
                   8587:     # look for any possible matching non extension_ package
                   8588:     foreach my $package (@specifics) {
                   8589: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8590: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8591: 	    return $packagetab{"$pack_type&$name&default"};
                   8592: 	}
1.585     albertel 8593: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8594: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8595: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8596: 	}
                   8597:     }
1.738     albertel 8598:     # look for any posible extension_ match
                   8599:     foreach my $package (@extension) {
                   8600: 	my ($package,$pack_type)=@{$package};
                   8601: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8602: 	    return $packagetab{"$pack_type&$name&default"};
                   8603: 	}
                   8604: 	if (defined($packagetab{$package."&$name&default"})) {
                   8605: 	    return $packagetab{$package."&$name&default"};
                   8606: 	}
                   8607:     }
                   8608:     # look for a global default setting
                   8609:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8610: 	return $packagetab{"default&$name&default"};
                   8611:     }
1.395     albertel 8612:     return undef;
                   8613: }
                   8614: 
1.334     albertel 8615: sub add_prefix_and_part {
                   8616:     my ($prefix,$part)=@_;
                   8617:     my $keyroot;
                   8618:     if (defined($prefix) && $prefix !~ /^__/) {
                   8619: 	# prefix that has a part already
                   8620: 	$keyroot=$prefix;
                   8621:     } elsif (defined($prefix)) {
                   8622: 	# prefix that is missing a part
                   8623: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8624:     } else {
                   8625: 	# no prefix at all
                   8626: 	if (defined($part)) { $keyroot='_'.$part; }
                   8627:     }
                   8628:     return $keyroot;
                   8629: }
                   8630: 
1.71      www      8631: # ---------------------------------------------------------------- Get metadata
                   8632: 
1.599     albertel 8633: my %metaentry;
1.71      www      8634: sub metadata {
1.176     www      8635:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8636:     $uri=&declutter($uri);
1.288     albertel 8637:     # if it is a non metadata possible uri return quickly
1.529     albertel 8638:     if (($uri eq '') || 
                   8639: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8640: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.26  raeburn  8641:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8642: 	return undef;
                   8643:     }
                   8644:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8645: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8646: 	return undef;
1.288     albertel 8647:     }
1.73      www      8648:     my $filename=$uri;
                   8649:     $uri=~s/\.meta$//;
1.172     www      8650: #
                   8651: # Is the metadata already cached?
1.177     www      8652: # Look at timestamp of caching
1.172     www      8653: # Everything is cached by the main uri, libraries are never directly cached
                   8654: #
1.428     albertel 8655:     if (!defined($liburi)) {
1.599     albertel 8656: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8657: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8658:     }
                   8659:     {
1.172     www      8660: #
                   8661: # Is this a recursive call for a library?
                   8662: #
1.599     albertel 8663: #	if (! exists($metacache{$uri})) {
                   8664: #	    $metacache{$uri}={};
                   8665: #	}
1.924     albertel 8666: 	my $cachetime = 60*60;
1.171     www      8667:         if ($liburi) {
                   8668: 	    $liburi=&declutter($liburi);
                   8669:             $filename=$liburi;
1.401     bowersj2 8670:         } else {
1.599     albertel 8671: 	    &devalidate_cache_new('meta',$uri);
                   8672: 	    undef(%metaentry);
1.401     bowersj2 8673: 	}
1.140     www      8674:         my %metathesekeys=();
1.73      www      8675:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8676: 	my $metastring;
1.924     albertel 8677: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8678: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8679: 	    $metastring = 
1.929     albertel 8680: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8681: 					  ('grade_target' => 'meta'));
                   8682: 	    $cachetime = 1; # only want this cached in the child not long term
1.1056.4.26  raeburn  8683: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8684:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8685: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8686: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8687: 	    $metastring=&getfile($file);
1.489     albertel 8688: 	}
1.208     albertel 8689:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8690:         my $token;
1.140     www      8691:         undef %metathesekeys;
1.71      www      8692:         while ($token=$parser->get_token) {
1.339     albertel 8693: 	    if ($token->[0] eq 'S') {
                   8694: 		if (defined($token->[2]->{'package'})) {
1.172     www      8695: #
                   8696: # This is a package - get package info
                   8697: #
1.339     albertel 8698: 		    my $package=$token->[2]->{'package'};
                   8699: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8700: 		    if (defined($token->[2]->{'id'})) { 
                   8701: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8702: 		    }
1.599     albertel 8703: 		    if ($metaentry{':packages'}) {
                   8704: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8705: 		    } else {
1.599     albertel 8706: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8707: 		    }
1.736     albertel 8708: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8709: 			my $part=$keyroot;
                   8710: 			$part=~s/^\_//;
1.736     albertel 8711: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8712: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8713: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8714: 			    # ignore package.tab specified default values
                   8715:                             # here &package_tab_default() will fetch those
                   8716: 			    if ($subp eq 'default') { next; }
1.736     albertel 8717: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8718: 			    my $unikey;
                   8719: 			    if ($pack =~ /_0$/) {
                   8720: 				$unikey='parameter_0_'.$name;
                   8721: 				$part=0;
                   8722: 			    } else {
                   8723: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8724: 			    }
1.339     albertel 8725: 			    if ($subp eq 'display') {
                   8726: 				$value.=' [Part: '.$part.']';
                   8727: 			    }
1.599     albertel 8728: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8729: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8730: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8731: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8732: 			    }
1.599     albertel 8733: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8734: 				$metaentry{':'.$unikey}=
                   8735: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8736: 			    }
1.339     albertel 8737: 			}
                   8738: 		    }
                   8739: 		} else {
1.172     www      8740: #
                   8741: # This is not a package - some other kind of start tag
1.339     albertel 8742: #
                   8743: 		    my $entry=$token->[1];
                   8744: 		    my $unikey;
                   8745: 		    if ($entry eq 'import') {
                   8746: 			$unikey='';
                   8747: 		    } else {
                   8748: 			$unikey=$entry;
                   8749: 		    }
                   8750: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8751: 
                   8752: 		    if (defined($token->[2]->{'id'})) { 
                   8753: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8754: 		    }
1.175     www      8755: 
1.339     albertel 8756: 		    if ($entry eq 'import') {
1.175     www      8757: #
                   8758: # Importing a library here
1.339     albertel 8759: #
                   8760: 			if ($depthcount<20) {
                   8761: 			    my $location=$parser->get_text('/import');
                   8762: 			    my $dir=$filename;
                   8763: 			    $dir=~s|[^/]*$||;
                   8764: 			    $location=&filelocation($dir,$location);
1.736     albertel 8765: 			    my $metadata = 
                   8766: 				&metadata($uri,'keys', $location,$unikey,
                   8767: 					  $depthcount+1);
                   8768: 			    foreach my $meta (split(',',$metadata)) {
                   8769: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8770: 				$metathesekeys{$meta}=1;
1.339     albertel 8771: 			    }
                   8772: 			}
                   8773: 		    } else { 
                   8774: 			if (defined($token->[2]->{'name'})) { 
                   8775: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8776: 			}
                   8777: 			$metathesekeys{$unikey}=1;
1.736     albertel 8778: 			foreach my $param (@{$token->[3]}) {
                   8779: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8780: 				$token->[2]->{$param};
1.339     albertel 8781: 			}
                   8782: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8783: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8784: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8785: 		 # only ws inside the tag, and not in default, so use default
                   8786: 		 # as value
1.599     albertel 8787: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8788: 			} elsif ( $internaltext =~ /\S/ ) {
                   8789: 		  # something interesting inside the tag
                   8790: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8791: 			} else {
1.908     albertel 8792: 		  # no interesting values, don't set a default
1.339     albertel 8793: 			}
1.172     www      8794: # end of not-a-package not-a-library import
1.339     albertel 8795: 		    }
1.172     www      8796: # end of not-a-package start tag
1.339     albertel 8797: 		}
1.172     www      8798: # the next is the end of "start tag"
1.339     albertel 8799: 	    }
                   8800: 	}
1.483     albertel 8801: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8802: 	$extension = lc($extension);
                   8803: 	if ($extension eq 'htm') { $extension='html'; }
                   8804: 
1.737     albertel 8805: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8806: 	    #no specific packages #how's our extension
                   8807: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8808: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8809: 					 \%metathesekeys);
                   8810: 	}
1.883     albertel 8811: 
                   8812: 	if (!exists($metaentry{':packages'})
                   8813: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8814: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8815: 		#no specific packages well let's get default then
                   8816: 		if ($key!~/^default&/) { next; }
1.488     albertel 8817: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8818: 					     \%metathesekeys);
                   8819: 	    }
                   8820: 	}
1.338     www      8821: # are there custom rights to evaluate
1.599     albertel 8822: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8823: 
1.338     www      8824:     #
                   8825:     # Importing a rights file here
1.339     albertel 8826:     #
                   8827: 	    unless ($depthcount) {
1.599     albertel 8828: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8829: 		my $dir=$filename;
                   8830: 		$dir=~s|[^/]*$||;
                   8831: 		$location=&filelocation($dir,$location);
1.736     albertel 8832: 		my $rights_metadata =
                   8833: 		    &metadata($uri,'keys',$location,'_rights',
                   8834: 			      $depthcount+1);
                   8835: 		foreach my $rights (split(',',$rights_metadata)) {
                   8836: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8837: 		    $metathesekeys{$rights}=1;
1.339     albertel 8838: 		}
                   8839: 	    }
                   8840: 	}
1.737     albertel 8841: 	# uniqifiy package listing
                   8842: 	my %seen;
                   8843: 	my @uniq_packages =
                   8844: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8845: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8846: 
                   8847: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8848: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8849: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8850: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8851: # this is the end of "was not already recently cached
1.71      www      8852:     }
1.599     albertel 8853:     return $metaentry{':'.$what};
1.261     albertel 8854: }
                   8855: 
1.488     albertel 8856: sub metadata_create_package_def {
1.483     albertel 8857:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8858:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8859:     if ($subp eq 'default') { next; }
                   8860:     
1.599     albertel 8861:     if (defined($metaentry{':packages'})) {
                   8862: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8863:     } else {
1.599     albertel 8864: 	$metaentry{':packages'}=$package;
1.483     albertel 8865:     }
                   8866:     my $value=$packagetab{$key};
                   8867:     my $unikey;
                   8868:     $unikey='parameter_0_'.$name;
1.599     albertel 8869:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8870:     $$metathesekeys{$unikey}=1;
1.599     albertel 8871:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8872: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8873:     }
1.599     albertel 8874:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8875: 	$metaentry{':'.$unikey}=
                   8876: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8877:     }
                   8878: }
                   8879: 
1.261     albertel 8880: sub metadata_generate_part0 {
                   8881:     my ($metadata,$metacache,$uri) = @_;
                   8882:     my %allnames;
1.737     albertel 8883:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8884: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8885: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8886: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8887: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8888: 	    $allnames{$name}=$part;
                   8889: 	  }
                   8890: 	}
                   8891:     }
                   8892:     foreach my $name (keys(%allnames)) {
                   8893:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8894:       my $key=":parameter_0_$name";
1.261     albertel 8895:       $$metacache{"$key.part"}='0';
                   8896:       $$metacache{"$key.name"}=$name;
1.428     albertel 8897:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8898: 					   $allnames{$name}.'_'.$name.
                   8899: 					   '.type'};
1.428     albertel 8900:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8901: 			     '.display'};
1.644     www      8902:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8903:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8904:       $$metacache{"$key.display"}=$olddis;
                   8905:     }
1.71      www      8906: }
                   8907: 
1.764     albertel 8908: # ------------------------------------------------------ Devalidate title cache
                   8909: 
                   8910: sub devalidate_title_cache {
                   8911:     my ($url)=@_;
                   8912:     if (!$env{'request.course.id'}) { return; }
                   8913:     my $symb=&symbread($url);
                   8914:     if (!$symb) { return; }
                   8915:     my $key=$env{'request.course.id'}."\0".$symb;
                   8916:     &devalidate_cache_new('title',$key);
                   8917: }
                   8918: 
1.1014    droeschl 8919: # ------------------------------------------------- Get the title of a course
                   8920: 
                   8921: sub current_course_title {
                   8922:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8923: }
1.301     www      8924: # ------------------------------------------------- Get the title of a resource
                   8925: 
                   8926: sub gettitle {
                   8927:     my $urlsymb=shift;
                   8928:     my $symb=&symbread($urlsymb);
1.534     albertel 8929:     if ($symb) {
1.620     albertel 8930: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8931: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8932: 	if (defined($cached)) { 
                   8933: 	    return $result;
                   8934: 	}
1.534     albertel 8935: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8936: 	my $title='';
1.907     albertel 8937: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8938: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8939: 	} else {
                   8940: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8941: 		    &GDBM_READER(),0640)) {
                   8942: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8943: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8944: 		untie(%bighash);
                   8945: 	    }
1.534     albertel 8946: 	}
                   8947: 	$title=~s/\&colon\;/\:/gs;
                   8948: 	if ($title) {
1.599     albertel 8949: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8950: 	}
                   8951: 	$urlsymb=$url;
                   8952:     }
                   8953:     my $title=&metadata($urlsymb,'title');
                   8954:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8955:     return $title;
1.301     www      8956: }
1.613     albertel 8957: 
1.614     albertel 8958: sub get_slot {
                   8959:     my ($which,$cnum,$cdom)=@_;
                   8960:     if (!$cnum || !$cdom) {
1.790     albertel 8961: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8962: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8963: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8964:     }
1.703     albertel 8965:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8966:     my %slotinfo;
                   8967:     if (exists($remembered{$key})) {
                   8968: 	$slotinfo{$which} = $remembered{$key};
                   8969:     } else {
                   8970: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8971: 	&Apache::lonhomework::showhash(%slotinfo);
                   8972: 	my ($tmp)=keys(%slotinfo);
                   8973: 	if ($tmp=~/^error:/) { return (); }
                   8974: 	$remembered{$key} = $slotinfo{$which};
                   8975:     }
1.616     albertel 8976:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8977: 	return %{$slotinfo{$which}};
                   8978:     }
                   8979:     return $slotinfo{$which};
1.614     albertel 8980: }
1.31      www      8981: # ------------------------------------------------- Update symbolic store links
                   8982: 
                   8983: sub symblist {
                   8984:     my ($mapname,%newhash)=@_;
1.438     www      8985:     $mapname=&deversion(&declutter($mapname));
1.31      www      8986:     my %hash;
1.620     albertel 8987:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8988:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8989:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8990: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8991: 		next if ($url eq 'last_known'
                   8992: 			 && $env{'form.no_update_last_known'});
                   8993: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8994: 						    $newhash{$url}->[1],
                   8995: 						    $newhash{$url}->[0]);
1.191     harris41 8996:             }
1.31      www      8997:             if (untie(%hash)) {
                   8998: 		return 'ok';
                   8999:             }
                   9000:         }
                   9001:     }
                   9002:     return 'error';
1.212     www      9003: }
                   9004: 
                   9005: # --------------------------------------------------------------- Verify a symb
                   9006: 
                   9007: sub symbverify {
1.510     www      9008:     my ($symb,$thisurl)=@_;
                   9009:     my $thisfn=$thisurl;
1.439     www      9010:     $thisfn=&declutter($thisfn);
1.215     www      9011: # direct jump to resource in page or to a sequence - will construct own symbs
                   9012:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9013: # check URL part
1.409     www      9014:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9015: 
1.431     www      9016:     unless ($url eq $thisfn) { return 0; }
1.213     www      9017: 
1.216     www      9018:     $symb=&symbclean($symb);
1.510     www      9019:     $thisurl=&deversion($thisurl);
1.439     www      9020:     $thisfn=&deversion($thisfn);
1.213     www      9021: 
                   9022:     my %bighash;
                   9023:     my $okay=0;
1.431     www      9024: 
1.620     albertel 9025:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9026:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9027:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9028:             $thisurl =~ s/\?.+$//;
                   9029:         }
1.510     www      9030:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      9031:         unless ($ids) { 
1.1056.4.21  raeburn  9032:            my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
                   9033:            $ids=$bighash{$idkey};
1.216     www      9034:         }
                   9035:         if ($ids) {
                   9036: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9037: 	    foreach my $id (split(/\,/,$ids)) {
                   9038: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9039:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9040:                    $symb =~ s/\?.+$//;
                   9041:                }
1.216     www      9042:                if (
                   9043:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9044:    eq $symb) { 
1.620     albertel 9045: 		   if (($env{'request.role.adv'}) ||
1.1056.4.20  raeburn  9046: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9047: 		       ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9048: 		       $okay=1; 
                   9049: 		   }
                   9050: 	       }
1.216     www      9051: 	   }
                   9052:         }
1.213     www      9053: 	untie(%bighash);
                   9054:     }
                   9055:     return $okay;
1.31      www      9056: }
                   9057: 
1.210     www      9058: # --------------------------------------------------------------- Clean-up symb
                   9059: 
                   9060: sub symbclean {
                   9061:     my $symb=shift;
1.568     albertel 9062:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9063: # remove version from map
                   9064:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9065: 
1.210     www      9066: # remove version from URL
                   9067:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9068: 
1.507     www      9069: # remove wrapper
                   9070: 
1.510     www      9071:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9072:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9073:     return $symb;
1.409     www      9074: }
                   9075: 
                   9076: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9077: 
                   9078: sub encode_symb {
                   9079:     my ($map,$resid,$url)=@_;
                   9080:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9081: }
1.409     www      9082: 
                   9083: sub decode_symb {
1.568     albertel 9084:     my $symb=shift;
                   9085:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9086:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9087:     return (&fixversion($map),$resid,&fixversion($url));
                   9088: }
                   9089: 
                   9090: sub fixversion {
                   9091:     my $fn=shift;
1.609     banghart 9092:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9093:     my %bighash;
                   9094:     my $uri=&clutter($fn);
1.620     albertel 9095:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9096: # is this cached?
1.599     albertel 9097:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9098:     if (defined($cached)) { return $result; }
                   9099: # unfortunately not cached, or expired
1.620     albertel 9100:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9101: 	    &GDBM_READER(),0640)) {
                   9102:  	if ($bighash{'version_'.$uri}) {
                   9103:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9104:  	    unless (($version eq 'mostrecent') || 
                   9105: 		    ($version==&getversion($uri))) {
1.440     www      9106:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9107:  	    }
                   9108:  	}
                   9109:  	untie %bighash;
1.413     www      9110:     }
1.599     albertel 9111:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9112: }
                   9113: 
                   9114: sub deversion {
                   9115:     my $url=shift;
                   9116:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9117:     return $url;
1.210     www      9118: }
                   9119: 
1.31      www      9120: # ------------------------------------------------------ Return symb list entry
                   9121: 
                   9122: sub symbread {
1.249     www      9123:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9124:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9125:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9126: # no filename provided? try from environment
1.44      www      9127:     unless ($thisfn) {
1.620     albertel 9128:         if ($env{'request.symb'}) {
                   9129: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9130: 	}
1.620     albertel 9131: 	$thisfn=$env{'request.filename'};
1.44      www      9132:     }
1.569     albertel 9133:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9134: # is that filename actually a symb? Verify, clean, and return
                   9135:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9136: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9137: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9138: 	}
1.242     www      9139:     }
1.44      www      9140:     $thisfn=declutter($thisfn);
1.31      www      9141:     my %hash;
1.37      www      9142:     my %bighash;
                   9143:     my $syval='';
1.620     albertel 9144:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9145:         my $targetfn = $thisfn;
1.609     banghart 9146:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9147:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9148:         }
1.687     albertel 9149: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9150: 	    $targetfn=$1;
                   9151: 	}
1.620     albertel 9152:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9153:                       &GDBM_READER(),0640)) {
1.481     raeburn  9154: 	    $syval=$hash{$targetfn};
1.37      www      9155:             untie(%hash);
                   9156:         }
                   9157: # ---------------------------------------------------------- There was an entry
                   9158:         if ($syval) {
1.601     albertel 9159: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9160: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9161: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9162: 		    #return $env{$cache_str}='';
1.601     albertel 9163: 		#}    
                   9164: 		#$syval.=$1;
                   9165: 	    #}
1.37      www      9166:         } else {
                   9167: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9168:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9169:                             &GDBM_READER(),0640)) {
1.37      www      9170: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9171:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9172:               unless ($ids) { 
                   9173:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9174:               }
                   9175:               unless ($ids) {
                   9176: # alias?
                   9177: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9178:               }
1.37      www      9179:               if ($ids) {
                   9180: # ------------------------------------------------------------------- Has ID(s)
                   9181:                  my @possibilities=split(/\,/,$ids);
1.39      www      9182:                  if ($#possibilities==0) {
                   9183: # ----------------------------------------------- There is only one possibility
1.37      www      9184: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9185: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9186: 						    $resid,$thisfn);
1.249     www      9187:                  } elsif (!$donotrecurse) {
1.39      www      9188: # ------------------------------------------ There is more than one possibility
                   9189:                      my $realpossible=0;
1.800     albertel 9190:                      foreach my $id (@possibilities) {
                   9191: 			 my $file=$bighash{'src_'.$id};
1.39      www      9192:                          if (&allowed('bre',$file)) {
1.800     albertel 9193:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9194:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9195: 				$realpossible++;
1.626     albertel 9196:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9197: 						    $resid,$thisfn);
1.39      www      9198:                             }
                   9199: 			 }
1.191     harris41 9200:                      }
1.39      www      9201: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9202:                  } else {
                   9203:                      $syval='';
1.37      www      9204:                  }
                   9205: 	      }
                   9206:               untie(%bighash)
1.481     raeburn  9207:            }
1.31      www      9208:         }
1.62      www      9209:         if ($syval) {
1.620     albertel 9210: 	    return $env{$cache_str}=$syval;
1.62      www      9211:         }
1.31      www      9212:     }
1.949     raeburn  9213:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9214:     return $env{$cache_str}='';
1.31      www      9215: }
                   9216: 
                   9217: # ---------------------------------------------------------- Return random seed
                   9218: 
1.32      www      9219: sub numval {
                   9220:     my $txt=shift;
                   9221:     $txt=~tr/A-J/0-9/;
                   9222:     $txt=~tr/a-j/0-9/;
                   9223:     $txt=~tr/K-T/0-9/;
                   9224:     $txt=~tr/k-t/0-9/;
                   9225:     $txt=~tr/U-Z/0-5/;
                   9226:     $txt=~tr/u-z/0-5/;
                   9227:     $txt=~s/\D//g;
1.564     albertel 9228:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9229:     return int($txt);
1.368     albertel 9230: }
                   9231: 
1.484     albertel 9232: sub numval2 {
                   9233:     my $txt=shift;
                   9234:     $txt=~tr/A-J/0-9/;
                   9235:     $txt=~tr/a-j/0-9/;
                   9236:     $txt=~tr/K-T/0-9/;
                   9237:     $txt=~tr/k-t/0-9/;
                   9238:     $txt=~tr/U-Z/0-5/;
                   9239:     $txt=~tr/u-z/0-5/;
                   9240:     $txt=~s/\D//g;
                   9241:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9242:     my $total;
                   9243:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9244:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9245:     return int($total);
                   9246: }
                   9247: 
1.575     albertel 9248: sub numval3 {
                   9249:     use integer;
                   9250:     my $txt=shift;
                   9251:     $txt=~tr/A-J/0-9/;
                   9252:     $txt=~tr/a-j/0-9/;
                   9253:     $txt=~tr/K-T/0-9/;
                   9254:     $txt=~tr/k-t/0-9/;
                   9255:     $txt=~tr/U-Z/0-5/;
                   9256:     $txt=~tr/u-z/0-5/;
                   9257:     $txt=~s/\D//g;
                   9258:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9259:     my $total;
                   9260:     foreach my $val (@txts) { $total+=$val; }
                   9261:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9262:     return $total;
                   9263: }
                   9264: 
1.675     albertel 9265: sub digest {
                   9266:     my ($data)=@_;
                   9267:     my $digest=&Digest::MD5::md5($data);
                   9268:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9269:     my ($e,$f);
                   9270:     {
                   9271:         use integer;
                   9272:         $e=($a+$b);
                   9273:         $f=($c+$d);
                   9274:         if ($_64bit) {
                   9275:             $e=(($e<<32)>>32);
                   9276:             $f=(($f<<32)>>32);
                   9277:         }
                   9278:     }
                   9279:     if (wantarray) {
                   9280: 	return ($e,$f);
                   9281:     } else {
                   9282: 	my $g;
                   9283: 	{
                   9284: 	    use integer;
                   9285: 	    $g=($e+$f);
                   9286: 	    if ($_64bit) {
                   9287: 		$g=(($g<<32)>>32);
                   9288: 	    }
                   9289: 	}
                   9290: 	return $g;
                   9291:     }
                   9292: }
                   9293: 
1.368     albertel 9294: sub latest_rnd_algorithm_id {
1.675     albertel 9295:     return '64bit5';
1.366     albertel 9296: }
1.32      www      9297: 
1.503     albertel 9298: sub get_rand_alg {
                   9299:     my ($courseid)=@_;
1.790     albertel 9300:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9301:     if ($courseid) {
1.620     albertel 9302: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9303:     }
                   9304:     return &latest_rnd_algorithm_id();
                   9305: }
                   9306: 
1.562     albertel 9307: sub validCODE {
                   9308:     my ($CODE)=@_;
                   9309:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9310:     return 0;
                   9311: }
                   9312: 
1.491     albertel 9313: sub getCODE {
1.620     albertel 9314:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9315:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9316: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9317: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9318: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9319:     }
                   9320:     return undef;
                   9321: }
                   9322: 
1.31      www      9323: sub rndseed {
1.155     albertel 9324:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9325:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9326:     if (!defined($symb)) {
1.366     albertel 9327: 	unless ($symb=$wsymb) { return time; }
                   9328:     }
                   9329:     if (!$courseid) { $courseid=$wcourseid; }
                   9330:     if (!$domain) { $domain=$wdomain; }
                   9331:     if (!$username) { $username=$wusername }
1.503     albertel 9332:     my $which=&get_rand_alg();
1.803     albertel 9333: 
1.491     albertel 9334:     if (defined(&getCODE())) {
1.675     albertel 9335: 	if ($which eq '64bit5') {
                   9336: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9337: 	} elsif ($which eq '64bit4') {
1.575     albertel 9338: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9339: 	} else {
                   9340: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9341: 	}
1.675     albertel 9342:     } elsif ($which eq '64bit5') {
                   9343: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9344:     } elsif ($which eq '64bit4') {
                   9345: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9346:     } elsif ($which eq '64bit3') {
                   9347: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9348:     } elsif ($which eq '64bit2') {
                   9349: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9350:     } elsif ($which eq '64bit') {
                   9351: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9352:     }
                   9353:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9354: }
                   9355: 
                   9356: sub rndseed_32bit {
                   9357:     my ($symb,$courseid,$domain,$username)=@_;
                   9358:     {
                   9359: 	use integer;
                   9360: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9361: 	my $symbseed=numval($symb) << 22;
                   9362: 	my $namechck=unpack("%32C*",$username) << 17;
                   9363: 	my $nameseed=numval($username) << 12;
                   9364: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9365: 	my $courseseed=unpack("%32C*",$courseid);
                   9366: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9367: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9368: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9369: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9370: 	return $num;
                   9371:     }
                   9372: }
                   9373: 
                   9374: sub rndseed_64bit {
                   9375:     my ($symb,$courseid,$domain,$username)=@_;
                   9376:     {
                   9377: 	use integer;
                   9378: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9379: 	my $symbseed=numval($symb) << 10;
                   9380: 	my $namechck=unpack("%32S*",$username);
                   9381: 	
                   9382: 	my $nameseed=numval($username) << 21;
                   9383: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9384: 	my $courseseed=unpack("%32S*",$courseid);
                   9385: 	
                   9386: 	my $num1=$symbchck+$symbseed+$namechck;
                   9387: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9388: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9389: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9390: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9391: 	return "$num1,$num2";
1.155     albertel 9392:     }
1.366     albertel 9393: }
                   9394: 
1.443     albertel 9395: sub rndseed_64bit2 {
                   9396:     my ($symb,$courseid,$domain,$username)=@_;
                   9397:     {
                   9398: 	use integer;
                   9399: 	# strings need to be an even # of cahracters long, it it is odd the
                   9400:         # last characters gets thrown away
                   9401: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9402: 	my $symbseed=numval($symb) << 10;
                   9403: 	my $namechck=unpack("%32S*",$username.' ');
                   9404: 	
                   9405: 	my $nameseed=numval($username) << 21;
1.501     albertel 9406: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9407: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9408: 	
                   9409: 	my $num1=$symbchck+$symbseed+$namechck;
                   9410: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9411: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9412: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9413: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9414: 	return "$num1,$num2";
                   9415:     }
                   9416: }
                   9417: 
                   9418: sub rndseed_64bit3 {
                   9419:     my ($symb,$courseid,$domain,$username)=@_;
                   9420:     {
                   9421: 	use integer;
                   9422: 	# strings need to be an even # of cahracters long, it it is odd the
                   9423:         # last characters gets thrown away
                   9424: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9425: 	my $symbseed=numval2($symb) << 10;
                   9426: 	my $namechck=unpack("%32S*",$username.' ');
                   9427: 	
                   9428: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9429: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9430: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9431: 	
                   9432: 	my $num1=$symbchck+$symbseed+$namechck;
                   9433: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9434: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9435: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9436: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9437: 	
1.503     albertel 9438: 	return "$num1:$num2";
1.443     albertel 9439:     }
                   9440: }
                   9441: 
1.575     albertel 9442: sub rndseed_64bit4 {
                   9443:     my ($symb,$courseid,$domain,$username)=@_;
                   9444:     {
                   9445: 	use integer;
                   9446: 	# strings need to be an even # of cahracters long, it it is odd the
                   9447:         # last characters gets thrown away
                   9448: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9449: 	my $symbseed=numval3($symb) << 10;
                   9450: 	my $namechck=unpack("%32S*",$username.' ');
                   9451: 	
                   9452: 	my $nameseed=numval3($username) << 21;
                   9453: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9454: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9455: 	
                   9456: 	my $num1=$symbchck+$symbseed+$namechck;
                   9457: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9458: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9459: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9460: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9461: 	
                   9462: 	return "$num1:$num2";
                   9463:     }
                   9464: }
                   9465: 
1.675     albertel 9466: sub rndseed_64bit5 {
                   9467:     my ($symb,$courseid,$domain,$username)=@_;
                   9468:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9469:     return "$num1:$num2";
                   9470: }
                   9471: 
1.366     albertel 9472: sub rndseed_CODE_64bit {
                   9473:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9474:     {
1.366     albertel 9475: 	use integer;
1.443     albertel 9476: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9477: 	my $symbseed=numval2($symb);
1.491     albertel 9478: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9479: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9480: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9481: 	my $num1=$symbseed+$CODEchck;
                   9482: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9483: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9484: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9485: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9486: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9487: 	return "$num1:$num2";
1.366     albertel 9488:     }
                   9489: }
                   9490: 
1.575     albertel 9491: sub rndseed_CODE_64bit4 {
                   9492:     my ($symb,$courseid,$domain,$username)=@_;
                   9493:     {
                   9494: 	use integer;
                   9495: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9496: 	my $symbseed=numval3($symb);
                   9497: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9498: 	my $CODEseed=numval3(&getCODE());
                   9499: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9500: 	my $num1=$symbseed+$CODEchck;
                   9501: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9502: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9503: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9504: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9505: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9506: 	return "$num1:$num2";
                   9507:     }
                   9508: }
                   9509: 
1.675     albertel 9510: sub rndseed_CODE_64bit5 {
                   9511:     my ($symb,$courseid,$domain,$username)=@_;
                   9512:     my $code = &getCODE();
                   9513:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9514:     return "$num1:$num2";
                   9515: }
                   9516: 
1.366     albertel 9517: sub setup_random_from_rndseed {
                   9518:     my ($rndseed)=@_;
1.503     albertel 9519:     if ($rndseed =~/([,:])/) {
                   9520: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9521: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9522:     } else {
                   9523: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9524:     }
1.36      albertel 9525: }
                   9526: 
1.474     albertel 9527: sub latest_receipt_algorithm_id {
1.835     albertel 9528:     return 'receipt3';
1.474     albertel 9529: }
                   9530: 
1.480     www      9531: sub recunique {
                   9532:     my $fucourseid=shift;
                   9533:     my $unique;
1.835     albertel 9534:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9535: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9536: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9537:     } else {
                   9538: 	$unique=$perlvar{'lonReceipt'};
                   9539:     }
                   9540:     return unpack("%32C*",$unique);
                   9541: }
                   9542: 
                   9543: sub recprefix {
                   9544:     my $fucourseid=shift;
                   9545:     my $prefix;
1.835     albertel 9546:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9547: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9548: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9549:     } else {
                   9550: 	$prefix=$perlvar{'lonHostID'};
                   9551:     }
                   9552:     return unpack("%32C*",$prefix);
                   9553: }
                   9554: 
1.76      www      9555: sub ireceipt {
1.474     albertel 9556:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9557: 
                   9558:     my $return =&recprefix($fucourseid).'-';
                   9559: 
                   9560:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9561: 	$env{'request.state'} eq 'construct') {
                   9562: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9563: 	return $return;
                   9564:     }
                   9565: 
1.76      www      9566:     my $cuname=unpack("%32C*",$funame);
                   9567:     my $cudom=unpack("%32C*",$fudom);
                   9568:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9569:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9570:     my $cunique=&recunique($fucourseid);
1.474     albertel 9571:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9572:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9573: 
1.790     albertel 9574: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9575: 			       
                   9576: 	$return.= ($cunique%$cuname+
                   9577: 		   $cunique%$cudom+
                   9578: 		   $cusymb%$cuname+
                   9579: 		   $cusymb%$cudom+
                   9580: 		   $cucourseid%$cuname+
                   9581: 		   $cucourseid%$cudom+
                   9582: 		   $cpart%$cuname+
                   9583: 		   $cpart%$cudom);
                   9584:     } else {
                   9585: 	$return.= ($cunique%$cuname+
                   9586: 		   $cunique%$cudom+
                   9587: 		   $cusymb%$cuname+
                   9588: 		   $cusymb%$cudom+
                   9589: 		   $cucourseid%$cuname+
                   9590: 		   $cucourseid%$cudom);
                   9591:     }
                   9592:     return $return;
1.76      www      9593: }
                   9594: 
                   9595: sub receipt {
1.474     albertel 9596:     my ($part)=@_;
1.790     albertel 9597:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9598:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9599: }
1.260     ng       9600: 
1.790     albertel 9601: sub whichuser {
                   9602:     my ($passedsymb)=@_;
                   9603:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9604:     if (defined($env{'form.grade_symb'})) {
                   9605: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9606: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9607: 	if (!$allowed &&
                   9608: 	    exists($env{'request.course.sec'}) &&
                   9609: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9610: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9611: 			      '/'.$env{'request.course.sec'});
                   9612: 	}
                   9613: 	if ($allowed) {
                   9614: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9615: 	    $courseid=$tmp_courseid;
                   9616: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9617: 	    ($name)=&get_env_multiple('form.grade_username');
                   9618: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9619: 	}
                   9620:     }
                   9621:     if (!$passedsymb) {
                   9622: 	$symb=&symbread();
                   9623:     } else {
                   9624: 	$symb=$passedsymb;
                   9625:     }
                   9626:     $courseid=$env{'request.course.id'};
                   9627:     $domain=$env{'user.domain'};
                   9628:     $name=$env{'user.name'};
                   9629:     if ($name eq 'public' && $domain eq 'public') {
                   9630: 	if (!defined($env{'form.username'})) {
                   9631: 	    $env{'form.username'}.=time.rand(10000000);
                   9632: 	}
                   9633: 	$name.=$env{'form.username'};
                   9634:     }
                   9635:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9636: 
                   9637: }
                   9638: 
1.36      albertel 9639: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9640: # returns either the contents of the file or 
                   9641: # -1 if the file doesn't exist
1.481     raeburn  9642: #
                   9643: # if the target is a file that was uploaded via DOCS, 
                   9644: # a check will be made to see if a current copy exists on the local server,
                   9645: # if it does this will be served, otherwise a copy will be retrieved from
                   9646: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9647: # the local server.   
1.472     albertel 9648: 
1.36      albertel 9649: sub getfile {
1.538     albertel 9650:     my ($file) = @_;
1.609     banghart 9651:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9652:     &repcopy($file);
                   9653:     return &readfile($file);
                   9654: }
                   9655: 
                   9656: sub repcopy_userfile {
                   9657:     my ($file)=@_;
1.609     banghart 9658:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9659:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9660:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9661: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9662:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9663:     if (-e "$file") {
1.828     www      9664: # we already have a local copy, check it out
1.538     albertel 9665: 	my @fileinfo = stat($file);
1.828     www      9666: 	my $rtncode;
                   9667: 	my $info;
1.538     albertel 9668: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9669: 	if ($lwpresp ne 'ok') {
1.828     www      9670: # there is no such file anymore, even though we had a local copy
1.482     albertel 9671: 	    if ($rtncode eq '404') {
1.538     albertel 9672: 		unlink($file);
1.482     albertel 9673: 	    }
                   9674: 	    return -1;
                   9675: 	}
                   9676: 	if ($info < $fileinfo[9]) {
1.828     www      9677: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9678: 	    return 'ok';
1.828     www      9679: 	} else {
                   9680: # the file is outdated, get rid of it
                   9681: 	    unlink($file);
1.482     albertel 9682: 	}
1.828     www      9683:     }
                   9684: # one way or the other, at this point, we don't have the file
                   9685: # construct the correct path for the file
                   9686:     my @parts = ($cdom,$cnum); 
                   9687:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9688: 	push @parts, split(/\//,$1);
                   9689:     }
                   9690:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9691:     foreach my $part (@parts) {
                   9692: 	$path .= '/'.$part;
                   9693: 	if (!-e $path) {
                   9694: 	    mkdir($path,0770);
1.482     albertel 9695: 	}
                   9696:     }
1.828     www      9697: # now the path exists for sure
                   9698: # get a user agent
                   9699:     my $ua=new LWP::UserAgent;
                   9700:     my $transferfile=$file.'.in.transfer';
                   9701: # FIXME: this should flock
                   9702:     if (-e $transferfile) { return 'ok'; }
                   9703:     my $request;
                   9704:     $uri=~s/^\///;
1.980     raeburn  9705:     my $homeserver = &homeserver($cnum,$cdom);
                   9706:     my $protocol = $protocol{$homeserver};
                   9707:     $protocol = 'http' if ($protocol ne 'https');
                   9708:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9709:     my $response=$ua->request($request,$transferfile);
                   9710: # did it work?
                   9711:     if ($response->is_error()) {
                   9712: 	unlink($transferfile);
                   9713: 	&logthis("Userfile repcopy failed for $uri");
                   9714: 	return -1;
                   9715:     }
                   9716: # worked, rename the transfer file
                   9717:     rename($transferfile,$file);
1.607     raeburn  9718:     return 'ok';
1.481     raeburn  9719: }
                   9720: 
1.517     albertel 9721: sub tokenwrapper {
                   9722:     my $uri=shift;
1.980     raeburn  9723:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9724:     $uri=~s|^/||;
1.620     albertel 9725:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9726:     my $token=$1;
1.552     albertel 9727:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9728:     if ($udom && $uname && $file) {
                   9729: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9730:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9731:         my $homeserver = &homeserver($uname,$udom);
                   9732:         my $protocol = $protocol{$homeserver};
                   9733:         $protocol = 'http' if ($protocol ne 'https');
                   9734:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9735:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9736:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9737:     } else {
                   9738:         return '/adm/notfound.html';
                   9739:     }
                   9740: }
                   9741: 
1.828     www      9742: # call with reqtype HEAD: get last modification time
                   9743: # call with reqtype GET: get the file contents
                   9744: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9745: #
1.481     raeburn  9746: sub getuploaded {
                   9747:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9748:     $uri=~s/^\///;
1.980     raeburn  9749:     my $homeserver = &homeserver($cnum,$cdom);
                   9750:     my $protocol = $protocol{$homeserver};
                   9751:     $protocol = 'http' if ($protocol ne 'https');
                   9752:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9753:     my $ua=new LWP::UserAgent;
                   9754:     my $request=new HTTP::Request($reqtype,$uri);
                   9755:     my $response=$ua->request($request);
                   9756:     $$rtncode = $response->code;
1.482     albertel 9757:     if (! $response->is_success()) {
                   9758: 	return 'failed';
                   9759:     }      
                   9760:     if ($reqtype eq 'HEAD') {
1.486     www      9761: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9762:     } elsif ($reqtype eq 'GET') {
                   9763: 	$$info = $response->content;
1.472     albertel 9764:     }
1.482     albertel 9765:     return 'ok';
1.36      albertel 9766: }
                   9767: 
1.481     raeburn  9768: sub readfile {
                   9769:     my $file = shift;
                   9770:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9771:     my $fh;
                   9772:     open($fh,"<$file");
                   9773:     my $a='';
1.800     albertel 9774:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9775:     return $a;
                   9776: }
                   9777: 
1.36      albertel 9778: sub filelocation {
1.590     banghart 9779:     my ($dir,$file) = @_;
                   9780:     my $location;
                   9781:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9782: 
                   9783:     if ($file =~ m-^/adm/-) {
                   9784: 	$file=~s-^/adm/wrapper/-/-;
                   9785: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9786:     }
1.882     albertel 9787: 
1.590     banghart 9788:     if ($file=~m:^/~:) { # is a contruction space reference
                   9789:         $location = $file;
                   9790:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9791:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9792: 	# is a correct contruction space reference
                   9793:         $location = $file;
1.956     raeburn  9794:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9795:         $location = $file;
1.609     banghart 9796:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9797:         my ($udom,$uname,$filename)=
1.811     albertel 9798:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9799:         my $home=&homeserver($uname,$udom);
                   9800:         my $is_me=0;
                   9801:         my @ids=&current_machine_ids();
                   9802:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9803:         if ($is_me) {
1.955     raeburn  9804:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9805:         } else {
                   9806:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9807:   	      $udom.'/'.$uname.'/'.$filename;
                   9808:         }
1.882     albertel 9809:     } elsif ($file =~ m-^/adm/-) {
                   9810: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9811:     } else {
                   9812:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9813:         $file=~s:^/res/:/:;
                   9814:         if ( !( $file =~ m:^/:) ) {
                   9815:             $location = $dir. '/'.$file;
                   9816:         } else {
                   9817:             $location = '/home/httpd/html/res'.$file;
                   9818:         }
1.59      albertel 9819:     }
1.590     banghart 9820:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9821:     while ($location=~m{/\.\./}) {
                   9822: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9823: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9824: 	} else {
                   9825: 	    $location=~ s{/\.\./}{/}g;
                   9826: 	}
                   9827:     } #remove dir/..
1.590     banghart 9828:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9829:     return $location;
1.46      www      9830: }
1.36      albertel 9831: 
1.46      www      9832: sub hreflocation {
                   9833:     my ($dir,$file)=@_;
1.980     raeburn  9834:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9835: 	$file=filelocation($dir,$file);
1.700     albertel 9836:     } elsif ($file=~m-^/adm/-) {
                   9837: 	$file=~s-^/adm/wrapper/-/-;
                   9838: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9839:     }
                   9840:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9841: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9842:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9843: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9844:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9845: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9846: 	    -/uploaded/$1/$2/-x;
1.46      www      9847:     }
1.913     albertel 9848:     if ($file=~ m{^/userfiles/}) {
                   9849: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9850:     }
1.462     albertel 9851:     return $file;
1.465     albertel 9852: }
                   9853: 
                   9854: sub current_machine_domains {
1.853     albertel 9855:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9856: }
                   9857: 
                   9858: sub machine_domains {
                   9859:     my ($hostname) = @_;
1.465     albertel 9860:     my @domains;
1.838     albertel 9861:     my %hostname = &all_hostnames();
1.465     albertel 9862:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9863: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9864: 	if ($hostname eq $name) {
1.844     albertel 9865: 	    push(@domains,&host_domain($id));
1.465     albertel 9866: 	}
                   9867:     }
                   9868:     return @domains;
                   9869: }
                   9870: 
                   9871: sub current_machine_ids {
1.853     albertel 9872:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9873: }
                   9874: 
                   9875: sub machine_ids {
                   9876:     my ($hostname) = @_;
                   9877:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9878:     my @ids;
1.888     albertel 9879:     my %name_to_host = &all_names();
1.889     albertel 9880:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9881: 	return @{ $name_to_host{$hostname} };
                   9882:     }
                   9883:     return;
1.31      www      9884: }
                   9885: 
1.824     raeburn  9886: sub additional_machine_domains {
                   9887:     my @domains;
                   9888:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9889:     while( my $line = <$fh>) {
                   9890:         $line =~ s/\s//g;
                   9891:         push(@domains,$line);
                   9892:     }
                   9893:     return @domains;
                   9894: }
                   9895: 
                   9896: sub default_login_domain {
                   9897:     my $domain = $perlvar{'lonDefDomain'};
                   9898:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9899:     foreach my $posdom (&current_machine_domains(),
                   9900:                         &additional_machine_domains()) {
                   9901:         if (lc($posdom) eq lc($testdomain)) {
                   9902:             $domain=$posdom;
                   9903:             last;
                   9904:         }
                   9905:     }
                   9906:     return $domain;
                   9907: }
                   9908: 
1.31      www      9909: # ------------------------------------------------------------- Declutters URLs
                   9910: 
                   9911: sub declutter {
                   9912:     my $thisfn=shift;
1.569     albertel 9913:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9914:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9915:     $thisfn=~s/^\///;
1.697     albertel 9916:     $thisfn=~s|^adm/wrapper/||;
                   9917:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9918:     $thisfn=~s/^res\///;
1.1032    raeburn  9919:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9920:         $thisfn=~s/\?.+$//;
                   9921:     }
1.268     www      9922:     return $thisfn;
                   9923: }
                   9924: 
                   9925: # ------------------------------------------------------------- Clutter up URLs
                   9926: 
                   9927: sub clutter {
                   9928:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9929:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9930: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9931:        $thisfn='/res'.$thisfn; 
                   9932:     }
1.1031    raeburn  9933:     if ($thisfn !~m|^/adm|) {
                   9934: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9935: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9936: 	} else {
                   9937: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9938: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9939: 	    if ($embstyle eq 'ssi'
                   9940: 		|| ($embstyle eq 'hdn')
                   9941: 		|| ($embstyle eq 'rat')
                   9942: 		|| ($embstyle eq 'prv')
                   9943: 		|| ($embstyle eq 'ign')) {
                   9944: 		#do nothing with these
                   9945: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9946: 		|| ($embstyle eq 'emb')
                   9947: 		|| ($embstyle eq 'wrp')) {
                   9948: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9949: 	    } elsif ($embstyle eq 'unk'
                   9950: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9951: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9952: 	    } else {
1.718     www      9953: #		&logthis("Got a blank emb style");
1.695     albertel 9954: 	    }
1.694     albertel 9955: 	}
                   9956:     }
1.31      www      9957:     return $thisfn;
1.12      www      9958: }
                   9959: 
1.787     albertel 9960: sub clutter_with_no_wrapper {
                   9961:     my $uri = &clutter(shift);
                   9962:     if ($uri =~ m-^/adm/-) {
                   9963: 	$uri =~ s-^/adm/wrapper/-/-;
                   9964: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9965:     }
                   9966:     return $uri;
                   9967: }
                   9968: 
1.557     albertel 9969: sub freeze_escape {
                   9970:     my ($value)=@_;
                   9971:     if (ref($value)) {
                   9972: 	$value=&nfreeze($value);
                   9973: 	return '__FROZEN__'.&escape($value);
                   9974:     }
                   9975:     return &escape($value);
                   9976: }
                   9977: 
1.11      www      9978: 
1.557     albertel 9979: sub thaw_unescape {
                   9980:     my ($value)=@_;
                   9981:     if ($value =~ /^__FROZEN__/) {
                   9982: 	substr($value,0,10,undef);
                   9983: 	$value=&unescape($value);
                   9984: 	return &thaw($value);
                   9985:     }
                   9986:     return &unescape($value);
                   9987: }
                   9988: 
1.436     albertel 9989: sub correct_line_ends {
                   9990:     my ($result)=@_;
                   9991:     $$result =~s/\r\n/\n/mg;
                   9992:     $$result =~s/\r/\n/mg;
1.415     albertel 9993: }
1.1       albertel 9994: # ================================================================ Main Program
                   9995: 
1.184     www      9996: sub goodbye {
1.204     albertel 9997:    &logthis("Starting Shut down");
1.443     albertel 9998: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9999:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10000: #converted
1.599     albertel 10001: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10002:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10003: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10004: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10005: #1.1 only
1.870     albertel 10006: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10007: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10008: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10009: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10010:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10011:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10012:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10013:    &flushcourselogs();
                   10014:    &logthis("Shutting down");
                   10015: }
                   10016: 
1.852     albertel 10017: sub get_dns {
1.869     albertel 10018:     my ($url,$func,$ignore_cache) = @_;
                   10019:     if (!$ignore_cache) {
                   10020: 	my ($content,$cached)=
                   10021: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10022: 	if ($cached) {
                   10023: 	    &$func($content);
                   10024: 	    return;
                   10025: 	}
                   10026:     }
                   10027: 
                   10028:     my %alldns;
1.852     albertel 10029:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10030:     foreach my $dns (<$config>) {
                   10031: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10032:         my $line = $1;
                   10033:         my ($host,$protocol) = split(/:/,$line);
                   10034:         if ($protocol ne 'https') {
                   10035:             $protocol = 'http';
                   10036:         }
                   10037: 	$alldns{$host} = $protocol;
1.869     albertel 10038:     }
                   10039:     while (%alldns) {
                   10040: 	my ($dns) = keys(%alldns);
1.852     albertel 10041: 	my $ua=new LWP::UserAgent;
1.1056.4.33  raeburn  10042:         $ua->timeout(30);
1.979     raeburn  10043: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10044: 	my $response=$ua->request($request);
1.979     raeburn  10045:         delete($alldns{$dns});
1.852     albertel 10046: 	next if ($response->is_error());
                   10047: 	my @content = split("\n",$response->content);
1.869     albertel 10048: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10049: 	&$func(\@content);
1.869     albertel 10050: 	return;
1.852     albertel 10051:     }
                   10052:     close($config);
1.871     albertel 10053:     my $which = (split('/',$url))[3];
                   10054:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10055:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10056:     my @content = <$config>;
                   10057:     &$func(\@content);
                   10058:     return;
1.852     albertel 10059: }
1.327     albertel 10060: # ------------------------------------------------------------ Read domain file
                   10061: {
1.852     albertel 10062:     my $loaded;
1.846     albertel 10063:     my %domain;
                   10064: 
1.852     albertel 10065:     sub parse_domain_tab {
                   10066: 	my ($lines) = @_;
                   10067: 	foreach my $line (@$lines) {
                   10068: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10069: 
1.846     albertel 10070: 	    chomp($line);
1.852     albertel 10071: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10072: 	    my %this_domain;
                   10073: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10074: 			       'lang_def', 'city', 'longi', 'lati',
                   10075: 			       'primary') {
                   10076: 		$this_domain{$field} = shift(@elements);
                   10077: 	    }
                   10078: 	    $domain{$name} = \%this_domain;
1.852     albertel 10079: 	}
                   10080:     }
1.864     albertel 10081: 
                   10082:     sub reset_domain_info {
                   10083: 	undef($loaded);
                   10084: 	undef(%domain);
                   10085:     }
                   10086: 
1.852     albertel 10087:     sub load_domain_tab {
1.869     albertel 10088: 	my ($ignore_cache) = @_;
                   10089: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10090: 	my $fh;
                   10091: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10092: 	    my @lines = <$fh>;
                   10093: 	    &parse_domain_tab(\@lines);
1.448     albertel 10094: 	}
1.852     albertel 10095: 	close($fh);
                   10096: 	$loaded = 1;
1.327     albertel 10097:     }
1.846     albertel 10098: 
                   10099:     sub domain {
1.852     albertel 10100: 	&load_domain_tab() if (!$loaded);
                   10101: 
1.846     albertel 10102: 	my ($name,$what) = @_;
                   10103: 	return if ( !exists($domain{$name}) );
                   10104: 
                   10105: 	if (!$what) {
                   10106: 	    return $domain{$name}{'description'};
                   10107: 	}
                   10108: 	return $domain{$name}{$what};
                   10109:     }
1.974     raeburn  10110: 
                   10111:     sub domain_info {
                   10112:         &load_domain_tab() if (!$loaded);
                   10113:         return %domain;
                   10114:     }
                   10115: 
1.327     albertel 10116: }
                   10117: 
                   10118: 
1.1       albertel 10119: # ------------------------------------------------------------- Read hosts file
                   10120: {
1.838     albertel 10121:     my %hostname;
1.844     albertel 10122:     my %hostdom;
1.845     albertel 10123:     my %libserv;
1.852     albertel 10124:     my $loaded;
1.888     albertel 10125:     my %name_to_host;
1.1056.4.6  raeburn  10126:     my %internetdom;
1.1056.4.25  raeburn  10127:     my %LC_dns_serv;
1.852     albertel 10128: 
                   10129:     sub parse_hosts_tab {
                   10130: 	my ($file) = @_;
                   10131: 	foreach my $configline (@$file) {
                   10132: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1056.4.25  raeburn  10133:             chomp($configline);
                   10134:             if ($configline =~ /^\^/) {
                   10135:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10136:                     $LC_dns_serv{$1} = 1;
                   10137:                 }
                   10138:                 next;
                   10139:             }
1.1056.4.6  raeburn  10140: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10141: 	    $name=~s/\s//g;
                   10142: 	    if ($id && $domain && $role && $name) {
                   10143: 		$hostname{$id}=$name;
1.888     albertel 10144: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10145: 		$hostdom{$id}=$domain;
                   10146: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10147:                 if (defined($protocol)) {
                   10148:                     if ($protocol eq 'https') {
                   10149:                         $protocol{$id} = $protocol;
                   10150:                     } else {
                   10151:                         $protocol{$id} = 'http'; 
                   10152:                     }
1.968     raeburn  10153:                 } else {
1.969     raeburn  10154:                     $protocol{$id} = 'http';
1.968     raeburn  10155:                 }
1.1056.4.6  raeburn  10156:                 if (defined($intdom)) {
                   10157:                     $internetdom{$id} = $intdom;
                   10158:                 }
1.852     albertel 10159: 	    }
                   10160: 	}
                   10161:     }
1.864     albertel 10162:     
                   10163:     sub reset_hosts_info {
1.897     albertel 10164: 	&purge_remembered();
1.864     albertel 10165: 	&reset_domain_info();
                   10166: 	&reset_hosts_ip_info();
1.892     albertel 10167: 	undef(%name_to_host);
1.864     albertel 10168: 	undef(%hostname);
                   10169: 	undef(%hostdom);
                   10170: 	undef(%libserv);
                   10171: 	undef($loaded);
                   10172:     }
1.1       albertel 10173: 
1.852     albertel 10174:     sub load_hosts_tab {
1.869     albertel 10175: 	my ($ignore_cache) = @_;
                   10176: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10177: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10178: 	my @config = <$config>;
                   10179: 	&parse_hosts_tab(\@config);
                   10180: 	close($config);
                   10181: 	$loaded=1;
1.1       albertel 10182:     }
1.852     albertel 10183: 
1.838     albertel 10184:     sub hostname {
1.852     albertel 10185: 	&load_hosts_tab() if (!$loaded);
                   10186: 
1.838     albertel 10187: 	my ($lonid) = @_;
                   10188: 	return $hostname{$lonid};
                   10189:     }
1.845     albertel 10190: 
1.838     albertel 10191:     sub all_hostnames {
1.852     albertel 10192: 	&load_hosts_tab() if (!$loaded);
                   10193: 
1.838     albertel 10194: 	return %hostname;
                   10195:     }
1.845     albertel 10196: 
1.888     albertel 10197:     sub all_names {
                   10198: 	&load_hosts_tab() if (!$loaded);
                   10199: 
                   10200: 	return %name_to_host;
                   10201:     }
                   10202: 
1.974     raeburn  10203:     sub all_host_domain {
                   10204:         &load_hosts_tab() if (!$loaded);
                   10205:         return %hostdom;
                   10206:     }
                   10207: 
1.845     albertel 10208:     sub is_library {
1.852     albertel 10209: 	&load_hosts_tab() if (!$loaded);
                   10210: 
1.845     albertel 10211: 	return exists($libserv{$_[0]});
                   10212:     }
                   10213: 
                   10214:     sub all_library {
1.852     albertel 10215: 	&load_hosts_tab() if (!$loaded);
                   10216: 
1.845     albertel 10217: 	return %libserv;
                   10218:     }
                   10219: 
1.1056.4.2  raeburn  10220:     sub unique_library {
                   10221:         #2x reverse removes all hostnames that appear more than once
                   10222:         my %unique = reverse &all_library();
                   10223:         return reverse %unique;
                   10224:     }
                   10225: 
1.841     albertel 10226:     sub get_servers {
1.852     albertel 10227: 	&load_hosts_tab() if (!$loaded);
                   10228: 
1.841     albertel 10229: 	my ($domain,$type) = @_;
                   10230: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10231: 	                                          : %hostname;
                   10232: 	my %result;
1.842     albertel 10233: 	if (ref($domain) eq 'ARRAY') {
                   10234: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10235: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10236: 		    $result{$host} = $hostname;
                   10237: 		}
                   10238: 	    }
                   10239: 	} else {
                   10240: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10241: 		if ($hostdom{$host} eq $domain) {
                   10242: 		    $result{$host} = $hostname;
                   10243: 		}
1.841     albertel 10244: 	    }
                   10245: 	}
                   10246: 	return %result;
                   10247:     }
1.845     albertel 10248: 
1.1056.4.2  raeburn  10249:     sub get_unique_servers {
                   10250:         my %unique = reverse &get_servers(@_);
                   10251:         return reverse %unique;
                   10252:     }
                   10253: 
1.844     albertel 10254:     sub host_domain {
1.852     albertel 10255: 	&load_hosts_tab() if (!$loaded);
                   10256: 
1.844     albertel 10257: 	my ($lonid) = @_;
                   10258: 	return $hostdom{$lonid};
                   10259:     }
                   10260: 
1.841     albertel 10261:     sub all_domains {
1.852     albertel 10262: 	&load_hosts_tab() if (!$loaded);
                   10263: 
1.841     albertel 10264: 	my %seen;
                   10265: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10266: 	return @uniq;
                   10267:     }
1.1056.4.3  raeburn  10268: 
                   10269:     sub internet_dom {
                   10270:         &load_hosts_tab() if (!$loaded);
                   10271: 
                   10272:         my ($lonid) = @_;
                   10273:         return $internetdom{$lonid};
                   10274:     }
1.1056.4.27  raeburn  10275: 
                   10276:     sub is_LC_dns {
                   10277:         &load_hosts_tab() if (!$loaded);
                   10278: 
                   10279:         my ($hostname) = @_;
                   10280:         return exists($LC_dns_serv{$hostname});
                   10281:     }
                   10282: 
1.1       albertel 10283: }
                   10284: 
1.847     albertel 10285: { 
                   10286:     my %iphost;
1.856     albertel 10287:     my %name_to_ip;
                   10288:     my %lonid_to_ip;
1.869     albertel 10289: 
1.847     albertel 10290:     sub get_hosts_from_ip {
                   10291: 	my ($ip) = @_;
                   10292: 	my %iphosts = &get_iphost();
                   10293: 	if (ref($iphosts{$ip})) {
                   10294: 	    return @{$iphosts{$ip}};
                   10295: 	}
                   10296: 	return;
1.839     albertel 10297:     }
1.864     albertel 10298:     
                   10299:     sub reset_hosts_ip_info {
                   10300: 	undef(%iphost);
                   10301: 	undef(%name_to_ip);
                   10302: 	undef(%lonid_to_ip);
                   10303:     }
1.856     albertel 10304: 
                   10305:     sub get_host_ip {
                   10306: 	my ($lonid) = @_;
                   10307: 	if (exists($lonid_to_ip{$lonid})) {
                   10308: 	    return $lonid_to_ip{$lonid};
                   10309: 	}
                   10310: 	my $name=&hostname($lonid);
                   10311:    	my $ip = gethostbyname($name);
                   10312: 	return if (!$ip || length($ip) ne 4);
                   10313: 	$ip=inet_ntoa($ip);
                   10314: 	$name_to_ip{$name}   = $ip;
                   10315: 	$lonid_to_ip{$lonid} = $ip;
                   10316: 	return $ip;
                   10317:     }
1.847     albertel 10318:     
                   10319:     sub get_iphost {
1.869     albertel 10320: 	my ($ignore_cache) = @_;
1.894     albertel 10321: 
1.869     albertel 10322: 	if (!$ignore_cache) {
                   10323: 	    if (%iphost) {
                   10324: 		return %iphost;
                   10325: 	    }
                   10326: 	    my ($ip_info,$cached)=
                   10327: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10328: 	    if ($cached) {
                   10329: 		%iphost      = %{$ip_info->[0]};
                   10330: 		%name_to_ip  = %{$ip_info->[1]};
                   10331: 		%lonid_to_ip = %{$ip_info->[2]};
                   10332: 		return %iphost;
                   10333: 	    }
                   10334: 	}
1.894     albertel 10335: 
                   10336: 	# get yesterday's info for fallback
                   10337: 	my %old_name_to_ip;
                   10338: 	my ($ip_info,$cached)=
                   10339: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10340: 	if ($cached) {
                   10341: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10342: 	}
                   10343: 
1.888     albertel 10344: 	my %name_to_host = &all_names();
                   10345: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10346: 	    my $ip;
                   10347: 	    if (!exists($name_to_ip{$name})) {
                   10348: 		$ip = gethostbyname($name);
                   10349: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10350: 		    if (defined($old_name_to_ip{$name})) {
                   10351: 			$ip = $old_name_to_ip{$name};
                   10352: 			&logthis("Can't find $name defaulting to old $ip");
                   10353: 		    } else {
                   10354: 			&logthis("Name $name no IP found");
                   10355: 			next;
                   10356: 		    }
                   10357: 		} else {
                   10358: 		    $ip=inet_ntoa($ip);
1.847     albertel 10359: 		}
                   10360: 		$name_to_ip{$name} = $ip;
                   10361: 	    } else {
                   10362: 		$ip = $name_to_ip{$name};
1.653     albertel 10363: 	    }
1.888     albertel 10364: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10365: 		$lonid_to_ip{$id} = $ip;
                   10366: 	    }
                   10367: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10368: 	}
1.869     albertel 10369: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10370: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10371: 				      48*60*60);
1.869     albertel 10372: 
1.847     albertel 10373: 	return %iphost;
1.598     albertel 10374:     }
                   10375: 
1.992     raeburn  10376:     #
                   10377:     #  Given a DNS returns the loncapa host name for that DNS 
                   10378:     # 
                   10379:     sub host_from_dns {
                   10380:         my ($dns) = @_;
                   10381:         my @hosts;
                   10382:         my $ip;
                   10383: 
1.993     raeburn  10384:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10385:             $ip = $name_to_ip{$dns};
                   10386:         }
                   10387:         if (!$ip) {
                   10388:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10389:             if (length($ip) == 4) { 
                   10390: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10391:             }
                   10392:         }
                   10393:         if ($ip) {
                   10394: 	    @hosts = get_hosts_from_ip($ip);
                   10395: 	    return $hosts[0];
                   10396:         }
                   10397:         return undef;
1.986     foxr     10398:     }
1.992     raeburn  10399: 
1.1056.4.3  raeburn  10400:     sub get_internet_names {
                   10401:         my ($lonid) = @_;
                   10402:         return if ($lonid eq '');
                   10403:         my ($idnref,$cached)=
                   10404:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10405:         if ($cached) {
                   10406:             return $idnref;
                   10407:         }
                   10408:         my $ip = &get_host_ip($lonid);
                   10409:         my @hosts = &get_hosts_from_ip($ip);
                   10410:         my %iphost = &get_iphost();
                   10411:         my (@idns,%seen);
                   10412:         foreach my $id (@hosts) {
                   10413:             my $dom = &host_domain($id);
                   10414:             my $prim_id = &domain($dom,'primary');
                   10415:             my $prim_ip = &get_host_ip($prim_id);
                   10416:             next if ($seen{$prim_ip});
                   10417:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10418:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10419:                     my $intdom = &internet_dom($id);
                   10420:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10421:                         push(@idns,$intdom);
                   10422:                     }
                   10423:                 }
                   10424:             }
                   10425:             $seen{$prim_ip} = 1;
                   10426:         }
                   10427:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10428:     }
                   10429: 
                   10430: }
                   10431: 
                   10432: sub all_loncaparevs {
                   10433:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
1.986     foxr     10434: }
                   10435: 
1.862     albertel 10436: BEGIN {
                   10437: 
                   10438: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10439:     unless ($readit) {
                   10440: {
                   10441:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10442:     %perlvar = (%perlvar,%{$configvars});
                   10443: }
                   10444: 
                   10445: 
1.1       albertel 10446: # ------------------------------------------------------ Read spare server file
                   10447: {
1.448     albertel 10448:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10449: 
                   10450:     while (my $configline=<$config>) {
                   10451:        chomp($configline);
1.284     matthew  10452:        if ($configline) {
1.784     albertel 10453: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10454: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10455: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10456:        }
                   10457:     }
1.448     albertel 10458:     close($config);
1.1       albertel 10459: }
1.11      www      10460: # ------------------------------------------------------------ Read permissions
                   10461: {
1.448     albertel 10462:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10463: 
                   10464:     while (my $configline=<$config>) {
1.448     albertel 10465: 	chomp($configline);
                   10466: 	if ($configline) {
                   10467: 	    my ($role,$perm)=split(/ /,$configline);
                   10468: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10469: 	}
1.11      www      10470:     }
1.448     albertel 10471:     close($config);
1.11      www      10472: }
                   10473: 
                   10474: # -------------------------------------------- Read plain texts for permissions
                   10475: {
1.448     albertel 10476:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10477: 
                   10478:     while (my $configline=<$config>) {
1.448     albertel 10479: 	chomp($configline);
                   10480: 	if ($configline) {
1.742     raeburn  10481: 	    my ($short,@plain)=split(/:/,$configline);
                   10482:             %{$prp{$short}} = ();
                   10483: 	    if (@plain > 0) {
                   10484:                 $prp{$short}{'std'} = $plain[0];
                   10485:                 for (my $i=1; $i<@plain; $i++) {
                   10486:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10487:                 }
                   10488:             }
1.448     albertel 10489: 	}
1.135     www      10490:     }
1.448     albertel 10491:     close($config);
1.135     www      10492: }
                   10493: 
                   10494: # ---------------------------------------------------------- Read package table
                   10495: {
1.448     albertel 10496:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10497: 
                   10498:     while (my $configline=<$config>) {
1.483     albertel 10499: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10500: 	chomp($configline);
                   10501: 	my ($short,$plain)=split(/:/,$configline);
                   10502: 	my ($pack,$name)=split(/\&/,$short);
                   10503: 	if ($plain ne '') {
                   10504: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10505: 	    $packagetab{$short}=$plain; 
                   10506: 	}
1.11      www      10507:     }
1.448     albertel 10508:     close($config);
1.329     matthew  10509: }
                   10510: 
1.1056.4.3  raeburn  10511: # ---------------------------------------------------------- Read loncaparev table
                   10512: {
                   10513:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10514:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10515:             while (my $configline=<$config>) {
                   10516:                 chomp($configline);
                   10517:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10518:                 $loncaparevs{$hostid}=$loncaparev;
                   10519:             }
                   10520:             close($config);
                   10521:         }
                   10522:     }
                   10523: }
                   10524: 
                   10525: # ---------------------------------------------------------- Read serverhostID table
                   10526: {
                   10527:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10528:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10529:             while (my $configline=<$config>) {
                   10530:                 chomp($configline);
                   10531:                 my ($name,$id)=split(/:/,$configline);
                   10532:                 $serverhomeIDs{$name}=$id;
                   10533:             }
                   10534:             close($config);
                   10535:         }
                   10536:     }
                   10537: }
                   10538: 
1.1056.4.5  raeburn  10539: {
                   10540:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10541:     if (-e $file) {
                   10542:         my $parser = HTML::LCParser->new($file);
                   10543:         while (my $token = $parser->get_token()) {
                   10544:             if ($token->[0] eq 'S') {
                   10545:                 my $item = $token->[1];
                   10546:                 my $name = $token->[2]{'name'};
                   10547:                 my $value = $token->[2]{'value'};
                   10548:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10549:                     my $release = $parser->get_text();
                   10550:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10551:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10552:                 }
                   10553:             }
                   10554:         }
                   10555:     }
                   10556: }
                   10557: 
1.1056.4.33  raeburn  10558: # ---------------------------------------------------------- Read managers table
                   10559: {
                   10560:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   10561:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   10562:             while (my $configline=<$config>) {
                   10563:                 chomp($configline);
                   10564:                 next if ($configline =~ /^\#/);
                   10565:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   10566:                     $managerstab{$configline} = 1;
                   10567:                 }
                   10568:             }
                   10569:             close($config);
                   10570:         }
                   10571:     }
                   10572: }
                   10573: 
1.329     matthew  10574: # ------------- set up temporary directory
                   10575: {
                   10576:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10577: 
1.11      www      10578: }
                   10579: 
1.794     albertel 10580: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10581: 				'compress_threshold'=> 20_000,
                   10582:  			        });
1.185     www      10583: 
1.281     www      10584: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10585: $dumpcount=0;
1.958     www      10586: $locknum=0;
1.22      www      10587: 
1.163     harris41 10588: &logtouch();
1.672     albertel 10589: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10590: $readit=1;
1.564     albertel 10591:     {
                   10592: 	use integer;
                   10593: 	my $test=(2**32)+1;
1.568     albertel 10594: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10595: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10596:     }
1.195     www      10597: }
1.1       albertel 10598: }
1.179     www      10599: 
1.1       albertel 10600: 1;
1.191     harris41 10601: __END__
                   10602: 
1.243     albertel 10603: =pod
                   10604: 
1.191     harris41 10605: =head1 NAME
                   10606: 
1.243     albertel 10607: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10608: 
                   10609: =head1 SYNOPSIS
                   10610: 
1.243     albertel 10611: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10612: 
                   10613:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10614: 
1.243     albertel 10615: Common parameters:
                   10616: 
                   10617: =over 4
                   10618: 
                   10619: =item *
                   10620: 
                   10621: $uname : an internal username (if $cname expecting a course Id specifically)
                   10622: 
                   10623: =item *
                   10624: 
                   10625: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10626: 
                   10627: =item *
                   10628: 
                   10629: $symb : a resource instance identifier
                   10630: 
                   10631: =item *
                   10632: 
                   10633: $namespace : the name of a .db file that contains the data needed or
                   10634: being set.
                   10635: 
                   10636: =back
                   10637: 
1.394     bowersj2 10638: =head1 OVERVIEW
1.191     harris41 10639: 
1.394     bowersj2 10640: lonnet provides subroutines which interact with the
                   10641: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10642: about classes, users, and resources.
1.243     albertel 10643: 
                   10644: For many of these objects you can also use this to store data about
                   10645: them or modify them in various ways.
1.191     harris41 10646: 
1.394     bowersj2 10647: =head2 Symbs
1.191     harris41 10648: 
1.394     bowersj2 10649: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10650: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10651: map, the resource number of the resource in the map, and the URL of
                   10652: the resource itself. The latter is somewhat redundant, but might help
                   10653: if maps change.
                   10654: 
                   10655: An example is
                   10656: 
                   10657:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10658: 
                   10659: The respective map entry is
                   10660: 
                   10661:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10662:   title="Problem 2">
                   10663:  </resource>
                   10664: 
                   10665: Symbs are used by the random number generator, as well as to store and
                   10666: restore data specific to a certain instance of for example a problem.
                   10667: 
                   10668: =head2 Storing And Retrieving Data
                   10669: 
                   10670: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10671: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10672: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10673: is is the non-critical message twin of cstore. These functions are for
                   10674: handlers to store a perl hash to a user's permanent data space in an
                   10675: easy manner, and to retrieve it again on another call. It is expected
                   10676: that a handler would use this once at the beginning to retrieve data,
                   10677: and then again once at the end to send only the new data back.
                   10678: 
                   10679: The data is stored in the user's data directory on the user's
                   10680: homeserver under the ID of the course.
                   10681: 
                   10682: The hash that is returned by restore will have all of the previous
                   10683: value for all of the elements of the hash.
                   10684: 
                   10685: Example:
                   10686: 
                   10687:  #creating a hash
                   10688:  my %hash;
                   10689:  $hash{'foo'}='bar';
                   10690: 
                   10691:  #storing it
                   10692:  &Apache::lonnet::cstore(\%hash);
                   10693: 
                   10694:  #changing a value
                   10695:  $hash{'foo'}='notbar';
                   10696: 
                   10697:  #adding a new value
                   10698:  $hash{'bar'}='foo';
                   10699:  &Apache::lonnet::cstore(\%hash);
                   10700: 
                   10701:  #retrieving the hash
                   10702:  my %history=&Apache::lonnet::restore();
                   10703: 
                   10704:  #print the hash
                   10705:  foreach my $key (sort(keys(%history))) {
                   10706:    print("\%history{$key} = $history{$key}");
                   10707:  }
                   10708: 
                   10709: Will print out:
1.191     harris41 10710: 
1.394     bowersj2 10711:  %history{1:foo} = bar
                   10712:  %history{1:keys} = foo:timestamp
                   10713:  %history{1:timestamp} = 990455579
                   10714:  %history{2:bar} = foo
                   10715:  %history{2:foo} = notbar
                   10716:  %history{2:keys} = foo:bar:timestamp
                   10717:  %history{2:timestamp} = 990455580
                   10718:  %history{bar} = foo
                   10719:  %history{foo} = notbar
                   10720:  %history{timestamp} = 990455580
                   10721:  %history{version} = 2
                   10722: 
                   10723: Note that the special hash entries C<keys>, C<version> and
                   10724: C<timestamp> were added to the hash. C<version> will be equal to the
                   10725: total number of versions of the data that have been stored. The
                   10726: C<timestamp> attribute will be the UNIX time the hash was
                   10727: stored. C<keys> is available in every historical section to list which
                   10728: keys were added or changed at a specific historical revision of a
                   10729: hash.
                   10730: 
                   10731: B<Warning>: do not store the hash that restore returns directly. This
                   10732: will cause a mess since it will restore the historical keys as if the
                   10733: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10734: 
1.394     bowersj2 10735: Calling convention:
1.191     harris41 10736: 
1.394     bowersj2 10737:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10738:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10739: 
1.394     bowersj2 10740: For more detailed information, see lonnet specific documentation.
1.191     harris41 10741: 
1.394     bowersj2 10742: =head1 RETURN MESSAGES
1.191     harris41 10743: 
1.394     bowersj2 10744: =over 4
1.191     harris41 10745: 
1.394     bowersj2 10746: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10747: 
1.394     bowersj2 10748: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10749: when the connection is brought back up
1.191     harris41 10750: 
1.394     bowersj2 10751: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10752: for later delivery
1.191     harris41 10753: 
1.967     bisitz   10754: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10755: 
1.394     bowersj2 10756: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10757: that was requested
1.191     harris41 10758: 
1.243     albertel 10759: =back
1.191     harris41 10760: 
1.243     albertel 10761: =head1 PUBLIC SUBROUTINES
1.191     harris41 10762: 
1.243     albertel 10763: =head2 Session Environment Functions
1.191     harris41 10764: 
1.243     albertel 10765: =over 4
1.191     harris41 10766: 
1.394     bowersj2 10767: =item * 
                   10768: X<appenv()>
1.949     raeburn  10769: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10770: the user envirnoment file, and will be restored for each access this
1.620     albertel 10771: user makes during this session, also modifies the %env for the current
1.949     raeburn  10772: process. Optional rolesarrayref - if defined contains a reference to an array
                   10773: of roles which are exempt from the restriction on modifying user.role entries 
                   10774: in the user's environment.db and in %env.    
1.191     harris41 10775: 
                   10776: =item *
1.394     bowersj2 10777: X<delenv()>
1.987     raeburn  10778: B<delenv($delthis,$regexp)>: removes all items from the session
                   10779: environment file that begin with $delthis. If the 
                   10780: optional second arg - $regexp - is true, $delthis is treated as a 
                   10781: regular expression, otherwise \Q$delthis\E is used. 
                   10782: The values are also deleted from the current processes %env.
1.191     harris41 10783: 
1.795     albertel 10784: =item * get_env_multiple($name) 
                   10785: 
                   10786: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10787: values may be defined and end up as an array ref.
                   10788: 
                   10789: returns an array of values
                   10790: 
1.243     albertel 10791: =back
                   10792: 
                   10793: =head2 User Information
1.191     harris41 10794: 
1.243     albertel 10795: =over 4
1.191     harris41 10796: 
                   10797: =item *
1.394     bowersj2 10798: X<queryauthenticate()>
                   10799: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10800: authentication scheme
                   10801: 
                   10802: =item *
1.394     bowersj2 10803: X<authenticate()>
1.1056.4.3  raeburn  10804: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10805: authenticate user from domain's lib servers (first use the current
                   10806: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10807: $checkdefauth is optional (value is 1 if a check should be made to
                   10808:    authenticate user using default authentication method, and allow
                   10809:    account creation if username does not have account in the domain).
                   10810: $clientcancheckhost is optional (value is 1 if checking whether the
                   10811:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10812: 
                   10813: =item *
1.394     bowersj2 10814: X<homeserver()>
                   10815: B<homeserver($uname,$udom)>: find the server which has
                   10816: the user's directory and files (there must be only one), this caches
                   10817: the answer, and also caches if there is a borken connection.
1.191     harris41 10818: 
                   10819: =item *
1.394     bowersj2 10820: X<idget()>
                   10821: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10822: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10823: username, and only 1 username per ID in a specific domain) (returns
                   10824: hash: id=>name,id=>name)
1.191     harris41 10825: 
                   10826: =item *
1.394     bowersj2 10827: X<idrget()>
                   10828: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10829: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10830: 
                   10831: =item *
1.394     bowersj2 10832: X<idput()>
                   10833: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10834: 
                   10835: =item *
1.394     bowersj2 10836: X<rolesinit()>
                   10837: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10838: 
                   10839: =item *
1.551     albertel 10840: X<getsection()>
                   10841: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10842: course $cname, return section name/number or '' for "not in course"
                   10843: and '-1' for "no section"
                   10844: 
                   10845: =item *
1.394     bowersj2 10846: X<userenvironment()>
                   10847: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10848: passed in @what from the requested user's environment, returns a hash
                   10849: 
1.858     raeburn  10850: =item * 
                   10851: X<userlog_query()>
1.859     albertel 10852: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10853: activity.log file. %filters defines filters applied when parsing the
                   10854: log file. These can be start or end timestamps, or the type of action
                   10855: - log to look for Login or Logout events, check for Checkin or
                   10856: Checkout, role for role selection. The response is in the form
                   10857: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10858: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10859: 
1.243     albertel 10860: =back
                   10861: 
                   10862: =head2 User Roles
                   10863: 
                   10864: =over 4
                   10865: 
                   10866: =item *
                   10867: 
1.810     raeburn  10868: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10869:  F: full access
                   10870:  U,I,K: authentication modes (cxx only)
                   10871:  '': forbidden
                   10872:  1: user needs to choose course
                   10873:  2: browse allowed
1.766     albertel 10874:  A: passphrase authentication needed
1.243     albertel 10875: 
                   10876: =item *
                   10877: 
                   10878: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10879: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10880: and course level
                   10881: 
                   10882: =item *
                   10883: 
1.988     raeburn  10884: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10885: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10886: $type is Course (default) or Community.
1.988     raeburn  10887: If $forcedefault evaluates to true, text returned will be default 
                   10888: text for $type. Otherwise, if this is a course, the text returned 
                   10889: will be a custom name for the role (if defined in the course's 
                   10890: environment).  If no custom name is defined the default is returned.
                   10891:    
1.832     raeburn  10892: =item *
                   10893: 
1.935     raeburn  10894: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10895: All arguments are optional. Returns a hash of a roles, either for
                   10896: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10897: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10898: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10899: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10900: For each key, value is set to colon-separated start and end times for
                   10901: the role.  If no username and domain are specified, will default to
1.934     raeburn  10902: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10903: of role statuses (active, future or previous), roles 
                   10904: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10905: to restrict the list of roles reported. If no array ref is 
                   10906: provided for types, will default to return only active roles.
1.834     albertel 10907: 
1.243     albertel 10908: =back
                   10909: 
                   10910: =head2 User Modification
                   10911: 
                   10912: =over 4
                   10913: 
                   10914: =item *
                   10915: 
1.957     raeburn  10916: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10917: user for the level given by URL.  Optional start and end dates (leave empty
                   10918: string or zero for "no date")
1.191     harris41 10919: 
                   10920: =item *
                   10921: 
1.243     albertel 10922: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10923: change a users, password, possible return values are: ok,
                   10924: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10925: refused
1.191     harris41 10926: 
                   10927: =item *
                   10928: 
1.243     albertel 10929: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10930: 
                   10931: =item *
                   10932: 
1.1056.4.1  raeburn  10933: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10934:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10935: 
                   10936: will update user information (firstname,middlename,lastname,generation,
                   10937: permanentemail), and if forceid is true, student/employee ID also.
                   10938: A user's institutional affiliation(s) can also be updated.
                   10939: User information fields will not be overwritten with empty entries 
                   10940: unless the field is included in the $candelete array reference.
                   10941: This array is included when a single user is modified via "Manage Users",
                   10942: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10943: 
                   10944: =item *
                   10945: 
1.286     matthew  10946: modifystudent
                   10947: 
1.957     raeburn  10948: modify a student's enrollment and identification information.
1.286     matthew  10949: The course id is resolved based on the current users environment.  
                   10950: This means the envoking user must be a course coordinator or otherwise
                   10951: associated with a course.
                   10952: 
1.297     matthew  10953: This call is essentially a wrapper for lonnet::modifyuser and
                   10954: lonnet::modify_student_enrollment
1.286     matthew  10955: 
                   10956: Inputs: 
                   10957: 
                   10958: =over 4
                   10959: 
1.957     raeburn  10960: =item B<$udom> Student's loncapa domain
1.286     matthew  10961: 
1.957     raeburn  10962: =item B<$uname> Student's loncapa login name
1.286     matthew  10963: 
1.964     bisitz   10964: =item B<$uid> Student/Employee ID
1.286     matthew  10965: 
1.957     raeburn  10966: =item B<$umode> Student's authentication mode
1.286     matthew  10967: 
1.957     raeburn  10968: =item B<$upass> Student's password
1.286     matthew  10969: 
1.957     raeburn  10970: =item B<$first> Student's first name
1.286     matthew  10971: 
1.957     raeburn  10972: =item B<$middle> Student's middle name
1.286     matthew  10973: 
1.957     raeburn  10974: =item B<$last> Student's last name
1.286     matthew  10975: 
1.957     raeburn  10976: =item B<$gene> Student's generation
1.286     matthew  10977: 
1.957     raeburn  10978: =item B<$usec> Student's section in course
1.286     matthew  10979: 
                   10980: =item B<$end> Unix time of the roles expiration
                   10981: 
                   10982: =item B<$start> Unix time of the roles start date
                   10983: 
                   10984: =item B<$forceid> If defined, allow $uid to be changed
                   10985: 
                   10986: =item B<$desiredhome> server to use as home server for student
                   10987: 
1.957     raeburn  10988: =item B<$email> Student's permanent e-mail address
                   10989: 
                   10990: =item B<$type> Type of enrollment (auto or manual)
                   10991: 
1.963     raeburn  10992: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10993: 
                   10994: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10995: 
1.963     raeburn  10996: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10997: 
1.963     raeburn  10998: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10999: 
1.963     raeburn  11000: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11001: 
1.286     matthew  11002: =back
1.297     matthew  11003: 
                   11004: =item *
                   11005: 
                   11006: modify_student_enrollment
                   11007: 
                   11008: Change a students enrollment status in a class.  The environment variable
                   11009: 'role.request.course' must be defined for this function to proceed.
                   11010: 
                   11011: Inputs:
                   11012: 
                   11013: =over 4
                   11014: 
                   11015: =item $udom, students domain
                   11016: 
                   11017: =item $uname, students name
                   11018: 
                   11019: =item $uid, students user id
                   11020: 
                   11021: =item $first, students first name
                   11022: 
                   11023: =item $middle
                   11024: 
                   11025: =item $last
                   11026: 
                   11027: =item $gene
                   11028: 
                   11029: =item $usec
                   11030: 
                   11031: =item $end
                   11032: 
                   11033: =item $start
                   11034: 
1.957     raeburn  11035: =item $type
                   11036: 
                   11037: =item $locktype
                   11038: 
                   11039: =item $cid
                   11040: 
                   11041: =item $selfenroll
                   11042: 
                   11043: =item $context
                   11044: 
1.297     matthew  11045: =back
                   11046: 
1.191     harris41 11047: 
                   11048: =item *
                   11049: 
1.243     albertel 11050: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11051: custom role; give a custom role to a user for the level given by URL.  Specify
                   11052: name and domain of role author, and role name
1.191     harris41 11053: 
                   11054: =item *
                   11055: 
1.243     albertel 11056: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11057: 
                   11058: =item *
                   11059: 
1.243     albertel 11060: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11061: 
                   11062: =back
                   11063: 
                   11064: =head2 Course Infomation
                   11065: 
                   11066: =over 4
1.191     harris41 11067: 
                   11068: =item *
                   11069: 
1.631     albertel 11070: coursedescription($courseid) : returns a hash of information about the
                   11071: specified course id, including all environment settings for the
                   11072: course, the description of the course will be in the hash under the
                   11073: key 'description'
1.191     harris41 11074: 
                   11075: =item *
                   11076: 
1.624     albertel 11077: resdata($name,$domain,$type,@which) : request for current parameter
                   11078: setting for a specific $type, where $type is either 'course' or 'user',
                   11079: @what should be a list of parameters to ask about. This routine caches
                   11080: answers for 5 minutes.
1.243     albertel 11081: 
1.877     foxr     11082: =item *
                   11083: 
                   11084: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11085: data base, returning a hash that is keyed by the resource name and has
                   11086: values that are the resource value.  I believe that the timestamps and
                   11087: versions are also returned.
                   11088: 
                   11089: 
1.243     albertel 11090: =back
                   11091: 
                   11092: =head2 Course Modification
                   11093: 
                   11094: =over 4
1.191     harris41 11095: 
                   11096: =item *
                   11097: 
1.243     albertel 11098: writecoursepref($courseid,%prefs) : write preferences (environment
                   11099: database) for a course
1.191     harris41 11100: 
                   11101: =item *
                   11102: 
1.1011    raeburn  11103: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11104: 
                   11105: =item *
                   11106: 
1.1038    raeburn  11107: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11108: 
                   11109: =back
                   11110: 
                   11111: =head2 Resource Subroutines
                   11112: 
                   11113: =over 4
1.191     harris41 11114: 
                   11115: =item *
                   11116: 
1.243     albertel 11117: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11118: 
                   11119: =item *
                   11120: 
1.243     albertel 11121: repcopy($filename) : subscribes to the requested file, and attempts to
                   11122: replicate from the owning library server, Might return
1.607     raeburn  11123: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11124: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11125: resource. Expects the local filesystem pathname
                   11126: (/home/httpd/html/res/....)
                   11127: 
                   11128: =back
                   11129: 
                   11130: =head2 Resource Information
                   11131: 
                   11132: =over 4
1.191     harris41 11133: 
                   11134: =item *
                   11135: 
1.243     albertel 11136: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11137: a vairety of different possible values, $varname should be a request
                   11138: string, and the other parameters can be used to specify who and what
                   11139: one is asking about.
                   11140: 
                   11141: Possible values for $varname are environment.lastname (or other item
                   11142: from the envirnment hash), user.name (or someother aspect about the
                   11143: user), resource.0.maxtries (or some other part and parameter of a
                   11144: resource)
1.204     albertel 11145: 
                   11146: =item *
                   11147: 
1.243     albertel 11148: directcondval($number) : get current value of a condition; reads from a state
                   11149: string
1.204     albertel 11150: 
                   11151: =item *
                   11152: 
1.243     albertel 11153: condval($condidx) : value of condition index based on state
1.204     albertel 11154: 
                   11155: =item *
                   11156: 
1.243     albertel 11157: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11158: resource's metadata, $what should be either a specific key, or either
                   11159: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11160: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11161: 
                   11162: this function automatically caches all requests
1.191     harris41 11163: 
                   11164: =item *
                   11165: 
1.243     albertel 11166: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11167: network of library servers; returns file handle of where SQL and regex results
                   11168: will be stored for query
1.191     harris41 11169: 
                   11170: =item *
                   11171: 
1.243     albertel 11172: symbread($filename) : return symbolic list entry (filename argument optional);
                   11173: returns the data handle
1.191     harris41 11174: 
                   11175: =item *
                   11176: 
1.243     albertel 11177: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11178: a possible symb for the URL in $thisfn, and if is an encryypted
                   11179: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11180: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11181: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11182: 
1.191     harris41 11183: 
                   11184: =item *
                   11185: 
1.243     albertel 11186: symbclean($symb) : removes versions numbers from a symb, returns the
                   11187: cleaned symb
1.191     harris41 11188: 
                   11189: =item *
                   11190: 
1.243     albertel 11191: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11192: course map, user must be in a course for it to work.
1.191     harris41 11193: 
                   11194: =item *
                   11195: 
1.243     albertel 11196: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11197: 
                   11198: =item *
                   11199: 
1.243     albertel 11200: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11201: a random seed, all arguments are optional, if they aren't sent it uses the
                   11202: environment to derive them. Note: if symb isn't sent and it can't get one
                   11203: from &symbread it will use the current time as its return value
1.191     harris41 11204: 
                   11205: =item *
                   11206: 
1.243     albertel 11207: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11208: unfakeable, receipt
1.191     harris41 11209: 
                   11210: =item *
                   11211: 
1.620     albertel 11212: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11213: 
                   11214: =item *
                   11215: 
1.243     albertel 11216: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11217: 
                   11218: =item *
                   11219: 
1.243     albertel 11220: 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 11221: 
                   11222: =item *
                   11223: 
1.243     albertel 11224: 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 11225: 
                   11226: =item *
                   11227: 
1.243     albertel 11228: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11229: 
                   11230: =item *
                   11231: 
1.243     albertel 11232: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11233: forcing spreadsheet to reevaluate the resource scores next time.
                   11234: 
                   11235: =back
                   11236: 
                   11237: =head2 Storing/Retreiving Data
                   11238: 
                   11239: =over 4
1.191     harris41 11240: 
                   11241: =item *
                   11242: 
1.243     albertel 11243: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11244: for this url; hashref needs to be given and should be a \%hashname; the
                   11245: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11246: be derived from the env
1.191     harris41 11247: 
                   11248: =item *
                   11249: 
1.243     albertel 11250: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11251: uses critical subroutine
1.191     harris41 11252: 
                   11253: =item *
                   11254: 
1.243     albertel 11255: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11256: all args are optional
1.191     harris41 11257: 
                   11258: =item *
                   11259: 
1.717     albertel 11260: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11261: dumps the complete (or key matching regexp) namespace into a hash
                   11262: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11263: normally &store()ed into
                   11264: 
                   11265: $range should be either an integer '100' (give me the first 100
                   11266:                                            matching records)
                   11267:               or be  two integers sperated by a - with no spaces
                   11268:                  '30-50' (give me the 30th through the 50th matching
                   11269:                           records)
                   11270: 
                   11271: 
                   11272: =item *
                   11273: 
                   11274: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11275: replaces a &store() version of data with a replacement set of data
                   11276: for a particular resource in a namespace passed in the $storehash hash 
                   11277: reference
                   11278: 
                   11279: =item *
                   11280: 
1.243     albertel 11281: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11282: works very similar to store/cstore, but all data is stored in a
                   11283: temporary location and can be reset using tmpreset, $storehash should
                   11284: be a hash reference, returns nothing on success
1.191     harris41 11285: 
                   11286: =item *
                   11287: 
1.243     albertel 11288: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11289: similar to restore, but all data is stored in a temporary location and
                   11290: can be reset using tmpreset. Returns a hash of values on success,
                   11291: error string otherwise.
1.191     harris41 11292: 
                   11293: =item *
                   11294: 
1.243     albertel 11295: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11296: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11297: 
                   11298: =item *
                   11299: 
1.243     albertel 11300: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11301: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11302: 
                   11303: =item *
                   11304: 
1.243     albertel 11305: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11306: namesp ($udom and $uname are optional)
1.191     harris41 11307: 
                   11308: =item *
                   11309: 
1.702     albertel 11310: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11311: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11312: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11313: 
1.702     albertel 11314: $range should be either an integer '100' (give me the first 100
                   11315:                                            matching records)
                   11316:               or be  two integers sperated by a - with no spaces
                   11317:                  '30-50' (give me the 30th through the 50th matching
                   11318:                           records)
1.449     matthew  11319: =item *
                   11320: 
                   11321: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11322: $store can be a scalar, an array reference, or if the amount to be 
                   11323: incremented is > 1, a hash reference.
                   11324: 
                   11325: ($udom and $uname are optional)
1.191     harris41 11326: 
                   11327: =item *
                   11328: 
1.243     albertel 11329: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11330: ($udom and $uname are optional)
1.191     harris41 11331: 
                   11332: =item *
                   11333: 
1.243     albertel 11334: cput($namespace,$storehash,$udom,$uname) : critical put
                   11335: ($udom and $uname are optional)
1.191     harris41 11336: 
                   11337: =item *
                   11338: 
1.748     albertel 11339: newput($namespace,$storehash,$udom,$uname) :
                   11340: 
                   11341: Attempts to store the items in the $storehash, but only if they don't
                   11342: currently exist, if this succeeds you can be certain that you have 
                   11343: successfully created a new key value pair in the $namespace db.
                   11344: 
                   11345: 
                   11346: Args:
                   11347:  $namespace: name of database to store values to
                   11348:  $storehash: hashref to store to the db
                   11349:  $udom: (optional) domain of user containing the db
                   11350:  $uname: (optional) name of user caontaining the db
                   11351: 
                   11352: Returns:
                   11353:  'ok' -> succeeded in storing all keys of $storehash
                   11354:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11355:                         least <key> already existed in the db (other
                   11356:                         requested keys may also already exist)
1.967     bisitz   11357:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11358:  'con_lost' -> unable to contact request server
                   11359:  'refused' -> action was not allowed by remote machine
                   11360: 
                   11361: 
                   11362: =item *
                   11363: 
1.243     albertel 11364: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11365: reference filled in from namesp (encrypts the return communication)
                   11366: ($udom and $uname are optional)
1.191     harris41 11367: 
                   11368: =item *
                   11369: 
1.243     albertel 11370: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11371: critical subroutine
                   11372: 
1.806     raeburn  11373: =item *
                   11374: 
1.860     raeburn  11375: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11376: array reference filled in from namespace found in domain level on either
                   11377: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11378: 
                   11379: =item *
                   11380: 
1.860     raeburn  11381: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11382: domain level either on specified domain server ($uhome) or primary domain 
                   11383: server ($udom and $uhome are optional)
1.806     raeburn  11384: 
1.943     raeburn  11385: =item * 
                   11386: 
                   11387: get_domain_defaults($target_domain) : returns hash with defaults for
                   11388: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11389: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11390: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11391: Values are retrieved from cache (if current), or from domain's configuration.db
                   11392: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11393: or lonTabs/domain.tab. 
                   11394: 
                   11395: %domdefaults = &get_auth_defaults($target_domain);
                   11396: 
1.243     albertel 11397: =back
                   11398: 
                   11399: =head2 Network Status Functions
                   11400: 
                   11401: =over 4
1.191     harris41 11402: 
                   11403: =item *
                   11404: 
                   11405: dirlist($uri) : return directory list based on URI
                   11406: 
                   11407: =item *
                   11408: 
1.243     albertel 11409: spareserver() : find server with least workload from spare.tab
                   11410: 
1.986     foxr     11411: 
                   11412: =item *
                   11413: 
                   11414: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11415: if there is no corresponding loncapa host.
                   11416: 
1.243     albertel 11417: =back
                   11418: 
1.986     foxr     11419: 
1.243     albertel 11420: =head2 Apache Request
                   11421: 
                   11422: =over 4
1.191     harris41 11423: 
                   11424: =item *
                   11425: 
1.243     albertel 11426: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11427: localhost, posts hash
                   11428: 
                   11429: =back
                   11430: 
                   11431: =head2 Data to String to Data
                   11432: 
                   11433: =over 4
1.191     harris41 11434: 
                   11435: =item *
                   11436: 
1.243     albertel 11437: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11438: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11439: 
                   11440: =item *
                   11441: 
1.243     albertel 11442: hashref2str($hashref) : convert a hashref into a string complete with
                   11443: escaping and '=' and '&' separators, supports elements that are
                   11444: arrayrefs and hashrefs
1.191     harris41 11445: 
                   11446: =item *
                   11447: 
1.243     albertel 11448: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11449: with escaping and '&' separators, supports elements that are arrayrefs
                   11450: and hashrefs
1.191     harris41 11451: 
                   11452: =item *
                   11453: 
1.243     albertel 11454: str2hash($string) : convert string to hash using unescaping and
                   11455: splitting on '=' and '&', supports elements that are arrayrefs and
                   11456: hashrefs
1.191     harris41 11457: 
                   11458: =item *
                   11459: 
1.243     albertel 11460: str2array($string) : convert string to hash using unescaping and
                   11461: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11462: 
                   11463: =back
                   11464: 
                   11465: =head2 Logging Routines
                   11466: 
                   11467: These routines allow one to make log messages in the lonnet.log and
                   11468: lonnet.perm logfiles.
1.191     harris41 11469: 
1.1056.4.31  raeburn  11470: =over 4
                   11471: 
1.191     harris41 11472: =item *
                   11473: 
1.243     albertel 11474: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11475: 
                   11476: =item *
                   11477: 
1.243     albertel 11478: logthis() : append message to the normal lonnet.log file, it gets
                   11479: preiodically rolled over and deleted.
1.191     harris41 11480: 
                   11481: =item *
                   11482: 
1.243     albertel 11483: logperm() : append a permanent message to lonnet.perm.log, this log
                   11484: file never gets deleted by any automated portion of the system, only
                   11485: messages of critical importance should go in here.
                   11486: 
                   11487: =back
                   11488: 
                   11489: =head2 General File Helper Routines
                   11490: 
                   11491: =over 4
1.191     harris41 11492: 
                   11493: =item *
                   11494: 
1.481     raeburn  11495: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11496: (a) files in /uploaded
                   11497:   (i) If a local copy of the file exists - 
                   11498:       compares modification date of local copy with last-modified date for 
                   11499:       definitive version stored on home server for course. If local copy is 
                   11500:       stale, requests a new version from the home server and stores it. 
                   11501:       If the original has been removed from the home server, then local copy 
                   11502:       is unlinked.
                   11503:   (ii) If local copy does not exist -
                   11504:       requests the file from the home server and stores it. 
                   11505:   
                   11506:   If $caller is 'uploadrep':  
                   11507:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11508:     for request for files originally uploaded via DOCS. 
                   11509:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11510:   
                   11511:   Otherwise:
                   11512:      This indicates a call from the content generation phase of the request.
                   11513:      -  returns the entire contents of the file or -1.
                   11514:      
                   11515: (b) files in /res
                   11516:    - returns the entire contents of a file or -1; 
                   11517:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11518: 
1.712     albertel 11519: 
                   11520: =item *
                   11521: 
                   11522: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11523:                   reference
                   11524: 
                   11525: returns either a stat() list of data about the file or an empty list
                   11526: if the file doesn't exist or couldn't find out about it (connection
                   11527: problems or user unknown)
                   11528: 
1.191     harris41 11529: =item *
                   11530: 
1.243     albertel 11531: filelocation($dir,$file) : returns file system location of a file
                   11532: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11533: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11534: and a file of ../bob will become /a/bob)
1.191     harris41 11535: 
                   11536: =item *
                   11537: 
                   11538: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11539: filelocation except for hrefs
                   11540: 
                   11541: =item *
                   11542: 
                   11543: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11544: 
1.243     albertel 11545: =back
                   11546: 
1.608     albertel 11547: =head2 Usererfile file routines (/uploaded*)
                   11548: 
                   11549: =over 4
                   11550: 
                   11551: =item *
                   11552: 
                   11553: userfileupload(): main rotine for putting a file in a user or course's
                   11554:                   filespace, arguments are,
                   11555: 
1.620     albertel 11556:  formname - required - this is the name of the element in $env where the
1.608     albertel 11557:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11558:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11559:            contents of the file is located in $env{'form.'.$formname}
1.1056.4.13  raeburn  11560:  context - if coursedoc, store the file in the course of the active role
                   11561:              of the current user;
                   11562:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11563:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11564:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11565:          if undefined, it will be placed in "unknown"
                   11566: 
                   11567:  (This routine calls clean_filename() to remove any dangerous
                   11568:  characters from the filename, and then calls finuserfileupload() to
                   11569:  complete the transaction)
                   11570: 
                   11571:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11572:  and /adm/notfound.html if unsuccessful
                   11573: 
                   11574: =item *
                   11575: 
                   11576: clean_filename(): routine for cleaing a filename up for storage in
                   11577:                  userfile space, argument is:
                   11578: 
                   11579:  filename - proposed filename
                   11580: 
                   11581: returns: the new clean filename
                   11582: 
                   11583: =item *
                   11584: 
1.1056.4.13  raeburn  11585: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11586: userspace, probably shouldn't be called directly
                   11587: 
                   11588:   docuname: username or courseid of destination for the file
                   11589:   docudom: domain of user/course of destination for the file
                   11590:   formname: same as for userfileupload()
1.1056.4.13  raeburn  11591:   fname: filename (including subdirectories) for the file
                   11592:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11593:   allfiles: reference to hash used to store objects found by parser
                   11594:   codebase: reference to hash used for codebases of java objects found by parser
                   11595:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11596:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11597:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11598:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11599:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11600:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1056.4.16  raeburn  11601:   mimetype: reference to scalar to accommodate mime type determined
                   11602:             from File::MMagic if $parser = parse.
1.608     albertel 11603: 
                   11604:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13  raeburn  11605:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11606:  was 'overwrite').
                   11607: 
1.608     albertel 11608: 
                   11609: =item *
                   11610: 
                   11611: renameuserfile(): renames an existing userfile to a new name
                   11612: 
                   11613:   Args:
                   11614:    docuname: username or courseid of destination for the file
                   11615:    docudom: domain of user/course of destination for the file
                   11616:    old: current file name (including any subdirs under userfiles)
                   11617:    new: desired file name (including any subdirs under userfiles)
                   11618: 
                   11619: =item *
                   11620: 
                   11621: mkdiruserfile(): creates a directory is a userfiles dir
                   11622: 
                   11623:   Args:
                   11624:    docuname: username or courseid of destination for the file
                   11625:    docudom: domain of user/course of destination for the file
                   11626:    dir: dir to create (including any subdirs under userfiles)
                   11627: 
                   11628: =item *
                   11629: 
                   11630: removeuserfile(): removes a file that exists in userfiles
                   11631: 
                   11632:   Args:
                   11633:    docuname: username or courseid of destination for the file
                   11634:    docudom: domain of user/course of destination for the file
                   11635:    fname: filname to delete (including any subdirs under userfiles)
                   11636: 
                   11637: =item *
                   11638: 
                   11639: removeuploadedurl(): convience function for removeuserfile()
                   11640: 
                   11641:   Args:
                   11642:    url:  a full /uploaded/... url to delete
                   11643: 
1.747     albertel 11644: =item * 
                   11645: 
                   11646: get_portfile_permissions():
                   11647:   Args:
                   11648:     domain: domain of user or course contain the portfolio files
                   11649:     user: name of user or num of course contain the portfolio files
                   11650:   Returns:
                   11651:     hashref of a dump of the proper file_permissions.db
                   11652:    
                   11653: 
                   11654: =item * 
                   11655: 
                   11656: get_access_controls():
                   11657: 
                   11658: Args:
                   11659:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11660:   group: (optional) the group you want the files associated with
                   11661:   file: (optional) the file you want access info on
                   11662: 
                   11663: Returns:
1.749     raeburn  11664:     a hash (keys are file names) of hashes containing
                   11665:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11666:         values are XML containing access control settings (see below) 
1.747     albertel 11667: 
                   11668: Internal notes:
                   11669: 
1.749     raeburn  11670:  access controls are stored in file_permissions.db as key=value pairs.
                   11671:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11672:         where scope -> public,guest,course,group,domains or users.
                   11673:               end -> UNIX time for end of access (0 -> no end date)
                   11674:               start -> UNIX time for start of access
                   11675: 
                   11676:     value -> XML description of access control
                   11677:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11678:             <start></start>
                   11679:             <end></end>
                   11680: 
                   11681:             <password></password>  for scope type = guest
                   11682: 
                   11683:             <domain></domain>     for scope type = course or group
                   11684:             <number></number>
                   11685:             <roles id="">
                   11686:              <role></role>
                   11687:              <access></access>
                   11688:              <section></section>
                   11689:              <group></group>
                   11690:             </roles>
                   11691: 
                   11692:             <dom></dom>         for scope type = domains
                   11693: 
                   11694:             <users>             for scope type = users
                   11695:              <user>
                   11696:               <uname></uname>
                   11697:               <udom></udom>
                   11698:              </user>
                   11699:             </users>
                   11700:            </scope> 
                   11701:               
                   11702:  Access data is also aggregated for each file in an additional key=value pair:
                   11703:  key -> path to file/file_name\0accesscontrol 
                   11704:  value -> reference to hash
                   11705:           hash contains key = value pairs
                   11706:           where key = uniqueID:scope_end_start
                   11707:                 value = UNIX time record was last updated
                   11708: 
                   11709:           Used to improve speed of look-ups of access controls for each file.  
                   11710:  
                   11711:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11712: 
                   11713: modify_access_controls():
                   11714: 
                   11715: Modifies access controls for a portfolio file
                   11716: Args
                   11717: 1. file name
                   11718: 2. reference to hash of required changes,
                   11719: 3. domain
                   11720: 4. username
                   11721:   where domain,username are the domain of the portfolio owner 
                   11722:   (either a user or a course) 
                   11723: 
                   11724: Returns:
                   11725: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11726: 2. result of deletions ('ok' or 'error', with error message).
                   11727: 3. reference to hash of any new or updated access controls.
                   11728: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11729:    key = integer (inbound ID)
                   11730:    value = uniqueID  
1.747     albertel 11731: 
1.608     albertel 11732: =back
                   11733: 
1.243     albertel 11734: =head2 HTTP Helper Routines
                   11735: 
                   11736: =over 4
                   11737: 
1.191     harris41 11738: =item *
                   11739: 
                   11740: escape() : unpack non-word characters into CGI-compatible hex codes
                   11741: 
                   11742: =item *
                   11743: 
                   11744: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11745: 
1.243     albertel 11746: =back
                   11747: 
                   11748: =head1 PRIVATE SUBROUTINES
                   11749: 
                   11750: =head2 Underlying communication routines (Shouldn't call)
                   11751: 
                   11752: =over 4
                   11753: 
                   11754: =item *
                   11755: 
                   11756: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11757: 
                   11758: =item *
                   11759: 
                   11760: reply() : uses subreply to send a message to remote machine, logs all failures
                   11761: 
                   11762: =item *
                   11763: 
                   11764: critical() : passes a critical message to another server; if cannot
                   11765: get through then place message in connection buffer directory and
                   11766: returns con_delayed, if incapable of saving message, returns
                   11767: con_failed
                   11768: 
                   11769: =item *
                   11770: 
                   11771: reconlonc() : tries to reconnect lonc client processes.
                   11772: 
                   11773: =back
                   11774: 
                   11775: =head2 Resource Access Logging
                   11776: 
                   11777: =over 4
                   11778: 
                   11779: =item *
                   11780: 
                   11781: flushcourselogs() : flush (save) buffer logs and access logs
                   11782: 
                   11783: =item *
                   11784: 
                   11785: courselog($what) : save message for course in hash
                   11786: 
                   11787: =item *
                   11788: 
                   11789: courseacclog($what) : save message for course using &courselog().  Perform
                   11790: special processing for specific resource types (problems, exams, quizzes, etc).
                   11791: 
1.191     harris41 11792: =item *
                   11793: 
                   11794: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11795: as a PerlChildExitHandler
1.243     albertel 11796: 
                   11797: =back
                   11798: 
                   11799: =head2 Other
                   11800: 
                   11801: =over 4
                   11802: 
                   11803: =item *
                   11804: 
                   11805: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11806: 
                   11807: =back
                   11808: 
                   11809: =cut
1.877     foxr     11810: 

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