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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.121! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.120 2020/01/21 14:01:54 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;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.807     albertel   98: use LONCAPA qw(:DEFAULT :match);
1.740     www        99: use LONCAPA::Configuration;
1.1160    www       100: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   101: use LONCAPA::Lond;
1.1172.2.110  raeburn   102: use LONCAPA::transliterate;
1.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.1172.2.79  raeburn   107: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.1172.2.9  raeburn   114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       115: {
                    116:     my $logid;
1.1172.2.9  raeburn   117:     sub write_log {
                    118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    119:         if ($context eq 'course') {
                    120:             if (($cnum eq '') || ($cdom eq '')) {
                    121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:             }
1.957     raeburn   124:         }
1.1172.2.13  raeburn   125: 	$logid ++;
1.957     raeburn   126:         my $now = time();
                    127: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   128:         my $logentry = {
                    129:                          $id => {
                    130:                                   'exe_uname' => $env{'user.name'},
                    131:                                   'exe_udom'  => $env{'user.domain'},
                    132:                                   'exe_time'  => $now,
                    133:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    134:                                   'delflag'   => $delflag,
                    135:                                   'logentry'  => $storehash,
                    136:                                   'uname'     => $uname,
                    137:                                   'udom'      => $udom,
                    138:                                 }
                    139:                        };
                    140:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       141:     }
                    142: }
1.1       albertel  143: 
1.163     harris41  144: sub logtouch {
                    145:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  146:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   147: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  148: 	close $fh;
                    149:     }
                    150:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    151:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    152: }
                    153: 
1.1       albertel  154: sub logthis {
                    155:     my $message=shift;
                    156:     my $execdir=$perlvar{'lonDaemons'};
                    157:     my $now=time;
                    158:     my $local=localtime($now);
1.1172.2.96  raeburn   159:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      160: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    161: 	print $fh $logstring;
1.448     albertel  162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
                    167: sub logperm {
                    168:     my $message=shift;
                    169:     my $execdir=$perlvar{'lonDaemons'};
                    170:     my $now=time;
                    171:     my $local=localtime($now);
1.1172.2.96  raeburn   172:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  173: 	print $fh "$now:$message:$local\n";
                    174: 	close($fh);
                    175:     }
1.1       albertel  176:     return 1;
                    177: }
                    178: 
1.850     albertel  179: sub create_connection {
1.853     albertel  180:     my ($hostname,$lonid) = @_;
1.851     albertel  181:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  182: 				     Type    => SOCK_STREAM,
                    183: 				     Timeout => 10);
                    184:     return 0 if (!$client);
1.890     albertel  185:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  186:     my $result = <$client>;
                    187:     chomp($result);
                    188:     return 1 if ($result eq 'done');
                    189:     return 0;
                    190: }
                    191: 
1.983     raeburn   192: sub get_server_timezone {
                    193:     my ($cnum,$cdom) = @_;
                    194:     my $home=&homeserver($cnum,$cdom);
                    195:     if ($home ne 'no_host') {
                    196:         my $cachetime = 24*3600;
                    197:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    198:         if (defined($cached)) {
                    199:             return $timezone;
                    200:         } else {
                    201:             my $timezone = &reply('servertimezone',$home);
                    202:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    203:         }
                    204:     }
                    205: }
1.850     albertel  206: 
1.1106    raeburn   207: sub get_server_distarch {
                    208:     my ($lonhost,$ignore_cache) = @_;
                    209:     if (defined($lonhost)) {
                    210:         if (!defined(&hostname($lonhost))) {
                    211:             return;
                    212:         }
                    213:         my $cachetime = 12*3600;
                    214:         if (!$ignore_cache) {
                    215:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    216:             if (defined($cached)) {
                    217:                 return $distarch;
                    218:             }
                    219:         }
                    220:         my $rep = &reply('serverdistarch',$lonhost);
                    221:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    222:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    223:                 $rep eq '') {
                    224:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    225:         }
                    226:     }
                    227:     return;
                    228: }
                    229: 
1.993     raeburn   230: sub get_server_loncaparev {
1.1073    raeburn   231:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   232:     if (defined($lonhost)) {
                    233:         if (!defined(&hostname($lonhost))) {
                    234:             undef($lonhost);
                    235:         }
                    236:     }
                    237:     if (!defined($lonhost)) {
                    238:         if (defined(&domain($dom,'primary'))) {
                    239:             $lonhost=&domain($dom,'primary');
                    240:             if ($lonhost eq 'no_host') {
                    241:                 undef($lonhost);
                    242:             }
                    243:         }
                    244:     }
                    245:     if (defined($lonhost)) {
1.1073    raeburn   246:         my $cachetime = 12*3600;
                    247:         if (!$ignore_cache) {
                    248:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    249:             if (defined($cached)) {
                    250:                 return $loncaparev;
                    251:             }
                    252:         }
                    253:         my ($answer,$loncaparev);
                    254:         my @ids=&current_machine_ids();
                    255:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    256:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   257:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   258:                 $loncaparev = $1;
                    259:             }
                    260:         } else {
                    261:             $answer = &reply('serverloncaparev',$lonhost);
                    262:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    263:                 if ($caller eq 'loncron') {
                    264:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   265:                     $ua->timeout(4);
1.1172.2.120  raeburn   266:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   267:                     my $protocol = $protocol{$lonhost};
                    268:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   269:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   270:                     my $request=new HTTP::Request('GET',$url);
                    271:                     my $response=$ua->request($request);
                    272:                     unless ($response->is_error()) {
                    273:                         my $content = $response->content;
1.1081    raeburn   274:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   275:                             $loncaparev = $1;
                    276:                         }
                    277:                     }
                    278:                 } else {
                    279:                     $loncaparev = $loncaparevs{$lonhost};
                    280:                 }
1.1081    raeburn   281:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   282:                 $loncaparev = $1;
                    283:             }
1.993     raeburn   284:         }
1.1073    raeburn   285:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   286:     }
                    287: }
                    288: 
1.1074    raeburn   289: sub get_server_homeID {
                    290:     my ($hostname,$ignore_cache,$caller) = @_;
                    291:     unless ($ignore_cache) {
                    292:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    293:         if (defined($cached)) {
                    294:             return $serverhomeID;
                    295:         }
                    296:     }
                    297:     my $cachetime = 12*3600;
                    298:     my $serverhomeID;
                    299:     if ($caller eq 'loncron') { 
                    300:         my @machine_ids = &machine_ids($hostname);
                    301:         foreach my $id (@machine_ids) {
                    302:             my $response = &reply('serverhomeID',$id);
                    303:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    304:                 $serverhomeID = $response;
                    305:                 last;
                    306:             }
                    307:         }
                    308:         if ($serverhomeID eq '') {
                    309:             $serverhomeID = $machine_ids[-1];
                    310:         }
                    311:     } else {
                    312:         $serverhomeID = $serverhomeIDs{$hostname};
                    313:     }
                    314:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    315: }
                    316: 
1.1121    raeburn   317: sub get_remote_globals {
                    318:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   319:     my ($result,%returnhash,%whatneeded);
                    320:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   321:         foreach my $what (sort(keys(%{$whathash}))) {
                    322:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   323:             my ($response,$cached);
1.1121    raeburn   324:             unless ($ignore_cache) {
1.1125    raeburn   325:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   326:             }
                    327:             if (defined($cached)) {
1.1125    raeburn   328:                 $returnhash{$what} = $response;
1.1121    raeburn   329:             } else {
1.1125    raeburn   330:                 $whatneeded{$what} = 1;
1.1121    raeburn   331:             }
                    332:         }
1.1125    raeburn   333:         if (keys(%whatneeded) == 0) {
                    334:             $result = 'ok';
                    335:         } else {
1.1121    raeburn   336:             my $requested = &freeze_escape(\%whatneeded);
                    337:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   338:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    339:                 ($rep eq 'unknown_cmd')) {
                    340:                 $result = $rep;
                    341:             } else {
                    342:                 $result = 'ok';
1.1121    raeburn   343:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   344:                 foreach my $item (@pairs) {
                    345:                     my ($key,$value)=split(/=/,$item,2);
                    346:                     my $what = &unescape($key);
                    347:                     my $hashid = $lonhost.'-'.$what;
                    348:                     $returnhash{$what}=&thaw_unescape($value);
                    349:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   350:                 }
                    351:             }
                    352:         }
                    353:     }
1.1125    raeburn   354:     return ($result,\%returnhash);
1.1121    raeburn   355: }
                    356: 
1.1124    raeburn   357: sub remote_devalidate_cache {
1.1172.2.35  raeburn   358:     my ($lonhost,$cachekeys) = @_;
                    359:     my $items;
                    360:     return unless (ref($cachekeys) eq 'ARRAY');
                    361:     my $cachestr = join('&',@{$cachekeys});
                    362:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   363: }
                    364: 
1.1       albertel  365: # -------------------------------------------------- Non-critical communication
                    366: sub subreply {
                    367:     my ($cmd,$server)=@_;
1.838     albertel  368:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      369:     #
                    370:     #  With loncnew process trimming, there's a timing hole between lonc server
                    371:     #  process exit and the master server picking up the listen on the AF_UNIX
                    372:     #  socket.  In that time interval, a lock file will exist:
                    373: 
                    374:     my $lockfile=$peerfile.".lock";
                    375:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   376: 	sleep(0.1);
1.549     foxr      377:     }
                    378:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      379:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      380:     #
1.550     foxr      381:     #   We'll give the connection a few tries before abandoning it.  If
                    382:     #   connection is not possible, we'll con_lost back to the client.
                    383:     #   
                    384:     my $client;
                    385:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    386: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    387: 				      Type    => SOCK_STREAM,
                    388: 				      Timeout => 10);
1.869     albertel  389: 	if ($client) {
1.550     foxr      390: 	    last;		# Connected!
1.850     albertel  391: 	} else {
1.853     albertel  392: 	    &create_connection(&hostname($server),$server);
1.550     foxr      393: 	}
1.1172.2.79  raeburn   394:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      395:     }
                    396:     my $answer;
                    397:     if ($client) {
1.704     albertel  398: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      399: 	$answer=<$client>;
                    400: 	if (!$answer) { $answer="con_lost"; }
                    401: 	chomp($answer);
                    402:     } else {
                    403: 	$answer = 'con_lost';	# Failed connection.
                    404:     }
1.1       albertel  405:     return $answer;
                    406: }
                    407: 
                    408: sub reply {
                    409:     my ($cmd,$server)=@_;
1.838     albertel  410:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  411:     my $answer=subreply($cmd,$server);
1.65      www       412:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   413:         my $logged = $cmd;
                    414:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    415:             my $subcmd = $1;
                    416:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    417:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    418:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    419:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    420:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    421:                     splice(@rest,2,1,'Hidden');
                    422:                 } elsif ($subcmd eq 'passwd') {
                    423:                     splice(@rest,2,2,('Hidden','Hidden'));
                    424:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    425:                          ($subcmd eq 'autoexportgrades')) {
                    426:                     splice(@rest,3,1,'Hidden');
                    427:                 }
                    428:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    429:             }
                    430:         }
                    431:         &logthis("<font color=\"blue\">WARNING:".
                    432:                  " $logged to $server returned $answer</font>");
1.12      www       433:     }
1.1       albertel  434:     return $answer;
                    435: }
                    436: 
                    437: # ----------------------------------------------------------- Send USR1 to lonc
                    438: 
                    439: sub reconlonc {
1.891     albertel  440:     my ($lonid) = @_;
                    441:     if ($lonid) {
1.1172.2.72  raeburn   442:         my $hostname = &hostname($lonid);
1.891     albertel  443: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    444: 	if ($hostname && -e $peerfile) {
                    445: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    446: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    447: 					     Type    => SOCK_STREAM,
                    448: 					     Timeout => 10);
                    449: 	    if ($client) {
                    450: 		print $client ("reset_retries\n");
                    451: 		my $answer=<$client>;
                    452: 		#reset just this one.
                    453: 	    }
                    454: 	}
                    455: 	return;
                    456:     }
                    457: 
1.836     www       458:     &logthis("Trying to reconnect lonc");
1.1       albertel  459:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   460:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  461: 	my $loncpid=<$fh>;
                    462:         chomp($loncpid);
                    463:         if (kill 0 => $loncpid) {
                    464: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    465:             kill USR1 => $loncpid;
                    466:             sleep 1;
1.836     www       467:          } else {
1.12      www       468: 	    &logthis(
1.672     albertel  469:                "<font color=\"blue\">WARNING:".
1.12      www       470:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  471:         }
                    472:     } else {
1.836     www       473: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  474:     }
                    475: }
                    476: 
                    477: # ------------------------------------------------------ Critical communication
1.12      www       478: 
1.1       albertel  479: sub critical {
                    480:     my ($cmd,$server)=@_;
1.838     albertel  481:     unless (&hostname($server)) {
1.672     albertel  482:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       483:                " Critical message to unknown server ($server)</font>");
                    484:         return 'no_such_host';
                    485:     }
1.1       albertel  486:     my $answer=reply($cmd,$server);
                    487:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   488: 	&reconlonc($server);
1.589     albertel  489: 	my $answer=reply($cmd,$server);
1.1       albertel  490:         if ($answer eq 'con_lost') {
                    491:             my $now=time;
                    492:             my $middlename=$cmd;
1.5       www       493:             $middlename=substr($middlename,0,16);
1.1       albertel  494:             $middlename=~s/\W//g;
                    495:             my $dfilename=
1.305     www       496:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    497:             $dumpcount++;
1.1       albertel  498:             {
1.448     albertel  499: 		my $dfh;
1.1172.2.96  raeburn   500: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  501: 		    print $dfh "$cmd\n"; 
                    502: 		    close($dfh);
                    503: 		}
1.1       albertel  504:             }
1.1172.2.79  raeburn   505:             sleep 1;
1.1       albertel  506:             my $wcmd='';
                    507:             {
1.448     albertel  508: 		my $dfh;
1.1172.2.96  raeburn   509: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  510: 		    $wcmd=<$dfh>; 
                    511: 		    close($dfh);
                    512: 		}
1.1       albertel  513:             }
                    514:             chomp($wcmd);
1.7       www       515:             if ($wcmd eq $cmd) {
1.672     albertel  516: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       517:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  518:                 &logperm("D:$server:$cmd");
                    519: 	        return 'con_delayed';
                    520:             } else {
1.672     albertel  521:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       522:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  523:                 &logperm("F:$server:$cmd");
                    524:                 return 'con_failed';
                    525:             }
                    526:         }
                    527:     }
                    528:     return $answer;
1.405     albertel  529: }
                    530: 
1.755     albertel  531: # ------------------------------------------- check if return value is an error
                    532: 
                    533: sub error {
                    534:     my ($result) = @_;
1.756     albertel  535:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  536: 	if ($2 == 2) { return undef; }
                    537: 	return $1;
                    538:     }
                    539:     return undef;
                    540: }
                    541: 
1.783     albertel  542: sub convert_and_load_session_env {
                    543:     my ($lonidsdir,$handle)=@_;
                    544:     my @profile;
                    545:     {
1.917     albertel  546: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    547: 	if (!$opened) {
1.915     albertel  548: 	    return 0;
                    549: 	}
1.783     albertel  550: 	flock($idf,LOCK_SH);
                    551: 	@profile=<$idf>;
                    552: 	close($idf);
                    553:     }
                    554:     my %temp_env;
                    555:     foreach my $line (@profile) {
1.786     albertel  556: 	if ($line !~ m/=/) {
                    557: 	    return 0;
                    558: 	}
1.783     albertel  559: 	chomp($line);
                    560: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    561: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    562:     }
                    563:     unlink("$lonidsdir/$handle.id");
                    564:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    565: 	    0640)) {
                    566: 	%disk_env = %temp_env;
                    567: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    568: 	untie(%disk_env);
                    569:     }
1.786     albertel  570:     return 1;
1.783     albertel  571: }
                    572: 
1.374     www       573: # ------------------------------------------- Transfer profile into environment
1.780     albertel  574: my $env_loaded;
                    575: sub transfer_profile_to_env {
1.788     albertel  576:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    577:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       578: 
1.720     albertel  579:     if (!defined($lonidsdir)) {
                    580: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    581:     }
                    582:     if (!defined($handle)) {
                    583:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    584:     }
                    585: 
1.786     albertel  586:     my $convert;
                    587:     {
1.917     albertel  588:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    589: 	if (!$opened) {
1.915     albertel  590: 	    return;
                    591: 	}
1.786     albertel  592: 	flock($idf,LOCK_SH);
                    593: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    594: 		&GDBM_READER(),0640)) {
                    595: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    596: 	    untie(%disk_env);
                    597: 	} else {
                    598: 	    $convert = 1;
                    599: 	}
                    600:     }
                    601:     if ($convert) {
                    602: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    603: 	    &logthis("Failed to load session, or convert session.");
                    604: 	}
1.374     www       605:     }
1.783     albertel  606: 
1.786     albertel  607:     my %remove;
1.783     albertel  608:     while ( my $envname = each(%env) ) {
1.433     matthew   609:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    610:             if ($time < time-300) {
1.783     albertel  611:                 $remove{$key}++;
1.433     matthew   612:             }
                    613:         }
                    614:     }
1.783     albertel  615: 
1.619     albertel  616:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  617:     $env_loaded=1;
1.783     albertel  618:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   619:         &delenv($expired_key);
1.374     www       620:     }
1.1       albertel  621: }
                    622: 
1.916     albertel  623: # ---------------------------------------------------- Check for valid session 
                    624: sub check_for_valid_session {
1.1172.2.96  raeburn   625:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  626:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   627:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   628:     if ($name eq 'lonDAV') {
                    629:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    630:     } else {
                    631:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   632:         if ($name eq '') {
                    633:             $name = 'lonID';
                    634:         }
                    635:     }
                    636:     if ($name eq 'lonID') {
                    637:         $secure = 'lonSID';
                    638:         $linkname = 'lonLinkID';
                    639:         $pubname = 'lonPubID';
                    640:         if (exists($cookies{$secure})) {
                    641:             $lonid=$cookies{$secure};
                    642:         } elsif (exists($cookies{$name})) {
                    643:             $lonid=$cookies{$name};
                    644:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    645:             $lonid=$cookies{$linkname};
                    646:         } elsif (exists($cookies{$pubname})) {
                    647:             $lonid=$cookies{$pubname};
                    648:         }
                    649:     } else {
                    650:         $lonid=$cookies{$name};
                    651:     }
                    652:     return undef if (!$lonid);
                    653: 
                    654:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    655:     if (-l "$lonidsdir/$handle.id") {
                    656:         my $link = readlink("$lonidsdir/$handle.id");
                    657:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    658:             $handle = $1;
                    659:         }
1.1155    raeburn   660:     }
1.1172.2.96  raeburn   661:     if (!-e "$lonidsdir/$handle.id") {
                    662:         if ((ref($domref)) && ($name eq 'lonID') &&
                    663:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    664:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    665:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    666:                 $$domref = $possudom;
                    667:             }
                    668:         }
                    669:         return undef;
                    670:     }
1.916     albertel  671: 
1.917     albertel  672:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    673:     return undef if (!$opened);
1.916     albertel  674: 
                    675:     flock($idf,LOCK_SH);
                    676:     my %disk_env;
                    677:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    678: 	    &GDBM_READER(),0640)) {
                    679: 	return undef;	
                    680:     }
                    681: 
                    682:     if (!defined($disk_env{'user.name'})
                    683: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   684:         untie(%disk_env);
1.916     albertel  685: 	return undef;
                    686:     }
1.1172.2.18  raeburn   687: 
1.1172.2.36  raeburn   688:     if (ref($userhashref) eq 'HASH') {
                    689:         $userhashref->{'name'} = $disk_env{'user.name'};
                    690:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   691:     }
1.1172.2.107  raeburn   692:     untie(%disk_env);
1.1172.2.18  raeburn   693: 
1.916     albertel  694:     return $handle;
                    695: }
                    696: 
1.830     albertel  697: sub timed_flock {
                    698:     my ($file,$lock_type) = @_;
                    699:     my $failed=0;
                    700:     eval {
                    701: 	local $SIG{__DIE__}='DEFAULT';
                    702: 	local $SIG{ALRM}=sub {
                    703: 	    $failed=1;
                    704: 	    die("failed lock");
                    705: 	};
                    706: 	alarm(13);
                    707: 	flock($file,$lock_type);
                    708: 	alarm(0);
                    709:     };
                    710:     if ($failed) {
                    711: 	return undef;
                    712:     } else {
                    713: 	return 1;
                    714:     }
                    715: }
                    716: 
1.1172.2.107  raeburn   717: sub get_sessionfile_vars {
                    718:     my ($handle,$lonidsdir,$storearr) = @_;
                    719:     my %returnhash;
                    720:     unless (ref($storearr) eq 'ARRAY') {
                    721:         return %returnhash;
                    722:     }
                    723:     if (-l "$lonidsdir/$handle.id") {
                    724:         my $link = readlink("$lonidsdir/$handle.id");
                    725:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    726:             $handle = $1;
                    727:         }
                    728:     }
                    729:     if ((-e "$lonidsdir/$handle.id") &&
                    730:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    731:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    732:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    733:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    734:                 flock($idf,LOCK_SH);
                    735:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    736:                         &GDBM_READER(),0640)) {
                    737:                     foreach my $item (@{$storearr}) {
                    738:                         $returnhash{$item} = $disk_env{$item};
                    739:                     }
                    740:                     untie(%disk_env);
                    741:                 }
                    742:             }
                    743:         }
                    744:     }
                    745:     return %returnhash;
                    746: }
                    747: 
1.5       www       748: # ---------------------------------------------------------- Append Environment
                    749: 
                    750: sub appenv {
1.949     raeburn   751:     my ($newenv,$roles) = @_;
                    752:     if (ref($newenv) eq 'HASH') {
                    753:         foreach my $key (keys(%{$newenv})) {
                    754:             my $refused = 0;
                    755: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    756:                 $refused = 1;
                    757:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   758:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   759:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    760:                         $refused = 0;
                    761:                     }
                    762:                 }
                    763:             }
                    764:             if ($refused) {
                    765:                 &logthis("<font color=\"blue\">WARNING: ".
                    766:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    767:                          .'</font>');
                    768: 	        delete($newenv->{$key});
                    769:             } else {
                    770:                 $env{$key}=$newenv->{$key};
                    771:             }
                    772:         }
1.1172.2.96  raeburn   773:         my $lonids = $perlvar{'lonIDsDir'};
                    774:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    775:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    776:             if ($opened
                    777: 	        && &timed_flock($env_file,LOCK_EX)
                    778: 	        &&
                    779: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    780: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    781: 	        while (my ($key,$value) = each(%{$newenv})) {
                    782: 	            $disk_env{$key} = $value;
                    783: 	        }
                    784: 	        untie(%disk_env);
                    785:             }
1.35      www       786:         }
1.191     harris41  787:     }
1.56      www       788:     return 'ok';
                    789: }
                    790: # ----------------------------------------------------- Delete from Environment
                    791: 
                    792: sub delenv {
1.1104    raeburn   793:     my ($delthis,$regexp,$roles) = @_;
                    794:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    795:         my $refused = 1;
                    796:         if (ref($roles) eq 'ARRAY') {
                    797:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    798:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    799:                 $refused = 0;
                    800:             }
                    801:         }
                    802:         if ($refused) {
                    803:             &logthis("<font color=\"blue\">WARNING: ".
                    804:                      "Attempt to delete from environment ".$delthis);
                    805:             return 'error';
                    806:         }
1.56      www       807:     }
1.917     albertel  808:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    809:     if ($opened
1.915     albertel  810: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  811: 	&&
                    812: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    813: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  814: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   815: 	    if ($regexp) {
                    816:                 if ($key=~/^$delthis/) {
                    817:                     delete($env{$key});
                    818:                     delete($disk_env{$key});
                    819:                 } 
                    820:             } else {
                    821:                 if ($key=~/^\Q$delthis\E/) {
                    822: 		    delete($env{$key});
                    823: 		    delete($disk_env{$key});
                    824: 	        }
                    825:             }
1.448     albertel  826: 	}
1.783     albertel  827: 	untie(%disk_env);
1.5       www       828:     }
                    829:     return 'ok';
1.369     albertel  830: }
                    831: 
1.790     albertel  832: sub get_env_multiple {
                    833:     my ($name) = @_;
                    834:     my @values;
                    835:     if (defined($env{$name})) {
                    836:         # exists is it an array
                    837:         if (ref($env{$name})) {
                    838:             @values=@{ $env{$name} };
                    839:         } else {
                    840:             $values[0]=$env{$name};
                    841:         }
                    842:     }
                    843:     return(@values);
                    844: }
                    845: 
1.958     www       846: # ------------------------------------------------------------------- Locking
                    847: 
                    848: sub set_lock {
                    849:     my ($text)=@_;
                    850:     $locknum++;
                    851:     my $id=$$.'-'.$locknum;
                    852:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    853:              'session.lock.'.$id => $text});
                    854:     return $id;
                    855: }
                    856: 
                    857: sub get_locks {
                    858:     my $num=0;
                    859:     my %texts=();
                    860:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    861:        if ($lock=~/\w/) {
                    862:           $num++;
                    863:           $texts{$lock}=$env{'session.lock.'.$lock};
                    864:        }
                    865:    }
                    866:    return ($num,%texts);
                    867: }
                    868: 
                    869: sub remove_lock {
                    870:     my ($id)=@_;
                    871:     my $newlocks='';
                    872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    873:        if (($lock=~/\w/) && ($lock ne $id)) {
                    874:           $newlocks.=','.$lock;
                    875:        }
                    876:     }
                    877:     &appenv({'session.locks' => $newlocks});
                    878:     &delenv('session.lock.'.$id);
                    879: }
                    880: 
                    881: sub remove_all_locks {
                    882:     my $activelocks=$env{'session.locks'};
                    883:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    884:        if ($lock=~/\w/) {
                    885:           &remove_lock($lock);
                    886:        }
                    887:     }
                    888: }
                    889: 
                    890: 
1.369     albertel  891: # ------------------------------------------ Find out current server userload
                    892: sub userload {
                    893:     my $numusers=0;
                    894:     {
                    895: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    896: 	my $filename;
                    897: 	my $curtime=time;
                    898: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  899: 	    next if ($filename eq '.' || $filename eq '..');
                    900: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   901:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  902: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  903: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  904: 	}
                    905: 	closedir(LONIDS);
                    906:     }
                    907:     my $userloadpercent=0;
                    908:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    909:     if ($maxuserload) {
1.371     albertel  910: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  911:     }
1.372     albertel  912:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  913:     return $userloadpercent;
1.283     www       914: }
                    915: 
1.1       albertel  916: # ------------------------------ Find server with least workload from spare.tab
1.11      www       917: 
1.1       albertel  918: sub spareserver {
1.1083    raeburn   919:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  920:     my $spare_server;
1.370     albertel  921:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  922:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    923:                                                      :  $userloadpercent;
1.1083    raeburn   924:     my ($uint_dom,$remotesessions);
                    925:     if (($udom ne '') && (&domain($udom) ne '')) {
                    926:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    927:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    928:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    929:         $remotesessions = $udomdefaults{'remotesessions'};
                    930:     }
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   935:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    936:                                              $try_server));
1.1123    raeburn   937: 	        ($spare_server, $lowest_load) =
                    938: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    939:             }
1.1083    raeburn   940:         }
1.784     albertel  941: 
1.1123    raeburn   942:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    943: 
                    944:         if (!$found_server) {
                    945:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    946: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   947:                     next unless (&spare_can_host($udom,$uint_dom,
                    948:                                                  $remotesessions,$try_server));
1.1123    raeburn   949: 	            ($spare_server, $lowest_load) =
                    950: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    951:                 }
                    952: 	    }
                    953:         }
1.784     albertel  954:     }
                    955: 
                    956:     if (!$want_server_name) {
1.1001    raeburn   957:         if (defined($spare_server)) {
                    958:             my $hostname = &hostname($spare_server);
1.1083    raeburn   959:             if (defined($hostname)) {
1.1172.2.120  raeburn   960:                 my $protocol = 'http';
                    961:                 if ($protocol{$spare_server} eq 'https') {
                    962:                     $protocol = $protocol{$spare_server};
                    963:                 }
1.1001    raeburn   964: 	        $spare_server = $protocol.'://'.$hostname;
                    965:             }
                    966:         }
1.784     albertel  967:     }
                    968:     return $spare_server;
                    969: }
                    970: 
                    971: sub compare_server_load {
1.1172.2.41  raeburn   972:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    973: 
                    974:     if ($required) {
                    975:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    976:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    977:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    978:         if (($major eq '' && $minor eq '') ||
                    979:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    980:             return ($spare_server,$lowest_load);
                    981:         }
                    982:     }
1.784     albertel  983: 
                    984:     my $loadans     = &reply('load',    $try_server);
                    985:     my $userloadans = &reply('userload',$try_server);
                    986: 
                    987:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   988: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  989:     }
                    990: 
                    991:     my $load;
                    992:     if ($loadans =~ /\d/) {
                    993: 	if ($userloadans =~ /\d/) {
                    994: 	    #both are numbers, pick the bigger one
                    995: 	    $load = ($loadans > $userloadans) ? $loadans 
                    996: 		                              : $userloadans;
1.411     albertel  997: 	} else {
1.784     albertel  998: 	    $load = $loadans;
1.411     albertel  999: 	}
1.784     albertel 1000:     } else {
                   1001: 	$load = $userloadans;
                   1002:     }
                   1003: 
                   1004:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1005: 	$spare_server = $try_server;
                   1006: 	$lowest_load  = $load;
1.370     albertel 1007:     }
1.784     albertel 1008:     return ($spare_server,$lowest_load);
1.202     matthew  1009: }
1.914     albertel 1010: 
                   1011: # --------------------------- ask offload servers if user already has a session
                   1012: sub find_existing_session {
                   1013:     my ($udom,$uname) = @_;
1.1123    raeburn  1014:     my $spareshash = &this_host_spares($udom);
                   1015:     if (ref($spareshash) eq 'HASH') {
                   1016:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1017:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1018:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1019:             }
                   1020:         }
                   1021:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1022:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1023:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1024:             }
                   1025:         }
1.914     albertel 1026:     }
                   1027:     return;
                   1028: }
                   1029: 
1.1172.2.107  raeburn  1030: # check if user's browser sent load balancer cookie and server still has session
                   1031: # and is not overloaded.
                   1032: sub check_for_balancer_cookie {
                   1033:     my ($r,$update_mtime) = @_;
                   1034:     my ($otherserver,$cookie);
                   1035:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1036:     if (exists($cookies{'balanceID'})) {
                   1037:         my $balid = $cookies{'balanceID'};
                   1038:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1039:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1040:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1041:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1042:                 my ($possudom,$possuname) = ($1,$2);
                   1043:                 my $has_session = 0;
                   1044:                 if ((&domain($possudom) ne '') &&
                   1045:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1046:                     my $try_server;
                   1047:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1048:                     if ($opened) {
                   1049:                         flock($idf,LOCK_SH);
                   1050:                         while (my $line = <$idf>) {
                   1051:                             chomp($line);
                   1052:                             if (&hostname($line) ne '') {
                   1053:                                 $try_server = $line;
                   1054:                                 last;
                   1055:                             }
                   1056:                         }
                   1057:                         close($idf);
                   1058:                         if (($try_server) &&
                   1059:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1060:                             my $lowest_load = 30000;
                   1061:                             ($otherserver,$lowest_load) =
                   1062:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1063:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1064:                                 $has_session = 1;
                   1065:                             } else {
                   1066:                                 undef($otherserver);
                   1067:                             }
                   1068:                         }
                   1069:                     }
                   1070:                 }
                   1071:                 if ($has_session) {
                   1072:                     if ($update_mtime) {
                   1073:                         my $atime = my $mtime = time;
                   1074:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1075:                     }
                   1076:                 } else {
                   1077:                     unlink("$balancedir/$cookie.id");
                   1078:                 }
                   1079:             }
                   1080:         }
                   1081:     }
                   1082:     return ($otherserver,$cookie);
                   1083: }
                   1084: 
                   1085: sub delbalcookie {
                   1086:     my ($cookie,$balancer) =@_;
                   1087:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1088:         my ($udom,$uname) = ($1,$2);
                   1089:         my $uprimary_id = &domain($udom,'primary');
                   1090:         my $uintdom = &internet_dom($uprimary_id);
                   1091:         my $intdom = &internet_dom($balancer);
                   1092:         my $serverhomedom = &host_domain($balancer);
                   1093:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1094:             return &reply("delbalcookie:$cookie",$balancer);
                   1095:         }
                   1096:     }
                   1097: }
                   1098: 
1.914     albertel 1099: # -------------------------------- ask if server already has a session for user
                   1100: sub has_user_session {
                   1101:     my ($lonid,$udom,$uname) = @_;
                   1102:     my $result = &reply(join(':','userhassession',
                   1103: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1104:     return 1 if ($result eq 'ok');
                   1105: 
                   1106:     return 0;
                   1107: }
                   1108: 
1.1076    raeburn  1109: # --------- determine least loaded server in a user's domain which allows login
                   1110: 
                   1111: sub choose_server {
1.1172.2.47  raeburn  1112:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1113:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1114:     my %servers = &get_servers($udom);
1.1076    raeburn  1115:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1116:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1117:     if ($skiploadbal) {
                   1118:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1119:         unless (defined($cached)) {
                   1120:             my $cachetime = 60*60*24;
                   1121:             my %domconfig =
                   1122:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1123:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1124:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1125:                                            $cachetime);
                   1126:             }
                   1127:         }
                   1128:     }
1.1076    raeburn  1129:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1130:         my $loginvia;
1.1172.2.47  raeburn  1131:         if ($skiploadbal) {
                   1132:             if (ref($balancers) eq 'HASH') {
                   1133:                 next if (exists($balancers->{$lonhost}));
                   1134:             }
                   1135:         }
1.1115    raeburn  1136:         if ($checkloginvia) {
                   1137:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1138:             if ($loginvia) {
                   1139:                 my ($server,$path) = split(/:/,$loginvia);
                   1140:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1141:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1142:                 if ($login_host eq $server) {
                   1143:                     $portal_path = $path;
1.1151    raeburn  1144:                     $isredirect = 1;
1.1116    raeburn  1145:                 }
                   1146:             } else {
                   1147:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1148:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1149:                 if ($login_host eq $lonhost) {
                   1150:                     $portal_path = '';
1.1151    raeburn  1151:                     $isredirect = ''; 
1.1116    raeburn  1152:                 }
                   1153:             }
                   1154:         } else {
1.1076    raeburn  1155:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1156:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1157:         }
                   1158:     }
                   1159:     if ($login_host ne '') {
1.1116    raeburn  1160:         $hostname = &hostname($login_host);
1.1076    raeburn  1161:     }
1.1172.2.88  raeburn  1162:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1163: }
                   1164: 
1.202     matthew  1165: # --------------------------------------------- Try to change a user's password
                   1166: 
                   1167: sub changepass {
1.799     raeburn  1168:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1169:     $currentpass = &escape($currentpass);
                   1170:     $newpass     = &escape($newpass);
1.1030    raeburn  1171:     my $lonhost = $perlvar{'lonHostID'};
                   1172:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1173: 		       $server);
                   1174:     if (! $answer) {
                   1175: 	&logthis("No reply on password change request to $server ".
                   1176: 		 "by $uname in domain $udom.");
                   1177:     } elsif ($answer =~ "^ok") {
                   1178:         &logthis("$uname in $udom successfully changed their password ".
                   1179: 		 "on $server.");
                   1180:     } elsif ($answer =~ "^pwchange_failure") {
                   1181: 	&logthis("$uname in $udom was unable to change their password ".
                   1182: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1183: 		 "or pwchange");
                   1184:     } elsif ($answer =~ "^non_authorized") {
                   1185:         &logthis("$uname in $udom did not get their password correct when ".
                   1186: 		 "attempting to change it on $server.");
                   1187:     } elsif ($answer =~ "^auth_mode_error") {
                   1188:         &logthis("$uname in $udom attempted to change their password despite ".
                   1189: 		 "not being locally or internally authenticated on $server.");
                   1190:     } elsif ($answer =~ "^unknown_user") {
                   1191:         &logthis("$uname in $udom attempted to change their password ".
                   1192: 		 "on $server but were unable to because $server is not ".
                   1193: 		 "their home server.");
                   1194:     } elsif ($answer =~ "^refused") {
                   1195: 	&logthis("$server refused to change $uname in $udom password because ".
                   1196: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1197:     } elsif ($answer =~ "invalid_client") {
                   1198:         &logthis("$server refused to change $uname in $udom password because ".
                   1199:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1200:     } elsif ($answer =~ "^prioruse") {
                   1201:        &logthis("$server refused to change $uname in $udom password because ".
                   1202:                 "the password had been used before");
1.202     matthew  1203:     }
                   1204:     return $answer;
1.1       albertel 1205: }
                   1206: 
1.169     harris41 1207: # ----------------------- Try to determine user's current authentication scheme
                   1208: 
                   1209: sub queryauthenticate {
                   1210:     my ($uname,$udom)=@_;
1.456     albertel 1211:     my $uhome=&homeserver($uname,$udom);
                   1212:     if (!$uhome) {
                   1213: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1214: 	return 'no_host';
                   1215:     }
                   1216:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1217:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1218: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1219:     }
1.456     albertel 1220:     return $answer;
1.169     harris41 1221: }
                   1222: 
1.1       albertel 1223: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1224: 
1.1       albertel 1225: sub authenticate {
1.1073    raeburn  1226:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1227:     $upass=&escape($upass);
                   1228:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1229:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1230:     my $newhome;
1.836     www      1231:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1232: # Maybe the machine was offline and only re-appeared again recently?
                   1233:         &reconlonc();
                   1234: # One more
1.952     raeburn  1235: 	$uhome=&homeserver($uname,$udom,1);
                   1236:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1237:             if (defined(&domain($udom,'primary'))) {
                   1238:                 $newhome=&domain($udom,'primary');
                   1239:             }
                   1240:             if ($newhome ne '') {
                   1241:                 $uhome = $newhome;
                   1242:             }
                   1243:         }
1.836     www      1244: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1245: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1246: 	    return 'no_host';
                   1247:         }
1.1       albertel 1248:     }
1.1073    raeburn  1249:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1250:     if ($answer eq 'authorized') {
1.952     raeburn  1251:         if ($newhome) {
                   1252:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1253:             return 'no_account_on_host'; 
                   1254:         } else {
                   1255:             &logthis("User $uname at $udom authorized by $uhome");
                   1256:             return $uhome;
                   1257:         }
1.471     albertel 1258:     }
                   1259:     if ($answer eq 'non_authorized') {
                   1260: 	&logthis("User $uname at $udom rejected by $uhome");
                   1261: 	return 'no_host'; 
1.9       www      1262:     }
1.471     albertel 1263:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1264:     return 'no_host';
                   1265: }
                   1266: 
1.1073    raeburn  1267: sub can_host_session {
1.1074    raeburn  1268:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1269:     my $canhost = 1;
1.1074    raeburn  1270:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1271:     if (ref($remotesessions) eq 'HASH') {
                   1272:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1273:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1274:                 $canhost = 0;
                   1275:             } else {
                   1276:                 $canhost = 1;
                   1277:             }
                   1278:         }
                   1279:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1280:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1281:                 $canhost = 1;
                   1282:             } else {
                   1283:                 $canhost = 0;
                   1284:             }
                   1285:         }
                   1286:         if ($canhost) {
                   1287:             if ($remotesessions->{'version'} ne '') {
                   1288:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1289:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1290:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1291:                         my $major = $1;
                   1292:                         my $minor = $2;
                   1293:                         if (($major < $reqmajor ) ||
                   1294:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1295:                             $canhost = 0;
                   1296:                         }
                   1297:                     } else {
                   1298:                         $canhost = 0;
                   1299:                     }
                   1300:                 }
                   1301:             }
                   1302:         }
                   1303:     }
                   1304:     if ($canhost) {
                   1305:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1306:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1307:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1308:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1309:                 if (($uint_dom ne '') && 
                   1310:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1311:                     $canhost = 0;
                   1312:                 } else {
                   1313:                     $canhost = 1;
                   1314:                 }
                   1315:             }
                   1316:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1317:                 if (($uint_dom ne '') && 
                   1318:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1319:                     $canhost = 1;
                   1320:                 } else {
                   1321:                     $canhost = 0;
                   1322:                 }
                   1323:             }
                   1324:         }
                   1325:     }
                   1326:     return $canhost;
                   1327: }
                   1328: 
1.1083    raeburn  1329: sub spare_can_host {
                   1330:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1331:     my $canhost=1;
1.1172.2.62  raeburn  1332:     my $try_server_hostname = &hostname($try_server);
                   1333:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1334:     my $serverhomedom = &host_domain($serverhomeID);
                   1335:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1336:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1337:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1338:             $canhost = 0;
                   1339:         }
                   1340:     }
                   1341:     if (($canhost) && ($uint_dom)) {
                   1342:         my @intdoms;
                   1343:         my $internet_names = &get_internet_names($try_server);
                   1344:         if (ref($internet_names) eq 'ARRAY') {
                   1345:             @intdoms = @{$internet_names};
                   1346:         }
                   1347:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1348:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1349:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1350:                                          $remotesessions,
                   1351:                                          $defdomdefaults{'hostedsessions'});
                   1352:         }
1.1083    raeburn  1353:     }
                   1354:     return $canhost;
                   1355: }
                   1356: 
1.1123    raeburn  1357: sub this_host_spares {
                   1358:     my ($dom) = @_;
1.1126    raeburn  1359:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1360:     my @hosts = &current_machine_ids();
                   1361:     foreach my $lonhost (@hosts) {
                   1362:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1363:             $dom_in_use = $dom;
                   1364:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1365:             last;
                   1366:         }
                   1367:     }
1.1126    raeburn  1368:     if ($dom_in_use ne '') {
                   1369:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1370:     }
                   1371:     if (ref($result) ne 'HASH') {
                   1372:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1373:         $dom_in_use = &host_domain($lonhost_in_use);
                   1374:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1375:         if (ref($result) ne 'HASH') {
                   1376:             $result = \%spareid;
                   1377:         }
                   1378:     }
                   1379:     return $result;
                   1380: }
                   1381: 
                   1382: sub spares_for_offload  {
                   1383:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1384:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1385:     if (defined($cached)) {
                   1386:         return $result;
                   1387:     } else {
1.1126    raeburn  1388:         my $cachetime = 60*60*24;
                   1389:         my %domconfig =
                   1390:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1391:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1392:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1393:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1394:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1395:                 }
                   1396:             }
                   1397:         }
                   1398:     }
1.1126    raeburn  1399:     return;
1.1123    raeburn  1400: }
                   1401: 
1.1129    raeburn  1402: sub get_lonbalancer_config {
                   1403:     my ($servers) = @_;
                   1404:     my ($currbalancer,$currtargets);
                   1405:     if (ref($servers) eq 'HASH') {
                   1406:         foreach my $server (keys(%{$servers})) {
                   1407:             my %what = (
                   1408:                          spareid => 1,
                   1409:                          perlvar => 1,
                   1410:                        );
                   1411:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1412:             if ($result eq 'ok') {
                   1413:                 if (ref($returnhash) eq 'HASH') {
                   1414:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1415:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1416:                             $currbalancer = $server;
                   1417:                             $currtargets = {};
                   1418:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1419:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1420:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1421:                                 }
                   1422:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1423:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1424:                                 }
                   1425:                             }
                   1426:                             last;
                   1427:                         }
                   1428:                     }
                   1429:                 }
                   1430:             }
                   1431:         }
                   1432:     }
                   1433:     return ($currbalancer,$currtargets);
                   1434: }
                   1435: 
                   1436: sub check_loadbalancing {
1.1172.2.88  raeburn  1437:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1438:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1439:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1440:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1441:     my @hosts = &current_machine_ids();
1.1129    raeburn  1442:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1443:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1444:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1445:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1446:     my $domneedscache; 
1.1129    raeburn  1447:     my $cachetime = 60*60*24;
                   1448: 
                   1449:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1450:         $dom_in_use = $udom;
                   1451:         $homeintdom = 1;
                   1452:     } else {
                   1453:         $dom_in_use = $serverhomedom;
                   1454:     }
                   1455:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1456:     unless (defined($cached)) {
                   1457:         my %domconfig =
                   1458:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1459:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1460:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1461:         } else {
                   1462:             $domneedscache = $dom_in_use;
1.1129    raeburn  1463:         }
                   1464:     }
                   1465:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1466:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1467:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1468:         if ($is_balancer) {
                   1469:             if (ref($currrules) eq 'HASH') {
                   1470:                 if ($homeintdom) {
                   1471:                     if ($uname ne '') {
                   1472:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1473:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1474:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1475:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1476:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1477:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1478:                             }
                   1479:                         }
                   1480:                         if ($rule_in_effect eq '') {
                   1481:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1482:                             if ($userenv{'inststatus'} ne '') {
                   1483:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1484:                                 my ($othertitle,$usertypes,$types) =
                   1485:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1486:                                 if (ref($types) eq 'ARRAY') {
                   1487:                                     foreach my $type (@{$types}) {
                   1488:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1489:                                             if (exists($currrules->{$type})) {
                   1490:                                                 $rule_in_effect = $currrules->{$type};
                   1491:                                             }
                   1492:                                         }
                   1493:                                     }
                   1494:                                 }
                   1495:                             } else {
                   1496:                                 if (exists($currrules->{'default'})) {
                   1497:                                     $rule_in_effect = $currrules->{'default'};
                   1498:                                 }
                   1499:                             }
                   1500:                         }
                   1501:                     } else {
                   1502:                         if (exists($currrules->{'default'})) {
                   1503:                             $rule_in_effect = $currrules->{'default'};
                   1504:                         }
                   1505:                     }
                   1506:                 } else {
                   1507:                     if ($currrules->{'_LC_external'} ne '') {
                   1508:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1509:                     }
                   1510:                 }
                   1511:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1512:                                                        $uname,$udom);
                   1513:             }
                   1514:         }
                   1515:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1516:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1517:         unless (defined($cached)) {
                   1518:             my %domconfig =
                   1519:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1520:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1521:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1522:             } else {
                   1523:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1524:             }
                   1525:         }
                   1526:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1527:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1528:                 &check_balancer_result($result,@hosts);
                   1529:             if ($is_balancer) {
1.1129    raeburn  1530:                 if (ref($currrules) eq 'HASH') {
                   1531:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1532:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1533:                     }
                   1534:                 }
                   1535:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1536:                                                        $uname,$udom);
                   1537:             }
                   1538:         } else {
                   1539:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1540:                 $is_balancer = 1;
                   1541:                 $offloadto = &this_host_spares($dom_in_use);
                   1542:             }
1.1172.2.75  raeburn  1543:             unless (defined($cached)) {
                   1544:                 $domneedscache = $serverhomedom;
                   1545:             }
1.1129    raeburn  1546:         }
                   1547:     } else {
                   1548:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1549:             $is_balancer = 1;
                   1550:             $offloadto = &this_host_spares($dom_in_use);
                   1551:         }
1.1172.2.75  raeburn  1552:         unless (defined($cached)) {
                   1553:             $domneedscache = $serverhomedom;
                   1554:         }
                   1555:     }
                   1556:     if ($domneedscache) {
                   1557:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1558:     }
1.1172.2.5  raeburn  1559:     if ($is_balancer) {
                   1560:         my $lowest_load = 30000;
                   1561:         if (ref($offloadto) eq 'HASH') {
                   1562:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1563:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1564:                     ($otherserver,$lowest_load) =
                   1565:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1566:                 }
1.1129    raeburn  1567:             }
1.1172.2.5  raeburn  1568:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1569: 
1.1172.2.5  raeburn  1570:             if (!$found_server) {
                   1571:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1572:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1573:                         ($otherserver,$lowest_load) =
                   1574:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1575:                     }
                   1576:                 }
                   1577:             }
                   1578:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1579:             if (@{$offloadto} == 1) {
                   1580:                 $otherserver = $offloadto->[0];
                   1581:             } elsif (@{$offloadto} > 1) {
                   1582:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1583:                     ($otherserver,$lowest_load) =
                   1584:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1585:                 }
                   1586:             }
                   1587:         }
1.1172.2.88  raeburn  1588:         unless ($caller eq 'login') {
                   1589:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1590:                 $is_balancer = 0;
                   1591:                 if ($uname ne '' && $udom ne '') {
                   1592:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1593:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1594:                                  'user.loadbalcheck.time' => time});
                   1595:                     }
1.1172.2.5  raeburn  1596:                 }
1.1129    raeburn  1597:             }
                   1598:         }
1.1172.2.107  raeburn  1599:         unless ($homeintdom) {
                   1600:             undef($setcookie);
                   1601:         }
1.1129    raeburn  1602:     }
1.1172.2.107  raeburn  1603:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1604: }
                   1605: 
1.1172.2.12  raeburn  1606: sub check_balancer_result {
                   1607:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1608:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1609:     if (ref($result) eq 'HASH') {
                   1610:         if ($result->{'lonhost'} ne '') {
                   1611:             my $currbalancer = $result->{'lonhost'};
                   1612:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1613:                 $is_balancer = 1;
                   1614:                 $currtargets = $result->{'targets'};
                   1615:                 $currrules = $result->{'rules'};
                   1616:             }
                   1617:         } else {
                   1618:             foreach my $key (keys(%{$result})) {
                   1619:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1620:                     (ref($result->{$key}) eq 'HASH')) {
                   1621:                     $is_balancer = 1;
                   1622:                     $currrules = $result->{$key}{'rules'};
                   1623:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1624:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1625:                     last;
                   1626:                 }
                   1627:             }
                   1628:         }
                   1629:     }
1.1172.2.107  raeburn  1630:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1631: }
                   1632: 
1.1129    raeburn  1633: sub get_loadbalancer_targets {
                   1634:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1635:     my $offloadto;
1.1172.2.4  raeburn  1636:     if ($rule_in_effect eq 'none') {
                   1637:         return [$perlvar{'lonHostID'}];
                   1638:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1639:         $offloadto = $currtargets;
                   1640:     } else {
                   1641:         if ($rule_in_effect eq 'homeserver') {
                   1642:             my $homeserver = &homeserver($uname,$udom);
                   1643:             if ($homeserver ne 'no_host') {
                   1644:                 $offloadto = [$homeserver];
                   1645:             }
                   1646:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1647:             my %domconfig =
                   1648:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1649:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1650:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1651:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1652:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1653:                     }
                   1654:                 }
                   1655:             } else {
1.1172.2.7  raeburn  1656:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1657:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1658:                 if (&hostname($remotebalancer) ne '') {
                   1659:                     $offloadto = [$remotebalancer];
                   1660:                 }
                   1661:             }
                   1662:         } elsif (&hostname($rule_in_effect) ne '') {
                   1663:             $offloadto = [$rule_in_effect];
                   1664:         }
                   1665:     }
                   1666:     return $offloadto;
                   1667: }
                   1668: 
1.1127    raeburn  1669: sub internet_dom_servers {
                   1670:     my ($dom) = @_;
                   1671:     my (%uniqservers,%servers);
                   1672:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1673:     my @machinedoms = &machine_domains($primaryserver);
                   1674:     foreach my $mdom (@machinedoms) {
                   1675:         my %currservers = %servers;
                   1676:         my %server = &get_servers($mdom);
                   1677:         %servers = (%currservers,%server);
                   1678:     }
                   1679:     my %by_hostname;
                   1680:     foreach my $id (keys(%servers)) {
                   1681:         push(@{$by_hostname{$servers{$id}}},$id);
                   1682:     }
                   1683:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1684:         if (@{$by_hostname{$hostname}} > 1) {
                   1685:             my $match = 0;
                   1686:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1687:                 if (&host_domain($id) eq $dom) {
                   1688:                     $uniqservers{$id} = $hostname;
                   1689:                     $match = 1;
                   1690:                 }
                   1691:             }
                   1692:             unless ($match) {
                   1693:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1694:             }
                   1695:         } else {
                   1696:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1697:         }
                   1698:     }
                   1699:     return %uniqservers;
                   1700: }
                   1701: 
1.1       albertel 1702: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1703: 
1.599     albertel 1704: my %homecache;
1.1       albertel 1705: sub homeserver {
1.230     stredwic 1706:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1707:     my $index="$uname:$udom";
1.426     albertel 1708: 
1.599     albertel 1709:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1710: 
                   1711:     my %servers = &get_servers($udom,'library');
                   1712:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1713:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1714: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1715: 
                   1716: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1717: 	if ($answer eq 'found') {
                   1718: 	    delete($badServerCache{$tryserver}); 
                   1719: 	    return $homecache{$index}=$tryserver;
                   1720: 	} elsif ($answer eq 'no_host') {
                   1721: 	    $badServerCache{$tryserver}=1;
                   1722: 	}
1.1       albertel 1723:     }    
                   1724:     return 'no_host';
1.70      www      1725: }
                   1726: 
                   1727: # ------------------------------------- Find the usernames behind a list of IDs
                   1728: 
                   1729: sub idget {
                   1730:     my ($udom,@ids)=@_;
                   1731:     my %returnhash=();
                   1732:     
1.841     albertel 1733:     my %servers = &get_servers($udom,'library');
                   1734:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1735: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1736: 	$idlist=~tr/A-Z/a-z/; 
                   1737: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1738: 	my @answer=();
                   1739: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1740: 	    @answer=split(/\&/,$reply);
                   1741: 	}                    ;
                   1742: 	my $i;
                   1743: 	for ($i=0;$i<=$#ids;$i++) {
                   1744: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1745: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1746: 	    } 
                   1747: 	}
                   1748:     } 
1.70      www      1749:     return %returnhash;
                   1750: }
                   1751: 
                   1752: # ------------------------------------- Find the IDs behind a list of usernames
                   1753: 
                   1754: sub idrget {
                   1755:     my ($udom,@unames)=@_;
                   1756:     my %returnhash=();
1.800     albertel 1757:     foreach my $uname (@unames) {
                   1758:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1759:     }
1.70      www      1760:     return %returnhash;
                   1761: }
                   1762: 
                   1763: # ------------------------------- Store away a list of names and associated IDs
                   1764: 
                   1765: sub idput {
                   1766:     my ($udom,%ids)=@_;
                   1767:     my %servers=();
1.800     albertel 1768:     foreach my $uname (keys(%ids)) {
                   1769: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1770:         my $uhom=&homeserver($uname,$udom);
1.70      www      1771:         if ($uhom ne 'no_host') {
1.800     albertel 1772:             my $id=&escape($ids{$uname});
1.70      www      1773:             $id=~tr/A-Z/a-z/;
1.800     albertel 1774:             my $esc_unam=&escape($uname);
1.70      www      1775: 	    if ($servers{$uhom}) {
1.800     albertel 1776: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1777:             } else {
1.800     albertel 1778:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1779:             }
                   1780:         }
1.191     harris41 1781:     }
1.800     albertel 1782:     foreach my $server (keys(%servers)) {
                   1783:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1784:     }
1.344     www      1785: }
                   1786: 
1.1172.2.30  raeburn  1787: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1788: 
                   1789: sub iddel {
                   1790:     my ($udom,$idshashref,$uhome)=@_;
                   1791:     my %result=();
                   1792:     unless (ref($idshashref) eq 'HASH') {
                   1793:         return %result;
                   1794:     }
                   1795:     my %servers=();
                   1796:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1797:         my $uhom;
                   1798:         if ($uhome) {
                   1799:             $uhom = $uhome;
                   1800:         } else {
                   1801:             $uhom=&homeserver($uname,$udom);
                   1802:         }
                   1803:         if ($uhom ne 'no_host') {
                   1804:             if ($servers{$uhom}) {
                   1805:                 $servers{$uhom}.='&'.&escape($id);
                   1806:             } else {
                   1807:                 $servers{$uhom}=&escape($id);
                   1808:             }
                   1809:         }
                   1810:     }
                   1811:     foreach my $server (keys(%servers)) {
                   1812:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1813:     }
                   1814:     return %result;
                   1815: }
                   1816: 
1.1023    raeburn  1817: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1818: sub dump_dom {
1.1165    droeschl 1819:     my ($namespace, $udom, $regexp) = @_;
                   1820: 
                   1821:     $udom ||= $env{'user.domain'};
                   1822: 
                   1823:     return () unless $udom;
                   1824: 
                   1825:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1826: }
                   1827: 
1.1023    raeburn  1828: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1829: 
                   1830: sub get_dom {
1.860     raeburn  1831:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1832:     return if ($udom eq 'public');
1.806     raeburn  1833:     my $items='';
                   1834:     foreach my $item (@$storearr) {
                   1835:         $items.=&escape($item).'&';
                   1836:     }
                   1837:     $items=~s/\&$//;
1.860     raeburn  1838:     if (!$udom) {
                   1839:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1840:         return if ($udom eq 'public');
1.860     raeburn  1841:         if (defined(&domain($udom,'primary'))) {
                   1842:             $uhome=&domain($udom,'primary');
                   1843:         } else {
1.874     albertel 1844:             undef($uhome);
1.860     raeburn  1845:         }
                   1846:     } else {
                   1847:         if (!$uhome) {
                   1848:             if (defined(&domain($udom,'primary'))) {
                   1849:                 $uhome=&domain($udom,'primary');
                   1850:             }
                   1851:         }
                   1852:     }
                   1853:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1854:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1855:         my %returnhash;
1.875     albertel 1856:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1857:             return %returnhash;
                   1858:         }
1.806     raeburn  1859:         my @pairs=split(/\&/,$rep);
                   1860:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1861:             return @pairs;
                   1862:         }
                   1863:         my $i=0;
                   1864:         foreach my $item (@$storearr) {
                   1865:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1866:             $i++;
                   1867:         }
                   1868:         return %returnhash;
                   1869:     } else {
1.880     banghart 1870:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1871:     }
                   1872: }
                   1873: 
                   1874: # -------------------------------------------- put items in domain db files 
                   1875: 
                   1876: sub put_dom {
1.860     raeburn  1877:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1878:     if (!$udom) {
                   1879:         $udom=$env{'user.domain'};
                   1880:         if (defined(&domain($udom,'primary'))) {
                   1881:             $uhome=&domain($udom,'primary');
                   1882:         } else {
1.874     albertel 1883:             undef($uhome);
1.860     raeburn  1884:         }
                   1885:     } else {
                   1886:         if (!$uhome) {
                   1887:             if (defined(&domain($udom,'primary'))) {
                   1888:                 $uhome=&domain($udom,'primary');
                   1889:             }
                   1890:         }
                   1891:     } 
                   1892:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1893:         my $items='';
                   1894:         foreach my $item (keys(%$storehash)) {
                   1895:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1896:         }
                   1897:         $items=~s/\&$//;
                   1898:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1899:     } else {
1.860     raeburn  1900:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1901:     }
                   1902: }
                   1903: 
1.1023    raeburn  1904: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1905: sub newput_dom {
1.1023    raeburn  1906:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1907:     my $result;
                   1908:     if (!$udom) {
                   1909:         $udom=$env{'user.domain'};
                   1910:     }
1.1023    raeburn  1911:     if ($udom) {
                   1912:         my $uname = &get_domainconfiguser($udom);
                   1913:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1914:     }
                   1915:     return $result;
                   1916: }
                   1917: 
1.1023    raeburn  1918: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1919: sub del_dom {
1.1023    raeburn  1920:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1921:     if (ref($storearr) eq 'ARRAY') {
                   1922:         if (!$udom) {
                   1923:             $udom=$env{'user.domain'};
                   1924:         }
1.1023    raeburn  1925:         if ($udom) {
                   1926:             my $uname = &get_domainconfiguser($udom); 
                   1927:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1928:         }
                   1929:     }
                   1930: }
                   1931: 
1.1023    raeburn  1932: # ----------------------------------construct domainconfig user for a domain 
                   1933: sub get_domainconfiguser {
                   1934:     my ($udom) = @_;
                   1935:     return $udom.'-domainconfig';
                   1936: }
                   1937: 
1.837     raeburn  1938: sub retrieve_inst_usertypes {
                   1939:     my ($udom) = @_;
                   1940:     my (%returnhash,@order);
1.989     raeburn  1941:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1942:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1943:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1944:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1945:     } else {
                   1946:         if (defined(&domain($udom,'primary'))) {
                   1947:             my $uhome=&domain($udom,'primary');
                   1948:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1949:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1950:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1951:                 return (\%returnhash,\@order);
                   1952:             }
                   1953:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1954:             my @pairs=split(/\&/,$hashitems);
                   1955:             foreach my $item (@pairs) {
                   1956:                 my ($key,$value)=split(/=/,$item,2);
                   1957:                 $key = &unescape($key);
                   1958:                 next if ($key =~ /^error: 2 /);
                   1959:                 $returnhash{$key}=&thaw_unescape($value);
                   1960:             }
                   1961:             my @esc_order = split(/\&/,$orderitems);
                   1962:             foreach my $item (@esc_order) {
                   1963:                 push(@order,&unescape($item));
                   1964:             }
                   1965:         } else {
1.1172.2.44  raeburn  1966:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1967:         }
1.1172.2.44  raeburn  1968:         return (\%returnhash,\@order);
1.837     raeburn  1969:     }
                   1970: }
                   1971: 
1.868     raeburn  1972: sub is_domainimage {
                   1973:     my ($url) = @_;
1.1172.2.74  raeburn  1974:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1975:         if (&domain($1) ne '') {
                   1976:             return '1';
                   1977:         }
                   1978:     }
                   1979:     return;
                   1980: }
                   1981: 
1.899     raeburn  1982: sub inst_directory_query {
                   1983:     my ($srch) = @_;
                   1984:     my $udom = $srch->{'srchdomain'};
                   1985:     my %results;
                   1986:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1987:     my $outcome;
1.899     raeburn  1988:     if ($homeserver ne '') {
1.1172.2.116  raeburn  1989:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   1990:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  1991:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  1992:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   1993:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   1994:                     (($major == 2) && ($minor < 11)) ||
                   1995:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   1996:                     return;
                   1997:                 }
                   1998:             }
                   1999:         }
1.904     albertel 2000: 	my $queryid=&reply("querysend:instdirsearch:".
                   2001: 			   &escape($srch->{'srchby'}).':'.
                   2002: 			   &escape($srch->{'srchterm'}).':'.
                   2003: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2004: 	my $host=&hostname($homeserver);
                   2005: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2006: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2007: 	    return;
                   2008: 	}
                   2009: 	my $response = &get_query_reply($queryid);
                   2010: 	my $maxtries = 5;
                   2011: 	my $tries = 1;
                   2012: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2013: 	    $response = &get_query_reply($queryid);
                   2014: 	    $tries ++;
                   2015: 	}
                   2016: 
                   2017:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2018:             if ($response eq 'unavailable') {
                   2019:                 $outcome = $response;
                   2020:             } else {
                   2021:                 $outcome = 'ok';
                   2022:                 my @matches = split(/\n/,$response);
                   2023:                 foreach my $match (@matches) {
                   2024:                     my ($key,$value) = split(/=/,$match);
                   2025:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2026:                 }
1.899     raeburn  2027:             }
                   2028:         }
                   2029:     }
1.909     raeburn  2030:     return ($outcome,%results);
1.899     raeburn  2031: }
                   2032: 
                   2033: sub usersearch {
                   2034:     my ($srch) = @_;
                   2035:     my $dom = $srch->{'srchdomain'};
                   2036:     my %results;
                   2037:     my %libserv = &all_library();
                   2038:     my $query = 'usersearch';
                   2039:     foreach my $tryserver (keys(%libserv)) {
                   2040:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2041:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2042:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2043:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2044:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2045:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2046:                              (($major == 2) && ($minor < 11)) ||
                   2047:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2048:                 }
                   2049:             }
1.899     raeburn  2050:             my $host=&hostname($tryserver);
                   2051:             my $queryid=
1.911     raeburn  2052:                 &reply("querysend:".&escape($query).':'.
                   2053:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2054:                        &escape($srch->{'srchtype'}).':'.
                   2055:                        &escape($srch->{'srchterm'}),$tryserver);
                   2056:             if ($queryid !~/^\Q$host\E\_/) {
                   2057:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2058:                 next;
1.899     raeburn  2059:             }
                   2060:             my $reply = &get_query_reply($queryid);
                   2061:             my $maxtries = 1;
                   2062:             my $tries = 1;
                   2063:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2064:                 $reply = &get_query_reply($queryid);
                   2065:                 $tries ++;
                   2066:             }
                   2067:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2068:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2069:             } else {
1.911     raeburn  2070:                 my @matches;
                   2071:                 if ($reply =~ /\n/) {
                   2072:                     @matches = split(/\n/,$reply);
                   2073:                 } else {
                   2074:                     @matches = split(/\&/,$reply);
                   2075:                 }
1.899     raeburn  2076:                 foreach my $match (@matches) {
                   2077:                     my ($uname,$udom,%userhash);
1.911     raeburn  2078:                     foreach my $entry (split(/:/,$match)) {
                   2079:                         my ($key,$value) =
                   2080:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2081:                         $userhash{$key} = $value;
                   2082:                         if ($key eq 'username') {
                   2083:                             $uname = $value;
                   2084:                         } elsif ($key eq 'domain') {
                   2085:                             $udom = $value;
1.911     raeburn  2086:                         }
1.899     raeburn  2087:                     }
                   2088:                     $results{$uname.':'.$udom} = \%userhash;
                   2089:                 }
                   2090:             }
                   2091:         }
                   2092:     }
                   2093:     return %results;
                   2094: }
                   2095: 
1.912     raeburn  2096: sub get_instuser {
                   2097:     my ($udom,$uname,$id) = @_;
                   2098:     my $homeserver = &domain($udom,'primary');
                   2099:     my ($outcome,%results);
                   2100:     if ($homeserver ne '') {
                   2101:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2102:                            &escape($id).':'.&escape($udom),$homeserver);
                   2103:         my $host=&hostname($homeserver);
                   2104:         if ($queryid !~/^\Q$host\E\_/) {
                   2105:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2106:             return;
                   2107:         }
                   2108:         my $response = &get_query_reply($queryid);
                   2109:         my $maxtries = 5;
                   2110:         my $tries = 1;
                   2111:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2112:             $response = &get_query_reply($queryid);
                   2113:             $tries ++;
                   2114:         }
                   2115:         if (!&error($response) && $response ne 'refused') {
                   2116:             if ($response eq 'unavailable') {
                   2117:                 $outcome = $response;
                   2118:             } else {
                   2119:                 $outcome = 'ok';
                   2120:                 my @matches = split(/\n/,$response);
                   2121:                 foreach my $match (@matches) {
                   2122:                     my ($key,$value) = split(/=/,$match);
                   2123:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2124:                 }
                   2125:             }
                   2126:         }
                   2127:     }
                   2128:     my %userinfo;
                   2129:     if (ref($results{$uname}) eq 'HASH') {
                   2130:         %userinfo = %{$results{$uname}};
                   2131:     } 
                   2132:     return ($outcome,%userinfo);
                   2133: }
                   2134: 
1.1172.2.69  raeburn  2135: sub get_multiple_instusers {
                   2136:     my ($udom,$users,$caller) = @_;
                   2137:     my ($outcome,$results);
                   2138:     if (ref($users) eq 'HASH') {
                   2139:         my $count = keys(%{$users});
                   2140:         my $requested = &freeze_escape($users);
                   2141:         my $homeserver = &domain($udom,'primary');
                   2142:         if ($homeserver ne '') {
                   2143:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2144:             my $host=&hostname($homeserver);
                   2145:             if ($queryid !~/^\Q$host\E\_/) {
                   2146:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2147:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2148:                 return ($outcome,$results);
                   2149:             }
                   2150:             my $response = &get_query_reply($queryid);
                   2151:             my $maxtries = 5;
                   2152:             if ($count > 100) {
                   2153:                 $maxtries = 1+int($count/20);
                   2154:             }
                   2155:             my $tries = 1;
                   2156:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2157:                 $response = &get_query_reply($queryid);
                   2158:                 $tries ++;
                   2159:             }
                   2160:             if ($response eq '') {
                   2161:                 $results = {};
                   2162:                 foreach my $key (keys(%{$users})) {
                   2163:                     my ($uname,$id);
                   2164:                     if ($caller eq 'id') {
                   2165:                         $id = $key;
                   2166:                     } else {
                   2167:                         $uname = $key;
                   2168:                     }
                   2169:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2170:                     $outcome = $resp;
                   2171:                     if ($resp eq 'ok') {
                   2172:                         %{$results} = (%{$results}, %info);
                   2173:                     } else {
                   2174:                         last;
                   2175:                     }
                   2176:                 }
                   2177:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2178:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2179:                     $outcome = $response;
                   2180:                 } else {
                   2181:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2182:                     if ($outcome eq 'ok') {
                   2183:                         $results = &thaw_unescape($userdata);
                   2184:                     }
                   2185:                 }
                   2186:             }
                   2187:         }
                   2188:     }
                   2189:     return ($outcome,$results);
                   2190: }
                   2191: 
1.912     raeburn  2192: sub inst_rulecheck {
1.923     raeburn  2193:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2194:     my %returnhash;
                   2195:     if ($udom ne '') {
                   2196:         if (ref($rules) eq 'ARRAY') {
                   2197:             @{$rules} = map {&escape($_);} (@{$rules});
                   2198:             my $rulestr = join(':',@{$rules});
                   2199:             my $homeserver=&domain($udom,'primary');
                   2200:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2201:                 my $response;
                   2202:                 if ($item eq 'username') {                
                   2203:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2204:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2205:                                               $homeserver));
1.923     raeburn  2206:                 } elsif ($item eq 'id') {
                   2207:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2208:                                               ':'.&escape($id).':'.$rulestr,
                   2209:                                               $homeserver));
1.945     raeburn  2210:                 } elsif ($item eq 'selfcreate') {
                   2211:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2212:                                                &escape($udom).':'.&escape($uname).
                   2213:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2214:                 }
1.912     raeburn  2215:                 if ($response ne 'refused') {
                   2216:                     my @pairs=split(/\&/,$response);
                   2217:                     foreach my $item (@pairs) {
                   2218:                         my ($key,$value)=split(/=/,$item,2);
                   2219:                         $key = &unescape($key);
                   2220:                         next if ($key =~ /^error: 2 /);
                   2221:                         $returnhash{$key}=&thaw_unescape($value);
                   2222:                     }
                   2223:                 }
                   2224:             }
                   2225:         }
                   2226:     }
                   2227:     return %returnhash;
                   2228: }
                   2229: 
                   2230: sub inst_userrules {
1.923     raeburn  2231:     my ($udom,$check) = @_;
1.912     raeburn  2232:     my (%ruleshash,@ruleorder);
                   2233:     if ($udom ne '') {
                   2234:         my $homeserver=&domain($udom,'primary');
                   2235:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2236:             my $response;
                   2237:             if ($check eq 'id') {
                   2238:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2239:                                  $homeserver);
1.943     raeburn  2240:             } elsif ($check eq 'email') {
                   2241:                 $response=&reply('instemailrules:'.&escape($udom),
                   2242:                                  $homeserver);
1.923     raeburn  2243:             } else {
                   2244:                 $response=&reply('instuserrules:'.&escape($udom),
                   2245:                                  $homeserver);
                   2246:             }
1.912     raeburn  2247:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2248:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2249:                 ($response ne 'no_such_host')) {
                   2250:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2251:                 my @pairs=split(/\&/,$hashitems);
                   2252:                 foreach my $item (@pairs) {
                   2253:                     my ($key,$value)=split(/=/,$item,2);
                   2254:                     $key = &unescape($key);
                   2255:                     next if ($key =~ /^error: 2 /);
                   2256:                     $ruleshash{$key}=&thaw_unescape($value);
                   2257:                 }
                   2258:                 my @esc_order = split(/\&/,$orderitems);
                   2259:                 foreach my $item (@esc_order) {
                   2260:                     push(@ruleorder,&unescape($item));
                   2261:                 }
                   2262:             }
                   2263:         }
                   2264:     }
                   2265:     return (\%ruleshash,\@ruleorder);
                   2266: }
                   2267: 
1.976     raeburn  2268: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2269: 
                   2270: sub get_domain_defaults {
1.1172.2.35  raeburn  2271:     my ($domain,$ignore_cache) = @_;
                   2272:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2273:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2274:     unless ($ignore_cache) {
                   2275:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2276:         if (defined($cached)) {
                   2277:             if (ref($result) eq 'HASH') {
                   2278:                 return %{$result};
                   2279:             }
1.943     raeburn  2280:         }
                   2281:     }
                   2282:     my %domdefaults;
                   2283:     my %domconfig =
1.989     raeburn  2284:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2285:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2286:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2287:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2288:                                   'coursecategories','autoenroll',
                   2289:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2290:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2291:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2292:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2293:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2294:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2295:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2296:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2297:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2298:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2299:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2300:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2301:     } else {
                   2302:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2303:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2304:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2305:     }
1.976     raeburn  2306:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2307:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2308:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2309:         } else {
                   2310:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2311:         }
1.1172.2.6  raeburn  2312:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2313:         foreach my $item (@usertools) {
                   2314:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2315:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2316:             }
                   2317:         }
1.1172.2.29  raeburn  2318:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2319:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2320:         }
1.976     raeburn  2321:     }
1.985     raeburn  2322:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2323:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2324:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2325:         }
                   2326:     }
1.1172.2.9  raeburn  2327:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2328:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2329:     }
1.989     raeburn  2330:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2331:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2332:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2333:         }
                   2334:     }
1.1047    raeburn  2335:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2336:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2337:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2338:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2339:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2340:         }
1.1172.2.41  raeburn  2341:         foreach my $type (@coursetypes) {
                   2342:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2343:                 unless ($type eq 'community') {
                   2344:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2345:                 }
                   2346:             }
                   2347:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2348:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2349:             }
1.1172.2.60  raeburn  2350:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2351:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2352:                     $domdefaults{$type.'postsubtimeout'} =
                   2353:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2354:                 }
                   2355:             }
1.1172.2.30  raeburn  2356:         }
1.1172.2.67  raeburn  2357:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2358:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2359:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2360:                 if (@clonecodes) {
                   2361:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2362:                 }
                   2363:             }
                   2364:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2365:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2366:         }
1.1172.2.103  raeburn  2367:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2368:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2369:         }
1.1047    raeburn  2370:     }
1.1073    raeburn  2371:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2372:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2373:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2374:         }
                   2375:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2376:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2377:         }
1.1172.2.62  raeburn  2378:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2379:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2380:         }
1.1073    raeburn  2381:     }
1.1172.2.41  raeburn  2382:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2383:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2384:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2385:                             'approval','limit');
                   2386:             foreach my $type (@coursetypes) {
                   2387:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2388:                     my @mgrdc = ();
                   2389:                     foreach my $item (@settings) {
                   2390:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2391:                             push(@mgrdc,$item);
                   2392:                         }
                   2393:                     }
                   2394:                     if (@mgrdc) {
                   2395:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2396:                     }
                   2397:                 }
                   2398:             }
                   2399:         }
                   2400:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2401:             foreach my $type (@coursetypes) {
                   2402:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2403:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2404:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2405:                     }
                   2406:                 }
                   2407:             }
                   2408:         }
                   2409:     }
1.1172.2.46  raeburn  2410:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2411:         $domdefaults{'catauth'} = 'std';
                   2412:         $domdefaults{'catunauth'} = 'std';
                   2413:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2414:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2415:         }
                   2416:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2417:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2418:         }
                   2419:     }
1.1172.2.76  raeburn  2420:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2421:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2422:     }
1.1172.2.89  raeburn  2423:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2424:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2425:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2426:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2427:         }
                   2428:     }
1.1172.2.23  raeburn  2429:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2430:     return %domdefaults;
                   2431: }
                   2432: 
1.1172.2.106  raeburn  2433: sub get_dom_cats {
                   2434:     my ($dom) = @_;
                   2435:     return unless (&domain($dom));
                   2436:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2437:     unless (defined($cached)) {
                   2438:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2439:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2440:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2441:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2442:             } else {
                   2443:                 $cats = {};
                   2444:             }
                   2445:         } else {
                   2446:             $cats = {};
                   2447:         }
                   2448:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2449:     }
                   2450:     return $cats;
                   2451: }
                   2452: 
                   2453: sub get_dom_instcats {
                   2454:     my ($dom) = @_;
                   2455:     return unless (&domain($dom));
                   2456:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2457:     unless (defined($cached)) {
                   2458:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2459:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2460:         if ($totcodes > 0) {
                   2461:             my $caller = 'global';
                   2462:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2463:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2464:                 $instcats = {
                   2465:                                 codes => \%codes,
                   2466:                                 codetitles => \@codetitles,
                   2467:                                 cat_titles => \%cat_titles,
                   2468:                                 cat_order => \%cat_order,
                   2469:                             };
                   2470:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2471:             }
                   2472:         }
                   2473:     }
                   2474:     return $instcats;
                   2475: }
                   2476: 
                   2477: sub retrieve_instcodes {
                   2478:     my ($coursecodes,$dom) = @_;
                   2479:     my $totcodes;
                   2480:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2481:     foreach my $course (keys(%courses)) {
                   2482:         if (ref($courses{$course}) eq 'HASH') {
                   2483:             if ($courses{$course}{'inst_code'} ne '') {
                   2484:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2485:                 $totcodes ++;
                   2486:             }
                   2487:         }
                   2488:     }
                   2489:     return $totcodes;
                   2490: }
                   2491: 
1.1172.2.113  raeburn  2492: # --------------------------------------------- Get domain config for passwords
                   2493: 
                   2494: sub get_passwdconf {
                   2495:     my ($dom) = @_;
                   2496:     my (%passwdconf,$gotconf,$lookup);
                   2497:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2498:     if (defined($cached)) {
                   2499:         if (ref($result) eq 'HASH') {
                   2500:             %passwdconf = %{$result};
                   2501:             $gotconf = 1;
                   2502:         }
                   2503:     }
                   2504:     unless ($gotconf) {
                   2505:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2506:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2507:             %passwdconf = %{$domconfig{'passwords'}};
                   2508:         }
                   2509:         my $cachetime = 24*60*60;
                   2510:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2511:     }
                   2512:     return %passwdconf;
                   2513: }
                   2514: 
1.344     www      2515: # --------------------------------------------------- Assign a key to a student
                   2516: 
                   2517: sub assign_access_key {
1.364     www      2518: #
                   2519: # a valid key looks like uname:udom#comments
                   2520: # comments are being appended
                   2521: #
1.498     www      2522:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2523:     $kdom=
1.620     albertel 2524:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2525:     $knum=
1.620     albertel 2526:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2527:     $cdom=
1.620     albertel 2528:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2529:     $cnum=
1.620     albertel 2530:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2531:     $udom=$env{'user.name'} unless (defined($udom));
                   2532:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2533:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2534:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2535:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2536:                                                   # assigned to this person
                   2537:                                                   # - this should not happen,
1.345     www      2538:                                                   # unless something went wrong
                   2539:                                                   # the first time around
                   2540: # ready to assign
1.364     www      2541:         $logentry=$1.'; '.$logentry;
1.496     www      2542:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2543:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2544: # key now belongs to user
1.346     www      2545: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2546:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2547:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2548:                 return 'ok';
                   2549:             } else {
                   2550:                 return 
                   2551:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2552: 	    }
                   2553:         } else {
                   2554:             return 'error: Could not assign key, try again later.';
                   2555:         }
1.364     www      2556:     } elsif (!$existing{$ckey}) {
1.345     www      2557: # the key does not exist
                   2558: 	return 'error: The key does not exist';
                   2559:     } else {
                   2560: # the key is somebody else's
                   2561: 	return 'error: The key is already in use';
                   2562:     }
1.344     www      2563: }
                   2564: 
1.364     www      2565: # ------------------------------------------ put an additional comment on a key
                   2566: 
                   2567: sub comment_access_key {
                   2568: #
                   2569: # a valid key looks like uname:udom#comments
                   2570: # comments are being appended
                   2571: #
                   2572:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2573:     $cdom=
1.620     albertel 2574:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2575:     $cnum=
1.620     albertel 2576:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2577:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2578:     if ($existing{$ckey}) {
                   2579:         $existing{$ckey}.='; '.$logentry;
                   2580: # ready to assign
1.367     www      2581:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2582:                                                  $cdom,$cnum) eq 'ok') {
                   2583: 	    return 'ok';
                   2584:         } else {
                   2585: 	    return 'error: Count not store comment.';
                   2586:         }
                   2587:     } else {
                   2588: # the key does not exist
                   2589: 	return 'error: The key does not exist';
                   2590:     }
                   2591: }
                   2592: 
1.344     www      2593: # ------------------------------------------------------ Generate a set of keys
                   2594: 
                   2595: sub generate_access_keys {
1.364     www      2596:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2597:     $cdom=
1.620     albertel 2598:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2599:     $cnum=
1.620     albertel 2600:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2601:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2602:     unless (($cdom) && ($cnum)) { return 0; }
                   2603:     if ($number>10000) { return 0; }
                   2604:     sleep(2); # make sure don't get same seed twice
                   2605:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2606:     my $total=0;
                   2607:     for (my $i=1;$i<=$number;$i++) {
                   2608:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2609:                   sprintf("%lx",int(100000*rand)).'-'.
                   2610:                   sprintf("%lx",int(100000*rand));
                   2611:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2612:        $newkey=~s/0/h/g; # and also 0 and O
                   2613:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2614:        if ($existing{$newkey}) {
                   2615:            $i--;
                   2616:        } else {
1.364     www      2617: 	  if (&put('accesskeys',
                   2618:               { $newkey => '# generated '.localtime().
1.620     albertel 2619:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2620:                            '; '.$logentry },
                   2621: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2622:               $total++;
                   2623: 	  }
                   2624:        }
                   2625:     }
1.620     albertel 2626:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2627:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2628:     return $total;
                   2629: }
                   2630: 
                   2631: # ------------------------------------------------------- Validate an accesskey
                   2632: 
                   2633: sub validate_access_key {
                   2634:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2635:     $cdom=
1.620     albertel 2636:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2637:     $cnum=
1.620     albertel 2638:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2639:     $udom=$env{'user.domain'} unless (defined($udom));
                   2640:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2641:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2642:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2643: }
                   2644: 
                   2645: # ------------------------------------- Find the section of student in a course
1.652     albertel 2646: sub devalidate_getsection_cache {
                   2647:     my ($udom,$unam,$courseid)=@_;
                   2648:     my $hashid="$udom:$unam:$courseid";
                   2649:     &devalidate_cache_new('getsection',$hashid);
                   2650: }
1.298     matthew  2651: 
1.815     albertel 2652: sub courseid_to_courseurl {
                   2653:     my ($courseid) = @_;
                   2654:     #already url style courseid
                   2655:     return $courseid if ($courseid =~ m{^/});
                   2656: 
                   2657:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2658: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2659: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2660: 	return "/$cdom/$cnum";
                   2661:     }
                   2662: 
                   2663:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2664:     if (exists($courseinfo{'num'})) {
                   2665: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2666:     }
                   2667: 
                   2668:     return undef;
                   2669: }
                   2670: 
1.298     matthew  2671: sub getsection {
                   2672:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2673:     my $cachetime=1800;
1.551     albertel 2674: 
                   2675:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2676:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2677:     if (defined($cached)) { return $result; }
                   2678: 
1.298     matthew  2679:     my %Pending; 
                   2680:     my %Expired;
                   2681:     #
                   2682:     # Each role can either have not started yet (pending), be active, 
                   2683:     #    or have expired.
                   2684:     #
                   2685:     # If there is an active role, we are done.
                   2686:     #
                   2687:     # If there is more than one role which has not started yet, 
                   2688:     #     choose the one which will start sooner
                   2689:     # If there is one role which has not started yet, return it.
                   2690:     #
                   2691:     # If there is more than one expired role, choose the one which ended last.
                   2692:     # If there is a role which has expired, return it.
                   2693:     #
1.815     albertel 2694:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2695:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2696:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2697:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2698:         my $section=$1;
                   2699:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2700:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2701:         my $now=time;
1.548     albertel 2702:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2703:             $Expired{$end}=$section;
                   2704:             next;
                   2705:         }
1.548     albertel 2706:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2707:             $Pending{$start}=$section;
                   2708:             next;
                   2709:         }
1.599     albertel 2710:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2711:     }
                   2712:     #
                   2713:     # Presumedly there will be few matching roles from the above
                   2714:     # loop and the sorting time will be negligible.
                   2715:     if (scalar(keys(%Pending))) {
                   2716:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2717:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2718:     } 
                   2719:     if (scalar(keys(%Expired))) {
                   2720:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2721:         my $time = pop(@sorted);
1.599     albertel 2722:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2723:     }
1.599     albertel 2724:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2725: }
1.70      www      2726: 
1.599     albertel 2727: sub save_cache {
                   2728:     &purge_remembered();
1.722     albertel 2729:     #&Apache::loncommon::validate_page();
1.620     albertel 2730:     undef(%env);
1.780     albertel 2731:     undef($env_loaded);
1.599     albertel 2732: }
1.452     albertel 2733: 
1.599     albertel 2734: my $to_remember=-1;
                   2735: my %remembered;
                   2736: my %accessed;
                   2737: my $kicks=0;
                   2738: my $hits=0;
1.849     albertel 2739: sub make_key {
                   2740:     my ($name,$id) = @_;
1.872     albertel 2741:     if (length($id) > 65 
                   2742: 	&& length(&escape($id)) > 200) {
                   2743: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2744:     }
1.849     albertel 2745:     return &escape($name.':'.$id);
                   2746: }
                   2747: 
1.599     albertel 2748: sub devalidate_cache_new {
                   2749:     my ($name,$id,$debug) = @_;
                   2750:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2751:     my $remembered_id=$name.':'.$id;
1.849     albertel 2752:     $id=&make_key($name,$id);
1.599     albertel 2753:     $memcache->delete($id);
1.1172.2.81  raeburn  2754:     delete($remembered{$remembered_id});
                   2755:     delete($accessed{$remembered_id});
1.599     albertel 2756: }
                   2757: 
                   2758: sub is_cached_new {
                   2759:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2760:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2761:                                      # keys in %remembered hash, which persists for
                   2762:                                      # duration of request (no restriction on key length).
                   2763:     if (exists($remembered{$remembered_id})) {
                   2764: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2765: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2766: 	$hits++;
1.1172.2.81  raeburn  2767: 	return ($remembered{$remembered_id},1);
1.599     albertel 2768:     }
1.1172.2.81  raeburn  2769:     $id=&make_key($name,$id);
1.599     albertel 2770:     my $value = $memcache->get($id);
                   2771:     if (!(defined($value))) {
                   2772: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2773: 	return (undef,undef);
1.416     albertel 2774:     }
1.599     albertel 2775:     if ($value eq '__undef__') {
                   2776: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2777: 	$value=undef;
                   2778:     }
1.1172.2.81  raeburn  2779:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2780:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2781:     return ($value,1);
                   2782: }
                   2783: 
                   2784: sub do_cache_new {
                   2785:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2786:     my $remembered_id=$name.':'.$id;
1.849     albertel 2787:     $id=&make_key($name,$id);
1.599     albertel 2788:     my $setvalue=$value;
                   2789:     if (!defined($setvalue)) {
                   2790: 	$setvalue='__undef__';
                   2791:     }
1.623     albertel 2792:     if (!defined($time) ) {
                   2793: 	$time=600;
                   2794:     }
1.599     albertel 2795:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2796:     my $result = $memcache->set($id,$setvalue,$time);
                   2797:     if (! $result) {
1.872     albertel 2798: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2799: 	$memcache->disconnect_all();
1.872     albertel 2800:     }
1.600     albertel 2801:     # need to make a copy of $value
1.1172.2.81  raeburn  2802:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2803:     return $value;
                   2804: }
                   2805: 
                   2806: sub make_room {
1.1172.2.81  raeburn  2807:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2808: 
1.1172.2.81  raeburn  2809:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2810:                                     : $value;
1.599     albertel 2811:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2812:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2813:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2814:     my $to_kick;
                   2815:     my $max_time=0;
                   2816:     foreach my $other (keys(%accessed)) {
                   2817: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2818: 	    $to_kick=$other;
                   2819: 	    $max_time=&tv_interval($accessed{$other});
                   2820: 	}
                   2821:     }
                   2822:     delete($remembered{$to_kick});
                   2823:     delete($accessed{$to_kick});
                   2824:     $kicks++;
                   2825:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2826:     return;
                   2827: }
                   2828: 
1.599     albertel 2829: sub purge_remembered {
1.604     albertel 2830:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2831:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2832:     undef(%remembered);
                   2833:     undef(%accessed);
1.428     albertel 2834: }
1.70      www      2835: # ------------------------------------- Read an entry from a user's environment
                   2836: 
                   2837: sub userenvironment {
                   2838:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2839:     my $items;
                   2840:     foreach my $item (@what) {
                   2841:         $items.=&escape($item).'&';
                   2842:     }
                   2843:     $items=~s/\&$//;
1.70      www      2844:     my %returnhash=();
1.1009    raeburn  2845:     my $uhome = &homeserver($unam,$udom);
                   2846:     unless ($uhome eq 'no_host') {
                   2847:         my @answer=split(/\&/, 
                   2848:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2849:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2850:             return %returnhash;
                   2851:         }
1.1009    raeburn  2852:         my $i;
                   2853:         for ($i=0;$i<=$#what;$i++) {
                   2854: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2855:         }
1.70      www      2856:     }
                   2857:     return %returnhash;
1.1       albertel 2858: }
                   2859: 
1.617     albertel 2860: # ---------------------------------------------------------- Get a studentphoto
                   2861: sub studentphoto {
                   2862:     my ($udom,$unam,$ext) = @_;
                   2863:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2864:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2865:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2866:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2867:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2868:             } else {
                   2869:                 my ($result,$perm_reqd)=
1.707     albertel 2870: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2871:                 if ($result eq 'ok') {
                   2872:                     if (!($perm_reqd eq 'yes')) {
                   2873:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2874:                     }
                   2875:                 }
                   2876:             }
                   2877:         }
                   2878:     } else {
                   2879:         my ($result,$perm_reqd) = 
1.707     albertel 2880: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2881:         if ($result eq 'ok') {
                   2882:             if (!($perm_reqd eq 'yes')) {
                   2883:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2884:             }
                   2885:         }
                   2886:     }
                   2887:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2888: }
                   2889: 
                   2890: sub retrievestudentphoto {
                   2891:     my ($udom,$unam,$ext,$type) = @_;
                   2892:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2893:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2894:     if ($ret eq 'ok') {
                   2895:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2896:         if ($type eq 'thumbnail') {
                   2897:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2898:         }
                   2899:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2900:         return $tokenurl;
                   2901:     } else {
                   2902:         if ($type eq 'thumbnail') {
                   2903:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2904:         } else { 
                   2905:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2906:         }
1.617     albertel 2907:     }
                   2908: }
                   2909: 
1.263     www      2910: # -------------------------------------------------------------------- New chat
                   2911: 
                   2912: sub chatsend {
1.724     raeburn  2913:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2914:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2915:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2916:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2917:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2918: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2919: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2920: }
                   2921: 
                   2922: # ------------------------------------------ Find current version of a resource
                   2923: 
                   2924: sub getversion {
                   2925:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2926:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2927:     return &currentversion(&filelocation('',$fname));
                   2928: }
                   2929: 
                   2930: sub currentversion {
                   2931:     my $fname=shift;
                   2932:     my $author=$fname;
                   2933:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2934:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2935:     my $home=&homeserver($uname,$udom);
1.292     www      2936:     if ($home eq 'no_host') { 
                   2937:         return -1; 
                   2938:     }
1.1112    www      2939:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2940:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2941: 	return -1;
                   2942:     }
1.1112    www      2943:     return $answer;
1.263     www      2944: }
                   2945: 
1.1111    www      2946: #
                   2947: # Return special version number of resource if set by override, empty otherwise
                   2948: #
                   2949: sub usedversion {
                   2950:     my $fname=shift;
                   2951:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2952:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2953:     if ($urlversion) { return $urlversion; }
                   2954:     return '';
                   2955: }
                   2956: 
1.1       albertel 2957: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2958: 
1.1       albertel 2959: sub subscribe {
                   2960:     my $fname=shift;
1.761     raeburn  2961:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2962:     $fname=~s/[\n\r]//g;
1.1       albertel 2963:     my $author=$fname;
                   2964:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2965:     my ($udom,$uname)=split(/\//,$author);
                   2966:     my $home=homeserver($uname,$udom);
1.335     albertel 2967:     if ($home eq 'no_host') {
                   2968:         return 'not_found';
1.1       albertel 2969:     }
                   2970:     my $answer=reply("sub:$fname",$home);
1.64      www      2971:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2972: 	$answer.=' by '.$home;
                   2973:     }
1.1       albertel 2974:     return $answer;
                   2975: }
                   2976:     
1.8       www      2977: # -------------------------------------------------------------- Replicate file
                   2978: 
                   2979: sub repcopy {
                   2980:     my $filename=shift;
1.23      www      2981:     $filename=~s/\/+/\//g;
1.1142    raeburn  2982:     my $londocroot = $perlvar{'lonDocRoot'};
                   2983:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2984:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2985:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2986: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2987: 	return &repcopy_userfile($filename);
                   2988:     }
1.532     albertel 2989:     $filename=~s/[\n\r]//g;
1.8       www      2990:     my $transname="$filename.in.transfer";
1.828     www      2991: # FIXME: this should flock
1.607     raeburn  2992:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2993:     my $remoteurl=subscribe($filename);
1.64      www      2994:     if ($remoteurl =~ /^con_lost by/) {
                   2995: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2996:            return 'unavailable';
1.8       www      2997:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2998: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2999: 	   return 'not_found';
1.64      www      3000:     } elsif ($remoteurl =~ /^rejected by/) {
                   3001: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3002:            return 'forbidden';
1.20      www      3003:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3004:            return 'ok';
1.8       www      3005:     } else {
1.290     www      3006:         my $author=$filename;
                   3007:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3008:         my ($udom,$uname)=split(/\//,$author);
                   3009:         my $home=homeserver($uname,$udom);
                   3010:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3011:            my @parts=split(/\//,$filename);
                   3012:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3013:            if ($path ne "$londocroot/res") {
1.8       www      3014:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3015: 	       return 'bad_request';
1.8       www      3016:            }
                   3017:            my $count;
                   3018:            for ($count=5;$count<$#parts;$count++) {
                   3019:                $path.="/$parts[$count]";
                   3020:                if ((-e $path)!=1) {
                   3021: 		   mkdir($path,0777);
                   3022:                }
                   3023:            }
                   3024:            my $ua=new LWP::UserAgent;
                   3025:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3026:            my $response=$ua->request($request,$transname);
                   3027:            if ($response->is_error()) {
                   3028: 	       unlink($transname);
                   3029:                my $message=$response->status_line;
1.672     albertel 3030:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3031:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3032:                return 'unavailable';
1.8       www      3033:            } else {
1.16      www      3034: 	       if ($remoteurl!~/\.meta$/) {
                   3035:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3036:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3037:                   if ($mresponse->is_error()) {
                   3038: 		      unlink($filename.'.meta');
                   3039:                       &logthis(
1.672     albertel 3040:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3041:                   }
                   3042: 	       }
1.8       www      3043:                rename($transname,$filename);
1.607     raeburn  3044:                return 'ok';
1.8       www      3045:            }
1.290     www      3046:        }
1.8       www      3047:     }
1.330     www      3048: }
                   3049: 
                   3050: # ------------------------------------------------ Get server side include body
                   3051: sub ssi_body {
1.381     albertel 3052:     my ($filelink,%form)=@_;
1.606     matthew  3053:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3054:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3055:     }
1.953     www      3056:     my $output='';
                   3057:     my $response;
1.980     raeburn  3058:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3059:        ($output,$response)=&externalssi($filelink);
1.953     www      3060:     } else {
1.1004    droeschl 3061:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3062:        $filelink .= 'inhibitmenu=yes';
1.953     www      3063:        ($output,$response)=&ssi($filelink,%form);
                   3064:     }
1.778     albertel 3065:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3066:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3067:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3068:     if (wantarray) {
                   3069:         return ($output, $response);
                   3070:     } else {
                   3071:         return $output;
                   3072:     }
1.8       www      3073: }
                   3074: 
1.15      www      3075: # --------------------------------------------------------- Server Side Include
                   3076: 
1.782     albertel 3077: sub absolute_url {
                   3078:     my ($host_name) = @_;
                   3079:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3080:     if ($host_name eq '') {
                   3081: 	$host_name = $ENV{'SERVER_NAME'};
                   3082:     }
                   3083:     return $protocol.$host_name;
                   3084: }
                   3085: 
1.942     foxr     3086: #
                   3087: #   Server side include.
                   3088: # Parameters:
                   3089: #  fn     Possibly encrypted resource name/id.
                   3090: #  form   Hash that describes how the rendering should be done
                   3091: #         and other things.
1.944     foxr     3092: # Returns:
1.950     raeburn  3093: #   Scalar context: The content of the response.
                   3094: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3095: #     
1.15      www      3096: sub ssi {
                   3097: 
1.944     foxr     3098:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3099:     my ($request,$response);
1.711     albertel 3100: 
                   3101:     $form{'no_update_last_known'}=1;
1.895     albertel 3102:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3103:     if (%form) {
1.782     albertel 3104:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3105:       $request->content(join('&',map {
                   3106:             my $name = escape($_);
                   3107:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3108:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3109:             : &escape($form{$_}) );
                   3110:         } keys(%form)));
1.23      www      3111:     } else {
1.782     albertel 3112:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3113:     }
                   3114: 
1.15      www      3115:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3116: 
1.1172.2.101  raeburn  3117:     if (($env{'request.course.id'}) &&
                   3118:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3119:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3120:         ($form{'grade_symb'} ne '') &&
                   3121:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3122:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3123:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3124:             my $ua=new LWP::UserAgent;
                   3125:             $ua->local_address('127.0.0.1');
                   3126:             $response = $ua->request($request);
                   3127:         } else {
                   3128:             {
                   3129:                 require LWP::Protocol::http;
                   3130:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3131:                 my $ua=new LWP::UserAgent;
                   3132:                 $response = $ua->request($request);
                   3133:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3134:             }
                   3135:         }
                   3136:     } else {
                   3137:         my $ua=new LWP::UserAgent;
                   3138:         $response = $ua->request($request);
                   3139:     }
1.944     foxr     3140:     if (wantarray) {
1.1172.2.3  raeburn  3141: 	return ($response->content, $response);
1.944     foxr     3142:     } else {
1.1172.2.3  raeburn  3143: 	return $response->content;
1.942     foxr     3144:     }
1.324     www      3145: }
                   3146: 
                   3147: sub externalssi {
                   3148:     my ($url)=@_;
                   3149:     my $ua=new LWP::UserAgent;
                   3150:     my $request=new HTTP::Request('GET',$url);
                   3151:     my $response=$ua->request($request);
1.954     raeburn  3152:     if (wantarray) {
                   3153:         return ($response->content, $response);
                   3154:     } else {
                   3155:         return $response->content;
                   3156:     }
1.15      www      3157: }
1.254     www      3158: 
1.1172.2.98  raeburn  3159: # If the local copy of a replicated resource is outdated, trigger a
                   3160: # connection from the homeserver to flush the delayed queue. If no update
                   3161: # happens, remove local copies of outdated resource (and corresponding
                   3162: # metadata file).
                   3163: 
                   3164: sub remove_stale_resfile {
                   3165:     my ($url) = @_;
                   3166:     my $removed;
                   3167:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3168:         my $audom = $1;
                   3169:         my $auname = $2;
                   3170:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3171:             my $homeserver = &homeserver($auname,$audom);
                   3172:             unless (($homeserver eq 'no_host') ||
                   3173:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3174:                 my $fname = &filelocation('',$url);
                   3175:                 if (-e $fname) {
                   3176:                     my $hostname = &hostname($homeserver);
                   3177:                     if ($hostname) {
1.1172.2.120  raeburn  3178:                         my $protocol = $protocol{$homeserver};
                   3179:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3180:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3181:                         my $ua=new LWP::UserAgent;
                   3182:                         $ua->timeout(5);
1.1172.2.98  raeburn  3183:                         my $request=new HTTP::Request('HEAD',$uri);
                   3184:                         my $response=$ua->request($request);
                   3185:                         if ($response->is_success()) {
                   3186:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3187:                             my $locmodtime = (stat($fname))[9];
                   3188:                             if ($locmodtime < $remmodtime) {
                   3189:                                 my $stale;
                   3190:                                 my $answer = &reply('pong',$homeserver);
                   3191:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3192:                                     sleep(0.2);
                   3193:                                     $locmodtime = (stat($fname))[9];
                   3194:                                     if ($locmodtime < $remmodtime) {
                   3195:                                         my $posstransfer = $fname.'.in.transfer';
                   3196:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3197:                                             $removed = 1;
                   3198:                                         } else {
                   3199:                                             $stale = 1;
                   3200:                                         }
                   3201:                                     } else {
                   3202:                                         $removed = 1;
                   3203:                                     }
                   3204:                                 } else {
                   3205:                                     $stale = 1;
                   3206:                                 }
                   3207:                                 if ($stale) {
                   3208:                                     unlink($fname);
                   3209:                                     if ($uri!~/\.meta$/) {
                   3210:                                         unlink($fname.'.meta');
                   3211:                                     }
                   3212:                                     &reply("unsub:$fname",$homeserver);
                   3213:                                     $removed = 1;
                   3214:                                 }
                   3215:                             }
                   3216:                         }
                   3217:                     }
                   3218:                 }
                   3219:             }
                   3220:         }
                   3221:     }
                   3222:     return $removed;
                   3223: }
                   3224: 
1.492     albertel 3225: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3226: 
                   3227: sub allowuploaded {
                   3228:     my ($srcurl,$url)=@_;
                   3229:     $url=&clutter(&declutter($url));
                   3230:     my $dir=$url;
                   3231:     $dir=~s/\/[^\/]+$//;
                   3232:     my %httpref=();
                   3233:     my $httpurl=&hreflocation('',$url);
                   3234:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3235:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3236: }
1.477     raeburn  3237: 
1.1172.2.13  raeburn  3238: #
                   3239: # Determine if the current user should be able to edit a particular resource,
                   3240: # when viewing in course context.
                   3241: # (a) When viewing resource used to determine if "Edit" item is included in
                   3242: #     Functions.
                   3243: # (b) When displaying folder contents in course editor, used to determine if
                   3244: #     "Edit" link will be displayed alongside resource.
                   3245: #
                   3246: #  input: six args -- filename (decluttered), course number, course domain,
                   3247: #                   url, symb (if registered) and group (if this is a group
                   3248: #                   item -- e.g., bulletin board, group page etc.).
                   3249: #  output: array of five scalars --
                   3250: #          $cfile -- url for file editing if editable on current server
                   3251: #          $home -- homeserver of resource (i.e., for author if published,
                   3252: #                                           or course if uploaded.).
                   3253: #          $switchserver --  1 if server switch will be needed.
                   3254: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3255: #          $forceview -- 1 if icon/link should be to go to view mode
                   3256: #
                   3257: 
                   3258: sub can_edit_resource {
                   3259:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3260:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3261: #
                   3262: # For aboutme pages user can only edit his/her own.
                   3263: #
                   3264:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3265:         my ($sdom,$sname) = ($1,$2);
                   3266:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3267:             $home = $env{'user.home'};
                   3268:             $cfile = $resurl;
                   3269:             if ($env{'form.forceedit'}) {
                   3270:                 $forceview = 1;
                   3271:             } else {
                   3272:                 $forceedit = 1;
                   3273:             }
                   3274:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3275:         } else {
                   3276:             return;
                   3277:         }
                   3278:     }
                   3279: 
                   3280:     if ($env{'request.course.id'}) {
                   3281:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3282:         if ($group ne '') {
                   3283: # if this is a group homepage or group bulletin board, check group privs
                   3284:             my $allowed = 0;
                   3285:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3286:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3287:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3288:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3289:                     $allowed = 1;
                   3290:                 }
                   3291:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3292:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3293:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3294:                     $allowed = 1;
                   3295:                 }
                   3296:             }
                   3297:             if ($allowed) {
                   3298:                 $home=&homeserver($cnum,$cdom);
                   3299:                 if ($env{'form.forceedit'}) {
                   3300:                     $forceview = 1;
                   3301:                 } else {
                   3302:                     $forceedit = 1;
                   3303:                 }
                   3304:                 $cfile = $resurl;
                   3305:             } else {
                   3306:                 return;
                   3307:             }
                   3308:         } else {
1.1172.2.15  raeburn  3309:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3310:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3311:                     return;
                   3312:                 }
                   3313:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3314: #
                   3315: # No edit allowed where CC has switched to student role.
                   3316: #
                   3317:                 return;
                   3318:             }
                   3319:         }
                   3320:     }
                   3321: 
                   3322:     if ($file ne '') {
                   3323:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3324:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3325:                 $uploaded = 1;
                   3326:                 $incourse = 1;
                   3327:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3328:                     $cfile = &hreflocation('',$file);
                   3329:                     if ($env{'form.forceedit'}) {
                   3330:                         $forceview = 1;
                   3331:                     } else {
                   3332:                         $forceedit = 1;
                   3333:                     }
                   3334:                 }
                   3335:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3336:                 $incourse = 1;
                   3337:                 if ($env{'form.forceedit'}) {
                   3338:                     $forceview = 1;
                   3339:                 } else {
                   3340:                     $forceedit = 1;
                   3341:                 }
                   3342:                 $cfile = $resurl;
                   3343:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3344:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3345:                     $incourse = 1;
                   3346:                     if ($env{'form.forceedit'}) {
                   3347:                         $forceview = 1;
                   3348:                     } else {
                   3349:                         $forceedit = 1;
                   3350:                     }
                   3351:                     $cfile = $resurl;
                   3352:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3353:                     $incourse = 1;
                   3354:                     $cfile = $resurl.'/smpedit';
                   3355:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3356:                     $incourse = 1;
                   3357:                     if ($env{'form.forceedit'}) {
                   3358:                         $forceview = 1;
                   3359:                     } else {
                   3360:                         $forceedit = 1;
                   3361:                     }
                   3362:                     $cfile = $resurl;
1.1172.2.15  raeburn  3363:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3364:                     $incourse = 1;
                   3365:                     if ($env{'form.forceedit'}) {
                   3366:                         $forceview = 1;
                   3367:                     } else {
                   3368:                         $forceedit = 1;
                   3369:                     }
                   3370:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3371:                 }
                   3372:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3373:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3374:                 if (&is_on_map($template)) {
                   3375:                     $incourse = 1;
                   3376:                     $forceview = 1;
                   3377:                     $cfile = $template;
                   3378:                 }
                   3379:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3380:                 $incourse = 1;
                   3381:                 if ($env{'form.forceedit'}) {
                   3382:                     $forceview = 1;
                   3383:                 } else {
                   3384:                     $forceedit = 1;
                   3385:                 }
                   3386:                 $cfile = $resurl;
1.1172.2.13  raeburn  3387:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3388:                 $incourse = 1;
                   3389:                 $forceview = 1;
                   3390:                 if ($symb) {
                   3391:                     my ($map,$id,$res)=&decode_symb($symb);
                   3392:                     $env{'request.symb'} = $symb;
                   3393:                     $cfile = &clutter($res);
                   3394:                 } else {
                   3395:                     $cfile = $env{'form.suppurl'};
                   3396:                     $cfile =~ s{^http://}{};
                   3397:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3398:                 }
1.1172.2.31  raeburn  3399:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3400:                 if ($env{'form.forceedit'}) {
                   3401:                     $forceview = 1;
                   3402:                 } else {
                   3403:                     $forceedit = 1;
                   3404:                 }
                   3405:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3406:             }
                   3407:         }
                   3408:         if ($uploaded || $incourse) {
                   3409:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3410:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3411:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3412:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3413:             # Check that the user has permission to edit this resource
                   3414:             my $setpriv = 1;
                   3415:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3416:             if (defined($cfudom)) {
                   3417:                 $home=&homeserver($cfuname,$cfudom);
                   3418:                 $cfile=$file;
                   3419:             }
                   3420:         }
                   3421:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3422:             (($home ne '') && ($home ne 'no_host'))) {
                   3423:             my @ids=&current_machine_ids();
                   3424:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3425:                 $switchserver=1;
                   3426:             }
                   3427:         }
                   3428:     }
                   3429:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3430: }
                   3431: 
                   3432: sub is_course_upload {
                   3433:     my ($file,$cnum,$cdom) = @_;
                   3434:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3435:     $uploadpath =~ s{^\/}{};
                   3436:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3437:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3438:         return 1;
                   3439:     }
                   3440:     return;
                   3441: }
                   3442: 
                   3443: sub in_course {
                   3444:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3445:     if ($hideprivileged) {
                   3446:         my $skipuser;
1.1172.2.23  raeburn  3447:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3448:         my @possdoms = ($cdom);
                   3449:         if ($coursehash{'checkforpriv'}) {
                   3450:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3451:         }
                   3452:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3453:             $skipuser = 1;
                   3454:             if ($coursehash{'nothideprivileged'}) {
                   3455:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3456:                     my $user;
                   3457:                     if ($item =~ /:/) {
                   3458:                         $user = $item;
                   3459:                     } else {
                   3460:                         $user = join(':',split(/[\@]/,$item));
                   3461:                     }
                   3462:                     if ($user eq $uname.':'.$udom) {
                   3463:                         undef($skipuser);
                   3464:                         last;
                   3465:                     }
                   3466:                 }
                   3467:             }
                   3468:             if ($skipuser) {
                   3469:                 return 0;
                   3470:             }
                   3471:         }
                   3472:     }
                   3473:     $type ||= 'any';
                   3474:     if (!defined($cdom) || !defined($cnum)) {
                   3475:         my $cid  = $env{'request.course.id'};
                   3476:         $cdom = $env{'course.'.$cid.'.domain'};
                   3477:         $cnum = $env{'course.'.$cid.'.num'};
                   3478:     }
                   3479:     my $typesref;
                   3480:     if (($type eq 'any') || ($type eq 'all')) {
                   3481:         $typesref = ['active','previous','future'];
                   3482:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3483:         $typesref = [$type];
                   3484:     }
                   3485:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3486:                               $typesref,undef,[$cdom]);
                   3487:     my ($tmp) = keys(%roles);
                   3488:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3489:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3490:     if (@course_roles > 0) {
                   3491:         return 1;
                   3492:     }
                   3493:     return 0;
                   3494: }
                   3495: 
1.478     albertel 3496: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3497: # input: action, courseID, current domain, intended
1.637     raeburn  3498: #        path to file, source of file, instruction to parse file for objects,
                   3499: #        ref to hash for embedded objects,
                   3500: #        ref to hash for codebase of java objects.
1.1095    raeburn  3501: #        reference to scalar to accommodate mime type determined
                   3502: #          from File::MMagic if $parser = parse.
1.637     raeburn  3503: #
1.485     raeburn  3504: # output: url to file (if action was uploaddoc), 
                   3505: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3506: #
1.478     albertel 3507: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3508: # course.
1.477     raeburn  3509: #
1.478     albertel 3510: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3511: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3512: #          course's home server.
1.477     raeburn  3513: #
1.478     albertel 3514: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3515: #          be copied from $source (current location) to 
                   3516: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3517: #         and will then be copied to
                   3518: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3519: #         course's home server.
1.485     raeburn  3520: #
1.481     raeburn  3521: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3522: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3523: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3524: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3525: #         in course's home server.
1.637     raeburn  3526: #
1.477     raeburn  3527: 
                   3528: sub process_coursefile {
1.1095    raeburn  3529:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3530:         $mimetype)=@_;
1.477     raeburn  3531:     my $fetchresult;
1.638     albertel 3532:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3533:     if ($action eq 'propagate') {
1.638     albertel 3534:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3535: 			     $home);
1.481     raeburn  3536:     } else {
1.477     raeburn  3537:         my $fpath = '';
                   3538:         my $fname = $file;
1.478     albertel 3539:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3540:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3541:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3542:         if ($action eq 'copy') {
                   3543:             if ($source eq '') {
                   3544:                 $fetchresult = 'no source file';
                   3545:                 return $fetchresult;
                   3546:             } else {
                   3547:                 my $destination = $filepath.'/'.$fname;
                   3548:                 rename($source,$destination);
                   3549:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3550:                                  $home);
1.481     raeburn  3551:             }
                   3552:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3553:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3554:             print $fh $env{'form.'.$source};
1.481     raeburn  3555:             close($fh);
1.637     raeburn  3556:             if ($parser eq 'parse') {
1.1024    raeburn  3557:                 my $mm = new File::MMagic;
1.1095    raeburn  3558:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3559:                 if ($type eq 'text/html') {
1.1024    raeburn  3560:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3561:                     unless ($parse_result eq 'ok') {
                   3562:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3563:                     }
1.637     raeburn  3564:                 }
1.1095    raeburn  3565:                 if (ref($mimetype)) {
                   3566:                     $$mimetype = $type;
                   3567:                 } 
1.637     raeburn  3568:             }
1.477     raeburn  3569:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3570:                                  $home);
1.481     raeburn  3571:             if ($fetchresult eq 'ok') {
                   3572:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3573:             } else {
                   3574:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3575:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3576:                 return '/adm/notfound.html';
                   3577:             }
1.477     raeburn  3578:         }
                   3579:     }
1.485     raeburn  3580:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3581:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3582:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3583:     }
                   3584:     return $fetchresult;
                   3585: }
                   3586: 
1.637     raeburn  3587: sub build_filepath {
                   3588:     my ($fpath) = @_;
                   3589:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3590:     unless ($fpath eq '') {
                   3591:         my @parts=split('/',$fpath);
                   3592:         foreach my $part (@parts) {
                   3593:             $filepath.= '/'.$part;
                   3594:             if ((-e $filepath)!=1) {
                   3595:                 mkdir($filepath,0777);
                   3596:             }
                   3597:         }
                   3598:     }
                   3599:     return $filepath;
                   3600: }
                   3601: 
                   3602: sub store_edited_file {
1.638     albertel 3603:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3604:     my $file = $primary_url;
                   3605:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3606:     my $fpath = '';
                   3607:     my $fname = $file;
                   3608:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3609:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3610:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3611:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3612:     print $fh $content;
                   3613:     close($fh);
1.638     albertel 3614:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3615:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3616: 			  $home);
1.637     raeburn  3617:     if ($$fetchresult eq 'ok') {
                   3618:         return '/uploaded/'.$fpath.'/'.$fname;
                   3619:     } else {
1.638     albertel 3620:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3621: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3622:         return '/adm/notfound.html';
                   3623:     }
                   3624: }
                   3625: 
1.531     albertel 3626: sub clean_filename {
1.831     albertel 3627:     my ($fname,$args)=@_;
1.315     www      3628: # Replace Windows backslashes by forward slashes
1.257     www      3629:     $fname=~s/\\/\//g;
1.831     albertel 3630:     if (!$args->{'keep_path'}) {
                   3631:         # Get rid of everything but the actual filename
                   3632: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3633:     }
1.315     www      3634: # Replace spaces by underscores
                   3635:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3636: # Transliterate non-ascii text to ascii
                   3637:     my $lang = &Apache::lonlocal::current_language();
                   3638:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3639: # Replace all other weird characters by nothing
1.831     albertel 3640:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3641: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3642: # numbers
                   3643:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3644:     return $fname;
                   3645: }
1.1172.2.110  raeburn  3646: 
1.1051    raeburn  3647: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3648: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3649: # image with the same aspect ratio as the original, but with dimensions which do 
                   3650: # not exceed $resizewidth and $resizeheight.
                   3651:  
1.984     neumanie 3652: sub resizeImage {
1.1051    raeburn  3653:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3654:     my $ima = Image::Magick->new;
                   3655:     my $resized;
                   3656:     if (-e $img_path) {
                   3657:         $ima->Read($img_path);
                   3658:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3659:             my $width = $ima->Get('width');
                   3660:             my $height = $ima->Get('height');
                   3661:             if ($width > $resizewidth) {
                   3662: 	        my $factor = $width/$resizewidth;
                   3663:                 my $newheight = $height/$factor;
                   3664:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3665:                 $resized = 1;
                   3666:             }
                   3667:         }
                   3668:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3669:             my $width = $ima->Get('width');
                   3670:             my $height = $ima->Get('height');
                   3671:             if ($height > $resizeheight) {
                   3672:                 my $factor = $height/$resizeheight;
                   3673:                 my $newwidth = $width/$factor;
                   3674:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3675:                 $resized = 1;
                   3676:             }
                   3677:         }
                   3678:         if ($resized) {
                   3679:             $ima->Write($img_path);
                   3680:         }
                   3681:     }
                   3682:     return;
1.977     amueller 3683: }
                   3684: 
1.608     albertel 3685: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3686: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3687: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3688: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3689: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3690: #                   if 'coursedoc': upload to the current course
                   3691: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3692: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3693: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3694: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3695: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3696: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3697: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3698: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3699: #        $allfiles - reference to hash for embedded objects
                   3700: #        $codebase - reference to hash for codebase of java objects
                   3701: #        $desuname - username for permanent storage of uploaded file
                   3702: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3703: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3704: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3705: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3706: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3707: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3708: #                    from File::MMagic.
1.858     raeburn  3709: # 
1.686     albertel 3710: # output: url of file in userspace, or error: <message> 
                   3711: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3712: 
1.531     albertel 3713: sub userfileupload {
1.1090    raeburn  3714:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3715:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3716:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3717:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3718:     $fname=&clean_filename($fname);
1.1090    raeburn  3719:     # See if there is anything left
1.257     www      3720:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3721:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3722:     if ($fname =~ /^\./) {
                   3723:         my ($s,$usec) = &gettimeofday();
                   3724:         while (length($usec) < 6) {
                   3725:             $usec = '0'.$usec;
                   3726:         }
                   3727:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3728:     }
1.1090    raeburn  3729:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3730:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3731:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3732:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3733:         my $now = time;
1.1090    raeburn  3734:         my $filepath;
1.1095    raeburn  3735:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3736:              $filepath = 'tmp/helprequests/'.$now;
                   3737:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3738:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3739:                          '_'.$env{'user.domain'}.'/pending';
                   3740:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3741:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3742:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3743:                 $docudom = $destudom;
                   3744:             } else {
                   3745:                 $docudom = $env{'user.domain'};
                   3746:             }
1.1172.2.96  raeburn  3747:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3748:                 $docuname = $destuname;
                   3749:             } else {
                   3750:                 $docuname = $env{'user.name'};
                   3751:             }
                   3752:             if (exists($env{'form.group'})) {
                   3753:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3754:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3755:             }
                   3756:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3757:             if ($context eq 'canceloverwrite') {
                   3758:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3759:                 if (-e  $tempfile) {
                   3760:                     my @info = stat($tempfile);
                   3761:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3762:                         unlink($tempfile);
                   3763:                     }
                   3764:                 }
                   3765:                 return;
1.523     raeburn  3766:             }
                   3767:         }
1.1090    raeburn  3768:         # Create the directory if not present
1.741     raeburn  3769:         my @parts=split(/\//,$filepath);
                   3770:         my $fullpath = $perlvar{'lonDaemons'};
                   3771:         for (my $i=0;$i<@parts;$i++) {
                   3772:             $fullpath .= '/'.$parts[$i];
                   3773:             if ((-e $fullpath)!=1) {
                   3774:                 mkdir($fullpath,0777);
                   3775:             }
                   3776:         }
1.1172.2.96  raeburn  3777:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3778:         print $fh $env{'form.'.$formname};
                   3779:         close($fh);
1.1090    raeburn  3780:         if ($context eq 'existingfile') {
                   3781:             my @info = stat($fullpath.'/'.$fname);
                   3782:             return ($fullpath.'/'.$fname,$info[9]);
                   3783:         } else {
                   3784:             return $fullpath.'/'.$fname;
                   3785:         }
1.523     raeburn  3786:     }
1.995     raeburn  3787:     if ($subdir eq 'scantron') {
                   3788:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3789:     } else {
1.995     raeburn  3790:         $fname="$subdir/$fname";
                   3791:     }
1.1090    raeburn  3792:     if ($context eq 'coursedoc') {
1.638     albertel 3793: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3794: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3795:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3796:             return &finishuserfileupload($docuname,$docudom,
                   3797: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3798: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3799:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3800:         } else {
1.1172.2.21  raeburn  3801:             if ($env{'form.folder'}) {
                   3802:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3803:             }
1.638     albertel 3804:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3805: 				       $fname,$formname,$parser,
1.1095    raeburn  3806: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3807:         }
1.719     banghart 3808:     } elsif (defined($destuname)) {
                   3809:         my $docuname=$destuname;
                   3810:         my $docudom=$destudom;
1.860     raeburn  3811: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3812: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3813:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3814:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3815:     } else {
1.638     albertel 3816:         my $docuname=$env{'user.name'};
                   3817:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3818:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3819:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3820:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3821:         }
1.860     raeburn  3822: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3823: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3824:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3825:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3826:     }
1.271     www      3827: }
                   3828: 
                   3829: sub finishuserfileupload {
1.860     raeburn  3830:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3831:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3832:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3833:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3834:   
1.860     raeburn  3835:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3836:     $file=$fname;
                   3837:     if ($fname=~m|/|) {
                   3838:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3839: 	$path.=$fnamepath.'/';
                   3840:     }
1.259     www      3841:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3842:     my $count;
                   3843:     for ($count=4;$count<=$#parts;$count++) {
                   3844:         $filepath.="/$parts[$count]";
                   3845:         if ((-e $filepath)!=1) {
                   3846: 	    mkdir($filepath,0777);
                   3847:         }
                   3848:     }
1.984     neumanie 3849: 
1.258     www      3850: # Save the file
                   3851:     {
1.1172.2.96  raeburn  3852: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3853: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3854: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3855: 	    return '/adm/notfound.html';
                   3856: 	}
1.1090    raeburn  3857:         if ($context eq 'overwrite') {
1.1117    foxr     3858:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3859:             my $target = $filepath.'/'.$file;
                   3860:             if (-e $source) {
                   3861:                 my @info = stat($source);
                   3862:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3863:                     unless (&File::Copy::move($source,$target)) {
                   3864:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3865:                         return "Moving from $source failed";
                   3866:                     }
                   3867:                 } else {
                   3868:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3869:                 }
                   3870:             } else {
                   3871:                 return "Temporary file: $source missing";
                   3872:             }
                   3873:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3874: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3875: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3876: 	    return '/adm/notfound.html';
                   3877: 	}
1.570     albertel 3878: 	close(FH);
1.1051    raeburn  3879:         if ($resizewidth && $resizeheight) {
                   3880:             my $mm = new File::MMagic;
                   3881:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3882:             if ($mime_type =~ m{^image/}) {
                   3883: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3884:             }  
1.977     amueller 3885: 	}
1.258     www      3886:     }
1.1152    raeburn  3887:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3888:         if (ref($mimetype)) {
                   3889:             if ($$mimetype eq '') {
                   3890:                 my $mm = new File::MMagic;
                   3891:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3892:                 $$mimetype = $type;
                   3893:             }
                   3894:         }
                   3895:     }
1.1172.2.109  raeburn  3896:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3897:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3898:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3899:                                                        $allfiles,$codebase);
                   3900:             unless ($parse_result eq 'ok') {
                   3901:                 &logthis('Failed to parse '.$filepath.$file.
                   3902: 	   	         ' for embedded media: '.$parse_result); 
                   3903:             }
1.637     raeburn  3904:         }
1.1172.2.109  raeburn  3905:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3906:         my $format = $env{'form.scantron_format'};
                   3907:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3908:     }
1.860     raeburn  3909:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3910:         my $input = $filepath.'/'.$file;
                   3911:         my $output = $filepath.'/'.'tn-'.$file;
                   3912:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3913:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3914:         system({$args[0]} @args);
1.860     raeburn  3915:         if (-e $filepath.'/'.'tn-'.$file) {
                   3916:             $fetchthumb  = 1; 
                   3917:         }
                   3918:     }
1.858     raeburn  3919:  
1.259     www      3920: # Notify homeserver to grep it
                   3921: #
1.984     neumanie 3922:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3923:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3924:     if ($fetchresult eq 'ok') {
1.860     raeburn  3925:         if ($fetchthumb) {
                   3926:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3927:             if ($thumbresult ne 'ok') {
                   3928:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3929:                          $docuhome.': '.$thumbresult);
                   3930:             }
                   3931:         }
1.259     www      3932: #
1.258     www      3933: # Return the URL to it
1.494     albertel 3934:         return '/uploaded/'.$path.$file;
1.263     www      3935:     } else {
1.494     albertel 3936:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3937: 		 ': '.$fetchresult);
1.263     www      3938:         return '/adm/notfound.html';
1.858     raeburn  3939:     }
1.493     albertel 3940: }
                   3941: 
1.637     raeburn  3942: sub extract_embedded_items {
1.961     raeburn  3943:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3944:     my @state = ();
1.1164    raeburn  3945:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3946:     my %javafiles = (
                   3947:                       codebase => '',
                   3948:                       code => '',
                   3949:                       archive => ''
                   3950:                     );
                   3951:     my %mediafiles = (
                   3952:                       src => '',
                   3953:                       movie => '',
                   3954:                      );
1.648     raeburn  3955:     my $p;
                   3956:     if ($content) {
                   3957:         $p = HTML::LCParser->new($content);
                   3958:     } else {
1.961     raeburn  3959:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3960:     }
1.641     albertel 3961:     while (my $t=$p->get_token()) {
1.640     albertel 3962: 	if ($t->[0] eq 'S') {
                   3963: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3964: 	    push(@state, $tagname);
1.648     raeburn  3965:             if (lc($tagname) eq 'allow') {
                   3966:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3967:             }
1.640     albertel 3968: 	    if (lc($tagname) eq 'img') {
                   3969: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3970: 	    }
1.886     albertel 3971: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3972:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3973: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3974:                 }
1.886     albertel 3975: 	    }
1.645     raeburn  3976:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3977:                 my $src;
1.645     raeburn  3978:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3979:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3980:                 } else {
1.1164    raeburn  3981:                     if ($attr->{'src'} ne '') {
                   3982:                         $src = $attr->{'src'};
                   3983:                         &add_filetype($allfiles,$src,'src');
                   3984:                     }
                   3985:                 }
                   3986:                 my $text = $p->get_trimmed_text();
                   3987:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3988:                     my @swfargs = split(/,/,$1);
                   3989:                     foreach my $item (@swfargs) {
                   3990:                         $item =~ s/["']//g;
                   3991:                         $item =~ s/^\s+//;
                   3992:                         $item =~ s/\s+$//;
                   3993:                     }
                   3994:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3995:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3996:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3997:                         } else {
                   3998:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3999:                         }
                   4000:                     }
1.645     raeburn  4001:                 }
                   4002:             }
                   4003:             if (lc($tagname) eq 'link') {
                   4004:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4005:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4006:                 }
                   4007:             }
1.640     albertel 4008: 	    if (lc($tagname) eq 'object' ||
                   4009: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4010: 		foreach my $item (keys(%javafiles)) {
                   4011: 		    $javafiles{$item} = '';
                   4012: 		}
1.1164    raeburn  4013:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4014:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4015:                 }
1.640     albertel 4016: 	    }
                   4017: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4018: 		my $name = lc($attr->{'name'});
                   4019: 		foreach my $item (keys(%javafiles)) {
                   4020: 		    if ($name eq $item) {
                   4021: 			$javafiles{$item} = $attr->{'value'};
                   4022: 			last;
                   4023: 		    }
                   4024: 		}
1.1164    raeburn  4025:                 my $pathfrom;
1.640     albertel 4026: 		foreach my $item (keys(%mediafiles)) {
                   4027: 		    if ($name eq $item) {
1.1164    raeburn  4028:                         $pathfrom = $attr->{'value'};
                   4029:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4030: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4031: 			last;
                   4032: 		    }
                   4033: 		}
1.1164    raeburn  4034:                 if ($name eq 'flashvars') {
                   4035:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4036:                 }
                   4037:                 if ($pathfrom ne '') {
                   4038:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4039:                                          $pathfrom);
                   4040:                 }
1.640     albertel 4041: 	    }
                   4042: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4043: 		foreach my $item (keys(%javafiles)) {
                   4044: 		    if ($attr->{$item}) {
                   4045: 			$javafiles{$item} = $attr->{$item};
                   4046: 			last;
                   4047: 		    }
                   4048: 		}
                   4049: 		foreach my $item (keys(%mediafiles)) {
                   4050: 		    if ($attr->{$item}) {
                   4051: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4052: 			last;
                   4053: 		    }
                   4054: 		}
1.1164    raeburn  4055:                 if (lc($tagname) eq 'embed') {
                   4056:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4057:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4058:                                              $attr->{'src'});
                   4059:                     }
                   4060:                 }
1.640     albertel 4061: 	    }
1.1172.2.35  raeburn  4062:             if (lc($tagname) eq 'iframe') {
                   4063:                 my $src = $attr->{'src'} ;
                   4064:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4065:                     &add_filetype($allfiles,$src,'src');
                   4066:                 } elsif ($src =~ m{^/}) {
                   4067:                     if ($env{'request.course.id'}) {
                   4068:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4069:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4070:                         my $url = &hreflocation('',$fullpath);
                   4071:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4072:                             my $relpath = $1;
                   4073:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4074:                                 &add_filetype($allfiles,$1,'src');
                   4075:                             }
                   4076:                         }
                   4077:                     }
                   4078:                 }
                   4079:             }
1.1164    raeburn  4080:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4081:                 pop(@state);
1.1164    raeburn  4082:             }
1.640     albertel 4083: 	} elsif ($t->[0] eq 'E') {
                   4084: 	    my ($tagname) = ($t->[1]);
                   4085: 	    if ($javafiles{'codebase'} ne '') {
                   4086: 		$javafiles{'codebase'} .= '/';
                   4087: 	    }  
                   4088: 	    if (lc($tagname) eq 'applet' ||
                   4089: 		lc($tagname) eq 'object' ||
                   4090: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4091: 		) {
                   4092: 		foreach my $item (keys(%javafiles)) {
                   4093: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4094: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4095: 			&add_filetype($allfiles,$file,$item);
                   4096: 		    }
                   4097: 		}
                   4098: 	    } 
                   4099: 	    pop @state;
                   4100: 	}
                   4101:     }
1.1164    raeburn  4102:     foreach my $id (sort(keys(%flashvars))) {
                   4103:         if ($shockwave{$id} ne '') {
                   4104:             my @pairs = split(/\&/,$flashvars{$id});
                   4105:             foreach my $pair (@pairs) {
                   4106:                 my ($key,$value) = split(/\=/,$pair);
                   4107:                 if ($key eq 'thumb') {
                   4108:                     &add_filetype($allfiles,$value,$key);
                   4109:                 } elsif ($key eq 'content') {
                   4110:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4111:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4112:                     if ($ext ne '') {
                   4113:                         &add_filetype($allfiles,$path.$value,$ext);
                   4114:                     }
                   4115:                 }
                   4116:             }
                   4117:         }
                   4118:     }
1.637     raeburn  4119:     return 'ok';
                   4120: }
                   4121: 
1.639     albertel 4122: sub add_filetype {
                   4123:     my ($allfiles,$file,$type)=@_;
                   4124:     if (exists($allfiles->{$file})) {
                   4125: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4126: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4127: 	}
                   4128:     } else {
                   4129: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4130:     }
                   4131: }
                   4132: 
1.1164    raeburn  4133: sub embedded_dependency {
                   4134:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4135:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4136:         if (($identifier ne '') &&
                   4137:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4138:             ($pathfrom ne '')) {
                   4139:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4140:             foreach my $dep (@{$related->{$identifier}}) {
                   4141:                 &add_filetype($allfiles,$path.$dep,'object');
                   4142:             }
                   4143:         }
                   4144:     }
                   4145:     return;
                   4146: }
                   4147: 
1.1172.2.109  raeburn  4148: sub bubblesheet_converter {
                   4149:     my ($cdom,$fullpath,$config,$format) = @_;
                   4150:     if ((&domain($cdom) ne '') &&
                   4151:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4152:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4153:         my (%csvcols,%csvoptions);
                   4154:         if (ref($config->{'fields'}) eq 'HASH') {
                   4155:             %csvcols = %{$config->{'fields'}};
                   4156:         }
                   4157:         if (ref($config->{'options'}) eq 'HASH') {
                   4158:             %csvoptions = %{$config->{'options'}};
                   4159:         }
                   4160:         my %csvbynum = reverse(%csvcols);
                   4161:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4162:         if (keys(%scantronconf)) {
                   4163:             my %bynum = (
                   4164:                           $scantronconf{CODEstart} => 'CODEstart',
                   4165:                           $scantronconf{IDstart}   => 'IDstart',
                   4166:                           $scantronconf{PaperID}   => 'PaperID',
                   4167:                           $scantronconf{FirstName} => 'FirstName',
                   4168:                           $scantronconf{LastName}  => 'LastName',
                   4169:                           $scantronconf{Qstart}    => 'Qstart',
                   4170:                         );
                   4171:             my @ordered;
                   4172:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4173:                 push(@ordered,$bynum{$item});
                   4174:             }
                   4175:             my %mapstart = (
                   4176:                               CODEstart => 'CODE',
                   4177:                               IDstart   => 'ID',
                   4178:                               PaperID   => 'PaperID',
                   4179:                               FirstName => 'FirstName',
                   4180:                               LastName  => 'LastName',
                   4181:                               Qstart    => 'FirstQuestion',
                   4182:                            );
                   4183:             my %maplength = (
                   4184:                               CODEstart => 'CODElength',
                   4185:                               IDstart   => 'IDlength',
                   4186:                               PaperID   => 'PaperIDlength',
                   4187:                               FirstName => 'FirstNamelength',
                   4188:                               LastName  => 'LastNamelength',
                   4189:             );
                   4190:             if (open(my $fh,'<',$fullpath)) {
                   4191:                 my $output;
                   4192:                 my %lettdig = &letter_to_digits();
                   4193:                 my %diglett = reverse(%lettdig);
                   4194:                 my $numletts = scalar(keys(%lettdig));
                   4195:                 my $num = 0;
                   4196:                 while (my $line=<$fh>) {
                   4197:                     $num ++;
                   4198:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4199:                     $line =~ s{[\r\n]+$}{};
                   4200:                     my %found;
                   4201:                     my @values = split(/,/,$line);
                   4202:                     my ($qstart,$record);
                   4203:                     for (my $i=0; $i<@values; $i++) {
                   4204:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4205:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4206:                             if ($values[$i] eq '') {
                   4207:                                 $values[$i] = $scantronconf{'Qoff'};
                   4208:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4209:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4210:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4211:                                 }
                   4212:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4213:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4214:                                     $values[$i] = $diglett{$values[$i]};
                   4215:                                 }
                   4216:                             } else {
                   4217:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4218:                                     my $digit;
                   4219:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4220:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4221:                                         if ($values[$i] eq 'J') {
                   4222:                                             $digit += $numletts;
                   4223:                                         }
                   4224:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4225:                                         $digit = $values[$i]-1;
                   4226:                                         if ($values[$i] eq '0') {
                   4227:                                             $digit += $numletts;
                   4228:                                         }
                   4229:                                     }
                   4230:                                     my $qval='';
                   4231:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4232:                                         if ($j == $digit) {
                   4233:                                             $qval .= $scantronconf{'Qon'};
                   4234:                                         } else {
                   4235:                                             $qval .= $scantronconf{'Qoff'};
                   4236:                                         }
                   4237:                                     }
                   4238:                                     $values[$i] = $qval;
                   4239:                                 }
                   4240:                             }
                   4241:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4242:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4243:                             }
                   4244:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4245:                             if ($numblank > 0) {
                   4246:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4247:                             }
                   4248:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4249:                                 $qstart = $i;
                   4250:                                 $found{$csvbynum{$i}} = $values[$i];
                   4251:                             } else {
                   4252:                                 $found{'FirstQuestion'} .= $values[$i];
                   4253:                             }
                   4254:                         } elsif (exists($csvbynum{$i})) {
                   4255:                             if ($csvoptions{'rem'}) {
                   4256:                                 $values[$i] =~ s/^\s+//;
                   4257:                             }
                   4258:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4259:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4260:                                     $values[$i] = '0'.$values[$i];
                   4261:                                 }
                   4262:                             }
                   4263:                             $found{$csvbynum{$i}} = $values[$i];
                   4264:                         }
                   4265:                     }
                   4266:                     foreach my $item (@ordered) {
                   4267:                         my $currlength = 1+length($record);
                   4268:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4269:                         if ($numspaces > 0) {
                   4270:                             $record .= (' ' x $numspaces);
                   4271:                         }
                   4272:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4273:                             unless ($item eq 'Qstart') {
                   4274:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4275:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4276:                                 }
                   4277:                             }
                   4278:                             $record .= $found{$mapstart{$item}};
                   4279:                         }
                   4280:                     }
                   4281:                     $output .= "$record\n";
                   4282:                 }
                   4283:                 close($fh);
                   4284:                 if ($output) {
                   4285:                     if (open(my $fh,'>',$fullpath)) {
                   4286:                         print $fh $output;
                   4287:                         close($fh);
                   4288:                     }
                   4289:                 }
                   4290:             }
                   4291:         }
                   4292:         return;
                   4293:     }
                   4294: }
                   4295: 
                   4296: sub letter_to_digits {
                   4297:     my %lettdig = (
                   4298:                     A => 1,
                   4299:                     B => 2,
                   4300:                     C => 3,
                   4301:                     D => 4,
                   4302:                     E => 5,
                   4303:                     F => 6,
                   4304:                     G => 7,
                   4305:                     H => 8,
                   4306:                     I => 9,
                   4307:                     J => 0,
                   4308:                   );
                   4309:     return %lettdig;
                   4310: }
                   4311: 
                   4312: sub get_scantron_config {
                   4313:     my ($which,$cdom) = @_;
                   4314:     my @lines = &get_scantronformat_file($cdom);
                   4315:     my %config;
                   4316:     #FIXME probably should move to XML it has already gotten a bit much now
                   4317:     foreach my $line (@lines) {
                   4318:         my ($name,$descrip)=split(/:/,$line);
                   4319:         if ($name ne $which ) { next; }
                   4320:         chomp($line);
                   4321:         my @config=split(/:/,$line);
                   4322:         $config{'name'}=$config[0];
                   4323:         $config{'description'}=$config[1];
                   4324:         $config{'CODElocation'}=$config[2];
                   4325:         $config{'CODEstart'}=$config[3];
                   4326:         $config{'CODElength'}=$config[4];
                   4327:         $config{'IDstart'}=$config[5];
                   4328:         $config{'IDlength'}=$config[6];
                   4329:         $config{'Qstart'}=$config[7];
                   4330:         $config{'Qlength'}=$config[8];
                   4331:         $config{'Qoff'}=$config[9];
                   4332:         $config{'Qon'}=$config[10];
                   4333:         $config{'PaperID'}=$config[11];
                   4334:         $config{'PaperIDlength'}=$config[12];
                   4335:         $config{'FirstName'}=$config[13];
                   4336:         $config{'FirstNamelength'}=$config[14];
                   4337:         $config{'LastName'}=$config[15];
                   4338:         $config{'LastNamelength'}=$config[16];
                   4339:         $config{'BubblesPerRow'}=$config[17];
                   4340:         last;
                   4341:     }
                   4342:     return %config;
                   4343: }
                   4344: 
                   4345: sub get_scantronformat_file {
                   4346:     my ($cdom) = @_;
                   4347:     if ($cdom eq '') {
                   4348:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4349:     }
                   4350:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4351:     my $gottab = 0;
                   4352:     my @lines;
                   4353:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4354:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4355:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4356:             if ($formatfile ne '-1') {
                   4357:                 @lines = split("\n",$formatfile,-1);
                   4358:                 $gottab = 1;
                   4359:             }
                   4360:         }
                   4361:     }
                   4362:     if (!$gottab) {
                   4363:         my $confname = $cdom.'-domainconfig';
                   4364:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4365:         my $formatfile = &getfile($default);
                   4366:         if ($formatfile ne '-1') {
                   4367:             @lines = split("\n",$formatfile,-1);
                   4368:             $gottab = 1;
                   4369:         }
                   4370:     }
                   4371:     if (!$gottab) {
                   4372:         my @domains = &current_machine_domains();
                   4373:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4374:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4375:                 @lines = <$fh>;
                   4376:                 close($fh);
                   4377:             }
                   4378:         } else {
                   4379:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4380:                 @lines = <$fh>;
                   4381:                 close($fh);
                   4382:             }
                   4383:         }
                   4384:     }
                   4385:     return @lines;
                   4386: }
                   4387: 
1.493     albertel 4388: sub removeuploadedurl {
1.984     neumanie 4389:     my ($url)=@_;	
                   4390:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4391:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4392: }
                   4393: 
                   4394: sub removeuserfile {
                   4395:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4396:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4397:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4398:     if ($result eq 'ok') {	
1.798     raeburn  4399:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4400:             my $metafile = $fname.'.meta';
                   4401:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4402: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4403:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4404:             my $sqlresult = 
1.823     albertel 4405:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4406:                                         'portfolio_metadata',$group,
                   4407:                                         'delete');
1.798     raeburn  4408:         }
                   4409:     }
                   4410:     return $result;
1.257     www      4411: }
1.15      www      4412: 
1.530     albertel 4413: sub mkdiruserfile {
                   4414:     my ($docuname,$docudom,$dir)=@_;
                   4415:     my $home=&homeserver($docuname,$docudom);
                   4416:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4417: }
                   4418: 
1.531     albertel 4419: sub renameuserfile {
                   4420:     my ($docuname,$docudom,$old,$new)=@_;
                   4421:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4422:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4423:                         &escape("$old").':'.&escape("$new"),$home);
                   4424:     if ($result eq 'ok') {
                   4425:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4426:             my $oldmeta = $old.'.meta';
                   4427:             my $newmeta = $new.'.meta';
                   4428:             my $metaresult = 
                   4429:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4430: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4431:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4432:             my $sqlresult = 
1.823     albertel 4433:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4434:                                         'portfolio_metadata',$group,
                   4435:                                         'delete');
1.798     raeburn  4436:         }
                   4437:     }
                   4438:     return $result;
1.531     albertel 4439: }
                   4440: 
1.14      www      4441: # ------------------------------------------------------------------------- Log
                   4442: 
                   4443: sub log {
                   4444:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4445:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4446: }
                   4447: 
                   4448: # ------------------------------------------------------------------ Course Log
1.352     www      4449: #
                   4450: # This routine flushes several buffers of non-mission-critical nature
                   4451: #
1.157     www      4452: 
                   4453: sub flushcourselogs {
1.352     www      4454:     &logthis('Flushing log buffers');
                   4455: #
                   4456: # course logs
                   4457: # This is a log of all transactions in a course, which can be used
                   4458: # for data mining purposes
                   4459: #
                   4460: # It also collects the courseid database, which lists last transaction
                   4461: # times and course titles for all courseids
                   4462: #
                   4463:     my %courseidbuffer=();
1.921     raeburn  4464:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4465:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4466: 		          &escape($courselogs{$crsid}),
                   4467: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4468: 	    delete $courselogs{$crsid};
                   4469:         } else {
                   4470:             &logthis('Failed to flush log buffer for '.$crsid);
                   4471:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4472:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4473:                         " exceeded maximum size, deleting.</font>");
                   4474:                delete $courselogs{$crsid};
                   4475:             }
1.352     www      4476:         }
1.920     raeburn  4477:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4478:             'description' => $coursedescrbuf{$crsid},
                   4479:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4480:             'type'        => $coursetypebuf{$crsid},
                   4481:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4482:         };
1.191     harris41 4483:     }
1.352     www      4484: #
                   4485: # Write course id database (reverse lookup) to homeserver of courses 
                   4486: # Is used in pickcourse
                   4487: #
1.840     albertel 4488:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4489:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4490:                                     $courseidbuffer{$crs_home},
                   4491:                                     $crs_home,'timeonly');
1.352     www      4492:     }
                   4493: #
                   4494: # File accesses
                   4495: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4496: #
1.449     matthew  4497:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4498:         if ($entry =~ /___count$/) {
                   4499:             my ($dom,$name);
1.807     albertel 4500:             ($dom,$name,undef)=
1.811     albertel 4501: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4502:             if (! defined($dom) || $dom eq '' || 
                   4503:                 ! defined($name) || $name eq '') {
1.620     albertel 4504:                 my $cid = $env{'request.course.id'};
                   4505:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4506:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4507:             }
1.450     matthew  4508:             my $value = $accesshash{$entry};
                   4509:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4510:             my %temphash=($url => $value);
1.449     matthew  4511:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4512:             if ($result eq 'ok') {
                   4513:                 delete $accesshash{$entry};
                   4514:             }
                   4515:         } else {
1.811     albertel 4516:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4517:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4518:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4519:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4520:                 delete $accesshash{$entry};
                   4521:             }
1.185     www      4522:         }
1.191     harris41 4523:     }
1.352     www      4524: #
                   4525: # Roles
                   4526: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4527: #
1.800     albertel 4528:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4529:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4530: 	    split(/\:/,$entry);
                   4531:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4532:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4533:                 $rudom,$runame) eq 'ok') {
                   4534: 	    delete $userrolehash{$entry};
                   4535:         }
                   4536:     }
1.662     raeburn  4537: #
1.1172.2.90  raeburn  4538: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4539: #
                   4540:     my %domrolebuffer = ();
1.1000    raeburn  4541:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4542:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4543:         if ($domrolebuffer{$rudom}) {
                   4544:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4545:                       '='.&escape($domainrolehash{$entry});
                   4546:         } else {
                   4547:             $domrolebuffer{$rudom}.=&escape($entry).
                   4548:                       '='.&escape($domainrolehash{$entry});
                   4549:         }
                   4550:         delete $domainrolehash{$entry};
                   4551:     }
                   4552:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4553:         my %servers;
                   4554:         if (defined(&domain($dom,'primary'))) {
                   4555:             my $primary=&domain($dom,'primary');
                   4556:             my $hostname=&hostname($primary);
                   4557:             $servers{$primary} = $hostname;
                   4558:         } else {
                   4559:             %servers = &get_servers($dom,'library');
                   4560:         }
1.841     albertel 4561: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4562: 	    if (&reply('domroleput:'.$dom.':'.
                   4563: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4564: 	        last;
                   4565: 	    } else {
1.841     albertel 4566: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4567: 	    }
1.662     raeburn  4568:         }
                   4569:     }
1.186     www      4570:     $dumpcount++;
1.157     www      4571: }
                   4572: 
                   4573: sub courselog {
                   4574:     my $what=shift;
1.158     www      4575:     $what=time.':'.$what;
1.620     albertel 4576:     unless ($env{'request.course.id'}) { return ''; }
                   4577:     $coursedombuf{$env{'request.course.id'}}=
                   4578:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4579:     $coursenumbuf{$env{'request.course.id'}}=
                   4580:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4581:     $coursehombuf{$env{'request.course.id'}}=
                   4582:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4583:     $coursedescrbuf{$env{'request.course.id'}}=
                   4584:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4585:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4586:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4587:     $courseownerbuf{$env{'request.course.id'}}=
                   4588:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4589:     $coursetypebuf{$env{'request.course.id'}}=
                   4590:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4591:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4592: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4593:     } else {
1.620     albertel 4594: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4595:     }
1.620     albertel 4596:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4597: 	&flushcourselogs();
                   4598:     }
1.158     www      4599: }
                   4600: 
                   4601: sub courseacclog {
                   4602:     my $fnsymb=shift;
1.620     albertel 4603:     unless ($env{'request.course.id'}) { return ''; }
                   4604:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4605:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4606:         $what.=':POST';
1.583     matthew  4607:         # FIXME: Probably ought to escape things....
1.800     albertel 4608: 	foreach my $key (keys(%env)) {
                   4609:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4610:                 my $formitem = $1;
                   4611:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4612:                     $what.=':'.$formitem.'='.$env{$key};
                   4613:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4614:                     $what.=':'.$formitem.'='.$env{$key};
                   4615:                 }
1.158     www      4616:             }
1.191     harris41 4617:         }
1.583     matthew  4618:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4619:         # FIXME: We should not be depending on a form parameter that someone
                   4620:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4621:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4622:             $what.= ':POST';
                   4623:             # FIXME: Probably ought to escape things....
                   4624:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4625:                                  'crsdiscuss') {
1.620     albertel 4626:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4627:             }
                   4628:         }
1.158     www      4629:     }
                   4630:     &courselog($what);
1.149     www      4631: }
                   4632: 
1.185     www      4633: sub countacc {
                   4634:     my $url=&declutter(shift);
1.458     matthew  4635:     return if (! defined($url) || $url eq '');
1.620     albertel 4636:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4637: #
                   4638: # Mark that this url was used in this course
                   4639: #
1.620     albertel 4640:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4641: #
                   4642: # Increase the access count for this resource in this child process
                   4643: #
1.281     www      4644:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4645:     $accesshash{$key}++;
1.185     www      4646: }
1.349     www      4647: 
1.361     www      4648: sub linklog {
                   4649:     my ($from,$to)=@_;
                   4650:     $from=&declutter($from);
                   4651:     $to=&declutter($to);
                   4652:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4653:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4654: }
1.1160    www      4655: 
                   4656: sub statslog {
                   4657:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4658:     if ($users<2) { return; }
                   4659:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4660:             'course'       => $env{'request.course.id'},
                   4661:             'sections'     => '"all"',
                   4662:             'num_students' => $users,
                   4663:             'part'         => $part,
                   4664:             'symb'         => $symb,
                   4665:             'mean_tries'   => $av_attempts,
                   4666:             'deg_of_diff'  => $degdiff});
                   4667:     foreach my $key (keys(%dynstore)) {
                   4668:         $accesshash{$key}=$dynstore{$key};
                   4669:     }
                   4670: }
1.361     www      4671:   
1.349     www      4672: sub userrolelog {
                   4673:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4674:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4675:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4676:        $userrolehash
                   4677:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4678:                     =$tend.':'.$tstart;
1.662     raeburn  4679:     }
1.1169    droeschl 4680:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4681:        $userrolehash
                   4682:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4683:                     =$tend.':'.$tstart;
                   4684:     }
1.1172.2.90  raeburn  4685:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4686:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4687:        $domainrolehash
                   4688:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4689:                     = $tend.':'.$tstart;
                   4690:     }
1.351     www      4691: }
                   4692: 
1.957     raeburn  4693: sub courserolelog {
                   4694:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4695:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4696:         my $cdom = $1;
                   4697:         my $cnum = $2;
                   4698:         my $sec = $3;
                   4699:         my $namespace = 'rolelog';
                   4700:         my %storehash = (
                   4701:                            role    => $trole,
                   4702:                            start   => $tstart,
                   4703:                            end     => $tend,
                   4704:                            selfenroll => $selfenroll,
                   4705:                            context    => $context,
                   4706:                         );
                   4707:         if ($trole eq 'gr') {
                   4708:             $namespace = 'groupslog';
                   4709:             $storehash{'group'} = $sec;
                   4710:         } else {
                   4711:             $storehash{'section'} = $sec;
                   4712:         }
                   4713:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4714:                    $domain,$cnum,$cdom);
                   4715:         if (($trole ne 'st') || ($sec ne '')) {
                   4716:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4717:         }
                   4718:     }
                   4719:     return;
                   4720: }
                   4721: 
1.1172.2.9  raeburn  4722: sub domainrolelog {
                   4723:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4724:     if ($area =~ m{^/($match_domain)/$}) {
                   4725:         my $cdom = $1;
                   4726:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4727:         my $namespace = 'rolelog';
                   4728:         my %storehash = (
                   4729:                            role    => $trole,
                   4730:                            start   => $tstart,
                   4731:                            end     => $tend,
                   4732:                            context => $context,
                   4733:                         );
                   4734:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4735:                    $domain,$domconfiguser,$cdom);
                   4736:     }
                   4737:     return;
                   4738: 
                   4739: }
                   4740: 
                   4741: sub coauthorrolelog {
                   4742:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4743:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4744:         my $audom = $1;
                   4745:         my $auname = $2;
                   4746:         my $namespace = 'rolelog';
                   4747:         my %storehash = (
                   4748:                            role    => $trole,
                   4749:                            start   => $tstart,
                   4750:                            end     => $tend,
                   4751:                            context => $context,
                   4752:                         );
                   4753:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4754:                    $domain,$auname,$audom);
                   4755:     }
                   4756:     return;
                   4757: }
                   4758: 
1.351     www      4759: sub get_course_adv_roles {
1.948     raeburn  4760:     my ($cid,$codes) = @_;
1.620     albertel 4761:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4762:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4763:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4764:     my %nothide=();
1.800     albertel 4765:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4766:         if ($user !~ /:/) {
                   4767: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4768:         } else {
                   4769:             $nothide{$user}=1;
                   4770:         }
1.470     www      4771:     }
1.1172.2.23  raeburn  4772:     my @possdoms = ($coursehash{'domain'});
                   4773:     if ($coursehash{'checkforpriv'}) {
                   4774:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4775:     }
1.351     www      4776:     my %returnhash=();
                   4777:     my %dumphash=
                   4778:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4779:     my $now=time;
1.997     raeburn  4780:     my %privileged;
1.1000    raeburn  4781:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4782: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4783:         if (($tstart) && ($tstart<0)) { next; }
                   4784:         if (($tend) && ($tend<$now)) { next; }
                   4785:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4786:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4787: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4788:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4789:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4790: 	if ($role eq 'cr') { next; }
1.948     raeburn  4791:         if ($codes) {
                   4792:             if ($section) { $role .= ':'.$section; }
                   4793:             if ($returnhash{$role}) {
                   4794:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4795:             } else {
                   4796:                 $returnhash{$role}=$username.':'.$domain;
                   4797:             }
1.351     www      4798:         } else {
1.988     raeburn  4799:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4800:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4801:             if ($returnhash{$key}) {
                   4802: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4803:             } else {
                   4804:                 $returnhash{$key}=$username.':'.$domain;
                   4805:             }
1.351     www      4806:         }
1.948     raeburn  4807:     }
1.400     www      4808:     return %returnhash;
                   4809: }
                   4810: 
                   4811: sub get_my_roles {
1.937     raeburn  4812:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4813:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4814:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4815:     my (%dumphash,%nothide);
1.1086    raeburn  4816:     if ($context eq 'userroles') {
1.1166    raeburn  4817:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4818:     } else {
1.1172.2.23  raeburn  4819:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4820:         if ($hidepriv) {
                   4821:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4822:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4823:                 if ($user !~ /:/) {
                   4824:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4825:                 } else {
                   4826:                     $nothide{$user} = 1;
                   4827:                 }
                   4828:             }
                   4829:         }
1.858     raeburn  4830:     }
1.400     www      4831:     my %returnhash=();
                   4832:     my $now=time;
1.999     raeburn  4833:     my %privileged;
1.800     albertel 4834:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4835:         my ($role,$tend,$tstart);
                   4836:         if ($context eq 'userroles') {
1.1149    raeburn  4837:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4838: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4839:         } else {
                   4840:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4841:         }
1.400     www      4842:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4843:         my $status = 'active';
1.939     raeburn  4844:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4845:             $status = 'previous';
                   4846:         } 
                   4847:         if (($tstart) && ($now<$tstart)) {
                   4848:             $status = 'future';
                   4849:         }
                   4850:         if (ref($types) eq 'ARRAY') {
                   4851:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4852:                 next;
                   4853:             } 
                   4854:         } else {
                   4855:             if ($status ne 'active') {
                   4856:                 next;
                   4857:             }
                   4858:         }
1.867     raeburn  4859:         my ($rolecode,$username,$domain,$section,$area);
                   4860:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4861:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4862:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4863:         } else {
                   4864:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4865:         }
1.832     raeburn  4866:         if (ref($roledoms) eq 'ARRAY') {
                   4867:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4868:                 next;
                   4869:             }
                   4870:         }
                   4871:         if (ref($roles) eq 'ARRAY') {
                   4872:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4873:                 if ($role =~ /^cr\//) {
                   4874:                     if (!grep(/^cr$/,@{$roles})) {
                   4875:                         next;
                   4876:                     }
1.1104    raeburn  4877:                 } elsif ($role =~ /^gr\//) {
                   4878:                     if (!grep(/^gr$/,@{$roles})) {
                   4879:                         next;
                   4880:                     }
1.922     raeburn  4881:                 } else {
                   4882:                     next;
                   4883:                 }
1.832     raeburn  4884:             }
1.867     raeburn  4885:         }
1.937     raeburn  4886:         if ($hidepriv) {
1.1172.2.23  raeburn  4887:             my @privroles = ('dc','su');
1.999     raeburn  4888:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4889:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4890:             } else {
1.1172.2.23  raeburn  4891:                 my $possdoms = [$domain];
                   4892:                 if (ref($roledoms) eq 'ARRAY') {
                   4893:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4894:                 }
1.1172.2.23  raeburn  4895:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4896:                     if (!$nothide{$username.':'.$domain}) {
                   4897:                         next;
                   4898:                     }
                   4899:                 }
1.937     raeburn  4900:             }
                   4901:         }
1.933     raeburn  4902:         if ($withsec) {
                   4903:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4904:                 $tstart.':'.$tend;
                   4905:         } else {
                   4906:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4907:         }
1.832     raeburn  4908:     }
1.373     www      4909:     return %returnhash;
1.399     www      4910: }
                   4911: 
1.1172.2.89  raeburn  4912: sub get_all_adhocroles {
                   4913:     my ($dom) = @_;
                   4914:     my @roles_by_num = ();
                   4915:     my %domdefaults = &get_domain_defaults($dom);
                   4916:     my (%description,%access_in_dom,%access_info);
                   4917:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4918:         my $count = 0;
                   4919:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4920:         my %ordered;
                   4921:         foreach my $role (sort(keys(%domcurrent))) {
                   4922:             my ($order,$desc,$access_in_dom);
                   4923:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4924:                 $order = $domcurrent{$role}{'order'};
                   4925:                 $desc = $domcurrent{$role}{'desc'};
                   4926:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4927:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4928:             }
                   4929:             if ($order eq '') {
                   4930:                 $order = $count;
                   4931:             }
                   4932:             $ordered{$order} = $role;
                   4933:             if ($desc ne '') {
                   4934:                 $description{$role} = $desc;
                   4935:             } else {
                   4936:                 $description{$role}= $role;
                   4937:             }
                   4938:             $count++;
                   4939:         }
                   4940:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4941:             push(@roles_by_num,$ordered{$item});
                   4942:         }
                   4943:     }
                   4944:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4945: }
                   4946: 
                   4947: sub get_my_adhocroles {
                   4948:     my ($cid,$checkreg) = @_;
                   4949:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4950:     if ($env{'request.course.id'} eq $cid) {
                   4951:         $cdom = $env{'course.'.$cid.'.domain'};
                   4952:         $cnum = $env{'course.'.$cid.'.num'};
                   4953:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4954:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4955:         $cdom = $1;
                   4956:         $cnum = $2;
                   4957:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4958:                                      $cdom,$cnum);
                   4959:     }
                   4960:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4961:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4962:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4963:         if ($rosterhash{$user} ne '') {
                   4964:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4965:             return ([],{}) if ($type eq 'auto');
                   4966:         }
                   4967:     }
                   4968:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4969:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4970:             my $then=$env{'user.login.time'};
                   4971:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4972:             if (!$update) {
                   4973:                 $update = $then;
                   4974:             }
                   4975:             my @liveroles;
                   4976:             foreach my $role ('dh','da') {
                   4977:                 if ($env{"user.role.$role./$cdom/"}) {
                   4978:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4979:                     my $limit = $update;
                   4980:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4981:                         $limit = $then;
                   4982:                     }
                   4983:                     my $activerole = 1;
                   4984:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4985:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4986:                     if ($activerole) {
                   4987:                         push(@liveroles,$role);
                   4988:                     }
                   4989:                 }
                   4990:             }
                   4991:             if (@liveroles) {
1.1172.2.89  raeburn  4992:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4993:                     my ($accessref,$accessinfo,%access_in_dom);
                   4994:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4995:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4996:                         if (@{$roles_by_num}) {
                   4997:                             my %settings;
                   4998:                             if ($env{'request.course.id'} eq $cid) {
                   4999:                                 foreach my $envkey (keys(%env)) {
                   5000:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5001:                                         $settings{$1} = $env{$envkey};
                   5002:                                     }
                   5003:                                 }
                   5004:                             } else {
                   5005:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5006:                             }
                   5007:                             my %setincrs;
                   5008:                             if ($settings{'internal.adhocaccess'}) {
                   5009:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5010:                             }
                   5011:                             my @statuses;
                   5012:                             if ($env{'environment.inststatus'}) {
                   5013:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5014:                             }
                   5015:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5016:                             if (ref($accessref) eq 'HASH') {
                   5017:                                 %access_in_dom = %{$accessref};
                   5018:                             }
                   5019:                             foreach my $role (@{$roles_by_num}) {
                   5020:                                 my ($curraccess,@okstatus,@personnel);
                   5021:                                 if ($setincrs{$role}) {
                   5022:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5023:                                     if ($curraccess eq 'status') {
                   5024:                                         @okstatus = split(/\&/,$rest);
                   5025:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5026:                                         @personnel = split(/\&/,$rest);
                   5027:                                     }
                   5028:                                 } else {
                   5029:                                     $curraccess = $access_in_dom{$role};
                   5030:                                     if (ref($accessinfo) eq 'HASH') {
                   5031:                                         if ($curraccess eq 'status') {
                   5032:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5033:                                                 @okstatus = @{$accessinfo->{$role}};
                   5034:                                             }
                   5035:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5036:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5037:                                                 @personnel = @{$accessinfo->{$role}};
                   5038:                                             }
                   5039:                                         }
                   5040:                                     }
                   5041:                                 }
                   5042:                                 if ($curraccess eq 'none') {
                   5043:                                     next;
                   5044:                                 } elsif ($curraccess eq 'all') {
                   5045:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5046:                                 } elsif ($curraccess eq 'dh') {
                   5047:                                     if (grep(/^dh$/,@liveroles)) {
                   5048:                                         push(@possroles,$role);
                   5049:                                     } else {
                   5050:                                         next;
                   5051:                                     }
                   5052:                                 } elsif ($curraccess eq 'da') {
                   5053:                                     if (grep(/^da$/,@liveroles)) {
                   5054:                                         push(@possroles,$role);
                   5055:                                     } else {
                   5056:                                         next;
                   5057:                                     }
1.1172.2.89  raeburn  5058:                                 } elsif ($curraccess eq 'status') {
                   5059:                                     if (@okstatus) {
                   5060:                                         if (!@statuses) {
                   5061:                                             if (grep(/^default$/,@okstatus)) {
                   5062:                                                 push(@possroles,$role);
                   5063:                                             }
                   5064:                                         } else {
                   5065:                                             foreach my $status (@okstatus) {
                   5066:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5067:                                                     push(@possroles,$role);
                   5068:                                                     last;
                   5069:                                                 }
                   5070:                                             }
                   5071:                                         }
                   5072:                                     }
                   5073:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5074:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5075:                                         if ($curraccess eq 'exc') {
                   5076:                                             push(@possroles,$role);
                   5077:                                         }
                   5078:                                     } elsif ($curraccess eq 'inc') {
                   5079:                                         push(@possroles,$role);
                   5080:                                     }
                   5081:                                 }
                   5082:                             }
                   5083:                         }
                   5084:                     }
                   5085:                 }
                   5086:             }
                   5087:         }
                   5088:     }
                   5089:     unless (ref($description) eq 'HASH') {
                   5090:         if (ref($roles_by_num) eq 'ARRAY') {
                   5091:             my %desc;
                   5092:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5093:             $description = \%desc;
                   5094:         } else {
                   5095:             $description = {};
                   5096:         }
                   5097:     }
                   5098:     return (\@possroles,$description);
                   5099: }
                   5100: 
1.399     www      5101: # ----------------------------------------------------- Frontpage Announcements
                   5102: #
                   5103: #
                   5104: 
                   5105: sub postannounce {
                   5106:     my ($server,$text)=@_;
1.844     albertel 5107:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5108:     unless ($text=~/\w/) { $text=''; }
                   5109:     return &reply('setannounce:'.&escape($text),$server);
                   5110: }
                   5111: 
                   5112: sub getannounce {
1.448     albertel 5113: 
1.1172.2.96  raeburn  5114:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5115: 	my $announcement='';
1.800     albertel 5116: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5117: 	close($fh);
1.399     www      5118: 	if ($announcement=~/\w/) { 
                   5119: 	    return 
                   5120:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5121:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5122: 	} else {
                   5123: 	    return '';
                   5124: 	}
                   5125:     } else {
                   5126: 	return '';
                   5127:     }
1.351     www      5128: }
1.353     www      5129: 
                   5130: # ---------------------------------------------------------- Course ID routines
                   5131: # Deal with domain's nohist_courseid.db files
                   5132: #
                   5133: 
                   5134: sub courseidput {
1.921     raeburn  5135:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5136:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5137:     my $outcome;
                   5138:     if ($caller eq 'timeonly') {
                   5139:         my $cids = '';
                   5140:         foreach my $item (keys(%$storehash)) {
                   5141:             $cids.=&escape($item).'&';
                   5142:         }
                   5143:         $cids=~s/\&$//;
                   5144:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5145:                           $coursehome);       
                   5146:     } else {
                   5147:         my $items = '';
                   5148:         foreach my $item (keys(%$storehash)) {
                   5149:             $items.= &escape($item).'='.
                   5150:                      &freeze_escape($$storehash{$item}).'&';
                   5151:         }
                   5152:         $items=~s/\&$//;
                   5153:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5154:                           $coursehome);
1.918     raeburn  5155:     }
                   5156:     if ($outcome eq 'unknown_cmd') {
                   5157:         my $what;
                   5158:         foreach my $cid (keys(%$storehash)) {
                   5159:             $what .= &escape($cid).'=';
1.921     raeburn  5160:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5161:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5162:             }
                   5163:             $what =~ s/\:$/&/;
                   5164:         }
                   5165:         $what =~ s/\&$//;  
                   5166:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5167:     } else {
                   5168:         return $outcome;
                   5169:     }
1.353     www      5170: }
                   5171: 
                   5172: sub courseiddump {
1.921     raeburn  5173:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5174:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5175:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5176:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5177:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5178:     my $as_hash = 1;
                   5179:     my %returnhash;
                   5180:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5181:     my %libserv = &all_library();
                   5182:     foreach my $tryserver (keys(%libserv)) {
                   5183:         if ( (  $hostidflag == 1 
                   5184: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5185: 	     || (!defined($hostidflag)) ) {
                   5186: 
1.918     raeburn  5187: 	    if (($domfilter eq '') ||
                   5188: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5189:                 my $rep;
                   5190:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5191:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5192:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5193:                                 &escape($descfilter), &escape($instcodefilter),
                   5194:                                 &escape($ownerfilter), &escape($coursefilter),
                   5195:                                 &escape($typefilter), &escape($regexp_ok),
                   5196:                                 $as_hash, &escape($selfenrollonly),
                   5197:                                 &escape($catfilter), $showhidden, $caller,
                   5198:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5199:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5200:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5201:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5202:                 } else {
                   5203:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5204:                              $sincefilter.':'.&escape($descfilter).':'.
                   5205:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5206:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5207:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5208:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5209:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5210:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5211:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5212:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5213:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5214:                 }
                   5215: 
1.918     raeburn  5216:                 my @pairs=split(/\&/,$rep);
                   5217:                 foreach my $item (@pairs) {
                   5218:                     my ($key,$value)=split(/\=/,$item,2);
                   5219:                     $key = &unescape($key);
                   5220:                     next if ($key =~ /^error: 2 /);
                   5221:                     my $result = &thaw_unescape($value);
                   5222:                     if (ref($result) eq 'HASH') {
                   5223:                         $returnhash{$key}=$result;
                   5224:                     } else {
1.921     raeburn  5225:                         my @responses = split(/:/,$value);
                   5226:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5227:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5228:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5229:                         }
1.1008    raeburn  5230:                     }
1.353     www      5231:                 }
                   5232:             }
                   5233:         }
                   5234:     }
                   5235:     return %returnhash;
                   5236: }
                   5237: 
1.1055    raeburn  5238: sub courselastaccess {
                   5239:     my ($cdom,$cnum,$hostidref) = @_;
                   5240:     my %returnhash;
                   5241:     if ($cdom && $cnum) {
                   5242:         my $chome = &homeserver($cnum,$cdom);
                   5243:         if ($chome ne 'no_host') {
                   5244:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5245:             &extract_lastaccess(\%returnhash,$rep);
                   5246:         }
                   5247:     } else {
                   5248:         if (!$cdom) { $cdom=''; }
                   5249:         my %libserv = &all_library();
                   5250:         foreach my $tryserver (keys(%libserv)) {
                   5251:             if (ref($hostidref) eq 'ARRAY') {
                   5252:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5253:             } 
                   5254:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5255:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5256:                 &extract_lastaccess(\%returnhash,$rep);
                   5257:             }
                   5258:         }
                   5259:     }
                   5260:     return %returnhash;
                   5261: }
                   5262: 
                   5263: sub extract_lastaccess {
                   5264:     my ($returnhash,$rep) = @_;
                   5265:     if (ref($returnhash) eq 'HASH') {
                   5266:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5267:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5268:                  $rep eq '') {
                   5269:             my @pairs=split(/\&/,$rep);
                   5270:             foreach my $item (@pairs) {
                   5271:                 my ($key,$value)=split(/\=/,$item,2);
                   5272:                 $key = &unescape($key);
                   5273:                 next if ($key =~ /^error: 2 /);
                   5274:                 $returnhash->{$key} = &thaw_unescape($value);
                   5275:             }
                   5276:         }
                   5277:     }
                   5278:     return;
                   5279: }
                   5280: 
1.658     raeburn  5281: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5282: 
                   5283: sub dcmailput {
1.685     raeburn  5284:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5285:     my $status = &Apache::lonnet::critical(
1.740     www      5286:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5287:        &escape($message),$server);
1.662     raeburn  5288:     return $status;
                   5289: }
                   5290: 
1.658     raeburn  5291: sub dcmaildump {
                   5292:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5293:     my %returnhash=();
1.846     albertel 5294: 
                   5295:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5296:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5297:                                                          &escape($enddate).':';
                   5298: 	my @esc_senders=map { &escape($_)} @$senders;
                   5299: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5300: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5301:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5302:             if (($key) && ($value)) {
                   5303:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5304:             }
                   5305:         }
                   5306:     }
                   5307:     return %returnhash;
                   5308: }
1.662     raeburn  5309: # ---------------------------------------------------------- Domain roles
                   5310: 
                   5311: sub get_domain_roles {
                   5312:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5313:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5314:         $startdate = '.';
                   5315:     }
1.1018    raeburn  5316:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5317:         $enddate = '.';
                   5318:     }
1.922     raeburn  5319:     my $rolelist;
                   5320:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5321:         $rolelist = join('&',@{$roles});
1.922     raeburn  5322:     }
1.662     raeburn  5323:     my %personnel = ();
1.841     albertel 5324: 
                   5325:     my %servers = &get_servers($dom,'library');
                   5326:     foreach my $tryserver (keys(%servers)) {
                   5327: 	%{$personnel{$tryserver}}=();
                   5328: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5329: 					    &escape($startdate).':'.
                   5330: 					    &escape($enddate).':'.
                   5331: 					    &escape($rolelist), $tryserver))) {
                   5332: 	    my ($key,$value) = split(/\=/,$line,2);
                   5333: 	    if (($key) && ($value)) {
                   5334: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5335: 	    }
                   5336: 	}
1.662     raeburn  5337:     }
                   5338:     return %personnel;
                   5339: }
1.658     raeburn  5340: 
1.1172.2.89  raeburn  5341: sub get_active_domroles {
                   5342:     my ($dom,$roles) = @_;
                   5343:     return () unless (ref($roles) eq 'ARRAY');
                   5344:     my $now = time;
                   5345:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5346:     my %domroles;
                   5347:     foreach my $server (keys(%dompersonnel)) {
                   5348:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5349:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5350:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5351:         }
                   5352:     }
                   5353:     return %domroles;
                   5354: }
                   5355: 
1.1057    www      5356: # ----------------------------------------------------------- Interval timing 
1.149     www      5357: 
1.1153    www      5358: {
                   5359: # Caches needed for speedup of navmaps
                   5360: # We don't want to cache this for very long at all (5 seconds at most)
                   5361: # 
                   5362: # The user for whom we cache
                   5363: my $cachedkey='';
                   5364: # The cached times for this user
                   5365: my %cachedtimes=();
                   5366: # When this was last done
1.1172.2.66  raeburn  5367: my $cachedtime='';
1.1153    www      5368: 
                   5369: sub load_all_first_access {
1.1154    raeburn  5370:     my ($uname,$udom)=@_;
1.1156    www      5371:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5372:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5373:         return;
                   5374:     }
                   5375:     $cachedtime=time;
                   5376:     $cachedkey=$uname.':'.$udom;
                   5377:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5378: }
                   5379: 
1.504     albertel 5380: sub get_first_access {
1.1162    raeburn  5381:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5382:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5383:     if ($argsymb) { $symb=$argsymb; }
                   5384:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5385:     if ($argmap) { $map = $argmap; }
1.926     albertel 5386:     if ($type eq 'course') {
                   5387: 	$res='course';
                   5388:     } elsif ($type eq 'map') {
1.588     albertel 5389: 	$res=&symbread($map);
                   5390:     } else {
                   5391: 	$res=$symb;
                   5392:     }
1.1153    www      5393:     &load_all_first_access($uname,$udom);
                   5394:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5395: }
                   5396: 
                   5397: sub set_first_access {
1.1162    raeburn  5398:     my ($type,$interval)=@_;
1.790     albertel 5399:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5400:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5401:     if ($type eq 'course') {
                   5402: 	$res='course';
                   5403:     } elsif ($type eq 'map') {
1.588     albertel 5404: 	$res=&symbread($map);
                   5405:     } else {
                   5406: 	$res=$symb;
                   5407:     }
1.1153    www      5408:     $cachedkey='';
1.1162    raeburn  5409:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5410:     if ($firstaccess) {
                   5411:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5412:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5413:                  "in $courseid");
                   5414:         return 'already_set';
                   5415:     } else {
1.1162    raeburn  5416:         my $start = time;
                   5417: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5418:                           $udom,$uname);
                   5419:         if ($putres eq 'ok') {
                   5420:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5421:                  $udom,$uname); 
                   5422:             &appenv(
                   5423:                      {
                   5424:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5425:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5426:                      }
                   5427:                   );
1.1172.2.97  raeburn  5428:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5429:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5430:             }
1.1172.2.102  raeburn  5431:         } elsif ($putres ne 'refused') {
                   5432:             &logthis("Result: $putres when attempting to set first access time ".
                   5433:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5434:         }
                   5435:         return $putres;
1.505     albertel 5436:     }
                   5437:     return 'already_set';
1.504     albertel 5438: }
1.1153    www      5439: }
1.1172.2.32  raeburn  5440: 
                   5441: sub checkout {
                   5442:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5443:     my $now=time;
                   5444:     my $lonhost=$perlvar{'lonHostID'};
                   5445:     my $infostr=&escape(
                   5446:                  'CHECKOUTTOKEN&'.
                   5447:                  $tuname.'&'.
                   5448:                  $tudom.'&'.
                   5449:                  $tcrsid.'&'.
                   5450:                  $symb.'&'.
                   5451:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5452:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5453:     if ($token=~/^error\:/) {
                   5454:         &logthis("<font color=\"blue\">WARNING: ".
                   5455:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5456:                  "</font>");
                   5457:         return '';
                   5458:     }
                   5459: 
                   5460:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5461:     $token=~tr/a-z/A-Z/;
                   5462: 
                   5463:     my %infohash=('resource.0.outtoken' => $token,
                   5464:                   'resource.0.checkouttime' => $now,
                   5465:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5466: 
                   5467:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5468:        return '';
                   5469:     } else {
                   5470:         &logthis("<font color=\"blue\">WARNING: ".
                   5471:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5472:                  "</font>");
                   5473:     }
                   5474: 
                   5475:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5476:                          &escape('Checkout '.$infostr.' - '.
                   5477:                                                  $token)) ne 'ok') {
                   5478:         return '';
                   5479:     } else {
                   5480:         &logthis("<font color=\"blue\">WARNING: ".
                   5481:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5482:                  "</font>");
                   5483:     }
                   5484:     return $token;
                   5485: }
                   5486: 
                   5487: # ------------------------------------------------------------ Check in an item
                   5488: 
                   5489: sub checkin {
                   5490:     my $token=shift;
                   5491:     my $now=time;
                   5492:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5493:     $lonhost=~tr/A-Z/a-z/;
                   5494:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5495:     $dtoken=~s/\W/\_/g;
                   5496:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5497:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5498: 
                   5499:     unless (($tuname) && ($tudom)) {
                   5500:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5501:         return '';
                   5502:     }
                   5503: 
                   5504:     unless (&allowed('mgr',$tcrsid)) {
                   5505:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5506:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5507:         return '';
                   5508:     }
                   5509: 
                   5510:     my %infohash=('resource.0.intoken' => $token,
                   5511:                   'resource.0.checkintime' => $now,
                   5512:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5513: 
                   5514:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5515:        return '';
                   5516:     }
                   5517: 
                   5518:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5519:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5520:         return '';
                   5521:     }
                   5522: 
                   5523:     return ($symb,$tuname,$tudom,$tcrsid);
                   5524: }
                   5525: 
1.110     www      5526: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5527: 
                   5528: sub expirespread {
                   5529:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5530:     my $cid=$env{'request.course.id'}; 
1.110     www      5531:     if ($cid) {
                   5532:        my $now=time;
                   5533:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5534:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5535:                             $env{'course.'.$cid.'.num'}.
1.110     www      5536: 	        	    ':nohist_expirationdates:'.
                   5537:                             &escape($key).'='.$now,
1.620     albertel 5538:                             $env{'course.'.$cid.'.home'})
1.110     www      5539:     }
                   5540:     return 'ok';
1.14      www      5541: }
                   5542: 
1.109     www      5543: # ----------------------------------------------------- Devalidate Spreadsheets
                   5544: 
                   5545: sub devalidate {
1.325     www      5546:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5547:     my $cid=$env{'request.course.id'}; 
1.109     www      5548:     if ($cid) {
1.391     matthew  5549:         # delete the stored spreadsheets for
                   5550:         # - the student level sheet of this user in course's homespace
                   5551:         # - the assessment level sheet for this resource 
                   5552:         #   for this user in user's homespace
1.553     albertel 5553: 	# - current conditional state info
1.325     www      5554: 	my $key=$uname.':'.$udom.':';
1.109     www      5555:         my $status=
1.299     matthew  5556: 	    &del('nohist_calculatedsheets',
1.391     matthew  5557: 		 [$key.'studentcalc:'],
1.620     albertel 5558: 		 $env{'course.'.$cid.'.domain'},
                   5559: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5560: 		.' '.
                   5561: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5562: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5563:         unless ($status eq 'ok ok') {
                   5564:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5565:                     $uname.' at '.$udom.' for '.
1.109     www      5566: 		    $symb.': '.$status);
1.133     albertel 5567:         }
1.553     albertel 5568: 	&delenv('user.state.'.$cid);
1.109     www      5569:     }
                   5570: }
                   5571: 
1.265     albertel 5572: sub get_scalar {
                   5573:     my ($string,$end) = @_;
                   5574:     my $value;
                   5575:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5576: 	$value = $1;
                   5577:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5578: 	$value = $1;
                   5579:     }
                   5580:     return &unescape($value);
                   5581: }
                   5582: 
                   5583: sub array2str {
                   5584:   my (@array) = @_;
                   5585:   my $result=&arrayref2str(\@array);
                   5586:   $result=~s/^__ARRAY_REF__//;
                   5587:   $result=~s/__END_ARRAY_REF__$//;
                   5588:   return $result;
                   5589: }
                   5590: 
1.204     albertel 5591: sub arrayref2str {
                   5592:   my ($arrayref) = @_;
1.265     albertel 5593:   my $result='__ARRAY_REF__';
1.204     albertel 5594:   foreach my $elem (@$arrayref) {
1.265     albertel 5595:     if(ref($elem) eq 'ARRAY') {
                   5596:       $result.=&arrayref2str($elem).'&';
                   5597:     } elsif(ref($elem) eq 'HASH') {
                   5598:       $result.=&hashref2str($elem).'&';
                   5599:     } elsif(ref($elem)) {
                   5600:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5601:     } else {
                   5602:       $result.=&escape($elem).'&';
                   5603:     }
                   5604:   }
                   5605:   $result=~s/\&$//;
1.265     albertel 5606:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5607:   return $result;
                   5608: }
                   5609: 
1.168     albertel 5610: sub hash2str {
1.204     albertel 5611:   my (%hash) = @_;
                   5612:   my $result=&hashref2str(\%hash);
1.265     albertel 5613:   $result=~s/^__HASH_REF__//;
                   5614:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5615:   return $result;
                   5616: }
                   5617: 
                   5618: sub hashref2str {
                   5619:   my ($hashref)=@_;
1.265     albertel 5620:   my $result='__HASH_REF__';
1.800     albertel 5621:   foreach my $key (sort(keys(%$hashref))) {
                   5622:     if (ref($key) eq 'ARRAY') {
                   5623:       $result.=&arrayref2str($key).'=';
                   5624:     } elsif (ref($key) eq 'HASH') {
                   5625:       $result.=&hashref2str($key).'=';
                   5626:     } elsif (ref($key)) {
1.265     albertel 5627:       $result.='=';
1.800     albertel 5628:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5629:     } else {
1.1132    raeburn  5630: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5631:     }
                   5632: 
1.800     albertel 5633:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5634:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5635:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5636:       $result.=&hashref2str($hashref->{$key}).'&';
                   5637:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5638:        $result.='&';
1.800     albertel 5639:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5640:     } else {
1.800     albertel 5641:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5642:     }
                   5643:   }
1.168     albertel 5644:   $result=~s/\&$//;
1.265     albertel 5645:   $result .= '__END_HASH_REF__';
1.168     albertel 5646:   return $result;
                   5647: }
                   5648: 
                   5649: sub str2hash {
1.265     albertel 5650:     my ($string)=@_;
                   5651:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5652:     return %$hash;
                   5653: }
                   5654: 
                   5655: sub str2hashref {
1.168     albertel 5656:   my ($string) = @_;
1.265     albertel 5657: 
                   5658:   my %hash;
                   5659: 
                   5660:   if($string !~ /^__HASH_REF__/) {
                   5661:       if (! ($string eq '' || !defined($string))) {
                   5662: 	  $hash{'error'}='Not hash reference';
                   5663:       }
                   5664:       return (\%hash, $string);
                   5665:   }
                   5666: 
                   5667:   $string =~ s/^__HASH_REF__//;
                   5668: 
                   5669:   while($string !~ /^__END_HASH_REF__/) {
                   5670:       #key
                   5671:       my $key='';
                   5672:       if($string =~ /^__HASH_REF__/) {
                   5673:           ($key, $string)=&str2hashref($string);
                   5674:           if(defined($key->{'error'})) {
                   5675:               $hash{'error'}='Bad data';
                   5676:               return (\%hash, $string);
                   5677:           }
                   5678:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5679:           ($key, $string)=&str2arrayref($string);
                   5680:           if($key->[0] eq 'Array reference error') {
                   5681:               $hash{'error'}='Bad data';
                   5682:               return (\%hash, $string);
                   5683:           }
                   5684:       } else {
                   5685:           $string =~ s/^(.*?)=//;
1.267     albertel 5686: 	  $key=&unescape($1);
1.265     albertel 5687:       }
                   5688:       $string =~ s/^=//;
                   5689: 
                   5690:       #value
                   5691:       my $value='';
                   5692:       if($string =~ /^__HASH_REF__/) {
                   5693:           ($value, $string)=&str2hashref($string);
                   5694:           if(defined($value->{'error'})) {
                   5695:               $hash{'error'}='Bad data';
                   5696:               return (\%hash, $string);
                   5697:           }
                   5698:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5699:           ($value, $string)=&str2arrayref($string);
                   5700:           if($value->[0] eq 'Array reference error') {
                   5701:               $hash{'error'}='Bad data';
                   5702:               return (\%hash, $string);
                   5703:           }
                   5704:       } else {
                   5705: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5706:       }
                   5707:       $string =~ s/^&//;
                   5708: 
                   5709:       $hash{$key}=$value;
1.204     albertel 5710:   }
1.265     albertel 5711: 
                   5712:   $string =~ s/^__END_HASH_REF__//;
                   5713: 
                   5714:   return (\%hash, $string);
1.204     albertel 5715: }
                   5716: 
                   5717: sub str2array {
1.265     albertel 5718:     my ($string)=@_;
                   5719:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5720:     return @$array;
                   5721: }
                   5722: 
                   5723: sub str2arrayref {
1.204     albertel 5724:   my ($string) = @_;
1.265     albertel 5725:   my @array;
                   5726: 
                   5727:   if($string !~ /^__ARRAY_REF__/) {
                   5728:       if (! ($string eq '' || !defined($string))) {
                   5729: 	  $array[0]='Array reference error';
                   5730:       }
                   5731:       return (\@array, $string);
                   5732:   }
                   5733: 
                   5734:   $string =~ s/^__ARRAY_REF__//;
                   5735: 
                   5736:   while($string !~ /^__END_ARRAY_REF__/) {
                   5737:       my $value='';
                   5738:       if($string =~ /^__HASH_REF__/) {
                   5739:           ($value, $string)=&str2hashref($string);
                   5740:           if(defined($value->{'error'})) {
                   5741:               $array[0] ='Array reference error';
                   5742:               return (\@array, $string);
                   5743:           }
                   5744:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5745:           ($value, $string)=&str2arrayref($string);
                   5746:           if($value->[0] eq 'Array reference error') {
                   5747:               $array[0] ='Array reference error';
                   5748:               return (\@array, $string);
                   5749:           }
                   5750:       } else {
                   5751: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5752:       }
                   5753:       $string =~ s/^&//;
                   5754: 
                   5755:       push(@array, $value);
1.191     harris41 5756:   }
1.265     albertel 5757: 
                   5758:   $string =~ s/^__END_ARRAY_REF__//;
                   5759: 
                   5760:   return (\@array, $string);
1.168     albertel 5761: }
                   5762: 
1.167     albertel 5763: # -------------------------------------------------------------------Temp Store
                   5764: 
1.168     albertel 5765: sub tmpreset {
                   5766:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5767:   if (!$symb) {
                   5768:     $symb=&symbread();
1.620     albertel 5769:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5770:   }
                   5771:   $symb=escape($symb);
                   5772: 
1.620     albertel 5773:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5774:   $namespace=~s/\//\_/g;
                   5775:   $namespace=~s/\W//g;
                   5776: 
1.620     albertel 5777:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5778:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5779:   if ($domain eq 'public' && $stuname eq 'public') {
                   5780:       $stuname=$ENV{'REMOTE_ADDR'};
                   5781:   }
1.1117    foxr     5782:   my $path=LONCAPA::tempdir();
1.168     albertel 5783:   my %hash;
                   5784:   if (tie(%hash,'GDBM_File',
                   5785: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5786: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5787:     foreach my $key (keys(%hash)) {
1.180     albertel 5788:       if ($key=~ /:$symb/) {
1.168     albertel 5789: 	delete($hash{$key});
                   5790:       }
                   5791:     }
                   5792:   }
                   5793: }
                   5794: 
1.167     albertel 5795: sub tmpstore {
1.168     albertel 5796:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5797: 
                   5798:   if (!$symb) {
                   5799:     $symb=&symbread();
1.620     albertel 5800:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5801:   }
                   5802:   $symb=escape($symb);
                   5803: 
                   5804:   if (!$namespace) {
                   5805:     # I don't think we would ever want to store this for a course.
                   5806:     # it seems this will only be used if we don't have a course.
1.620     albertel 5807:     #$namespace=$env{'request.course.id'};
1.168     albertel 5808:     #if (!$namespace) {
1.620     albertel 5809:       $namespace=$env{'request.state'};
1.168     albertel 5810:     #}
                   5811:   }
                   5812:   $namespace=~s/\//\_/g;
                   5813:   $namespace=~s/\W//g;
1.620     albertel 5814:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5815:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5816:   if ($domain eq 'public' && $stuname eq 'public') {
                   5817:       $stuname=$ENV{'REMOTE_ADDR'};
                   5818:   }
1.168     albertel 5819:   my $now=time;
                   5820:   my %hash;
1.1117    foxr     5821:   my $path=LONCAPA::tempdir();
1.168     albertel 5822:   if (tie(%hash,'GDBM_File',
                   5823: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5824: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5825:     $hash{"version:$symb"}++;
                   5826:     my $version=$hash{"version:$symb"};
                   5827:     my $allkeys=''; 
                   5828:     foreach my $key (keys(%$storehash)) {
                   5829:       $allkeys.=$key.':';
1.591     albertel 5830:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5831:     }
                   5832:     $hash{"$version:$symb:timestamp"}=$now;
                   5833:     $allkeys.='timestamp';
                   5834:     $hash{"$version:keys:$symb"}=$allkeys;
                   5835:     if (untie(%hash)) {
                   5836:       return 'ok';
                   5837:     } else {
                   5838:       return "error:$!";
                   5839:     }
                   5840:   } else {
                   5841:     return "error:$!";
                   5842:   }
                   5843: }
1.167     albertel 5844: 
1.168     albertel 5845: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5846: 
1.168     albertel 5847: sub tmprestore {
                   5848:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5849: 
1.168     albertel 5850:   if (!$symb) {
                   5851:     $symb=&symbread();
1.620     albertel 5852:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5853:   }
                   5854:   $symb=escape($symb);
                   5855: 
1.620     albertel 5856:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5857: 
1.620     albertel 5858:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5859:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5860:   if ($domain eq 'public' && $stuname eq 'public') {
                   5861:       $stuname=$ENV{'REMOTE_ADDR'};
                   5862:   }
1.168     albertel 5863:   my %returnhash;
                   5864:   $namespace=~s/\//\_/g;
                   5865:   $namespace=~s/\W//g;
                   5866:   my %hash;
1.1117    foxr     5867:   my $path=LONCAPA::tempdir();
1.168     albertel 5868:   if (tie(%hash,'GDBM_File',
                   5869: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5870: 	  &GDBM_READER(),0640)) {
1.168     albertel 5871:     my $version=$hash{"version:$symb"};
                   5872:     $returnhash{'version'}=$version;
                   5873:     my $scope;
                   5874:     for ($scope=1;$scope<=$version;$scope++) {
                   5875:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5876:       my @keys=split(/:/,$vkeys);
                   5877:       my $key;
                   5878:       $returnhash{"$scope:keys"}=$vkeys;
                   5879:       foreach $key (@keys) {
1.591     albertel 5880: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5881: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5882:       }
                   5883:     }
1.168     albertel 5884:     if (!(untie(%hash))) {
                   5885:       return "error:$!";
                   5886:     }
                   5887:   } else {
                   5888:     return "error:$!";
                   5889:   }
                   5890:   return %returnhash;
1.167     albertel 5891: }
                   5892: 
1.9       www      5893: # ----------------------------------------------------------------------- Store
                   5894: 
                   5895: sub store {
1.1172.2.64  raeburn  5896:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5897:     my $home='';
                   5898: 
1.168     albertel 5899:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5900: 
1.213     www      5901:     $symb=&symbclean($symb);
1.122     albertel 5902:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5903: 
1.620     albertel 5904:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5905:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5906: 
                   5907:     &devalidate($symb,$stuname,$domain);
1.109     www      5908: 
                   5909:     $symb=escape($symb);
1.187     www      5910:     if (!$namespace) { 
1.620     albertel 5911:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5912:           return ''; 
                   5913:        } 
                   5914:     }
1.620     albertel 5915:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5916: 
                   5917:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5918:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5919: 
1.12      www      5920:     my $namevalue='';
1.800     albertel 5921:     foreach my $key (keys(%$storehash)) {
                   5922:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5923:     }
1.12      www      5924:     $namevalue=~s/\&$//;
1.187     www      5925:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5926:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5927: }
                   5928: 
1.47      www      5929: # -------------------------------------------------------------- Critical Store
                   5930: 
                   5931: sub cstore {
1.1172.2.64  raeburn  5932:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5933:     my $home='';
                   5934: 
1.168     albertel 5935:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5936: 
1.213     www      5937:     $symb=&symbclean($symb);
1.122     albertel 5938:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5939: 
1.620     albertel 5940:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5941:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5942: 
                   5943:     &devalidate($symb,$stuname,$domain);
1.109     www      5944: 
                   5945:     $symb=escape($symb);
1.187     www      5946:     if (!$namespace) { 
1.620     albertel 5947:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5948:           return ''; 
                   5949:        } 
                   5950:     }
1.620     albertel 5951:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5952: 
                   5953:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5954:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5955: 
1.47      www      5956:     my $namevalue='';
1.800     albertel 5957:     foreach my $key (keys(%$storehash)) {
                   5958:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5959:     }
1.47      www      5960:     $namevalue=~s/\&$//;
1.187     www      5961:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5962:     return critical
1.1172.2.64  raeburn  5963:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5964: }
                   5965: 
1.9       www      5966: # --------------------------------------------------------------------- Restore
                   5967: 
                   5968: sub restore {
1.124     www      5969:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5970:     my $home='';
                   5971: 
1.168     albertel 5972:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5973: 
1.122     albertel 5974:     if (!$symb) {
1.1172.2.26  raeburn  5975:         return if ($namespace eq 'courserequests');
                   5976:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5977:     } else {
1.1172.2.26  raeburn  5978:         unless ($namespace eq 'courserequests') {
                   5979:             $symb=&escape(&symbclean($symb));
                   5980:         }
1.122     albertel 5981:     }
1.188     www      5982:     if (!$namespace) { 
1.620     albertel 5983:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5984:           return ''; 
                   5985:        } 
                   5986:     }
1.620     albertel 5987:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5988:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5989:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5990:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5991: 
1.12      www      5992:     my %returnhash=();
1.800     albertel 5993:     foreach my $line (split(/\&/,$answer)) {
                   5994: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5995:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5996:     }
1.75      www      5997:     my $version;
                   5998:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5999:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6000:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6001:        }
1.75      www      6002:     }
1.13      www      6003:     return %returnhash;
1.34      www      6004: }
                   6005: 
                   6006: # ---------------------------------------------------------- Course Description
1.1118    foxr     6007: #
                   6008: #  
1.34      www      6009: 
                   6010: sub coursedescription {
1.731     albertel 6011:     my ($courseid,$args)=@_;
1.34      www      6012:     $courseid=~s/^\///;
1.49      www      6013:     $courseid=~s/\_/\//g;
1.34      www      6014:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6015:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6016:     my $normalid=$cdomain.'_'.$cnum;
                   6017:     # need to always cache even if we get errors otherwise we keep 
                   6018:     # trying and trying and trying to get the course description.
                   6019:     my %envhash=();
                   6020:     my %returnhash=();
1.731     albertel 6021:     
                   6022:     my $expiretime=600;
                   6023:     if ($env{'request.course.id'} eq $normalid) {
                   6024: 	$expiretime=120;
                   6025:     }
                   6026: 
                   6027:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6028:     if (!$args->{'freshen_cache'}
                   6029: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6030: 	foreach my $key (keys(%env)) {
                   6031: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6032: 	    my ($setting) = $1;
                   6033: 	    $returnhash{$setting} = $env{$key};
                   6034: 	}
                   6035: 	return %returnhash;
                   6036:     }
                   6037: 
1.1118    foxr     6038:     # get the data again
                   6039: 
1.731     albertel 6040:     if (!$args->{'one_time'}) {
                   6041: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6042:     }
1.811     albertel 6043: 
1.34      www      6044:     if ($chome ne 'no_host') {
1.302     albertel 6045:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6046:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6047: 	   my $username = $env{'user.name'}; # Defult username
                   6048: 	   if(defined $args->{'user'}) {
                   6049: 	       $username = $args->{'user'};
                   6050: 	   }
1.129     albertel 6051:            $returnhash{'home'}= $chome;
                   6052: 	   $returnhash{'domain'} = $cdomain;
                   6053: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6054:            if (!defined($returnhash{'type'})) {
                   6055:                $returnhash{'type'} = 'Course';
                   6056:            }
1.130     albertel 6057:            while (my ($name,$value) = each %returnhash) {
1.53      www      6058:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6059:            }
1.270     www      6060:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6061:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6062: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6063:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6064:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6065:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6066:        }
                   6067:     }
1.731     albertel 6068:     if (!$args->{'one_time'}) {
1.949     raeburn  6069: 	&appenv(\%envhash);
1.731     albertel 6070:     }
1.302     albertel 6071:     return %returnhash;
1.461     www      6072: }
                   6073: 
1.1080    raeburn  6074: sub update_released_required {
                   6075:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6076:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6077:         $cid = $env{'request.course.id'};
                   6078:         $cdom = $env{'course.'.$cid.'.domain'};
                   6079:         $cnum = $env{'course.'.$cid.'.num'};
                   6080:         $chome = $env{'course.'.$cid.'.home'};
                   6081:     }
                   6082:     if ($needsrelease) {
                   6083:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6084:         my $needsupdate;
                   6085:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6086:             $needsupdate = 1;
                   6087:         } else {
                   6088:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6089:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6090:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6091:                 $needsupdate = 1;
                   6092:             }
                   6093:         }
                   6094:         if ($needsupdate) {
                   6095:             my %needshash = (
                   6096:                              'internal.releaserequired' => $needsrelease,
                   6097:                             );
                   6098:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6099:             if ($putresult eq 'ok') {
                   6100:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6101:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6102:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6103:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6104:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6105:                 }
                   6106:             }
                   6107:         }
                   6108:     }
                   6109:     return;
                   6110: }
                   6111: 
1.461     www      6112: # -------------------------------------------------See if a user is privileged
                   6113: 
                   6114: sub privileged {
1.1172.2.23  raeburn  6115:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6116:     my $now = time;
1.1172.2.23  raeburn  6117:     my $roles;
                   6118:     if (ref($possroles) eq 'ARRAY') {
                   6119:         $roles = $possroles;
                   6120:     } else {
                   6121:         $roles = ['dc','su'];
                   6122:     }
                   6123:     if (ref($possdomains) eq 'ARRAY') {
                   6124:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6125:         foreach my $dom (@{$possdomains}) {
                   6126:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6127:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6128:                 foreach my $role (@{$roles}) {
                   6129:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6130:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6131:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6132:                             return 1 unless (($end && $end < $now) ||
                   6133:                                              ($start && $start > $now));
                   6134:                         }
                   6135:                     }
                   6136:                 }
                   6137:             }
                   6138:         }
                   6139:     } else {
                   6140:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6141:         my $now = time;
1.1170    droeschl 6142: 
1.1172.2.58  raeburn  6143:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6144:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6145:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6146:                 return 1 unless ($tend && $tend < $now)
                   6147:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6148:             }
1.1172.2.23  raeburn  6149:         }
                   6150:     }
1.461     www      6151:     return 0;
1.9       www      6152: }
1.1       albertel 6153: 
1.1172.2.23  raeburn  6154: sub privileged_by_domain {
                   6155:     my ($domains,$roles) = @_;
                   6156:     my %privileged = ();
                   6157:     my $cachetime = 60*60*24;
                   6158:     my $now = time;
                   6159:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6160:         return %privileged;
                   6161:     }
                   6162:     foreach my $dom (@{$domains}) {
                   6163:         next if (ref($privileged{$dom}) eq 'HASH');
                   6164:         my $needroles;
                   6165:         foreach my $role (@{$roles}) {
                   6166:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6167:             if (defined($cached)) {
                   6168:                 if (ref($result) eq 'HASH') {
                   6169:                     $privileged{$dom}{$role} = $result;
                   6170:                 }
                   6171:             } else {
                   6172:                 $needroles = 1;
                   6173:             }
                   6174:         }
                   6175:         if ($needroles) {
                   6176:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6177:             $privileged{$dom} = {};
                   6178:             foreach my $server (keys(%dompersonnel)) {
                   6179:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6180:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6181:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6182:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6183:                         next if ($end && $end < $now);
                   6184:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6185:                             $dompersonnel{$server}{$item};
                   6186:                     }
                   6187:                 }
                   6188:             }
                   6189:             if (ref($privileged{$dom}) eq 'HASH') {
                   6190:                 foreach my $role (@{$roles}) {
                   6191:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6192:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6193:                     } else {
                   6194:                         my %hash = ();
                   6195:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6196:                     }
                   6197:                 }
                   6198:             }
                   6199:         }
                   6200:     }
                   6201:     return %privileged;
                   6202: }
                   6203: 
1.103     harris41 6204: # -------------------------------------------------------- Get user privileges
1.11      www      6205: 
                   6206: sub rolesinit {
1.1169    droeschl 6207:     my ($domain, $username) = @_;
                   6208:     my %userroles = ('user.login.time' => time);
                   6209:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6210: 
                   6211:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6212:     # also, blocking can be triggered by an activating timer
                   6213:     # it's saved in the user's %env.
                   6214:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6215:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6216:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6217:         %timerintchk, %timerintenv);
                   6218: 
1.1162    raeburn  6219:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6220:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6221:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6222:     }
1.1169    droeschl 6223: 
1.1162    raeburn  6224:     foreach my $key (keys(%timerinterval)) {
                   6225:         my ($cid,$rest) = split(/\0/,$key);
                   6226:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6227:     }
1.1169    droeschl 6228: 
1.11      www      6229:     my %allroles=();
1.1162    raeburn  6230:     my %allgroups=();
1.11      www      6231: 
1.1172.2.58  raeburn  6232:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6233:         my $role = $rolesdump{$area};
                   6234:         $area =~ s/\_\w\w$//;
                   6235: 
                   6236:         my ($trole, $tend, $tstart, $group_privs);
                   6237: 
                   6238:         if ($role =~ /^cr/) {
                   6239:         # Custom role, defined by a user 
                   6240:         # e.g., user.role.cr/msu/smith/mynewrole
                   6241:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6242:                 $trole = $1;
                   6243:                 ($tend, $tstart) = split('_', $2);
                   6244:             } else {
                   6245:                 $trole = $role;
                   6246:             }
                   6247:         } elsif ($role =~ m|^gr/|) {
                   6248:         # Role of member in a group, defined within a course/community
                   6249:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6250:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6251:             next if $tstart eq '-1';
                   6252:             ($trole, $group_privs) = split(/\//, $trole);
                   6253:             $group_privs = &unescape($group_privs);
                   6254:         } else {
                   6255:         # Just a normal role, defined in roles.tab
                   6256:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6257:         }
                   6258: 
                   6259:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6260:                  $username);
                   6261:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6262: 
                   6263:         # role expired or not available yet?
                   6264:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6265:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6266: 
                   6267:         next if $area eq '' or $trole eq '';
                   6268: 
                   6269:         my $spec = "$trole.$area";
                   6270:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6271: 
                   6272:         if ($trole =~ /^cr\//) {
                   6273:         # Custom role, defined by a user
                   6274:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6275:         } elsif ($trole eq 'gr') {
                   6276:         # Role of a member in a group, defined within a course/community
                   6277:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6278:             next;
                   6279:         } else {
                   6280:         # Normal role, defined in roles.tab
                   6281:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6282:         }
                   6283: 
                   6284:         my $cid = $tdomain.'_'.$trest;
                   6285:         unless ($firstaccchk{$cid}) {
                   6286:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6287:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6288:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6289:                         $coursetimerstarts{$cid}{$item}; 
                   6290:                 }
                   6291:             }
                   6292:             $firstaccchk{$cid} = 1;
                   6293:         }
                   6294:         unless ($timerintchk{$cid}) {
                   6295:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6296:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6297:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6298:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6299:                 }
1.12      www      6300:             }
1.1169    droeschl 6301:             $timerintchk{$cid} = 1;
1.191     harris41 6302:         }
1.11      www      6303:     }
1.1169    droeschl 6304: 
1.1172.2.91  raeburn  6305:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6306:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6307:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6308:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6309: 
1.1162    raeburn  6310:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6311: }
                   6312: 
1.567     raeburn  6313: sub set_arearole {
1.1172.2.19  raeburn  6314:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6315:     unless ($nolog) {
1.567     raeburn  6316: # log the associated role with the area
1.1172.2.19  raeburn  6317:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6318:     }
1.743     albertel 6319:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6320: }
                   6321: 
                   6322: sub custom_roleprivs {
                   6323:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6324:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6325:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6326:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6327:         my ($rdummy,$roledef)=
                   6328:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6329:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6330:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6331:             if (defined($syspriv)) {
1.1043    raeburn  6332:                 if ($trest =~ /^$match_community$/) {
                   6333:                     $syspriv =~ s/bre\&S//; 
                   6334:                 }
1.567     raeburn  6335:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6336:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6337:             }
                   6338:             if ($tdomain ne '') {
                   6339:                 if (defined($dompriv)) {
                   6340:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6341:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6342:                 }
                   6343:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6344:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6345:                         my $rolename = $1;
                   6346:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6347:                     }
1.567     raeburn  6348:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6349:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6350:                 }
                   6351:             }
                   6352:         }
                   6353:     }
                   6354: }
                   6355: 
1.1172.2.89  raeburn  6356: sub course_adhocrole_privs {
                   6357:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6358:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6359:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6360:         my (%currprivs,%storeprivs);
                   6361:         foreach my $item (split(/:/,$coursepriv)) {
                   6362:             my ($priv,$restrict) = split(/\&/,$item);
                   6363:             $currprivs{$priv} = $restrict;
                   6364:         }
                   6365:         my (%possadd,%possremove,%full);
                   6366:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6367:             my ($priv,$restrict)=split(/\&/,$item);
                   6368:             $full{$priv} = $restrict;
                   6369:         }
                   6370:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6371:              next if ($item eq '');
                   6372:              my ($rule,$rest) = split(/=/,$item);
                   6373:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6374:              foreach my $priv (split(/:/,$rest)) {
                   6375:                  if ($priv ne '') {
                   6376:                      if ($rule eq 'off') {
                   6377:                          $possremove{$priv} = 1;
                   6378:                      } else {
                   6379:                          $possadd{$priv} = 1;
                   6380:                      }
                   6381:                  }
                   6382:              }
                   6383:          }
                   6384:          foreach my $priv (sort(keys(%full))) {
                   6385:              if (exists($currprivs{$priv})) {
                   6386:                  unless (exists($possremove{$priv})) {
                   6387:                      $storeprivs{$priv} = $currprivs{$priv};
                   6388:                  }
                   6389:              } elsif (exists($possadd{$priv})) {
                   6390:                  $storeprivs{$priv} = $full{$priv};
                   6391:              }
                   6392:          }
                   6393:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6394:      }
                   6395:      return $coursepriv;
                   6396: }
                   6397: 
1.678     raeburn  6398: sub group_roleprivs {
                   6399:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6400:     my $access = 1;
                   6401:     my $now = time;
                   6402:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6403:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6404:     if ($access) {
1.811     albertel 6405:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6406:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6407:     }
                   6408: }
1.567     raeburn  6409: 
                   6410: sub standard_roleprivs {
                   6411:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6412:     if (defined($pr{$trole.':s'})) {
                   6413:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6414:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6415:     }
                   6416:     if ($tdomain ne '') {
                   6417:         if (defined($pr{$trole.':d'})) {
                   6418:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6419:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6420:         }
                   6421:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6422:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6423:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6424:         }
                   6425:     }
                   6426: }
                   6427: 
                   6428: sub set_userprivs {
1.1064    raeburn  6429:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6430:     my $author=0;
                   6431:     my $adv=0;
1.1172.2.91  raeburn  6432:     my $rar=0;
1.678     raeburn  6433:     my %grouproles = ();
                   6434:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6435:         my @groupkeys; 
1.1000    raeburn  6436:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6437:             push(@groupkeys,$role);
                   6438:         }
                   6439:         if (ref($groups_roles) eq 'HASH') {
                   6440:             foreach my $key (keys(%{$groups_roles})) {
                   6441:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6442:                     push(@groupkeys,$key);
                   6443:                 }
                   6444:             }
                   6445:         }
                   6446:         if (@groupkeys > 0) {
                   6447:             foreach my $role (@groupkeys) {
                   6448:                 my ($trole,$area,$sec,$extendedarea);
                   6449:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6450:                     $trole = $1;
                   6451:                     $area = $2;
                   6452:                     $sec = $3;
                   6453:                     $extendedarea = $area.$sec;
                   6454:                     if (exists($$allgroups{$area})) {
                   6455:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6456:                             my $spec = $trole.'.'.$extendedarea;
                   6457:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6458:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6459:                         }
1.678     raeburn  6460:                     }
                   6461:                 }
                   6462:             }
                   6463:         }
                   6464:     }
1.800     albertel 6465:     foreach my $group (keys(%grouproles)) {
                   6466:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6467:     }
1.800     albertel 6468:     foreach my $role (keys(%{$allroles})) {
                   6469:         my %thesepriv;
1.941     raeburn  6470:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6471:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6472:             if ($item ne '') {
                   6473:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6474:                 if ($restrictions eq '') {
                   6475:                     $thesepriv{$privilege}='F';
                   6476:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6477:                     $thesepriv{$privilege}.=$restrictions;
                   6478:                 }
                   6479:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6480:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6481:             }
                   6482:         }
                   6483:         my $thesestr='';
1.1104    raeburn  6484:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6485: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6486: 	}
                   6487:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6488:     }
1.1172.2.91  raeburn  6489:     return ($author,$adv,$rar);
1.567     raeburn  6490: }
                   6491: 
1.994     raeburn  6492: sub role_status {
1.1104    raeburn  6493:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6494:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6495:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6496:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6497:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6498:             $$where = '/'.$two;
1.994     raeburn  6499:             $$trolecode=$$role.'.'.$$where;
                   6500:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6501:             $$tstatus='is';
1.1104    raeburn  6502:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6503:                 $$tstatus='future';
1.1034    raeburn  6504:                 if ($$tstart<$now) {
                   6505:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6506:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6507:                             my (%allroles,%allgroups,$group_privs,
                   6508:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6509:                             my %userroles = (
                   6510:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6511:                             );
1.1064    raeburn  6512:                             @rolecodes = ('cm'); 
1.1002    raeburn  6513:                             my $spec=$$role.'.'.$$where;
                   6514:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6515:                             if ($$role =~ /^cr\//) {
                   6516:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6517:                                 push(@rolecodes,'cr');
1.1002    raeburn  6518:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6519:                                 push(@rolecodes,$$role);
1.1002    raeburn  6520:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6521:                                                     $env{'user.name'});
1.1064    raeburn  6522:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6523:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6524:                                 $group_privs = &unescape($group_privs);
                   6525:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6526:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104    raeburn  6527:                                 &get_groups_roles($tdomain,$trest,
                   6528:                                                   \%course_roles,\@rolecodes,
                   6529:                                                   \%groups_roles);
1.1002    raeburn  6530:                             } else {
1.1064    raeburn  6531:                                 push(@rolecodes,$$role);
1.1002    raeburn  6532:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6533:                             }
1.1172.2.91  raeburn  6534:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6535:                                                                    \%groups_roles);
1.1064    raeburn  6536:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6537:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6538:                         }
                   6539:                     }
1.1034    raeburn  6540:                     $$tstatus = 'is';
1.1002    raeburn  6541:                 }
1.994     raeburn  6542:             }
                   6543:             if ($$tend) {
1.1104    raeburn  6544:                 if ($$tend<$update) {
1.994     raeburn  6545:                     $$tstatus='expired';
                   6546:                 } elsif ($$tend<$now) {
                   6547:                     $$tstatus='will_not';
                   6548:                 }
                   6549:             }
                   6550:         }
                   6551:     }
                   6552: }
                   6553: 
1.1104    raeburn  6554: sub get_groups_roles {
                   6555:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6556:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6557:                   (ref($rolecodes) eq 'ARRAY') && 
                   6558:                   (ref($groups_roles) eq 'HASH')); 
                   6559:     if (keys(%{$cdom_courseroles}) > 0) {
                   6560:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6561:         if ($cdom ne '' && $cnum ne '') {
                   6562:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6563:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6564:                     my $crsrole = $1;
                   6565:                     my $crssec = $2;
                   6566:                     if ($crsrole =~ /^cr/) {
                   6567:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6568:                             push(@{$rolecodes},'cr');
                   6569:                         }
                   6570:                     } else {
                   6571:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6572:                             push(@{$rolecodes},$crsrole);
                   6573:                         }
                   6574:                     }
                   6575:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6576:                     if ($crssec ne '') {
                   6577:                         $rolekey .= "/$crssec";
                   6578:                     }
                   6579:                     $rolekey .= './';
                   6580:                     $groups_roles->{$rolekey} = $rolecodes;
                   6581:                 }
                   6582:             }
                   6583:         }
                   6584:     }
                   6585:     return;
                   6586: }
                   6587: 
                   6588: sub delete_env_groupprivs {
                   6589:     my ($where,$courseroles,$possroles) = @_;
                   6590:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6591:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6592:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6593:         %{$courseroles->{$udom}} =
                   6594:             &get_my_roles('','','userroles',['active'],
                   6595:                           $possroles,[$udom],1);
                   6596:     }
                   6597:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6598:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6599:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6600:             my $area = '/'.$cdom.'/'.$cnum;
                   6601:             my $privkey = "user.priv.$crsrole.$area";
                   6602:             if ($crssec ne '') {
                   6603:                 $privkey .= '/'.$crssec;
                   6604:             }
                   6605:             $privkey .= ".$area/$group";
                   6606:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6607:         }
                   6608:     }
                   6609:     return;
                   6610: }
                   6611: 
1.994     raeburn  6612: sub check_adhoc_privs {
1.1172.2.86  raeburn  6613:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6614:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6615:     if ($sec) {
                   6616:         $cckey .= '/'.$sec;
                   6617:     }
1.1172.2.9  raeburn  6618:     my $setprivs;
1.994     raeburn  6619:     if ($env{$cckey}) {
                   6620:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6621:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6622:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6623:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6624:             $setprivs = 1;
1.994     raeburn  6625:         }
                   6626:     } else {
1.1172.2.87  raeburn  6627:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6628:         $setprivs = 1;
1.994     raeburn  6629:     }
1.1172.2.9  raeburn  6630:     return $setprivs;
1.994     raeburn  6631: }
                   6632: 
                   6633: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6634: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6635:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6636:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6637:     if ($sec ne '') {
                   6638:         $area .= '/'.$sec;
                   6639:     }
1.994     raeburn  6640:     my $spec = $role.'.'.$area;
                   6641:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6642:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6643:     my %rolehash = ();
1.1172.2.89  raeburn  6644:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6645:         my $rolename = $1;
1.1172.2.84  raeburn  6646:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6647:         my %domdef = &get_domain_defaults($dcdom);
                   6648:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6649:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6650:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6651:             }
                   6652:         }
1.1172.2.84  raeburn  6653:     } else {
                   6654:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6655:     }
1.1172.2.91  raeburn  6656:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6657:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6658:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6659:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6660:         &appenv( {'request.role'        => $spec,
                   6661:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6662:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6663:                  }
                   6664:                );
                   6665:         my $tadv=0;
                   6666:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6667:         &appenv({'request.role.adv'    => $tadv});
                   6668:     }
1.994     raeburn  6669: }
                   6670: 
1.12      www      6671: # --------------------------------------------------------------- get interface
                   6672: 
                   6673: sub get {
1.131     albertel 6674:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6675:    my $items='';
1.800     albertel 6676:    foreach my $item (@$storearr) {
                   6677:        $items.=&escape($item).'&';
1.191     harris41 6678:    }
1.12      www      6679:    $items=~s/\&$//;
1.620     albertel 6680:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6681:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6682:    my $uhome=&homeserver($uname,$udomain);
                   6683: 
1.133     albertel 6684:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6685:    my @pairs=split(/\&/,$rep);
1.273     albertel 6686:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6687:      return @pairs;
                   6688:    }
1.15      www      6689:    my %returnhash=();
1.42      www      6690:    my $i=0;
1.800     albertel 6691:    foreach my $item (@$storearr) {
                   6692:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6693:       $i++;
1.191     harris41 6694:    }
1.15      www      6695:    return %returnhash;
1.27      www      6696: }
                   6697: 
                   6698: # --------------------------------------------------------------- del interface
                   6699: 
                   6700: sub del {
1.133     albertel 6701:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6702:    my $items='';
1.800     albertel 6703:    foreach my $item (@$storearr) {
                   6704:        $items.=&escape($item).'&';
1.191     harris41 6705:    }
1.984     neumanie 6706: 
1.27      www      6707:    $items=~s/\&$//;
1.620     albertel 6708:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6709:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6710:    my $uhome=&homeserver($uname,$udomain);
                   6711:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6712: }
                   6713: 
                   6714: # -------------------------------------------------------------- dump interface
                   6715: 
1.1172.2.22  raeburn  6716: sub unserialize {
                   6717:     my ($rep, $escapedkeys) = @_;
                   6718: 
                   6719:     return {} if $rep =~ /^error/;
                   6720: 
                   6721:     my %returnhash=();
                   6722:     foreach my $item (split(/\&/,$rep)) {
                   6723:         my ($key, $value) = split(/=/, $item, 2);
                   6724:         $key = unescape($key) unless $escapedkeys;
                   6725:         next if $key =~ /^error: 2 /;
                   6726:         $returnhash{$key} = &thaw_unescape($value);
                   6727:     }
                   6728:     return \%returnhash;
                   6729: }
                   6730: 
                   6731: # see Lond::dump_with_regexp
                   6732: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6733: sub dump {
1.1172.2.22  raeburn  6734:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6735:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6736:     if (!$uname) { $uname=$env{'user.name'}; }
                   6737:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6738: 
1.1172.2.55  raeburn  6739:     if ($regexp) {
                   6740:         $regexp=&escape($regexp);
                   6741:     } else {
                   6742:         $regexp='.';
                   6743:     }
1.1172.2.22  raeburn  6744:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6745:         # user is hosted on this machine
1.1172.2.55  raeburn  6746:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6747:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6748:         return %{&unserialize($reply, $escapedkeys)};
                   6749:     }
1.1166    raeburn  6750:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6751:     my @pairs=split(/\&/,$rep);
                   6752:     my %returnhash=();
1.1098    foxr     6753:     if (!($rep =~ /^error/ )) {
                   6754: 	foreach my $item (@pairs) {
                   6755: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6756:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6757: 	    next if ($key =~ /^error: 2 /);
                   6758: 	    $returnhash{$key}=&thaw_unescape($value);
                   6759: 	}
1.755     albertel 6760:     }
                   6761:     return %returnhash;
1.407     www      6762: }
                   6763: 
1.1098    foxr     6764: 
1.717     albertel 6765: # --------------------------------------------------------- dumpstore interface
                   6766: 
                   6767: sub dumpstore {
                   6768:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6769:    # same as dump but keys must be escaped. They may contain colon separated
                   6770:    # lists of values that may themself contain colons (e.g. symbs).
                   6771:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6772: }
                   6773: 
1.407     www      6774: # -------------------------------------------------------------- keys interface
                   6775: 
                   6776: sub getkeys {
                   6777:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6778:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6779:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6780:    my $uhome=&homeserver($uname,$udomain);
                   6781:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6782:    my @keyarray=();
1.800     albertel 6783:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6784:       next if ($key =~ /^error: 2 /);
1.800     albertel 6785:       push(@keyarray,&unescape($key));
1.407     www      6786:    }
                   6787:    return @keyarray;
1.318     matthew  6788: }
                   6789: 
1.319     matthew  6790: # --------------------------------------------------------------- currentdump
                   6791: sub currentdump {
1.328     matthew  6792:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6793:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6794:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6795:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6796:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6797:    my $rep;
                   6798: 
                   6799:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6800:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6801:                    $courseid)));
                   6802:    } else {
                   6803:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6804:    }
                   6805: 
1.318     matthew  6806:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6807:    #
1.318     matthew  6808:    my %returnhash=();
1.319     matthew  6809:    #
                   6810:    if ($rep eq "unknown_cmd") { 
                   6811:        # an old lond will not know currentdump
                   6812:        # Do a dump and make it look like a currentdump
1.822     albertel 6813:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6814:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6815:        my %hash = @tmp;
                   6816:        @tmp=();
1.424     matthew  6817:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6818:    } else {
                   6819:        my @pairs=split(/\&/,$rep);
1.800     albertel 6820:        foreach my $pair (@pairs) {
                   6821:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6822:            my ($symb,$param) = split(/:/,$key);
                   6823:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6824:                                                         &thaw_unescape($value);
1.319     matthew  6825:        }
1.191     harris41 6826:    }
1.12      www      6827:    return %returnhash;
1.424     matthew  6828: }
                   6829: 
                   6830: sub convert_dump_to_currentdump{
                   6831:     my %hash = %{shift()};
                   6832:     my %returnhash;
                   6833:     # Code ripped from lond, essentially.  The only difference
                   6834:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6835:     # we might run in to problems with parameter names =~ /^v\./
                   6836:     while (my ($key,$value) = each(%hash)) {
                   6837:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6838: 	$symb  = &unescape($symb);
                   6839: 	$param = &unescape($param);
1.424     matthew  6840:         next if ($v eq 'version' || $symb eq 'keys');
                   6841:         next if (exists($returnhash{$symb}) &&
                   6842:                  exists($returnhash{$symb}->{$param}) &&
                   6843:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6844:         $returnhash{$symb}->{$param}=$value;
                   6845:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6846:     }
                   6847:     #
                   6848:     # Remove all of the keys in the hashes which keep track of
                   6849:     # the version of the parameter.
                   6850:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6851:         # use a foreach because we are going to delete from the hash.
                   6852:         foreach my $key (keys(%$param_hash)) {
                   6853:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6854:         }
                   6855:     }
                   6856:     return \%returnhash;
1.12      www      6857: }
                   6858: 
1.627     albertel 6859: # ------------------------------------------------------ critical inc interface
                   6860: 
                   6861: sub cinc {
                   6862:     return &inc(@_,'critical');
                   6863: }
                   6864: 
1.449     matthew  6865: # --------------------------------------------------------------- inc interface
                   6866: 
                   6867: sub inc {
1.627     albertel 6868:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6869:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6870:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6871:     my $uhome=&homeserver($uname,$udomain);
                   6872:     my $items='';
                   6873:     if (! ref($store)) {
                   6874:         # got a single value, so use that instead
                   6875:         $items = &escape($store).'=&';
                   6876:     } elsif (ref($store) eq 'SCALAR') {
                   6877:         $items = &escape($$store).'=&';        
                   6878:     } elsif (ref($store) eq 'ARRAY') {
                   6879:         $items = join('=&',map {&escape($_);} @{$store});
                   6880:     } elsif (ref($store) eq 'HASH') {
                   6881:         while (my($key,$value) = each(%{$store})) {
                   6882:             $items.= &escape($key).'='.&escape($value).'&';
                   6883:         }
                   6884:     }
                   6885:     $items=~s/\&$//;
1.627     albertel 6886:     if ($critical) {
                   6887: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6888:     } else {
                   6889: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6890:     }
1.449     matthew  6891: }
                   6892: 
1.12      www      6893: # --------------------------------------------------------------- put interface
                   6894: 
                   6895: sub put {
1.134     albertel 6896:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6897:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6898:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6899:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6900:    my $items='';
1.800     albertel 6901:    foreach my $item (keys(%$storehash)) {
                   6902:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6903:    }
1.12      www      6904:    $items=~s/\&$//;
1.134     albertel 6905:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6906: }
                   6907: 
1.631     albertel 6908: # ------------------------------------------------------------ newput interface
                   6909: 
                   6910: sub newput {
                   6911:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6912:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6913:    if (!$uname) { $uname=$env{'user.name'}; }
                   6914:    my $uhome=&homeserver($uname,$udomain);
                   6915:    my $items='';
                   6916:    foreach my $key (keys(%$storehash)) {
                   6917:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6918:    }
                   6919:    $items=~s/\&$//;
                   6920:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6921: }
                   6922: 
                   6923: # ---------------------------------------------------------  putstore interface
                   6924: 
1.524     raeburn  6925: sub putstore {
1.1172.2.59  raeburn  6926:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6927:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6928:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6929:    my $uhome=&homeserver($uname,$udomain);
                   6930:    my $items='';
1.715     albertel 6931:    foreach my $key (keys(%$storehash)) {
                   6932:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6933:    }
1.715     albertel 6934:    $items=~s/\&$//;
1.716     albertel 6935:    my $esc_symb=&escape($symb);
                   6936:    my $esc_v=&escape($version);
1.715     albertel 6937:    my $reply =
1.716     albertel 6938:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6939: 	      $uhome);
1.1172.2.59  raeburn  6940:    if (($tolog) && ($reply eq 'ok')) {
                   6941:        my $namevalue='';
                   6942:        foreach my $key (keys(%{$storehash})) {
                   6943:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6944:        }
                   6945:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6946:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6947:                      '&version='.$esc_v.
                   6948:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6949:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6950:    }
1.715     albertel 6951:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6952:        # gfall back to way things use to be done
1.715     albertel 6953:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6954: 			    $uname);
1.524     raeburn  6955:    }
1.715     albertel 6956:    return $reply;
                   6957: }
                   6958: 
                   6959: sub old_putstore {
1.716     albertel 6960:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6961:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6962:     if (!$uname) { $uname=$env{'user.name'}; }
                   6963:     my $uhome=&homeserver($uname,$udomain);
                   6964:     my %newstorehash;
1.800     albertel 6965:     foreach my $item (keys(%$storehash)) {
                   6966: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6967: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6968:     }
                   6969:     my $items='';
                   6970:     my %allitems = ();
1.800     albertel 6971:     foreach my $item (keys(%newstorehash)) {
                   6972: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6973: 	    my $key = $1.':keys:'.$2;
                   6974: 	    $allitems{$key} .= $3.':';
                   6975: 	}
1.800     albertel 6976: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6977:     }
1.800     albertel 6978:     foreach my $item (keys(%allitems)) {
                   6979: 	$allitems{$item} =~ s/\:$//;
                   6980: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6981:     }
                   6982:     $items=~s/\&$//;
                   6983:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6984: }
                   6985: 
1.47      www      6986: # ------------------------------------------------------ critical put interface
                   6987: 
                   6988: sub cput {
1.134     albertel 6989:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6990:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6991:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6992:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6993:    my $items='';
1.800     albertel 6994:    foreach my $item (keys(%$storehash)) {
                   6995:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6996:    }
1.47      www      6997:    $items=~s/\&$//;
1.134     albertel 6998:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6999: }
                   7000: 
                   7001: # -------------------------------------------------------------- eget interface
                   7002: 
                   7003: sub eget {
1.133     albertel 7004:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7005:    my $items='';
1.800     albertel 7006:    foreach my $item (@$storearr) {
                   7007:        $items.=&escape($item).'&';
1.191     harris41 7008:    }
1.12      www      7009:    $items=~s/\&$//;
1.620     albertel 7010:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7011:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7012:    my $uhome=&homeserver($uname,$udomain);
                   7013:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7014:    my @pairs=split(/\&/,$rep);
                   7015:    my %returnhash=();
1.42      www      7016:    my $i=0;
1.800     albertel 7017:    foreach my $item (@$storearr) {
                   7018:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7019:       $i++;
1.191     harris41 7020:    }
1.12      www      7021:    return %returnhash;
                   7022: }
                   7023: 
1.667     albertel 7024: # ------------------------------------------------------------ tmpput interface
                   7025: sub tmpput {
1.802     raeburn  7026:     my ($storehash,$server,$context)=@_;
1.667     albertel 7027:     my $items='';
1.800     albertel 7028:     foreach my $item (keys(%$storehash)) {
                   7029: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7030:     }
                   7031:     $items=~s/\&$//;
1.802     raeburn  7032:     if (defined($context)) {
                   7033:         $items .= ':'.&escape($context);
                   7034:     }
1.667     albertel 7035:     return &reply("tmpput:$items",$server);
                   7036: }
                   7037: 
                   7038: # ------------------------------------------------------------ tmpget interface
                   7039: sub tmpget {
1.688     albertel 7040:     my ($token,$server)=@_;
                   7041:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7042:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7043:     my %returnhash;
1.1172.2.85  raeburn  7044:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7045:         return %returnhash;
                   7046:     }
1.667     albertel 7047:     foreach my $item (split(/\&/,$rep)) {
                   7048: 	my ($key,$value)=split(/=/,$item);
                   7049: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7050:     }
                   7051:     return %returnhash;
                   7052: }
                   7053: 
1.1113    raeburn  7054: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7055: sub tmpdel {
                   7056:     my ($token,$server)=@_;
                   7057:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7058:     return &reply("tmpdel:$token",$server);
                   7059: }
                   7060: 
1.1172.2.13  raeburn  7061: # ------------------------------------------------------------ get_timebased_id
                   7062: 
                   7063: sub get_timebased_id {
                   7064:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7065:         $maxtries) = @_;
                   7066:     my ($newid,$error,$dellock);
                   7067:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7068:         return ('','ok','invalid call to get suffix');
                   7069:     }
                   7070: 
                   7071: # set defaults for any optional args for which values were not supplied
                   7072:     if ($who eq '') {
                   7073:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7074:     }
                   7075:     if (!$locktries) {
                   7076:         $locktries = 3;
                   7077:     }
                   7078:     if (!$maxtries) {
                   7079:         $maxtries = 10;
                   7080:     }
                   7081: 
                   7082:     if (($cdom eq '') || ($cnum eq '')) {
                   7083:         if ($env{'request.course.id'}) {
                   7084:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7085:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7086:         }
                   7087:         if (($cdom eq '') || ($cnum eq '')) {
                   7088:             return ('','ok','call to get suffix not in course context');
                   7089:         }
                   7090:     }
                   7091: 
                   7092: # construct locking item
                   7093:     my $lockhash = {
                   7094:                       $prefix."\0".'locked_'.$keyid => $who,
                   7095:                    };
                   7096:     my $tries = 0;
                   7097: 
                   7098: # attempt to get lock on nohist_$namespace file
                   7099:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7100:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7101:         $tries ++;
                   7102:         sleep 1;
                   7103:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7104:     }
                   7105: 
                   7106: # attempt to get unique identifier, based on current timestamp
                   7107:     if ($gotlock eq 'ok') {
                   7108:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7109:         my $id = time;
                   7110:         $newid = $id;
1.1172.2.56  raeburn  7111:         if ($idtype eq 'addcode') {
                   7112:             $newid .= &sixnum_code();
                   7113:         }
1.1172.2.13  raeburn  7114:         my $idtries = 0;
                   7115:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7116:             if ($idtype eq 'concat') {
                   7117:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7118:             } elsif ($idtype eq 'addcode') {
                   7119:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7120:             } else {
                   7121:                 $newid ++;
                   7122:             }
                   7123:             $idtries ++;
                   7124:         }
                   7125:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7126:             my %new_item =  (
                   7127:                               $prefix."\0".$newid => $who,
                   7128:                             );
                   7129:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7130:                                                  $cdom,$cnum);
                   7131:             if ($putresult ne 'ok') {
                   7132:                 undef($newid);
                   7133:                 $error = 'error saving new item: '.$putresult;
                   7134:             }
                   7135:         } else {
1.1172.2.56  raeburn  7136:              undef($newid);
1.1172.2.13  raeburn  7137:              $error = ('error: no unique suffix available for the new item ');
                   7138:         }
                   7139: #  remove lock
                   7140:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7141:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7142:     } else {
                   7143:         $error = "error: could not obtain lockfile\n";
                   7144:         $dellock = 'ok';
1.1172.2.58  raeburn  7145:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7146:             $dellock = 'nolock';
                   7147:         }
1.1172.2.13  raeburn  7148:     }
                   7149:     return ($newid,$dellock,$error);
                   7150: }
                   7151: 
1.1172.2.56  raeburn  7152: sub sixnum_code {
                   7153:     my $code;
                   7154:     for (0..6) {
                   7155:         $code .= int( rand(9) );
                   7156:     }
                   7157:     return $code;
                   7158: }
                   7159: 
1.765     albertel 7160: # -------------------------------------------------- portfolio access checking
                   7161: 
                   7162: sub portfolio_access {
1.1172.2.77  raeburn  7163:     my ($requrl,$clientip) = @_;
1.765     albertel 7164:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7165:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7166:     if ($result) {
                   7167:         my %setters;
                   7168:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7169:             my ($startblock,$endblock) =
                   7170:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7171:             if ($startblock && $endblock) {
                   7172:                 return 'B';
                   7173:             }
                   7174:         } else {
                   7175:             my ($startblock,$endblock) =
                   7176:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7177:             if ($startblock && $endblock) {
                   7178:                 return 'B';
                   7179:             }
                   7180:         }
                   7181:     }
1.765     albertel 7182:     if ($result eq 'ok') {
1.766     albertel 7183:        return 'F';
1.765     albertel 7184:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7185:        return 'A';
1.765     albertel 7186:     }
1.766     albertel 7187:     return '';
1.765     albertel 7188: }
                   7189: 
                   7190: sub get_portfolio_access {
1.1172.2.77  raeburn  7191:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7192: 
                   7193:     if (!ref($access_hash)) {
                   7194: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7195: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7196: 						   $file_name);
                   7197: 	$access_hash = $access_controls{$file_name};
                   7198:     }
                   7199: 
1.1172.2.77  raeburn  7200:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7201:     my $now = time;
                   7202:     if (ref($access_hash) eq 'HASH') {
                   7203:         foreach my $key (keys(%{$access_hash})) {
                   7204:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7205:             if ($start > $now) {
                   7206:                 next;
                   7207:             }
                   7208:             if ($end && $end<$now) {
                   7209:                 next;
                   7210:             }
                   7211:             if ($scope eq 'public') {
                   7212:                 $public = $key;
                   7213:                 last;
                   7214:             } elsif ($scope eq 'guest') {
                   7215:                 $guest = $key;
                   7216:             } elsif ($scope eq 'domains') {
                   7217:                 push(@domains,$key);
                   7218:             } elsif ($scope eq 'users') {
                   7219:                 push(@users,$key);
                   7220:             } elsif ($scope eq 'course') {
                   7221:                 push(@courses,$key);
                   7222:             } elsif ($scope eq 'group') {
                   7223:                 push(@groups,$key);
1.1172.2.77  raeburn  7224:             } elsif ($scope eq 'ip') {
                   7225:                 push(@ips,$key);
1.765     albertel 7226:             }
                   7227:         }
                   7228:         if ($public) {
                   7229:             return 'ok';
1.1172.2.77  raeburn  7230:         } elsif (@ips > 0) {
                   7231:             my $allowed;
                   7232:             foreach my $ipkey (@ips) {
                   7233:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7234:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7235:                         $allowed = 1;
                   7236:                         last;
                   7237:                     }
                   7238:                 }
                   7239:             }
                   7240:             if ($allowed) {
                   7241:                 return 'ok';
                   7242:             }
1.765     albertel 7243:         }
                   7244:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7245:             if ($guest) {
                   7246:                 return $guest;
                   7247:             }
                   7248:         } else {
                   7249:             if (@domains > 0) {
                   7250:                 foreach my $domkey (@domains) {
                   7251:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7252:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7253:                             return 'ok';
                   7254:                         }
                   7255:                     }
                   7256:                 }
                   7257:             }
                   7258:             if (@users > 0) {
                   7259:                 foreach my $userkey (@users) {
1.865     raeburn  7260:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7261:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7262:                             if (ref($item) eq 'HASH') {
                   7263:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7264:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7265:                                     return 'ok';
                   7266:                                 }
                   7267:                             }
                   7268:                         }
                   7269:                     } 
1.765     albertel 7270:                 }
                   7271:             }
                   7272:             my %roleshash;
                   7273:             my @courses_and_groups = @courses;
                   7274:             push(@courses_and_groups,@groups); 
                   7275:             if (@courses_and_groups > 0) {
                   7276:                 my (%allgroups,%allroles); 
                   7277:                 my ($start,$end,$role,$sec,$group);
                   7278:                 foreach my $envkey (%env) {
1.1060    raeburn  7279:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7280:                         my $cid = $2.'_'.$3; 
                   7281:                         if ($1 eq 'gr') {
                   7282:                             $group = $4;
                   7283:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7284:                         } else {
                   7285:                             if ($4 eq '') {
                   7286:                                 $sec = 'none';
                   7287:                             } else {
                   7288:                                 $sec = $4;
                   7289:                             }
                   7290:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7291:                         }
1.811     albertel 7292:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7293:                         my $cid = $2.'_'.$3;
                   7294:                         if ($4 eq '') {
                   7295:                             $sec = 'none';
                   7296:                         } else {
                   7297:                             $sec = $4;
                   7298:                         }
                   7299:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7300:                     }
                   7301:                 }
                   7302:                 if (keys(%allroles) == 0) {
                   7303:                     return;
                   7304:                 }
                   7305:                 foreach my $key (@courses_and_groups) {
                   7306:                     my %content = %{$$access_hash{$key}};
                   7307:                     my $cnum = $content{'number'};
                   7308:                     my $cdom = $content{'domain'};
                   7309:                     my $cid = $cdom.'_'.$cnum;
                   7310:                     if (!exists($allroles{$cid})) {
                   7311:                         next;
                   7312:                     }    
                   7313:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7314:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7315:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7316:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7317:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7318:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7319:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7320:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7321:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7322:                                         if (grep/^all$/,@sections) {
                   7323:                                             return 'ok';
                   7324:                                         } else {
                   7325:                                             if (grep/^$sec$/,@sections) {
                   7326:                                                 return 'ok';
                   7327:                                             }
                   7328:                                         }
                   7329:                                     }
                   7330:                                 }
                   7331:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7332:                                     if (grep/^none$/,@groups) {
                   7333:                                         return 'ok';
                   7334:                                     }
                   7335:                                 } else {
                   7336:                                     if (grep/^all$/,@groups) {
                   7337:                                         return 'ok';
                   7338:                                     } 
                   7339:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7340:                                         if (grep/^$group$/,@groups) {
                   7341:                                             return 'ok';
                   7342:                                         }
                   7343:                                     }
                   7344:                                 } 
                   7345:                             }
                   7346:                         }
                   7347:                     }
                   7348:                 }
                   7349:             }
                   7350:             if ($guest) {
                   7351:                 return $guest;
                   7352:             }
                   7353:         }
                   7354:     }
                   7355:     return;
                   7356: }
                   7357: 
                   7358: sub course_group_datechecker {
                   7359:     my ($dates,$now,$status) = @_;
                   7360:     my ($start,$end) = split(/\./,$dates);
                   7361:     if (!$start && !$end) {
                   7362:         return 'ok';
                   7363:     }
                   7364:     if (grep/^active$/,@{$status}) {
                   7365:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7366:             return 'ok';
                   7367:         }
                   7368:     }
                   7369:     if (grep/^previous$/,@{$status}) {
                   7370:         if ($end > $now ) {
                   7371:             return 'ok';
                   7372:         }
                   7373:     }
                   7374:     if (grep/^future$/,@{$status}) {
                   7375:         if ($start > $now) {
                   7376:             return 'ok';
                   7377:         }
                   7378:     }
                   7379:     return; 
                   7380: }
                   7381: 
                   7382: sub parse_portfolio_url {
                   7383:     my ($url) = @_;
                   7384: 
                   7385:     my ($type,$udom,$unum,$group,$file_name);
                   7386:     
1.823     albertel 7387:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7388: 	$type = 1;
                   7389:         $udom = $1;
                   7390:         $unum = $2;
                   7391:         $file_name = $3;
1.823     albertel 7392:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7393: 	$type = 2;
                   7394:         $udom = $1;
                   7395:         $unum = $2;
                   7396:         $group = $3;
                   7397:         $file_name = $3.'/'.$4;
                   7398:     }
                   7399:     if (wantarray) {
                   7400: 	return ($type,$udom,$unum,$file_name,$group);
                   7401:     }
                   7402:     return $type;
                   7403: }
                   7404: 
                   7405: sub is_portfolio_url {
                   7406:     my ($url) = @_;
                   7407:     return scalar(&parse_portfolio_url($url));
                   7408: }
                   7409: 
1.798     raeburn  7410: sub is_portfolio_file {
                   7411:     my ($file) = @_;
1.820     raeburn  7412:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7413:         return 1;
                   7414:     }
                   7415:     return;
                   7416: }
                   7417: 
1.976     raeburn  7418: sub usertools_access {
1.1084    raeburn  7419:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7420:     my ($access,%tools);
                   7421:     if ($context eq '') {
                   7422:         $context = 'tools';
                   7423:     }
                   7424:     if ($context eq 'requestcourses') {
                   7425:         %tools = (
                   7426:                       official   => 1,
                   7427:                       unofficial => 1,
1.1006    raeburn  7428:                       community  => 1,
1.1172.2.37  raeburn  7429:                       textbook   => 1,
1.985     raeburn  7430:                  );
1.1172.2.9  raeburn  7431:     } elsif ($context eq 'requestauthor') {
                   7432:         %tools = (
                   7433:                       requestauthor => 1,
                   7434:                  );
1.985     raeburn  7435:     } else {
                   7436:         %tools = (
                   7437:                       aboutme   => 1,
                   7438:                       blog      => 1,
1.1172.2.6  raeburn  7439:                       webdav    => 1,
1.985     raeburn  7440:                       portfolio => 1,
                   7441:                  );
                   7442:     }
1.976     raeburn  7443:     return if (!defined($tools{$tool}));
                   7444: 
1.1172.2.35  raeburn  7445:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7446:         $udom = $env{'user.domain'};
                   7447:         $uname = $env{'user.name'};
                   7448:     }
                   7449: 
1.978     raeburn  7450:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7451:         if ($action ne 'reload') {
1.985     raeburn  7452:             if ($context eq 'requestcourses') {
                   7453:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7454:             } elsif ($context eq 'requestauthor') {
                   7455:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7456:             } else {
                   7457:                 return $env{'environment.availabletools.'.$tool};
                   7458:             }
                   7459:         }
1.976     raeburn  7460:     }
                   7461: 
1.1172.2.9  raeburn  7462:     my ($toolstatus,$inststatus,$envkey);
                   7463:     if ($context eq 'requestauthor') {
                   7464:         $envkey = $context;
                   7465:     } else {
                   7466:         $envkey = $context.'.'.$tool;
                   7467:     }
1.976     raeburn  7468: 
1.985     raeburn  7469:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7470:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7471:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7472:         $inststatus = $env{'environment.inststatus'};
                   7473:     } else {
1.1084    raeburn  7474:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7475:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7476:             $inststatus = $userenvref->{'inststatus'};
                   7477:         } else {
1.1172.2.9  raeburn  7478:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7479:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7480:             $inststatus = $userenv{'inststatus'};
                   7481:         }
1.976     raeburn  7482:     }
                   7483: 
                   7484:     if ($toolstatus ne '') {
                   7485:         if ($toolstatus) {
                   7486:             $access = 1;
                   7487:         } else {
                   7488:             $access = 0;
                   7489:         }
                   7490:         return $access;
                   7491:     }
                   7492: 
1.1084    raeburn  7493:     my ($is_adv,%domdef);
                   7494:     if (ref($is_advref) eq 'HASH') {
                   7495:         $is_adv = $is_advref->{'is_adv'};
                   7496:     } else {
                   7497:         $is_adv = &is_advanced_user($udom,$uname);
                   7498:     }
                   7499:     if (ref($domdefref) eq 'HASH') {
                   7500:         %domdef = %{$domdefref};
                   7501:     } else {
                   7502:         %domdef = &get_domain_defaults($udom);
                   7503:     }
1.976     raeburn  7504:     if (ref($domdef{$tool}) eq 'HASH') {
                   7505:         if ($is_adv) {
                   7506:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7507:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7508:                     $access = 1;
                   7509:                 } else {
                   7510:                     $access = 0;
                   7511:                 }
                   7512:                 return $access;
                   7513:             }
                   7514:         }
                   7515:         if ($inststatus ne '') {
                   7516:             my ($hasaccess,$hasnoaccess);
                   7517:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7518:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7519:                     if ($domdef{$tool}{$affiliation}) {
                   7520:                         $hasaccess = 1;
                   7521:                     } else {
                   7522:                         $hasnoaccess = 1;
                   7523:                     }
                   7524:                 }
                   7525:             }
                   7526:             if ($hasaccess || $hasnoaccess) {
                   7527:                 if ($hasaccess) {
                   7528:                     $access = 1;
                   7529:                 } elsif ($hasnoaccess) {
                   7530:                     $access = 0; 
                   7531:                 }
                   7532:                 return $access;
                   7533:             }
                   7534:         } else {
                   7535:             if ($domdef{$tool}{'default'} ne '') {
                   7536:                 if ($domdef{$tool}{'default'}) {
                   7537:                     $access = 1;
                   7538:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7539:                     $access = 0;
                   7540:                 }
                   7541:                 return $access;
                   7542:             }
                   7543:         }
                   7544:     } else {
1.1172.2.6  raeburn  7545:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7546:             $access = 1;
                   7547:         } else {
                   7548:             $access = 0;
                   7549:         }
1.976     raeburn  7550:         return $access;
                   7551:     }
                   7552: }
                   7553: 
1.1050    raeburn  7554: sub is_course_owner {
                   7555:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7556:     if (($udom eq '') || ($uname eq '')) {
                   7557:         $udom = $env{'user.domain'};
                   7558:         $uname = $env{'user.name'};
                   7559:     }
                   7560:     unless (($udom eq '') || ($uname eq '')) {
                   7561:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7562:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7563:                 return 1;
                   7564:             } else {
                   7565:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7566:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7567:                     return 1;
                   7568:                 }
                   7569:             }
                   7570:         }
                   7571:     }
                   7572:     return;
                   7573: }
                   7574: 
1.976     raeburn  7575: sub is_advanced_user {
                   7576:     my ($udom,$uname) = @_;
1.1085    raeburn  7577:     if ($udom ne '' && $uname ne '') {
                   7578:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7579:             if (wantarray) {
                   7580:                 return ($env{'user.adv'},$env{'user.author'});
                   7581:             } else {
                   7582:                 return $env{'user.adv'};
                   7583:             }
1.1085    raeburn  7584:         }
                   7585:     }
1.976     raeburn  7586:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7587:     my %allroles;
1.1128    raeburn  7588:     my ($is_adv,$is_author);
1.976     raeburn  7589:     foreach my $role (keys(%roleshash)) {
                   7590:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7591:         my $area = '/'.$tdomain.'/'.$trest;
                   7592:         if ($sec ne '') {
                   7593:             $area .= '/'.$sec;
                   7594:         }
                   7595:         if (($area ne '') && ($trole ne '')) {
                   7596:             my $spec=$trole.'.'.$area;
                   7597:             if ($trole =~ /^cr\//) {
                   7598:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7599:             } elsif ($trole ne 'gr') {
                   7600:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7601:             }
1.1128    raeburn  7602:             if ($trole eq 'au') {
                   7603:                 $is_author = 1;
                   7604:             }
1.976     raeburn  7605:         }
                   7606:     }
                   7607:     foreach my $role (keys(%allroles)) {
                   7608:         last if ($is_adv);
                   7609:         foreach my $item (split(/:/,$allroles{$role})) {
                   7610:             if ($item ne '') {
                   7611:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7612:                 if ($privilege eq 'adv') {
                   7613:                     $is_adv = 1;
                   7614:                     last;
                   7615:                 }
                   7616:             }
                   7617:         }
                   7618:     }
1.1128    raeburn  7619:     if (wantarray) {
                   7620:         return ($is_adv,$is_author);
                   7621:     }
1.976     raeburn  7622:     return $is_adv;
                   7623: }
1.798     raeburn  7624: 
1.1035    raeburn  7625: sub check_can_request {
1.1036    raeburn  7626:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7627:     my $canreq = 0;
                   7628:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7629:     my @options = ('approval','validate','autolimit');
                   7630:     my $optregex = join('|',@options);
                   7631:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7632:         foreach my $type (@{$types}) {
                   7633:             if (&usertools_access($env{'user.name'},
                   7634:                                   $env{'user.domain'},
                   7635:                                   $type,undef,'requestcourses')) {
                   7636:                 $canreq ++;
1.1036    raeburn  7637:                 if (ref($request_domains) eq 'HASH') {
                   7638:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7639:                 }
1.1035    raeburn  7640:                 if ($dom eq $env{'user.domain'}) {
                   7641:                     $can_request->{$type} = 1;
                   7642:                 }
                   7643:             }
                   7644:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7645:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7646:                 if (@curr > 0) {
1.1036    raeburn  7647:                     foreach my $item (@curr) {
                   7648:                         if (ref($request_domains) eq 'HASH') {
                   7649:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7650:                             if ($otherdom ne '') {
                   7651:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7652:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7653:                                         push(@{$request_domains->{$type}},$otherdom);
                   7654:                                     }
                   7655:                                 } else {
                   7656:                                     push(@{$request_domains->{$type}},$otherdom);
                   7657:                                 }
                   7658:                             }
                   7659:                         }
                   7660:                     }
                   7661:                     unless($dom eq $env{'user.domain'}) {
                   7662:                         $canreq ++;
1.1035    raeburn  7663:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7664:                             $can_request->{$type} = 1;
                   7665:                         }
                   7666:                     }
                   7667:                 }
                   7668:             }
                   7669:         }
                   7670:     }
                   7671:     return $canreq;
                   7672: }
                   7673: 
1.341     www      7674: # ---------------------------------------------- Custom access rule evaluation
                   7675: 
                   7676: sub customaccess {
                   7677:     my ($priv,$uri)=@_;
1.807     albertel 7678:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7679:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7680:     $udom = &LONCAPA::clean_domain($udom);
                   7681:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7682:     my $access=0;
1.800     albertel 7683:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7684: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7685: 	if ($type eq 'user') {
                   7686: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7687: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7688: 		if ($tdom) {
                   7689: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7690: 		}
1.896     albertel 7691: 		if ($tuname) {
                   7692: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7693: 		}
                   7694: 		$access=($effect eq 'allow');
                   7695: 		last;
                   7696: 	    }
                   7697: 	} else {
                   7698: 	    if ($role) {
                   7699: 		if ($role ne $urole) { next; }
                   7700: 	    }
                   7701: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7702: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7703: 		if ($tdom) {
                   7704: 		    if ($tdom ne $udom) { next; }
                   7705: 		}
                   7706: 		if ($tcrs) {
                   7707: 		    if ($tcrs ne $ucrs) { next; }
                   7708: 		}
                   7709: 		if ($tsec) {
                   7710: 		    if ($tsec ne $usec) { next; }
                   7711: 		}
                   7712: 		$access=($effect eq 'allow');
                   7713: 		last;
                   7714: 	    }
                   7715: 	    if ($realm eq '' && $role eq '') {
                   7716: 		$access=($effect eq 'allow');
                   7717: 	    }
1.402     bowersj2 7718: 	}
1.341     www      7719:     }
                   7720:     return $access;
                   7721: }
                   7722: 
1.103     harris41 7723: # ------------------------------------------------- Check for a user privilege
1.12      www      7724: 
                   7725: sub allowed {
1.1172.2.65  raeburn  7726:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7727:     my $ver_orguri=$uri;
1.439     www      7728:     $uri=&deversion($uri);
1.152     www      7729:     my $orguri=$uri;
1.52      www      7730:     $uri=&declutter($uri);
1.809     raeburn  7731: 
1.810     raeburn  7732:     if ($priv eq 'evb') {
                   7733: # Evade communication block restrictions for specified role in a course
                   7734:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7735:             return $1;
                   7736:         } else {
                   7737:             return;
                   7738:         }
                   7739:     }
                   7740: 
1.620     albertel 7741:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7742: # Free bre access to adm and meta resources
1.775     albertel 7743:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7744: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7745: 	&& ($priv eq 'bre')) {
1.14      www      7746: 	return 'F';
1.159     www      7747:     }
                   7748: 
1.545     banghart 7749: # Free bre access to user's own portfolio contents
1.714     raeburn  7750:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7751:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7752: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7753:         my %setters;
                   7754:         my ($startblock,$endblock) = 
                   7755:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7756:         if ($startblock && $endblock) {
                   7757:             return 'B';
                   7758:         } else {
                   7759:             return 'F';
                   7760:         }
1.545     banghart 7761:     }
                   7762: 
1.762     raeburn  7763: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7764:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7765:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7766:         if (exists($env{'request.course.id'})) {
                   7767:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7768:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7769:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7770:                 my $courseprivid=$env{'request.course.id'};
                   7771:                 $courseprivid=~s/\_/\//;
                   7772:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7773:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7774:                     return $1; 
1.762     raeburn  7775:                 } else {
                   7776:                     if ($env{'request.course.sec'}) {
                   7777:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7778:                     }
                   7779:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7780:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7781:                         return $2;
                   7782:                     }
1.714     raeburn  7783:                 }
                   7784:             }
                   7785:         }
                   7786:     }
                   7787: 
1.159     www      7788: # Free bre to public access
                   7789: 
                   7790:     if ($priv eq 'bre') {
1.238     www      7791:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7792: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7793:            return 'F'; 
                   7794:         }
1.238     www      7795:         if ($copyright eq 'priv') {
                   7796:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7797: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7798: 		return '';
                   7799:             }
                   7800:         }
                   7801:         if ($copyright eq 'domain') {
                   7802:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7803: 	    unless (($env{'user.domain'} eq $1) ||
                   7804:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7805: 		return '';
                   7806:             }
1.262     matthew  7807:         }
1.620     albertel 7808:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7809:             # Library role, so allow browsing of resources in this domain.
                   7810:             return 'F';
1.238     www      7811:         }
1.341     www      7812:         if ($copyright eq 'custom') {
                   7813: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7814:         }
1.14      www      7815:     }
1.264     matthew  7816:     # Domain coordinator is trying to create a course
1.620     albertel 7817:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7818:         # uri is the requested domain in this case.
                   7819:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7820:         # a role of dc for the domain in question.
1.620     albertel 7821:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7822:     }
1.29      www      7823: 
1.52      www      7824:     my $thisallowed='';
                   7825:     my $statecond=0;
                   7826:     my $courseprivid='';
                   7827: 
1.1039    raeburn  7828:     my $ownaccess;
1.1043    raeburn  7829:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7830:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7831:         if ($uri eq '') {
                   7832:             $ownaccess = 1;
                   7833:         } else {
                   7834:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7835:                 my $udom = $env{'user.domain'};
                   7836:                 my $uname = $env{'user.name'};
                   7837:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7838:                     $ownaccess = 1;
1.1040    raeburn  7839:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7840:                     unless ($uri =~ m{\.\./}) {
                   7841:                         $ownaccess = 1;
                   7842:                     }
                   7843:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7844:                     my $now = time;
                   7845:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7846:                         my $adom = $1;
                   7847:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7848:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7849:                                 my ($start,$end) = split('.',$env{$key});
                   7850:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7851:                                     $ownaccess = 1;
                   7852:                                     last;
                   7853:                                 }
                   7854:                             }
                   7855:                         }
                   7856:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7857:                         my $adom = $1;
                   7858:                         my $aname = $2;
1.1042    raeburn  7859:                         foreach my $role ('ca','aa') { 
                   7860:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7861:                                 my ($start,$end) =
                   7862:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7863:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7864:                                     $ownaccess = 1;
                   7865:                                     last;
                   7866:                                 }
1.1039    raeburn  7867:                             }
                   7868:                         }
                   7869:                     }
                   7870:                 }
                   7871:             }
                   7872:         }
                   7873:     }
                   7874: 
1.52      www      7875: # Course
                   7876: 
1.620     albertel 7877:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7878:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7879:             $thisallowed.=$1;
                   7880:         }
1.52      www      7881:     }
1.29      www      7882: 
1.52      www      7883: # Domain
                   7884: 
1.620     albertel 7885:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7886:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7887:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7888:             $thisallowed.=$1;
                   7889:         }
1.12      www      7890:     }
1.52      www      7891: 
1.1141    raeburn  7892: # User who is not author or co-author might still be able to edit
                   7893: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7894:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7895:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7896:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7897:             $thisallowed.=$1;
                   7898:         }
                   7899:     }
                   7900: 
1.52      www      7901: # Course: uri itself is a course
1.66      www      7902:     my $courseuri=$uri;
                   7903:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7904:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7905: 
1.620     albertel 7906:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7907:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  7908:         if ($priv eq 'mip') {
                   7909:             my $rem = $1;
                   7910:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   7911:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   7912:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7913:                 if ($cdom ne '') {
                   7914:                     my %passwdconf = &get_passwdconf($cdom);
                   7915:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   7916:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   7917:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   7918:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   7919:                                 unless (@inststatuses) {
                   7920:                                     @inststatuses = ('default');
                   7921:                                 }
                   7922:                                 foreach my $status (@inststatuses) {
                   7923:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   7924:                                         $thisallowed.=$rem;
                   7925:                                     }
                   7926:                                 }
                   7927:                             }
                   7928:                         }
                   7929:                     }
                   7930:                 }
                   7931:             }
                   7932:         } else {
                   7933:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   7934:                 $thisallowed.=$1;
                   7935:             }
1.1039    raeburn  7936:         }
1.12      www      7937:     }
1.29      www      7938: 
1.665     albertel 7939: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7940: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7941:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7942: 	$thisallowed='';
1.671     raeburn  7943:         my ($match)=&is_on_map($uri);
                   7944:         if ($match) {
                   7945:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7946:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7947:                 my $value = $1;
                   7948:                 if ($noblockcheck) {
                   7949:                     $thisallowed.=$value;
1.1162    raeburn  7950:                 } else {
1.1172.2.65  raeburn  7951:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7952:                     if (@blockers > 0) {
                   7953:                         $thisallowed = 'B';
                   7954:                     } else {
                   7955:                         $thisallowed.=$value;
                   7956:                     }
1.1162    raeburn  7957:                 }
1.671     raeburn  7958:             }
                   7959:         } else {
1.705     albertel 7960:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7961:             if ($refuri) {
                   7962:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7963:                     $thisallowed='F';
1.671     raeburn  7964:                 } else {
                   7965:                     $refuri=&declutter($refuri);
                   7966:                     my ($match) = &is_on_map($refuri);
                   7967:                     if ($match) {
1.1172.2.65  raeburn  7968:                         if ($noblockcheck) {
1.1162    raeburn  7969:                             $thisallowed='F';
1.1172.2.65  raeburn  7970:                         } else {
                   7971:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7972:                             if (@blockers > 0) {
                   7973:                                 $thisallowed = 'B';
                   7974:                             } else {
                   7975:                                 $thisallowed='F';
                   7976:                             }
1.1162    raeburn  7977:                         }
1.671     raeburn  7978:                     }
1.669     raeburn  7979:                 }
1.671     raeburn  7980:             }
                   7981:         }
1.314     www      7982:     }
1.492     albertel 7983: 
1.766     albertel 7984:     if ($priv eq 'bre'
                   7985: 	&& $thisallowed ne 'F' 
                   7986: 	&& $thisallowed ne '2'
                   7987: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7988: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7989:     }
                   7990:     
1.52      www      7991: # Full access at system, domain or course-wide level? Exit.
1.29      www      7992:     if ($thisallowed=~/F/) {
                   7993: 	return 'F';
                   7994:     }
                   7995: 
1.52      www      7996: # If this is generating or modifying users, exit with special codes
1.29      www      7997: 
1.643     www      7998:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7999: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8000: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8001: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8002: 	    unless ($auname) { return $thisallowed; }
                   8003: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8004: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8005: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8006: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8007: 	}
1.52      www      8008: 	return $thisallowed;
                   8009:     }
                   8010: #
1.103     harris41 8011: # Gathered so far: system, domain and course wide privileges
1.52      www      8012: #
                   8013: # Course: See if uri or referer is an individual resource that is part of 
                   8014: # the course
                   8015: 
1.620     albertel 8016:     if ($env{'request.course.id'}) {
1.232     www      8017: 
1.1172.2.115  raeburn  8018: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8019: 
                   8020:         if ($priv eq 'mip') {
                   8021:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8022:                 return $thisallowed;
                   8023:             } else {
                   8024:                 return '';
                   8025:             }
                   8026:         }
                   8027: 
1.620     albertel 8028:        $courseprivid=$env{'request.course.id'};
                   8029:        if ($env{'request.course.sec'}) {
                   8030:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8031:        }
                   8032:        $courseprivid=~s/\_/\//;
                   8033:        my $checkreferer=1;
1.232     www      8034:        my ($match,$cond)=&is_on_map($uri);
                   8035:        if ($match) {
                   8036:            $statecond=$cond;
1.620     albertel 8037:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8038:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8039:                my $value = $1;
                   8040:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8041:                    if ($noblockcheck) {
1.1162    raeburn  8042:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8043:                    } else {
                   8044:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8045:                        if (@blockers > 0) {
                   8046:                            $thisallowed = 'B';
                   8047:                        } else {
                   8048:                            $thisallowed.=$value;
                   8049:                        }
1.1162    raeburn  8050:                    }
                   8051:                } else {
                   8052:                    $thisallowed.=$value;
                   8053:                }
1.52      www      8054:                $checkreferer=0;
                   8055:            }
1.29      www      8056:        }
1.83      www      8057:        
1.148     www      8058:        if ($checkreferer) {
1.620     albertel 8059: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8060:             unless ($refuri) {
1.800     albertel 8061:                 foreach my $key (keys(%env)) {
                   8062: 		    if ($key=~/^httpref\..*\*/) {
                   8063: 			my $pattern=$key;
1.156     www      8064:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8065:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8066:                         $pattern=~s/\//\\\//g;
1.152     www      8067:                         if ($orguri=~/$pattern/) {
1.800     albertel 8068: 			    $refuri=$env{$key};
1.148     www      8069:                         }
                   8070:                     }
1.191     harris41 8071:                 }
1.148     www      8072:             }
1.232     www      8073: 
1.148     www      8074:          if ($refuri) { 
1.152     www      8075: 	  $refuri=&declutter($refuri);
1.232     www      8076:           my ($match,$cond)=&is_on_map($refuri);
                   8077:             if ($match) {
                   8078:               my $refstatecond=$cond;
1.620     albertel 8079:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8080:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8081:                   my $value = $1;
                   8082:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8083:                       if ($noblockcheck) {
1.1162    raeburn  8084:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8085:                       } else {
                   8086:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8087:                           if (@blockers > 0) {
                   8088:                               $thisallowed = 'B';
                   8089:                           } else {
                   8090:                               $thisallowed.=$value;
                   8091:                           }
1.1162    raeburn  8092:                       }
                   8093:                   } else {
                   8094:                       $thisallowed.=$value;
                   8095:                   }
1.53      www      8096:                   $uri=$refuri;
                   8097:                   $statecond=$refstatecond;
1.52      www      8098:               }
                   8099:           }
1.148     www      8100:         }
1.29      www      8101:        }
1.52      www      8102:    }
1.29      www      8103: 
1.52      www      8104: #
1.103     harris41 8105: # Gathered now: all privileges that could apply, and condition number
1.52      www      8106: # 
                   8107: #
                   8108: # Full or no access?
                   8109: #
1.29      www      8110: 
1.52      www      8111:     if ($thisallowed=~/F/) {
                   8112: 	return 'F';
                   8113:     }
1.29      www      8114: 
1.52      www      8115:     unless ($thisallowed) {
                   8116:         return '';
                   8117:     }
1.29      www      8118: 
1.52      www      8119: # Restrictions exist, deal with them
                   8120: #
                   8121: #   C:according to course preferences
                   8122: #   R:according to resource settings
                   8123: #   L:unless locked
                   8124: #   X:according to user session state
                   8125: #
                   8126: 
                   8127: # Possibly locked functionality, check all courses
1.54      www      8128: # Locks might take effect only after 10 minutes cache expiration for other
                   8129: # courses, and 2 minutes for current course
1.52      www      8130: 
                   8131:     my $envkey;
                   8132:     if ($thisallowed=~/L/) {
1.1000    raeburn  8133:         foreach $envkey (keys(%env)) {
1.54      www      8134:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8135:                my $courseid=$2;
                   8136:                my $roleid=$1.'.'.$2;
1.92      www      8137:                $courseid=~s/^\///;
1.54      www      8138:                my $expiretime=600;
1.620     albertel 8139:                if ($env{'request.role'} eq $roleid) {
1.54      www      8140: 		  $expiretime=120;
                   8141:                }
                   8142: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8143:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8144:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8145: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8146:                }
1.620     albertel 8147:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8148:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8149: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8150:                        &log($env{'user.domain'},$env{'user.name'},
                   8151:                             $env{'user.home'},
1.57      www      8152:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8153:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8154:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8155: 		       return '';
                   8156:                    }
                   8157:                }
1.620     albertel 8158:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8159:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8160: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8161:                        &log($env{'user.domain'},$env{'user.name'},
                   8162:                             $env{'user.home'},
1.57      www      8163:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8164:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8165:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8166: 		       return '';
                   8167:                    }
                   8168:                }
                   8169: 	   }
1.29      www      8170:        }
1.52      www      8171:     }
                   8172:    
                   8173: #
                   8174: # Rest of the restrictions depend on selected course
                   8175: #
                   8176: 
1.620     albertel 8177:     unless ($env{'request.course.id'}) {
1.766     albertel 8178: 	if ($thisallowed eq 'A') {
                   8179: 	    return 'A';
1.814     raeburn  8180:         } elsif ($thisallowed eq 'B') {
                   8181:             return 'B';
1.766     albertel 8182: 	} else {
                   8183: 	    return '1';
                   8184: 	}
1.52      www      8185:     }
1.29      www      8186: 
1.52      www      8187: #
                   8188: # Now user is definitely in a course
                   8189: #
1.53      www      8190: 
                   8191: 
                   8192: # Course preferences
                   8193: 
                   8194:    if ($thisallowed=~/C/) {
1.620     albertel 8195:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8196:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8197:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8198: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8199: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8200: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8201: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8202: 			$env{'request.course.id'});
                   8203: 	   }
1.237     www      8204:            return '';
                   8205:        }
                   8206: 
1.620     albertel 8207:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8208: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8209: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8210: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8211: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8212: 			$env{'request.course.id'});
                   8213: 	   }
1.54      www      8214:            return '';
                   8215:        }
1.53      www      8216:    }
                   8217: 
                   8218: # Resource preferences
                   8219: 
                   8220:    if ($thisallowed=~/R/) {
1.620     albertel 8221:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8222:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8223: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8224: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8225: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8226: 	   }
                   8227: 	   return '';
1.54      www      8228:        }
1.53      www      8229:    }
1.30      www      8230: 
1.246     www      8231: # Restricted by state or randomout?
1.30      www      8232: 
1.52      www      8233:    if ($thisallowed=~/X/) {
1.620     albertel 8234:       if ($env{'acc.randomout'}) {
1.579     albertel 8235: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8236:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8237:             return ''; 
                   8238:          }
1.247     www      8239:       }
                   8240:       if (&condval($statecond)) {
1.52      www      8241: 	 return '2';
                   8242:       } else {
                   8243:          return '';
                   8244:       }
                   8245:    }
1.30      www      8246: 
1.766     albertel 8247:     if ($thisallowed eq 'A') {
                   8248: 	return 'A';
1.814     raeburn  8249:     } elsif ($thisallowed eq 'B') {
                   8250:         return 'B';
1.766     albertel 8251:     }
1.52      www      8252:    return 'F';
1.232     www      8253: }
1.1162    raeburn  8254: 
1.1172.2.13  raeburn  8255: # ------------------------------------------- Check construction space access
                   8256: 
                   8257: sub constructaccess {
                   8258:     my ($url,$setpriv)=@_;
                   8259: 
                   8260: # We do not allow editing of previous versions of files
                   8261:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8262: 
                   8263: # Get username and domain from URL
                   8264:     my ($ownername,$ownerdomain,$ownerhome);
                   8265: 
                   8266:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8267:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8268: 
                   8269: # The URL does not really point to any authorspace, forget it
                   8270:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8271: 
                   8272: # Now we need to see if the user has access to the authorspace of
                   8273: # $ownername at $ownerdomain
                   8274: 
                   8275:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8276: # Real author for this?
                   8277:        $ownerhome = $env{'user.home'};
                   8278:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8279:           return ($ownername,$ownerdomain,$ownerhome);
                   8280:        }
                   8281:     } else {
                   8282: # Co-author for this?
                   8283:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8284:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8285:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8286:             return ($ownername,$ownerdomain,$ownerhome);
                   8287:         }
                   8288:     }
                   8289: 
                   8290: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8291: # we might as well leave
                   8292:    unless ($setpriv) { return ''; }
                   8293: 
                   8294: # Backdoor access?
                   8295:     my $allowed=&allowed('eco',$ownerdomain);
                   8296: # Nope
                   8297:     unless ($allowed) { return ''; }
                   8298: # Looks like we may have access, but could be locked by the owner of the construction space
                   8299:     if ($allowed eq 'U') {
                   8300:         my %blocked=&get('environment',['domcoord.author'],
                   8301:                          $ownerdomain,$ownername);
                   8302: # Is blocked by owner
                   8303:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8304:     }
                   8305:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8306: # Grant temporary access
                   8307:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8308:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8309:         if (!$update) { $update = $then; }
                   8310:         my $refresh=$env{'user.refresh.time'};
                   8311:         if (!$refresh) { $refresh = $update; }
                   8312:         my $now = time;
                   8313:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8314:                            $now,'ca','constructaccess');
                   8315:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8316:         return($ownername,$ownerdomain,$ownerhome);
                   8317:     }
                   8318: # No business here
                   8319:     return '';
                   8320: }
                   8321: 
1.1172.2.66  raeburn  8322: # ----------------------------------------------------------- Content Blocking
                   8323: 
                   8324: {
                   8325: # Caches for faster Course Contents display where content blocking
                   8326: # is in operation (i.e., interval param set) for timed quiz.
                   8327: #
                   8328: # User for whom data are being temporarily cached.
                   8329: my $cacheduser='';
                   8330: # Cached blockers for this user (a hash of blocking items).
                   8331: my %cachedblockers=();
                   8332: # When the data were last cached.
                   8333: my $cachedlast='';
                   8334: 
                   8335: sub load_all_blockers {
                   8336:     my ($uname,$udom,$blocks)=@_;
                   8337:     if (($uname ne '') && ($udom ne '')) {
                   8338:         if (($cacheduser eq $uname.':'.$udom) &&
                   8339:             (abs($cachedlast-time)<5)) {
                   8340:             return;
                   8341:         }
                   8342:     }
                   8343:     $cachedlast=time;
                   8344:     $cacheduser=$uname.':'.$udom;
                   8345:     %cachedblockers = &get_commblock_resources($blocks);
                   8346: }
                   8347: 
1.1162    raeburn  8348: sub get_comm_blocks {
                   8349:     my ($cdom,$cnum) = @_;
                   8350:     if ($cdom eq '' || $cnum eq '') {
                   8351:         return unless ($env{'request.course.id'});
                   8352:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8353:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8354:     }
                   8355:     my %commblocks;
                   8356:     my $hashid=$cdom.'_'.$cnum;
                   8357:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8358:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8359:         %commblocks = %{$blocksref};
                   8360:     } else {
                   8361:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8362:         my $cachetime = 600;
                   8363:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8364:     }
                   8365:     return %commblocks;
                   8366: }
                   8367: 
1.1172.2.66  raeburn  8368: sub get_commblock_resources {
                   8369:     my ($blocks) = @_;
                   8370:     my %blockers = ();
                   8371:     return %blockers unless ($env{'request.course.id'});
                   8372:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8373:     my %commblocks;
                   8374:     if (ref($blocks) eq 'HASH') {
                   8375:         %commblocks = %{$blocks};
                   8376:     } else {
                   8377:         %commblocks = &get_comm_blocks();
                   8378:     }
1.1172.2.66  raeburn  8379:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8380:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8381:     return %blockers unless (ref($navmap));
                   8382:     my $now = time;
1.1162    raeburn  8383:     foreach my $block (keys(%commblocks)) {
                   8384:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8385:             my ($start,$end) = ($1,$2);
                   8386:             if ($start <= $now && $end >= $now) {
                   8387:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8388:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8389:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8390:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8391:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8392:                             }
                   8393:                         }
                   8394:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8395:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8396:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8397:                             }
                   8398:                         }
                   8399:                     }
                   8400:                 }
                   8401:             }
                   8402:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8403:             my $item = $1;
1.1163    raeburn  8404:             my @to_test;
1.1162    raeburn  8405:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8406:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8407:                     my @interval;
                   8408:                     my $type = 'map';
                   8409:                     if ($item eq 'course') {
                   8410:                         $type = 'course';
                   8411:                         @interval=&EXT("resource.0.interval");
                   8412:                     } else {
                   8413:                         if ($item =~ /___\d+___/) {
                   8414:                             $type = 'resource';
                   8415:                             @interval=&EXT("resource.0.interval",$item);
                   8416:                             if (ref($navmap)) {
                   8417:                                 my $res = $navmap->getBySymb($item);
                   8418:                                 push(@to_test,$res);
                   8419:                             }
1.1162    raeburn  8420:                         } else {
1.1172.2.66  raeburn  8421:                             my $mapsymb = &symbread($item,1);
                   8422:                             if ($mapsymb) {
                   8423:                                 if (ref($navmap)) {
                   8424:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8425:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8426:                                     foreach my $res (@to_test) {
                   8427:                                         my $symb = $res->symb();
                   8428:                                         next if ($symb eq $mapsymb);
                   8429:                                         if ($symb ne '') {
                   8430:                                             @interval=&EXT("resource.0.interval",$symb);
                   8431:                                             if ($interval[1] eq 'map') {
                   8432:                                                 last;
1.1162    raeburn  8433:                                             }
                   8434:                                         }
                   8435:                                     }
                   8436:                                 }
                   8437:                             }
                   8438:                         }
1.1172.2.66  raeburn  8439:                     }
                   8440:                     if ($interval[0] =~ /^\d+$/) {
                   8441:                         my $first_access;
                   8442:                         if ($type eq 'resource') {
                   8443:                             $first_access=&get_first_access($interval[1],$item);
                   8444:                         } elsif ($type eq 'map') {
                   8445:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8446:                         } else {
                   8447:                             $first_access=&get_first_access($interval[1]);
                   8448:                         }
                   8449:                         if ($first_access) {
                   8450:                             my $timesup = $first_access+$interval[0];
                   8451:                             if ($timesup > $now) {
                   8452:                                 my $activeblock;
                   8453:                                 foreach my $res (@to_test) {
                   8454:                                     if ($res->answerable()) {
                   8455:                                         $activeblock = 1;
                   8456:                                         last;
                   8457:                                     }
                   8458:                                 }
                   8459:                                 if ($activeblock) {
                   8460:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8461:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8462:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8463:                                          }
                   8464:                                     }
                   8465:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8466:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8467:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8468:                                         }
1.1162    raeburn  8469:                                     }
                   8470:                                 }
                   8471:                             }
                   8472:                         }
                   8473:                     }
                   8474:                 }
                   8475:             }
                   8476:         }
                   8477:     }
1.1172.2.66  raeburn  8478:     return %blockers;
1.1162    raeburn  8479: }
                   8480: 
1.1172.2.66  raeburn  8481: sub has_comm_blocking {
                   8482:     my ($priv,$symb,$uri,$blocks) = @_;
                   8483:     my @blockers;
                   8484:     return unless ($env{'request.course.id'});
                   8485:     return unless ($priv eq 'bre');
                   8486:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8487:     return if ($env{'request.state'} eq 'construct');
                   8488:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8489:     return unless (keys(%cachedblockers) > 0);
                   8490:     my (%possibles,@symbs);
                   8491:     if (!$symb) {
                   8492:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8493:     }
1.1172.2.66  raeburn  8494:     if ($symb) {
                   8495:         @symbs = ($symb);
                   8496:     } elsif (keys(%possibles)) {
                   8497:         @symbs = keys(%possibles);
                   8498:     }
                   8499:     my $noblock;
                   8500:     foreach my $symb (@symbs) {
                   8501:         last if ($noblock);
                   8502:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8503:         foreach my $block (keys(%cachedblockers)) {
                   8504:             if ($block =~ /^firstaccess____(.+)$/) {
                   8505:                 my $item = $1;
                   8506:                 if (($item eq $map) || ($item eq $symb)) {
                   8507:                     $noblock = 1;
                   8508:                     last;
                   8509:                 }
1.1162    raeburn  8510:             }
1.1172.2.66  raeburn  8511:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8512:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8513:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8514:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8515:                             push(@blockers,$block);
                   8516:                         }
                   8517:                     }
                   8518:                 }
                   8519:             }
                   8520:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8521:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8522:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8523:                         push(@blockers,$block);
                   8524:                     }
                   8525:                 }
1.1162    raeburn  8526:             }
                   8527:         }
                   8528:     }
1.1172.2.66  raeburn  8529:     return if ($noblock);
                   8530:     return @blockers;
                   8531: }
1.1162    raeburn  8532: }
                   8533: 
1.1172.2.66  raeburn  8534: # -------------------------------- Deversion and split uri into path an filename
                   8535: 
1.1133    foxr     8536: #
1.1172.2.66  raeburn  8537: #   Removes the version from a URI and
1.1133    foxr     8538: #   splits it in to its filename and path to the filename.
                   8539: #   Seems like File::Basename could have done this more clearly.
                   8540: #   Parameters:
                   8541: #      $uri   - input URI
                   8542: #   Returns:
                   8543: #     Two element list consisting of 
                   8544: #     $pathname  - the URI up to and excluding the trailing /
                   8545: #     $filename  - The part of the URI following the last /
                   8546: #  NOTE:
                   8547: #    Another realization of this is simply:
                   8548: #    use File::Basename;
                   8549: #    ...
                   8550: #    $uri = shift;
                   8551: #    $filename = basename($uri);
                   8552: #    $path     = dirname($uri);
                   8553: #    return ($filename, $path);
                   8554: #
                   8555: #     The implementation below is probably faster however.
                   8556: #
1.710     albertel 8557: sub split_uri_for_cond {
                   8558:     my $uri=&deversion(&declutter(shift));
                   8559:     my @uriparts=split(/\//,$uri);
                   8560:     my $filename=pop(@uriparts);
                   8561:     my $pathname=join('/',@uriparts);
                   8562:     return ($pathname,$filename);
                   8563: }
1.232     www      8564: # --------------------------------------------------- Is a resource on the map?
                   8565: 
                   8566: sub is_on_map {
1.710     albertel 8567:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8568:     #Trying to find the conditional for the file
1.620     albertel 8569:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8570: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8571:     if ($match) {
1.289     bowersj2 8572: 	return (1,$1);
                   8573:     } else {
1.434     www      8574: 	return (0,0);
1.289     bowersj2 8575:     }
1.12      www      8576: }
                   8577: 
1.427     www      8578: # --------------------------------------------------------- Get symb from alias
                   8579: 
                   8580: sub get_symb_from_alias {
                   8581:     my $symb=shift;
                   8582:     my ($map,$resid,$url)=&decode_symb($symb);
                   8583: # Already is a symb
                   8584:     if ($url) { return $symb; }
                   8585: # Must be an alias
                   8586:     my $aliassymb='';
                   8587:     my %bighash;
1.620     albertel 8588:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8589:                             &GDBM_READER(),0640)) {
                   8590:         my $rid=$bighash{'mapalias_'.$symb};
                   8591: 	if ($rid) {
                   8592: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8593: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8594: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8595: 	}
                   8596:         untie %bighash;
                   8597:     }
                   8598:     return $aliassymb;
                   8599: }
                   8600: 
1.12      www      8601: # ----------------------------------------------------------------- Define Role
                   8602: 
                   8603: sub definerole {
                   8604:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8605:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8606:     foreach my $role (split(':',$sysrole)) {
                   8607: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8608:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8609:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8610: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8611:                return "refused:s:$crole&$cqual"; 
                   8612:             }
                   8613:         }
1.191     harris41 8614:     }
1.800     albertel 8615:     foreach my $role (split(':',$domrole)) {
                   8616: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8617:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8618:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8619: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8620:                return "refused:d:$crole&$cqual"; 
                   8621:             }
                   8622:         }
1.191     harris41 8623:     }
1.800     albertel 8624:     foreach my $role (split(':',$courole)) {
                   8625: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8626:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8627:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8628: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8629:                return "refused:c:$crole&$cqual"; 
                   8630:             }
                   8631:         }
1.191     harris41 8632:     }
1.1172.2.84  raeburn  8633:     my $uhome;
                   8634:     if (($uname ne '') && ($udom ne '')) {
                   8635:         $uhome = &homeserver($uname,$udom);
                   8636:         return $uhome if ($uhome eq 'no_host');
                   8637:     } else {
                   8638:         $uname = $env{'user.name'};
                   8639:         $udom = $env{'user.domain'};
                   8640:         $uhome = $env{'user.home'};
                   8641:     }
1.620     albertel 8642:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8643:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8644:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8645:     return reply($command,$uhome);
1.12      www      8646:   } else {
                   8647:     return 'refused';
                   8648:   }
1.105     harris41 8649: }
                   8650: 
                   8651: # ---------------- Make a metadata query against the network of library servers
                   8652: 
                   8653: sub metadata_query {
1.1172.2.33  raeburn  8654:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8655:     my %rhash;
1.845     albertel 8656:     my %libserv = &all_library();
1.244     matthew  8657:     my @server_list = (defined($server_array) ? @$server_array
                   8658:                                               : keys(%libserv) );
                   8659:     for my $server (@server_list) {
1.1172.2.33  raeburn  8660:         my $domains = '';
                   8661:         if (ref($domains_hash) eq 'HASH') {
                   8662:             $domains = $domains_hash->{$server};    
                   8663:         }
1.118     harris41 8664: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8665: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8666: 	    $rhash{$server}=$reply;
                   8667: 	}
                   8668: 	else {
                   8669: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8670: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8671: 			     $server);
                   8672: 	    $rhash{$server}=$reply;
                   8673: 	}
1.112     harris41 8674:     }
1.118     harris41 8675:     return \%rhash;
1.240     www      8676: }
                   8677: 
                   8678: # ----------------------------------------- Send log queries and wait for reply
                   8679: 
                   8680: sub log_query {
                   8681:     my ($uname,$udom,$query,%filters)=@_;
                   8682:     my $uhome=&homeserver($uname,$udom);
                   8683:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8684:     my $uhost=&hostname($uhome);
1.800     albertel 8685:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8686:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8687:                        $uhome);
1.479     albertel 8688:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8689:     return get_query_reply($queryid);
                   8690: }
                   8691: 
1.818     raeburn  8692: # -------------------------- Update MySQL table for portfolio file
                   8693: 
                   8694: sub update_portfolio_table {
1.821     raeburn  8695:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8696:     if ($group ne '') {
                   8697:         $file_name =~s /^\Q$group\E//;
                   8698:     }
1.818     raeburn  8699:     my $homeserver = &homeserver($uname,$udom);
                   8700:     my $queryid=
1.821     raeburn  8701:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8702:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8703:     my $reply = &get_query_reply($queryid);
                   8704:     return $reply;
                   8705: }
                   8706: 
1.899     raeburn  8707: # -------------------------- Update MySQL allusers table
                   8708: 
                   8709: sub update_allusers_table {
                   8710:     my ($uname,$udom,$names) = @_;
                   8711:     my $homeserver = &homeserver($uname,$udom);
                   8712:     my $queryid=
                   8713:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8714:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8715:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8716:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8717:                'generation='.&escape($names->{'generation'}).'%%'.
                   8718:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8719:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8720:     return;
1.899     raeburn  8721: }
                   8722: 
1.508     raeburn  8723: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8724: 
                   8725: sub fetch_enrollment_query {
1.511     raeburn  8726:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8727:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8728:     my $maxtries = 1;
1.508     raeburn  8729:     if ($context eq 'automated') {
                   8730:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8731:         $sleep = 2;
                   8732:         $loopmax = 100;
1.547     raeburn  8733:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8734:     } else {
                   8735:         $homeserver = &homeserver($cnum,$dom);
                   8736:     }
1.838     albertel 8737:     my $host=&hostname($homeserver);
1.506     raeburn  8738:     my $cmd = '';
1.1000    raeburn  8739:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8740:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8741:     }
                   8742:     $cmd =~ s/%%$//;
                   8743:     $cmd = &escape($cmd);
                   8744:     my $query = 'fetchenrollment';
1.620     albertel 8745:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8746:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8747:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8748:         return 'error: '.$queryid;
                   8749:     }
1.1172.2.93  raeburn  8750:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8751:     my $tries = 1;
                   8752:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8753:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8754:         $tries ++;
                   8755:     }
1.526     raeburn  8756:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8757:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8758:     } else {
1.901     albertel 8759:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8760:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8761:             foreach my $line (@responses) {
                   8762:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8763:                 $$replyref{$key} = $value;
                   8764:             }
                   8765:         } else {
1.1117    foxr     8766:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8767:             foreach my $line (@responses) {
                   8768:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8769:                 $$replyref{$key} = $value;
                   8770:                 if ($value > 0) {
1.800     albertel 8771:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8772:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8773:                         my $destname = $pathname.'/'.$filename;
                   8774:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8775:                         if ($xml_classlist =~ /^error/) {
                   8776:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8777:                         } else {
1.1172.2.96  raeburn  8778:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8779:                                 print FILE &unescape($xml_classlist);
                   8780:                                 close(FILE);
1.526     raeburn  8781:                             } else {
                   8782:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8783:                             }
                   8784:                         }
                   8785:                     }
                   8786:                 }
                   8787:             }
                   8788:         }
                   8789:         return 'ok';
                   8790:     }
                   8791:     return 'error';
                   8792: }
                   8793: 
1.242     www      8794: sub get_query_reply {
1.1172.2.79  raeburn  8795:     my ($queryid,$sleep,$loopmax) = @_;
                   8796:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8797:         $sleep = 0.2;
                   8798:     }
                   8799:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8800:         $loopmax = 100;
                   8801:     }
1.1117    foxr     8802:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8803:     my $reply='';
1.1172.2.79  raeburn  8804:     for (1..$loopmax) {
                   8805: 	sleep($sleep);
1.240     www      8806:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8807: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8808: 		$reply = join('',<$fh>);
                   8809: 		close($fh);
1.240     www      8810: 	   } else { return 'error: reply_file_error'; }
1.242     www      8811:            return &unescape($reply);
                   8812: 	}
1.240     www      8813:     }
1.242     www      8814:     return 'timeout:'.$queryid;
1.240     www      8815: }
                   8816: 
                   8817: sub courselog_query {
1.241     www      8818: #
                   8819: # possible filters:
                   8820: # url: url or symb
                   8821: # username
                   8822: # domain
                   8823: # action: view, submit, grade
                   8824: # start: timestamp
                   8825: # end: timestamp
                   8826: #
1.240     www      8827:     my (%filters)=@_;
1.620     albertel 8828:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8829:     if ($filters{'url'}) {
                   8830: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8831:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8832:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8833:     }
1.620     albertel 8834:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8835:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8836:     return &log_query($cname,$cdom,'courselog',%filters);
                   8837: }
                   8838: 
                   8839: sub userlog_query {
1.858     raeburn  8840: #
                   8841: # possible filters:
                   8842: # action: log check role
                   8843: # start: timestamp
                   8844: # end: timestamp
                   8845: #
1.240     www      8846:     my ($uname,$udom,%filters)=@_;
                   8847:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8848: }
                   8849: 
1.506     raeburn  8850: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8851: 
                   8852: sub auto_run {
1.508     raeburn  8853:     my ($cnum,$cdom) = @_;
1.876     raeburn  8854:     my $response = 0;
                   8855:     my $settings;
                   8856:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8857:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8858:         $settings = $domconfig{'autoenroll'};
                   8859:         if ($settings->{'run'} eq '1') {
                   8860:             $response = 1;
                   8861:         }
                   8862:     } else {
1.934     raeburn  8863:         my $homeserver;
                   8864:         if (&is_course($cdom,$cnum)) {
                   8865:             $homeserver = &homeserver($cnum,$cdom);
                   8866:         } else {
                   8867:             $homeserver = &domain($cdom,'primary');
                   8868:         }
                   8869:         if ($homeserver ne 'no_host') {
                   8870:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8871:         }
1.876     raeburn  8872:     }
1.506     raeburn  8873:     return $response;
                   8874: }
1.776     albertel 8875: 
1.506     raeburn  8876: sub auto_get_sections {
1.508     raeburn  8877:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8878:     my $homeserver;
                   8879:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8880:         $homeserver = &homeserver($cnum,$cdom);
                   8881:     }
                   8882:     if (!defined($homeserver)) { 
                   8883:         if ($cdom =~ /^$match_domain$/) {
                   8884:             $homeserver = &domain($cdom,'primary');
                   8885:         }
                   8886:     }
                   8887:     my @secs;
                   8888:     if (defined($homeserver)) {
                   8889:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8890:         unless ($response eq 'refused') {
                   8891:             @secs = split(/:/,$response);
                   8892:         }
1.506     raeburn  8893:     }
                   8894:     return @secs;
                   8895: }
1.776     albertel 8896: 
1.506     raeburn  8897: sub auto_new_course {
1.1099    raeburn  8898:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8899:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8900:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8901:     return $response;
                   8902: }
1.776     albertel 8903: 
1.506     raeburn  8904: sub auto_validate_courseID {
1.508     raeburn  8905:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8906:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8907:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8908:     return $response;
                   8909: }
1.776     albertel 8910: 
1.1007    raeburn  8911: sub auto_validate_instcode {
1.1020    raeburn  8912:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8913:     my ($homeserver,$response);
                   8914:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8915:         $homeserver = &homeserver($cnum,$cdom);
                   8916:     }
                   8917:     if (!defined($homeserver)) {
                   8918:         if ($cdom =~ /^$match_domain$/) {
                   8919:             $homeserver = &domain($cdom,'primary');
                   8920:         }
                   8921:     }
1.1065    raeburn  8922:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8923:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8924:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8925:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8926: }
                   8927: 
1.506     raeburn  8928: sub auto_create_password {
1.873     raeburn  8929:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8930:     my ($homeserver,$response);
1.506     raeburn  8931:     my $create_passwd = 0;
                   8932:     my $authchk = '';
1.873     raeburn  8933:     if ($udom =~ /^$match_domain$/) {
                   8934:         $homeserver = &domain($udom,'primary');
                   8935:     }
                   8936:     if ($homeserver eq '') {
                   8937:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8938:             $homeserver = &homeserver($cnum,$cdom);
                   8939:         }
                   8940:     }
                   8941:     if ($homeserver eq '') {
                   8942:         $authchk = 'nodomain';
1.506     raeburn  8943:     } else {
1.873     raeburn  8944:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8945:         if ($response eq 'refused') {
                   8946:             $authchk = 'refused';
                   8947:         } else {
1.901     albertel 8948:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8949:         }
1.506     raeburn  8950:     }
                   8951:     return ($authparam,$create_passwd,$authchk);
                   8952: }
                   8953: 
1.706     raeburn  8954: sub auto_photo_permission {
                   8955:     my ($cnum,$cdom,$students) = @_;
                   8956:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8957:     my ($outcome,$perm_reqd,$conditions) = 
                   8958: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8959:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8960: 	return (undef,undef);
                   8961:     }
1.706     raeburn  8962:     return ($outcome,$perm_reqd,$conditions);
                   8963: }
                   8964: 
                   8965: sub auto_checkphotos {
                   8966:     my ($uname,$udom,$pid) = @_;
                   8967:     my $homeserver = &homeserver($uname,$udom);
                   8968:     my ($result,$resulttype);
                   8969:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8970: 				   &escape($uname).':'.&escape($pid),
                   8971: 				   $homeserver));
1.709     albertel 8972:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8973: 	return (undef,undef);
                   8974:     }
1.706     raeburn  8975:     if ($outcome) {
                   8976:         ($result,$resulttype) = split(/:/,$outcome);
                   8977:     } 
                   8978:     return ($result,$resulttype);
                   8979: }
                   8980: 
                   8981: sub auto_photochoice {
                   8982:     my ($cnum,$cdom) = @_;
                   8983:     my $homeserver = &homeserver($cnum,$cdom);
                   8984:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8985: 						       &escape($cdom),
                   8986: 						       $homeserver)));
1.709     albertel 8987:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8988: 	return (undef,undef);
                   8989:     }
1.706     raeburn  8990:     return ($update,$comment);
                   8991: }
                   8992: 
                   8993: sub auto_photoupdate {
                   8994:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8995:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8996:     my $host=&hostname($homeserver);
1.706     raeburn  8997:     my $cmd = '';
                   8998:     my $maxtries = 1;
1.800     albertel 8999:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9000:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9001:     }
                   9002:     $cmd =~ s/%%$//;
                   9003:     $cmd = &escape($cmd);
                   9004:     my $query = 'institutionalphotos';
                   9005:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9006:     unless ($queryid=~/^\Q$host\E\_/) {
                   9007:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9008:         return 'error: '.$queryid;
                   9009:     }
                   9010:     my $reply = &get_query_reply($queryid);
                   9011:     my $tries = 1;
                   9012:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9013:         $reply = &get_query_reply($queryid);
                   9014:         $tries ++;
                   9015:     }
                   9016:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9017:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9018:     } else {
                   9019:         my @responses = split(/:/,$reply);
                   9020:         my $outcome = shift(@responses); 
                   9021:         foreach my $item (@responses) {
                   9022:             my ($key,$value) = split(/=/,$item);
                   9023:             $$photo{$key} = $value;
                   9024:         }
                   9025:         return $outcome;
                   9026:     }
                   9027:     return 'error';
                   9028: }
                   9029: 
1.521     raeburn  9030: sub auto_instcode_format {
1.793     albertel 9031:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9032: 	$cat_order) = @_;
1.521     raeburn  9033:     my $courses = '';
1.772     raeburn  9034:     my @homeservers;
1.521     raeburn  9035:     if ($caller eq 'global') {
1.841     albertel 9036: 	my %servers = &get_servers($codedom,'library');
                   9037: 	foreach my $tryserver (keys(%servers)) {
                   9038: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9039: 		push(@homeservers,$tryserver);
                   9040: 	    }
1.584     raeburn  9041:         }
1.1022    raeburn  9042:     } elsif ($caller eq 'requests') {
                   9043:         if ($codedom =~ /^$match_domain$/) {
                   9044:             my $chome = &domain($codedom,'primary');
                   9045:             unless ($chome eq 'no_host') {
                   9046:                 push(@homeservers,$chome);
                   9047:             }
                   9048:         }
1.521     raeburn  9049:     } else {
1.772     raeburn  9050:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9051:     }
1.793     albertel 9052:     foreach my $code (keys(%{$instcodes})) {
                   9053:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9054:     }
                   9055:     chop($courses);
1.772     raeburn  9056:     my $ok_response = 0;
                   9057:     my $response;
                   9058:     while (@homeservers > 0 && $ok_response == 0) {
                   9059:         my $server = shift(@homeservers); 
                   9060:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9061:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9062:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9063: 		split(/:/,$response);
1.772     raeburn  9064:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9065:             push(@{$codetitles},&str2array($codetitles_str));
                   9066:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9067:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9068:             $ok_response = 1;
                   9069:         }
                   9070:     }
                   9071:     if ($ok_response) {
1.521     raeburn  9072:         return 'ok';
1.772     raeburn  9073:     } else {
                   9074:         return $response;
1.521     raeburn  9075:     }
                   9076: }
                   9077: 
1.792     raeburn  9078: sub auto_instcode_defaults {
                   9079:     my ($domain,$returnhash,$code_order) = @_;
                   9080:     my @homeservers;
1.841     albertel 9081: 
                   9082:     my %servers = &get_servers($domain,'library');
                   9083:     foreach my $tryserver (keys(%servers)) {
                   9084: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9085: 	    push(@homeservers,$tryserver);
                   9086: 	}
1.792     raeburn  9087:     }
1.841     albertel 9088: 
1.792     raeburn  9089:     my $response;
1.841     albertel 9090:     foreach my $server (@homeservers) {
1.792     raeburn  9091:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9092:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9093: 	
                   9094: 	foreach my $pair (split(/\&/,$response)) {
                   9095: 	    my ($name,$value)=split(/\=/,$pair);
                   9096: 	    if ($name eq 'code_order') {
                   9097: 		@{$code_order} = split(/\&/,&unescape($value));
                   9098: 	    } else {
                   9099: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9100: 	    }
                   9101: 	}
                   9102: 	return 'ok';
1.792     raeburn  9103:     }
1.841     albertel 9104: 
                   9105:     return $response;
1.1003    raeburn  9106: }
                   9107: 
                   9108: sub auto_possible_instcodes {
1.1007    raeburn  9109:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9110:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9111:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9112:         return;
                   9113:     }
1.1003    raeburn  9114:     my (@homeservers,$uhome);
                   9115:     if (defined(&domain($domain,'primary'))) {
                   9116:         $uhome=&domain($domain,'primary');
                   9117:         push(@homeservers,&domain($domain,'primary'));
                   9118:     } else {
                   9119:         my %servers = &get_servers($domain,'library');
                   9120:         foreach my $tryserver (keys(%servers)) {
                   9121:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9122:                 push(@homeservers,$tryserver);
                   9123:             }
                   9124:         }
                   9125:     }
                   9126:     my $response;
                   9127:     foreach my $server (@homeservers) {
                   9128:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9129:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9130:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9131:             split(':',$response);
                   9132:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9133:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9134:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9135:             my ($name,$value)=split('=',$item);
                   9136:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9137:         }
                   9138:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9139:             my ($name,$value)=split('=',$item);
                   9140:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9141:         }
                   9142:         return 'ok';
                   9143:     }
                   9144:     return $response;
                   9145: }
1.792     raeburn  9146: 
1.1010    raeburn  9147: sub auto_courserequest_checks {
                   9148:     my ($dom) = @_;
1.1020    raeburn  9149:     my ($homeserver,%validations);
                   9150:     if ($dom =~ /^$match_domain$/) {
                   9151:         $homeserver = &domain($dom,'primary');
                   9152:     }
                   9153:     unless ($homeserver eq 'no_host') {
                   9154:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9155:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9156:             my @items = split(/&/,$response);
                   9157:             foreach my $item (@items) {
                   9158:                 my ($key,$value) = split('=',$item);
                   9159:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9160:             }
                   9161:         }
                   9162:     }
1.1010    raeburn  9163:     return %validations; 
                   9164: }
                   9165: 
1.1020    raeburn  9166: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9167:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9168:     my ($homeserver,$response);
                   9169:     if ($dom =~ /^$match_domain$/) {
                   9170:         $homeserver = &domain($dom,'primary');
                   9171:     }
1.1172.2.43  raeburn  9172:     unless ($homeserver eq 'no_host') {
                   9173:         my $customdata;
                   9174:         if (ref($custominfo) eq 'HASH') {
                   9175:             $customdata = &freeze_escape($custominfo);
                   9176:         }
1.1020    raeburn  9177:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9178:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9179:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9180:                                     $customdata,$homeserver));
1.1020    raeburn  9181:     }
                   9182:     return $response;
                   9183: }
                   9184: 
1.777     albertel 9185: sub auto_validate_class_sec {
1.918     raeburn  9186:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9187:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9188:     my $ownerlist;
                   9189:     if (ref($owners) eq 'ARRAY') {
                   9190:         $ownerlist = join(',',@{$owners});
                   9191:     } else {
                   9192:         $ownerlist = $owners;
                   9193:     }
1.773     raeburn  9194:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9195:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9196:     return $response;
                   9197: }
                   9198: 
1.1172.2.94  raeburn  9199: sub auto_validate_instclasses {
                   9200:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9201:     my ($homeserver,%validations);
                   9202:     $homeserver = &homeserver($cnum,$cdom);
                   9203:     unless ($homeserver eq 'no_host') {
                   9204:         my $ownerlist;
                   9205:         if (ref($owners) eq 'ARRAY') {
                   9206:             $ownerlist = join(',',@{$owners});
                   9207:         } else {
                   9208:             $ownerlist = $owners;
                   9209:         }
                   9210:         if (ref($classesref) eq 'HASH') {
                   9211:             my $classes = &freeze_escape($classesref);
                   9212:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9213:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9214:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9215:                 my @items = split(/&/,$response);
                   9216:                 foreach my $item (@items) {
                   9217:                     my ($key,$value) = split('=',$item);
                   9218:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9219:                 }
                   9220:             }
                   9221:         }
                   9222:     }
                   9223:     return %validations;
                   9224: }
                   9225: 
1.1172.2.38  raeburn  9226: sub auto_crsreq_update {
                   9227:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9228:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9229:     my ($homeserver,%crsreqresponse);
                   9230:     if ($cdom =~ /^$match_domain$/) {
                   9231:         $homeserver = &domain($cdom,'primary');
                   9232:     }
                   9233:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9234:         my $info;
                   9235:         if (ref($inbound) eq 'HASH') {
                   9236:             $info = &freeze_escape($inbound);
                   9237:         }
                   9238:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9239:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9240:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9241:                             &escape($title).':'.&escape($code).':'.
                   9242:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9243:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9244:             my @items = split(/&/,$response);
                   9245:             foreach my $item (@items) {
                   9246:                 my ($key,$value) = split('=',$item);
                   9247:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9248:             }
                   9249:         }
                   9250:     }
                   9251:     return \%crsreqresponse;
                   9252: }
                   9253: 
1.1172.2.78  raeburn  9254: sub auto_export_grades {
                   9255:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9256:     my ($homeserver,%exportresponse);
                   9257:     if ($cdom =~ /^$match_domain$/) {
                   9258:         $homeserver = &domain($cdom,'primary');
                   9259:     }
                   9260:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9261:         my $info;
                   9262:         if (ref($inforef) eq 'HASH') {
                   9263:             $info = &freeze_escape($inforef);
                   9264:         }
                   9265:         if (ref($gradesref) eq 'HASH') {
                   9266:             my $grades = &freeze_escape($gradesref);
                   9267:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9268:                                 $info.':'.$grades,$homeserver);
                   9269:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9270:                 my @items = split(/&/,$response);
                   9271:                 foreach my $item (@items) {
                   9272:                     my ($key,$value) = split('=',$item);
                   9273:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9274:                 }
                   9275:             }
                   9276:         }
                   9277:     }
                   9278:     return \%exportresponse;
                   9279: }
                   9280: 
1.1172.2.68  raeburn  9281: sub check_instcode_cloning {
                   9282:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9283:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9284:         return;
                   9285:     }
                   9286:     my $canclone;
                   9287:     if (@{$code_order} > 0) {
                   9288:         my $instcoderegexp ='^';
                   9289:         my @clonecodes = split(/\&/,$cloner);
                   9290:         foreach my $item (@{$code_order}) {
                   9291:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9292:                 foreach my $pair (@clonecodes) {
                   9293:                     my ($key,$val) = split(/\=/,$pair,2);
                   9294:                     $val = &unescape($val);
                   9295:                     if ($key eq $item) {
                   9296:                         $instcoderegexp .= '('.$val.')';
                   9297:                         last;
                   9298:                     }
                   9299:                 }
                   9300:             } else {
                   9301:                 $instcoderegexp .= $codedefaults->{$item};
                   9302:             }
                   9303:         }
                   9304:         $instcoderegexp .= '$';
                   9305:         my (@from,@to);
                   9306:         eval {
                   9307:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9308:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9309:         };
                   9310:         if ((@from > 0) && (@to > 0)) {
                   9311:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9312:             if (!@diffs) {
                   9313:                 $canclone = 1;
                   9314:             }
                   9315:         }
                   9316:     }
                   9317:     return $canclone;
                   9318: }
                   9319: 
                   9320: sub default_instcode_cloning {
                   9321:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9322:     my (%codedefaults,@code_order,$canclone);
                   9323:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9324:         %codedefaults = %{$codedefaultsref};
                   9325:         @code_order = @{$codeorderref};
                   9326:     } elsif ($clonedom) {
                   9327:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9328:     }
                   9329:     if (($domdefclone) && (@code_order)) {
                   9330:         my @clonecodes = split(/\+/,$domdefclone);
                   9331:         my $instcoderegexp ='^';
                   9332:         foreach my $item (@code_order) {
                   9333:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9334:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9335:             } else {
                   9336:                 $instcoderegexp .= $codedefaults{$item};
                   9337:             }
                   9338:         }
                   9339:         $instcoderegexp .= '$';
                   9340:         my (@from,@to);
                   9341:         eval {
                   9342:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9343:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9344:         };
                   9345:         if ((@from > 0) && (@to > 0)) {
                   9346:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9347:             if (!@diffs) {
                   9348:                 $canclone = 1;
                   9349:             }
                   9350:         }
                   9351:     }
                   9352:     return $canclone;
                   9353: }
                   9354: 
1.679     raeburn  9355: # ------------------------------------------------------- Course Group routines
                   9356: 
                   9357: sub get_coursegroups {
1.809     raeburn  9358:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9359:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9360: }
                   9361: 
1.679     raeburn  9362: sub modify_coursegroup {
                   9363:     my ($cdom,$cnum,$groupsettings) = @_;
                   9364:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9365: }
                   9366: 
1.809     raeburn  9367: sub toggle_coursegroup_status {
                   9368:     my ($cdom,$cnum,$group,$action) = @_;
                   9369:     my ($from_namespace,$to_namespace);
                   9370:     if ($action eq 'delete') {
                   9371:         $from_namespace = 'coursegroups';
                   9372:         $to_namespace = 'deleted_groups';
                   9373:     } else {
                   9374:         $from_namespace = 'deleted_groups';
                   9375:         $to_namespace = 'coursegroups';
                   9376:     }
                   9377:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9378:     if (my $tmp = &error(%curr_group)) {
                   9379:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9380:         return ('read error',$tmp);
                   9381:     } else {
                   9382:         my %savedsettings = %curr_group; 
1.809     raeburn  9383:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9384:         my $deloutcome;
                   9385:         if ($result eq 'ok') {
1.809     raeburn  9386:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9387:         } else {
                   9388:             return ('write error',$result);
                   9389:         }
                   9390:         if ($deloutcome eq 'ok') {
                   9391:             return 'ok';
                   9392:         } else {
                   9393:             return ('delete error',$deloutcome);
                   9394:         }
                   9395:     }
                   9396: }
                   9397: 
1.679     raeburn  9398: sub modify_group_roles {
1.957     raeburn  9399:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9400:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9401:     my $role = 'gr/'.&escape($userprivs);
                   9402:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9403:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9404:     if ($result eq 'ok') {
                   9405:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9406:     }
1.679     raeburn  9407:     return $result;
                   9408: }
                   9409: 
                   9410: sub modify_coursegroup_membership {
                   9411:     my ($cdom,$cnum,$membership) = @_;
                   9412:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9413:     return $result;
                   9414: }
                   9415: 
1.682     raeburn  9416: sub get_active_groups {
                   9417:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9418:     my $now = time;
                   9419:     my %groups = ();
                   9420:     foreach my $key (keys(%env)) {
1.811     albertel 9421:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9422:             my ($start,$end) = split(/\./,$env{$key});
                   9423:             if (($end!=0) && ($end<$now)) { next; }
                   9424:             if (($start!=0) && ($start>$now)) { next; }
                   9425:             if ($1 eq $cdom && $2 eq $cnum) {
                   9426:                 $groups{$3} = $env{$key} ;
                   9427:             }
                   9428:         }
                   9429:     }
                   9430:     return %groups;
                   9431: }
                   9432: 
1.683     raeburn  9433: sub get_group_membership {
                   9434:     my ($cdom,$cnum,$group) = @_;
                   9435:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9436: }
                   9437: 
                   9438: sub get_users_groups {
                   9439:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9440:     my @usersgroups;
1.683     raeburn  9441:     my $cachetime=1800;
                   9442: 
                   9443:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9444:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9445:     if (defined($cached)) {
1.734     albertel 9446:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9447:     } else {  
                   9448:         $grouplist = '';
1.816     raeburn  9449:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9450:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9451:         my $access_end = $env{'course.'.$courseid.
                   9452:                               '.default_enrollment_end_date'};
                   9453:         my $now = time;
                   9454:         foreach my $key (keys(%roleshash)) {
                   9455:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9456:                 my $group = $1;
                   9457:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9458:                     my $start = $2;
                   9459:                     my $end = $1;
                   9460:                     if ($start == -1) { next; } # deleted from group
                   9461:                     if (($start!=0) && ($start>$now)) { next; }
                   9462:                     if (($end!=0) && ($end<$now)) {
                   9463:                         if ($access_end && $access_end < $now) {
                   9464:                             if ($access_end - $end < 86400) {
                   9465:                                 push(@usersgroups,$group);
1.733     raeburn  9466:                             }
                   9467:                         }
1.817     raeburn  9468:                         next;
1.733     raeburn  9469:                     }
1.817     raeburn  9470:                     push(@usersgroups,$group);
1.683     raeburn  9471:                 }
                   9472:             }
                   9473:         }
1.817     raeburn  9474:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9475:         $grouplist = join(':',@usersgroups);
                   9476:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9477:     }
1.733     raeburn  9478:     return @usersgroups;
1.683     raeburn  9479: }
                   9480: 
                   9481: sub devalidate_getgroups_cache {
                   9482:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9483:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9484: 
1.683     raeburn  9485:     my $hashid="$udom:$uname:$courseid";
                   9486:     &devalidate_cache_new('getgroups',$hashid);
                   9487: }
                   9488: 
1.12      www      9489: # ------------------------------------------------------------------ Plain Text
                   9490: 
                   9491: sub plaintext {
1.988     raeburn  9492:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9493:     if ($short =~ m{^cr/}) {
1.758     albertel 9494: 	return (split('/',$short))[-1];
                   9495:     }
1.742     raeburn  9496:     if (!defined($cid)) {
                   9497:         $cid = $env{'request.course.id'};
                   9498:     }
                   9499:     my %rolenames = (
1.1008    raeburn  9500:                       Course    => 'std',
                   9501:                       Community => 'alt1',
1.742     raeburn  9502:                     );
1.1037    raeburn  9503:     if ($cid ne '') {
                   9504:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9505:             unless ($forcedefault) {
                   9506:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9507:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9508:                 return &Apache::lonlocal::mt($roletext);
                   9509:             }
                   9510:         }
                   9511:     }
                   9512:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9513:         (defined($rolenames{$type})) && 
                   9514:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9515:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9516:     } elsif ($cid ne '') {
                   9517:         my $crstype = $env{'course.'.$cid.'.type'};
                   9518:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9519:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9520:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9521:         }
1.742     raeburn  9522:     }
1.1037    raeburn  9523:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9524: }
                   9525: 
                   9526: # ----------------------------------------------------------------- Assign Role
                   9527: 
                   9528: sub assignrole {
1.957     raeburn  9529:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9530:         $context)=@_;
1.21      www      9531:     my $mrole;
                   9532:     if ($role =~ /^cr\//) {
1.393     www      9533:         my $cwosec=$url;
1.811     albertel 9534:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9535: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9536:            my $refused = 1;
                   9537:            if ($context eq 'requestcourses') {
                   9538:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9539:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9540:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9541:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9542:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9543:                            if ($crsenv{'internal.courseowner'} eq
                   9544:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9545:                                $refused = '';
                   9546:                            }
                   9547:                        }
                   9548:                    }
                   9549:                }
                   9550:            }
                   9551:            if ($refused) {
                   9552:                &logthis('Refused custom assignrole: '.
                   9553:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9554:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9555:                return 'refused';
                   9556:            }
1.104     www      9557:         }
1.21      www      9558:         $mrole='cr';
1.678     raeburn  9559:     } elsif ($role =~ /^gr\//) {
                   9560:         my $cwogrp=$url;
1.811     albertel 9561:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9562:         unless (&allowed('mdg',$cwogrp)) {
                   9563:             &logthis('Refused group assignrole: '.
                   9564:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9565:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9566:             return 'refused';
                   9567:         }
                   9568:         $mrole='gr';
1.21      www      9569:     } else {
1.82      www      9570:         my $cwosec=$url;
1.811     albertel 9571:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9572:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9573:             my $refused;
                   9574:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9575:                 if (!(&allowed('c'.$role,$url))) {
                   9576:                     $refused = 1;
                   9577:                 }
                   9578:             } else {
                   9579:                 $refused = 1;
                   9580:             }
1.947     raeburn  9581:             if ($refused) {
1.1045    raeburn  9582:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9583:                 if (!$selfenroll && $context eq 'course') {
                   9584:                     my %crsenv;
                   9585:                     if ($role eq 'cc' || $role eq 'co') {
                   9586:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9587:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9588:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9589:                                 if ($crsenv{'internal.courseowner'} eq 
                   9590:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9591:                                     $refused = '';
                   9592:                                 }
                   9593:                             }
                   9594:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9595:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9596:                                 if ($crsenv{'internal.courseowner'} eq 
                   9597:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9598:                                     $refused = '';
                   9599:                                 }
                   9600:                             }
                   9601:                         }
                   9602:                     }
                   9603:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9604:                     $refused = '';
1.1017    raeburn  9605:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9606:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9607:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9608:                         my $wrongcc;
                   9609:                         if ($cnum =~ /^$match_community$/) {
                   9610:                             $wrongcc = 1 if ($role eq 'cc');
                   9611:                         } else {
                   9612:                             $wrongcc = 1 if ($role eq 'co');
                   9613:                         }
                   9614:                         unless ($wrongcc) {
                   9615:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9616:                             if ($crsenv{'internal.courseowner'} eq 
                   9617:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9618:                                 $refused = '';
                   9619:                             }
1.1017    raeburn  9620:                         }
                   9621:                     }
1.1172.2.9  raeburn  9622:                 } elsif ($context eq 'requestauthor') {
                   9623:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9624:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9625:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9626:                             $refused = '';
                   9627:                         } else {
                   9628:                             my %domdefaults = &get_domain_defaults($udom);
                   9629:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9630:                                 my $checkbystatus;
                   9631:                                 if ($env{'user.adv'}) {
                   9632:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9633:                                     if ($disposition eq 'automatic') {
                   9634:                                         $refused = '';
                   9635:                                     } elsif ($disposition eq '') {
                   9636:                                         $checkbystatus = 1;
                   9637:                                     }
                   9638:                                 } else {
                   9639:                                     $checkbystatus = 1;
                   9640:                                 }
                   9641:                                 if ($checkbystatus) {
                   9642:                                     if ($env{'environment.inststatus'}) {
                   9643:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9644:                                         foreach my $type (@inststatuses) {
                   9645:                                             if (($type ne '') &&
                   9646:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9647:                                                 $refused = '';
                   9648:                                             }
                   9649:                                         }
                   9650:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9651:                                         $refused = '';
                   9652:                                     }
                   9653:                                 }
                   9654:                             }
                   9655:                         }
                   9656:                     }
1.1017    raeburn  9657:                 }
                   9658:                 if ($refused) {
1.947     raeburn  9659:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9660:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9661: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9662:                     return 'refused';
                   9663:                 }
1.932     raeburn  9664:             }
1.1131    raeburn  9665:         } elsif ($role eq 'au') {
                   9666:             if ($url ne '/'.$udom.'/') {
                   9667:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9668:                          ' to assign author role for '.$uname.':'.$udom.
                   9669:                          ' in domain: '.$url.' refused (wrong domain).');
                   9670:                 return 'refused';
                   9671:             }
1.104     www      9672:         }
1.21      www      9673:         $mrole=$role;
                   9674:     }
1.620     albertel 9675:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9676:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9677:     if ($end) { $command.='_'.$end; }
1.21      www      9678:     if ($start) {
                   9679: 	if ($end) { 
1.81      www      9680:            $command.='_'.$start; 
1.21      www      9681:         } else {
1.81      www      9682:            $command.='_0_'.$start;
1.21      www      9683:         }
                   9684:     }
1.739     raeburn  9685:     my $origstart = $start;
                   9686:     my $origend = $end;
1.957     raeburn  9687:     my $delflag;
1.357     www      9688: # actually delete
                   9689:     if ($deleteflag) {
1.373     www      9690: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9691: # modify command to delete the role
1.620     albertel 9692:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9693:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9694: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9695: # set start and finish to negative values for userrolelog
                   9696:            $start=-1;
                   9697:            $end=-1;
1.957     raeburn  9698:            $delflag = 1;
1.357     www      9699:         }
                   9700:     }
                   9701: # send command
1.349     www      9702:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9703: # log new user role if status is ok
1.349     www      9704:     if ($answer eq 'ok') {
1.663     raeburn  9705: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9706:         if (($role eq 'cc') || ($role eq 'in') ||
                   9707:             ($role eq 'ep') || ($role eq 'ad') ||
                   9708:             ($role eq 'ta') || ($role eq 'st') ||
                   9709:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9710:             ($role eq 'co')) {
1.1172.2.13  raeburn  9711: # for course roles, perform group memberships changes triggered by role change.
                   9712:             unless ($role =~ /^gr/) {
                   9713:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9714:                                                  $origstart,$selfenroll,$context);
                   9715:             }
1.1172.2.9  raeburn  9716:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9717:                            $selfenroll,$context);
                   9718:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9719:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9720:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9721:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9722:                            $context);
                   9723:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9724:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9725:                              $context);
                   9726:         }
1.1053    raeburn  9727:         if ($role eq 'cc') {
                   9728:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9729:         }
1.349     www      9730:     }
                   9731:     return $answer;
1.169     harris41 9732: }
                   9733: 
1.1053    raeburn  9734: sub autoupdate_coowners {
                   9735:     my ($url,$end,$start,$uname,$udom) = @_;
                   9736:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9737:     if (($cdom ne '') && ($cnum ne '')) {
                   9738:         my $now = time;
                   9739:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9740:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9741:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9742:             my $instcode = $coursehash{'internal.coursecode'};
                   9743:             if ($instcode ne '') {
1.1056    raeburn  9744:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9745:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9746:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9747:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9748:                         if ($result eq 'valid') {
                   9749:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9750:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9751:                                     push(@newcoowners,$coowner);
                   9752:                                 }
                   9753:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9754:                                     push(@newcoowners,$uname.':'.$udom);
                   9755:                                 }
                   9756:                                 @newcoowners = sort(@newcoowners);
                   9757:                             } else {
                   9758:                                 push(@newcoowners,$uname.':'.$udom);
                   9759:                             }
                   9760:                         } else {
                   9761:                             if ($coursehash{'internal.co-owners'}) {
                   9762:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9763:                                     unless ($coowner eq $uname.':'.$udom) {
                   9764:                                         push(@newcoowners,$coowner);
                   9765:                                     }
                   9766:                                 }
                   9767:                                 unless (@newcoowners > 0) {
                   9768:                                     $delcoowners = 1;
                   9769:                                     $coowners = '';
                   9770:                                 }
                   9771:                             }
                   9772:                         }
                   9773:                         if (@newcoowners || $delcoowners) {
                   9774:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9775:                                             $delcoowners,@newcoowners);
                   9776:                         }
                   9777:                     }
                   9778:                 }
                   9779:             }
                   9780:         }
                   9781:     }
                   9782: }
                   9783: 
                   9784: sub store_coowners {
                   9785:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9786:     my $cid = $cdom.'_'.$cnum;
                   9787:     my ($coowners,$delresult,$putresult);
                   9788:     if (@newcoowners) {
                   9789:         $coowners = join(',',@newcoowners);
                   9790:         my %coownershash = (
                   9791:                             'internal.co-owners' => $coowners,
                   9792:                            );
                   9793:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9794:         if ($putresult eq 'ok') {
                   9795:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9796:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9797:             }
                   9798:         }
                   9799:     }
                   9800:     if ($delcoowners) {
                   9801:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9802:         if ($delresult eq 'ok') {
                   9803:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9804:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9805:             }
                   9806:         }
                   9807:     }
                   9808:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9809:         my %crsinfo =
                   9810:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9811:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9812:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9813:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9814:         }
                   9815:     }
                   9816: }
                   9817: 
1.169     harris41 9818: # -------------------------------------------------- Modify user authentication
1.197     www      9819: # Overrides without validation
                   9820: 
1.169     harris41 9821: sub modifyuserauth {
                   9822:     my ($udom,$uname,$umode,$upass)=@_;
                   9823:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9824:     my $allowed;
                   9825:     if (&allowed('mau',$udom)) {
                   9826:         $allowed = 1;
                   9827:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9828:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9829:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9830:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9831:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9832:         if (($cdom ne '') && ($cnum ne '')) {
                   9833:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9834:             if ($is_owner) {
                   9835:                 $allowed = 1;
                   9836:             }
                   9837:         }
                   9838:     }
                   9839:     unless ($allowed) { return 'refused'; }
1.197     www      9840:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9841:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9842:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9843:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9844: 		     &escape($upass),$uhome);
1.620     albertel 9845:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9846:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9847:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9848:     &log($udom,,$uname,$uhome,
1.620     albertel 9849:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9850:                                      $env{'user.name'}.', '.$umode.
1.197     www      9851:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9852:     unless ($reply eq 'ok') {
1.197     www      9853:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9854: 	return 'error: '.$reply;
                   9855:     }   
1.170     harris41 9856:     return 'ok';
1.80      www      9857: }
                   9858: 
1.81      www      9859: # --------------------------------------------------------------- Modify a user
1.80      www      9860: 
1.81      www      9861: sub modifyuser {
1.206     matthew  9862:     my ($udom,    $uname, $uid,
                   9863:         $umode,   $upass, $first,
                   9864:         $middle,  $last,  $gene,
1.1058    raeburn  9865:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9866:     $udom= &LONCAPA::clean_domain($udom);
                   9867:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9868:     my $showcandelete = 'none';
                   9869:     if (ref($candelete) eq 'ARRAY') {
                   9870:         if (@{$candelete} > 0) {
                   9871:             $showcandelete = join(', ',@{$candelete});
                   9872:         }
                   9873:     }
1.81      www      9874:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9875:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9876: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9877:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9878:                                      ' desiredhome not specified'). 
1.620     albertel 9879:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9880:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9881:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9882:     my $newuser;
                   9883:     if ($uhome eq 'no_host') {
                   9884:         $newuser = 1;
                   9885:     }
1.80      www      9886: # ----------------------------------------------------------------- Create User
1.406     albertel 9887:     if (($uhome eq 'no_host') && 
                   9888: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9889:         my $unhome='';
1.844     albertel 9890:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9891:             $unhome = $desiredhome;
1.620     albertel 9892: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9893: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9894:         } else { # load balancing routine for determining $unhome
1.81      www      9895:             my $loadm=10000000;
1.841     albertel 9896: 	    my %servers = &get_servers($udom,'library');
                   9897: 	    foreach my $tryserver (keys(%servers)) {
                   9898: 		my $answer=reply('load',$tryserver);
                   9899: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9900: 		    $loadm=$answer;
                   9901: 		    $unhome=$tryserver;
                   9902: 		}
1.80      www      9903: 	    }
                   9904:         }
                   9905:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9906: 	    return 'error: unable to find a home server for '.$uname.
                   9907:                    ' in domain '.$udom;
1.80      www      9908:         }
                   9909:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9910:                          &escape($upass),$unhome);
                   9911: 	unless ($reply eq 'ok') {
                   9912:             return 'error: '.$reply;
                   9913:         }   
1.230     stredwic 9914:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9915:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9916: 	    return 'error: unable verify users home machine.';
1.80      www      9917:         }
1.209     matthew  9918:     }   # End of creation of new user
1.80      www      9919: # ---------------------------------------------------------------------- Add ID
                   9920:     if ($uid) {
                   9921:        $uid=~tr/A-Z/a-z/;
                   9922:        my %uidhash=&idrget($udom,$uname);
1.196     www      9923:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9924:          && (!$forceid)) {
1.80      www      9925: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9926: 	      return 'error: user id "'.$uid.'" does not match '.
                   9927:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9928:           }
                   9929:        } else {
                   9930: 	  &idput($udom,($uname => $uid));
                   9931:        }
                   9932:     }
                   9933: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9934:     my @tmp=&get('environment',
1.899     raeburn  9935: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9936:                     'permanentemail','inststatus'],
1.134     albertel 9937: 		   $udom,$uname);
1.1075    raeburn  9938:     my (%names,%oldnames);
1.313     matthew  9939:     if ($tmp[0] =~ m/^error:.*/) { 
                   9940:         %names=(); 
                   9941:     } else {
                   9942:         %names = @tmp;
1.1075    raeburn  9943:         %oldnames = %names;
1.313     matthew  9944:     }
1.388     www      9945: #
1.1058    raeburn  9946: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9947: # of users did not contain them), do not overwrite existing values
                   9948: # unless field is in $candelete array ref.  
                   9949: #
                   9950: 
                   9951:     my @fields = ('firstname','middlename','lastname','generation',
                   9952:                   'permanentemail','id');
                   9953:     my %newvalues;
                   9954:     if (ref($candelete) eq 'ARRAY') {
                   9955:         foreach my $field (@fields) {
                   9956:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9957:                 if ($field eq 'firstname') {
                   9958:                     $names{$field} = $first;
                   9959:                 } elsif ($field eq 'middlename') {
                   9960:                     $names{$field} = $middle;
                   9961:                 } elsif ($field eq 'lastname') {
                   9962:                     $names{$field} = $last;
                   9963:                 } elsif ($field eq 'generation') { 
                   9964:                     $names{$field} = $gene;
                   9965:                 } elsif ($field eq 'permanentemail') {
                   9966:                     $names{$field} = $email;
                   9967:                 } elsif ($field eq 'id') {
                   9968:                     $names{$field}  = $uid;
                   9969:                 }
                   9970:             }
                   9971:         }
                   9972:     }
1.388     www      9973:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9974:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9975:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9976:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9977:     if ($email) {
                   9978:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9979:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9980:     }
1.899     raeburn  9981:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9982:     if (defined($inststatus)) {
                   9983:         $names{'inststatus'} = '';
                   9984:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9985:         if (ref($usertypes) eq 'HASH') {
                   9986:             my @okstatuses; 
                   9987:             foreach my $item (split(/:/,$inststatus)) {
                   9988:                 if (defined($usertypes->{$item})) {
                   9989:                     push(@okstatuses,$item);  
                   9990:                 }
                   9991:             }
                   9992:             if (@okstatuses) {
                   9993:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9994:             }
                   9995:         }
                   9996:     }
1.1075    raeburn  9997:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9998:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9999:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10000:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10001:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10002:     } else {
                   10003:         $logmsg .= ' during self creation';
                   10004:     }
1.1075    raeburn  10005:     my $changed;
                   10006:     if ($newuser) {
                   10007:         $changed = 1;
                   10008:     } else {
                   10009:         foreach my $field (@fields) {
                   10010:             if ($names{$field} ne $oldnames{$field}) {
                   10011:                 $changed = 1;
                   10012:                 last;
                   10013:             }
                   10014:         }
                   10015:     }
                   10016:     unless ($changed) {
                   10017:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10018:         &logthis($logmsg);
                   10019:         return 'ok';
                   10020:     }
                   10021:     my $reply = &put('environment', \%names, $udom,$uname);
                   10022:     if ($reply ne 'ok') { 
                   10023:         return 'error: '.$reply;
                   10024:     }
1.1087    raeburn  10025:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10026:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10027:     }
1.1075    raeburn  10028:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10029:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10030:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10031:     &logthis($logmsg);
1.134     albertel 10032:     return 'ok';
1.80      www      10033: }
                   10034: 
1.81      www      10035: # -------------------------------------------------------------- Modify student
1.80      www      10036: 
1.81      www      10037: sub modifystudent {
                   10038:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10039:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10040:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10041:     if (!$cid) {
1.620     albertel 10042: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10043: 	    return 'not_in_class';
                   10044: 	}
1.80      www      10045:     }
                   10046: # --------------------------------------------------------------- Make the user
1.81      www      10047:     my $reply=&modifyuser
1.209     matthew  10048: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10049:          $desiredhome,$email,$inststatus);
1.80      www      10050:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10051:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10052:     # student's environment
1.297     matthew  10053:     $uid = undef if (!$forceid);
1.455     albertel 10054:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10055: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10056:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10057:     return $reply;
                   10058: }
                   10059: 
                   10060: sub modify_student_enrollment {
1.1172.2.23  raeburn  10061:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10062:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10063:     my ($cdom,$cnum,$chome);
                   10064:     if (!$cid) {
1.620     albertel 10065: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10066: 	    return 'not_in_class';
                   10067: 	}
1.620     albertel 10068: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10069: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10070:     } else {
                   10071: 	($cdom,$cnum)=split(/_/,$cid);
                   10072:     }
1.620     albertel 10073:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10074:     if (!$chome) {
1.457     raeburn  10075: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10076:     }
1.455     albertel 10077:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10078:     # Make sure the user exists
1.81      www      10079:     my $uhome=&homeserver($uname,$udom);
                   10080:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10081: 	return 'error: no such user';
                   10082:     }
1.297     matthew  10083:     # Get student data if we were not given enough information
                   10084:     if (!defined($first)  || $first  eq '' || 
                   10085:         !defined($last)   || $last   eq '' || 
                   10086:         !defined($uid)    || $uid    eq '' || 
                   10087:         !defined($middle) || $middle eq '' || 
                   10088:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10089:         # They did not supply us with enough data to enroll the student, so
                   10090:         # we need to pick up more information.
1.297     matthew  10091:         my %tmp = &get('environment',
1.294     matthew  10092:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10093:                        ,$udom,$uname);
                   10094: 
1.800     albertel 10095:         #foreach my $key (keys(%tmp)) {
                   10096:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10097:         #}
1.294     matthew  10098:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10099:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10100:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10101:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10102:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10103:     }
1.556     albertel 10104:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10105:     my $user = "$uname:$udom";
                   10106:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10107:     my $reply=cput('classlist',
1.1148    raeburn  10108: 		   {$user => 
1.1172.2.76  raeburn  10109: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10110: 		   $cdom,$cnum);
1.1148    raeburn  10111:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10112:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10113:     } else { 
1.81      www      10114: 	return 'error: '.$reply;
                   10115:     }
1.297     matthew  10116:     # Add student role to user
1.83      www      10117:     my $uurl='/'.$cid;
1.81      www      10118:     $uurl=~s/\_/\//g;
                   10119:     if ($usec) {
                   10120: 	$uurl.='/'.$usec;
                   10121:     }
1.1148    raeburn  10122:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10123:                              $selfenroll,$context);
                   10124:     if ($result ne 'ok') {
                   10125:         if ($old_entry{$user} ne '') {
                   10126:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10127:         } else {
                   10128:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10129:         }
                   10130:     }
                   10131:     return $result; 
1.21      www      10132: }
                   10133: 
1.556     albertel 10134: sub format_name {
                   10135:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10136:     my $name;
                   10137:     if ($first ne 'lastname') {
                   10138: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10139:     } else {
                   10140: 	if ($lastname=~/\S/) {
                   10141: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10142: 	    $name=~s/\s+,/,/;
                   10143: 	} else {
                   10144: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10145: 	}
                   10146:     }
                   10147:     $name=~s/^\s+//;
                   10148:     $name=~s/\s+$//;
                   10149:     $name=~s/\s+/ /g;
                   10150:     return $name;
                   10151: }
                   10152: 
1.84      www      10153: # ------------------------------------------------- Write to course preferences
                   10154: 
                   10155: sub writecoursepref {
                   10156:     my ($courseid,%prefs)=@_;
                   10157:     $courseid=~s/^\///;
                   10158:     $courseid=~s/\_/\//g;
                   10159:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10160:     my $chome=homeserver($cnum,$cdomain);
                   10161:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10162: 	return 'error: no such course';
                   10163:     }
                   10164:     my $cstring='';
1.800     albertel 10165:     foreach my $pref (keys(%prefs)) {
                   10166: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10167:     }
1.84      www      10168:     $cstring=~s/\&$//;
                   10169:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10170: }
                   10171: 
                   10172: # ---------------------------------------------------------- Make/modify course
                   10173: 
                   10174: sub createcourse {
1.741     raeburn  10175:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10176:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10177:     $url=&declutter($url);
                   10178:     my $cid='';
1.1028    raeburn  10179:     if ($context eq 'requestcourses') {
                   10180:         my $can_create = 0;
                   10181:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10182:         if ($udom eq $ownerdom) {
                   10183:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10184:                                   $context)) {
                   10185:                 $can_create = 1;
                   10186:             }
                   10187:         } else {
                   10188:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10189:                                            $category);
                   10190:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10191:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10192:                 if (@curr > 0) {
                   10193:                     my @options = qw(approval validate autolimit);
                   10194:                     my $optregex = join('|',@options);
                   10195:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10196:                         $can_create = 1;
                   10197:                     }
                   10198:                 }
                   10199:             }
                   10200:         }
                   10201:         if ($can_create) {
                   10202:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10203:                 unless (&allowed('ccc',$udom)) {
                   10204:                     return 'refused'; 
                   10205:                 }
1.1017    raeburn  10206:             }
                   10207:         } else {
                   10208:             return 'refused';
                   10209:         }
1.1028    raeburn  10210:     } elsif (!&allowed('ccc',$udom)) {
                   10211:         return 'refused';
1.84      www      10212:     }
1.1011    raeburn  10213: # --------------------------------------------------------------- Get Unique ID
                   10214:     my $uname;
                   10215:     if ($cnum =~ /^$match_courseid$/) {
                   10216:         my $chome=&homeserver($cnum,$udom,'true');
                   10217:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10218:             $uname = $cnum;
                   10219:         } else {
1.1038    raeburn  10220:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10221:         }
                   10222:     } else {
1.1038    raeburn  10223:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10224:     }
                   10225:     return $uname if ($uname =~ /^error/);
                   10226: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10227:     if (!defined($course_server)) {
                   10228:         if (defined(&domain($udom,'primary'))) {
                   10229:             $course_server = &domain($udom,'primary');
                   10230:         } else {
                   10231:             $course_server = $env{'user.home'}; 
                   10232:         }
                   10233:     }
                   10234:     my %host_servers =
                   10235:         &Apache::lonnet::get_servers($udom,'library');
                   10236:     unless ($host_servers{$course_server}) {
                   10237:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10238:     }
1.84      www      10239: # ------------------------------------------------------------- Make the course
                   10240:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10241:                       $course_server);
1.84      www      10242:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10243:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10244:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10245: 	return 'error: no such course';
                   10246:     }
1.271     www      10247: # ----------------------------------------------------------------- Course made
1.516     raeburn  10248: # log existence
1.1029    raeburn  10249:     my $now = time;
1.918     raeburn  10250:     my $newcourse = {
                   10251:                     $udom.'_'.$uname => {
1.921     raeburn  10252:                                      description => $description,
                   10253:                                      inst_code   => $inst_code,
                   10254:                                      owner       => $course_owner,
                   10255:                                      type        => $crstype,
1.1029    raeburn  10256:                                      creator     => $env{'user.name'}.':'.
                   10257:                                                     $env{'user.domain'},
                   10258:                                      created     => $now,
                   10259:                                      context     => $context,
1.918     raeburn  10260:                                                 },
                   10261:                     };
1.921     raeburn  10262:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10263: # set toplevel url
1.271     www      10264:     my $topurl=$url;
                   10265:     unless ($nonstandard) {
                   10266: # ------------------------------------------ For standard courses, make top url
                   10267:         my $mapurl=&clutter($url);
1.278     www      10268:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10269:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10270: <map>
                   10271: <resource id="1" type="start"></resource>
                   10272: <resource id="2" src="$mapurl"></resource>
                   10273: <resource id="3" type="finish"></resource>
                   10274: <link index="1" from="1" to="2"></link>
                   10275: <link index="2" from="2" to="3"></link>
                   10276: </map>
                   10277: ENDINITMAP
                   10278:         $topurl=&declutter(
1.638     albertel 10279:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10280:                           );
                   10281:     }
                   10282: # ----------------------------------------------------------- Write preferences
1.84      www      10283:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10284:                      ('description'              => $description,
                   10285:                       'url'                      => $topurl,
                   10286:                       'internal.creator'         => $env{'user.name'}.':'.
                   10287:                                                     $env{'user.domain'},
                   10288:                       'internal.created'         => $now,
                   10289:                       'internal.creationcontext' => $context)
                   10290:                     );
1.84      www      10291:     return '/'.$udom.'/'.$uname;
                   10292: }
                   10293: 
1.1011    raeburn  10294: # ------------------------------------------------------------------- Create ID
                   10295: sub generate_coursenum {
1.1038    raeburn  10296:     my ($udom,$crstype) = @_;
1.1011    raeburn  10297:     my $domdesc = &domain($udom);
                   10298:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10299:     my $first;
                   10300:     if ($crstype eq 'Community') {
                   10301:         $first = '0';
                   10302:     } else {
                   10303:         $first = int(1+rand(9)); 
                   10304:     } 
                   10305:     my $uname=$first.
1.1011    raeburn  10306:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10307:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10308:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10309: # ----------------------------------------------- Make sure that does not exist
                   10310:     my $uhome=&homeserver($uname,$udom,'true');
                   10311:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10312:         if ($crstype eq 'Community') {
                   10313:             $first = '0';
                   10314:         } else {
                   10315:             $first = int(1+rand(9));
                   10316:         }
                   10317:         $uname=$first.
1.1011    raeburn  10318:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10319:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10320:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10321:         $uhome=&homeserver($uname,$udom,'true');
                   10322:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10323:             return 'error: unable to generate unique course-ID';
                   10324:         }
                   10325:     }
                   10326:     return $uname;
                   10327: }
                   10328: 
1.813     albertel 10329: sub is_course {
1.1167    droeschl 10330:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10331:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10332:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10333:     my $uhome=&homeserver($cnum,$cdom);
                   10334:     my $iscourse;
                   10335:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10336:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10337:     } else {
                   10338:         my $hashid = $cdom.':'.$cnum;
                   10339:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10340:         unless (defined($cached)) {
                   10341:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10342:                                         $cnum,undef,undef,'.');
                   10343:             $iscourse = 0;
                   10344:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10345:                 $iscourse = 1;
                   10346:             }
                   10347:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10348:         }
                   10349:     }
                   10350:     return unless($iscourse);
1.1167    droeschl 10351:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10352: }
                   10353: 
1.1015    raeburn  10354: sub store_userdata {
                   10355:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10356:     my $result;
1.1016    raeburn  10357:     if ($datakey ne '') {
1.1013    raeburn  10358:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10359:             if ($udom eq '' || $uname eq '') {
                   10360:                 $udom = $env{'user.domain'};
                   10361:                 $uname = $env{'user.name'};
                   10362:             }
                   10363:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10364:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10365:                 $result = 'error: no_host';
                   10366:             } else {
                   10367:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10368:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10369: 
                   10370:                 my $namevalue='';
                   10371:                 foreach my $key (keys(%{$storehash})) {
                   10372:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10373:                 }
                   10374:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10375:                 unless ($namespace eq 'courserequests') {
                   10376:                     $datakey = &escape($datakey);
                   10377:                 }
1.1105    raeburn  10378:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10379:                                   $namevalue,$uhome);
1.1013    raeburn  10380:             }
                   10381:         } else {
                   10382:             $result = 'error: data to store was not a hash reference'; 
                   10383:         }
                   10384:     } else {
                   10385:         $result= 'error: invalid requestkey'; 
                   10386:     }
                   10387:     return $result;
                   10388: }
                   10389: 
1.21      www      10390: # ---------------------------------------------------------- Assign Custom Role
                   10391: 
                   10392: sub assigncustomrole {
1.957     raeburn  10393:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10394:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10395:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10396: }
                   10397: 
                   10398: # ----------------------------------------------------------------- Revoke Role
                   10399: 
                   10400: sub revokerole {
1.957     raeburn  10401:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10402:     my $now=time;
1.965     raeburn  10403:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10404: }
                   10405: 
                   10406: # ---------------------------------------------------------- Revoke Custom Role
                   10407: 
                   10408: sub revokecustomrole {
1.957     raeburn  10409:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10410:     my $now=time;
1.357     www      10411:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10412:            $deleteflag,$selfenroll,$context);
1.17      www      10413: }
                   10414: 
1.533     banghart 10415: # ------------------------------------------------------------ Disk usage
1.535     albertel 10416: sub diskusage {
1.955     raeburn  10417:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10418:     $directorypath =~ s/\/$//;
                   10419:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10420:                        .&escape($getpropath).':'.&escape($uname).':'
                   10421:                        .&escape($udom),homeserver($uname,$udom));
                   10422:     if ($listing eq 'unknown_cmd') {
                   10423:         if ($getpropath) {
                   10424:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10425:         }
                   10426:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10427:     }
1.514     albertel 10428:     return $listing;
1.512     banghart 10429: }
                   10430: 
1.566     banghart 10431: sub is_locked {
1.1096    raeburn  10432:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10433:     my @check;
                   10434:     my $is_locked;
1.1093    raeburn  10435:     push (@check,$file_name);
1.613     albertel 10436:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10437: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10438:     my ($tmp)=keys(%locked);
                   10439:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10440:     
1.566     banghart 10441:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10442:         $is_locked = 'false';
                   10443:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10444:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10445:                $is_locked = 'true';
1.1096    raeburn  10446:                if (ref($which) eq 'ARRAY') {
                   10447:                    push(@{$which},$entry);
                   10448:                } else {
                   10449:                    last;
                   10450:                }
1.745     raeburn  10451:            }
                   10452:        }
1.566     banghart 10453:     } else {
                   10454:         $is_locked = 'false';
                   10455:     }
1.1093    raeburn  10456:     return $is_locked;
1.566     banghart 10457: }
                   10458: 
1.759     albertel 10459: sub declutter_portfile {
                   10460:     my ($file) = @_;
1.833     albertel 10461:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10462:     return $file;
                   10463: }
                   10464: 
1.559     banghart 10465: # ------------------------------------------------------------- Mark as Read Only
                   10466: 
                   10467: sub mark_as_readonly {
                   10468:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10469:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10470:     my ($tmp)=keys(%current_permissions);
                   10471:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10472:     foreach my $file (@{$files}) {
1.759     albertel 10473: 	$file = &declutter_portfile($file);
1.561     banghart 10474:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10475:     }
1.613     albertel 10476:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10477:     return;
                   10478: }
                   10479: 
1.572     banghart 10480: # ------------------------------------------------------------Save Selected Files
                   10481: 
                   10482: sub save_selected_files {
                   10483:     my ($user, $path, @files) = @_;
                   10484:     my $filename = $user."savedfiles";
1.573     banghart 10485:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10486:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10487:     foreach my $file (@files) {
1.620     albertel 10488:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10489:     }
                   10490:     foreach my $file (@other_files) {
1.574     banghart 10491:         print (OUT $file."\n");
1.572     banghart 10492:     }
1.574     banghart 10493:     close (OUT);
1.572     banghart 10494:     return 'ok';
                   10495: }
                   10496: 
1.574     banghart 10497: sub clear_selected_files {
                   10498:     my ($user) = @_;
                   10499:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10500:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10501:     print (OUT undef);
                   10502:     close (OUT);
                   10503:     return ("ok");    
                   10504: }
                   10505: 
1.572     banghart 10506: sub files_in_path {
                   10507:     my ($user, $path) = @_;
                   10508:     my $filename = $user."savedfiles";
                   10509:     my %return_files;
1.1172.2.96  raeburn  10510:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10511:     while (my $line_in = <IN>) {
1.574     banghart 10512:         chomp ($line_in);
                   10513:         my @paths_and_file = split (m!/!, $line_in);
                   10514:         my $file_part = pop (@paths_and_file);
                   10515:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10516:         $path_part.='/';
                   10517:         my $path_and_file = $path_part.$file_part;
                   10518:         if ($path_part eq $path) {
                   10519:             $return_files{$file_part}= 'selected';
                   10520:         }
                   10521:     }
1.574     banghart 10522:     close (IN);
                   10523:     return (\%return_files);
1.572     banghart 10524: }
                   10525: 
                   10526: # called in portfolio select mode, to show files selected NOT in current directory
                   10527: sub files_not_in_path {
                   10528:     my ($user, $path) = @_;
                   10529:     my $filename = $user."savedfiles";
                   10530:     my @return_files;
                   10531:     my $path_part;
1.1172.2.96  raeburn  10532:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10533:     while (my $line = <IN>) {
1.572     banghart 10534:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10535:         my @paths_and_file = split(m|/|, $line);
                   10536:         my $file_part = pop(@paths_and_file);
                   10537:         chomp($file_part);
                   10538:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10539:         $path_part .= '/';
                   10540:         my $path_and_file = $path_part.$file_part;
                   10541:         if ($path_part ne $path) {
1.800     albertel 10542:             push(@return_files, ($path_and_file));
1.572     banghart 10543:         }
                   10544:     }
1.800     albertel 10545:     close(OUT);
1.574     banghart 10546:     return (@return_files);
1.572     banghart 10547: }
                   10548: 
1.745     raeburn  10549: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10550: 
1.745     raeburn  10551: sub get_portfile_permissions {
                   10552:     my ($domain,$user) = @_;
1.613     albertel 10553:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10554:     my ($tmp)=keys(%current_permissions);
                   10555:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10556:     return \%current_permissions;
                   10557: }
                   10558: 
                   10559: #---------------------------------------------Get portfolio file access controls
                   10560: 
1.749     raeburn  10561: sub get_access_controls {
1.745     raeburn  10562:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10563:     my %access;
                   10564:     my $real_file = $file;
                   10565:     $file =~ s/\.meta$//;
1.745     raeburn  10566:     if (defined($file)) {
1.749     raeburn  10567:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10568:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10569:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10570:             }
                   10571:         }
1.745     raeburn  10572:     } else {
1.749     raeburn  10573:         foreach my $key (keys(%{$current_permissions})) {
                   10574:             if ($key =~ /\0accesscontrol$/) {
                   10575:                 if (defined($group)) {
                   10576:                     if ($key !~ m-^\Q$group\E/-) {
                   10577:                         next;
                   10578:                     }
                   10579:                 }
                   10580:                 my ($fullpath) = split(/\0/,$key);
                   10581:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10582:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10583:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10584:                     }
                   10585:                 }
                   10586:             }
                   10587:         }
                   10588:     }
                   10589:     return %access;
                   10590: }
                   10591: 
                   10592: sub modify_access_controls {
                   10593:     my ($file_name,$changes,$domain,$user)=@_;
                   10594:     my ($outcome,$deloutcome);
                   10595:     my %store_permissions;
                   10596:     my %new_values;
                   10597:     my %new_control;
                   10598:     my %translation;
                   10599:     my @deletions = ();
                   10600:     my $now = time;
                   10601:     if (exists($$changes{'activate'})) {
                   10602:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10603:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10604:             my $numnew = scalar(@newitems);
                   10605:             for (my $i=0; $i<$numnew; $i++) {
                   10606:                 my $newkey = $newitems[$i];
                   10607:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10608:                 if ($newkey =~ /^\d+:/) { 
                   10609:                     $newkey =~ s/^(\d+)/$newid/;
                   10610:                     $translation{$1} = $newid;
                   10611:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10612:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10613:                     $translation{$1} = $newid;
                   10614:                 }
1.749     raeburn  10615:                 $new_values{$file_name."\0".$newkey} = 
                   10616:                                           $$changes{'activate'}{$newitems[$i]};
                   10617:                 $new_control{$newkey} = $now;
                   10618:             }
                   10619:         }
                   10620:     }
                   10621:     my %todelete;
                   10622:     my %changed_items;
                   10623:     foreach my $action ('delete','update') {
                   10624:         if (exists($$changes{$action})) {
                   10625:             if (ref($$changes{$action}) eq 'HASH') {
                   10626:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10627:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10628:                     if ($action eq 'delete') { 
                   10629:                         $todelete{$itemnum} = 1;
                   10630:                     } else {
                   10631:                         $changed_items{$itemnum} = $key;
                   10632:                     }
                   10633:                 }
1.745     raeburn  10634:             }
                   10635:         }
1.749     raeburn  10636:     }
                   10637:     # get lock on access controls for file.
                   10638:     my $lockhash = {
                   10639:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10640:                                                        ':'.$env{'user.domain'},
                   10641:                    }; 
                   10642:     my $tries = 0;
                   10643:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10644:    
1.1172.2.79  raeburn  10645:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10646:         $tries ++;
1.1172.2.79  raeburn  10647:         sleep(0.1);
1.749     raeburn  10648:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10649:     }
                   10650:     if ($gotlock eq 'ok') {
                   10651:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10652:         my ($tmp)=keys(%curr_permissions);
                   10653:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10654:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10655:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10656:             if (ref($curr_controls) eq 'HASH') {
                   10657:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10658:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10659:                     if (defined($todelete{$itemnum})) {
                   10660:                         push(@deletions,$file_name."\0".$control_item);
                   10661:                     } else {
                   10662:                         if (defined($changed_items{$itemnum})) {
                   10663:                             $new_control{$changed_items{$itemnum}} = $now;
                   10664:                             push(@deletions,$file_name."\0".$control_item);
                   10665:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10666:                         } else {
                   10667:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10668:                         }
                   10669:                     }
1.745     raeburn  10670:                 }
                   10671:             }
                   10672:         }
1.970     raeburn  10673:         my ($group);
                   10674:         if (&is_course($domain,$user)) {
                   10675:             ($group,my $file) = split(/\//,$file_name,2);
                   10676:         }
1.749     raeburn  10677:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10678:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10679:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10680:         #  remove lock
                   10681:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10682:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10683:         my $sqlresult =
1.970     raeburn  10684:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10685:                                     $group);
1.749     raeburn  10686:     } else {
                   10687:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10688:     }
1.749     raeburn  10689:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10690: }
                   10691: 
1.827     raeburn  10692: sub make_public_indefinitely {
                   10693:     my ($requrl) = @_;
                   10694:     my $now = time;
                   10695:     my $action = 'activate';
                   10696:     my $aclnum = 0;
                   10697:     if (&is_portfolio_url($requrl)) {
                   10698:         my (undef,$udom,$unum,$file_name,$group) =
                   10699:             &parse_portfolio_url($requrl);
                   10700:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10701:         my %access_controls = &get_access_controls($current_perms,
                   10702:                                                    $group,$file_name);
                   10703:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10704:             my ($num,$scope,$end,$start) = 
                   10705:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10706:             if ($scope eq 'public') {
                   10707:                 if ($start <= $now && $end == 0) {
                   10708:                     $action = 'none';
                   10709:                 } else {
                   10710:                     $action = 'update';
                   10711:                     $aclnum = $num;
                   10712:                 }
                   10713:                 last;
                   10714:             }
                   10715:         }
                   10716:         if ($action eq 'none') {
                   10717:              return 'ok';
                   10718:         } else {
                   10719:             my %changes;
                   10720:             my $newend = 0;
                   10721:             my $newstart = $now;
                   10722:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10723:             $changes{$action}{$newkey} = {
                   10724:                 type => 'public',
                   10725:                 time => {
                   10726:                     start => $newstart,
                   10727:                     end   => $newend,
                   10728:                 },
                   10729:             };
                   10730:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10731:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10732:             return $outcome;
                   10733:         }
                   10734:     } else {
                   10735:         return 'invalid';
                   10736:     }
                   10737: }
                   10738: 
1.745     raeburn  10739: #------------------------------------------------------Get Marked as Read Only
                   10740: 
                   10741: sub get_marked_as_readonly {
                   10742:     my ($domain,$user,$what,$group) = @_;
                   10743:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10744:     my @readonly_files;
1.629     banghart 10745:     my $cmp1=$what;
                   10746:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10747:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10748:         if (defined($group)) {
                   10749:             if ($file_name !~ m-^\Q$group\E/-) {
                   10750:                 next;
                   10751:             }
                   10752:         }
1.561     banghart 10753:         if (ref($value) eq "ARRAY"){
                   10754:             foreach my $stored_what (@{$value}) {
1.629     banghart 10755:                 my $cmp2=$stored_what;
1.759     albertel 10756:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10757:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10758:                 }
1.629     banghart 10759:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10760:                     push(@readonly_files, $file_name);
1.745     raeburn  10761:                     last;
1.563     banghart 10762:                 } elsif (!defined($what)) {
                   10763:                     push(@readonly_files, $file_name);
1.745     raeburn  10764:                     last;
1.561     banghart 10765:                 }
                   10766:             }
1.745     raeburn  10767:         }
1.561     banghart 10768:     }
                   10769:     return @readonly_files;
                   10770: }
1.577     banghart 10771: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10772: 
1.577     banghart 10773: sub get_marked_as_readonly_hash {
1.745     raeburn  10774:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10775:     my %readonly_files;
1.745     raeburn  10776:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10777:         if (defined($group)) {
                   10778:             if ($file_name !~ m-^\Q$group\E/-) {
                   10779:                 next;
                   10780:             }
                   10781:         }
1.577     banghart 10782:         if (ref($value) eq "ARRAY"){
                   10783:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10784:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10785:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10786:                         if ($lock_descriptor eq 'graded') {
                   10787:                             $readonly_files{$file_name} = 'graded';
                   10788:                         } elsif ($lock_descriptor eq 'handback') {
                   10789:                             $readonly_files{$file_name} = 'handback';
                   10790:                         } else {
                   10791:                             if (!exists($readonly_files{$file_name})) {
                   10792:                                 $readonly_files{$file_name} = 'locked';
                   10793:                             }
                   10794:                         }
1.745     raeburn  10795:                     }
1.750     banghart 10796:                 } 
1.577     banghart 10797:             }
                   10798:         } 
                   10799:     }
                   10800:     return %readonly_files;
                   10801: }
1.559     banghart 10802: # ------------------------------------------------------------ Unmark as Read Only
                   10803: 
                   10804: sub unmark_as_readonly {
1.629     banghart 10805:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10806:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10807:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10808:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10809:     my $symb_crs = $what;
                   10810:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10811:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10812:     my ($tmp)=keys(%current_permissions);
                   10813:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10814:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10815:     foreach my $file (@readonly_files) {
1.759     albertel 10816: 	my $clean_file = &declutter_portfile($file);
                   10817: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10818: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10819:         my @new_locks;
                   10820:         my @del_keys;
                   10821:         if (ref($current_locks) eq "ARRAY"){
                   10822:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10823:                 my $compare=$locker;
1.749     raeburn  10824:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10825:                     $compare=join('',@{$locker});
1.746     raeburn  10826:                     if ($compare ne $symb_crs) {
                   10827:                         push(@new_locks, $locker);
                   10828:                     }
1.563     banghart 10829:                 }
                   10830:             }
1.650     albertel 10831:             if (scalar(@new_locks) > 0) {
1.563     banghart 10832:                 $current_permissions{$file} = \@new_locks;
                   10833:             } else {
                   10834:                 push(@del_keys, $file);
1.613     albertel 10835:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10836:                 delete($current_permissions{$file});
1.563     banghart 10837:             }
                   10838:         }
1.561     banghart 10839:     }
1.613     albertel 10840:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10841:     return;
                   10842: }
1.512     banghart 10843: 
1.17      www      10844: # ------------------------------------------------------------ Directory lister
                   10845: 
                   10846: sub dirlist {
1.955     raeburn  10847:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10848:     $uri=~s/^\///;
                   10849:     $uri=~s/\/$//;
1.253     stredwic 10850:     my ($udom, $uname);
1.955     raeburn  10851:     if ($getuserdir) {
1.253     stredwic 10852:         $udom = $userdomain;
                   10853:         $uname = $username;
1.955     raeburn  10854:     } else {
                   10855:         (undef,$udom,$uname)=split(/\//,$uri);
                   10856:         if(defined($userdomain)) {
                   10857:             $udom = $userdomain;
                   10858:         }
                   10859:         if(defined($username)) {
                   10860:             $uname = $username;
                   10861:         }
1.253     stredwic 10862:     }
1.955     raeburn  10863:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10864: 
1.955     raeburn  10865:     $dirRoot = $perlvar{'lonDocRoot'};
                   10866:     if (defined($getpropath)) {
                   10867:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10868:         $dirRoot =~ s/\/$//;
1.955     raeburn  10869:     } elsif (defined($getuserdir)) {
                   10870:         my $subdir=$uname.'__';
                   10871:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10872:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10873:                    ."/$udom/$subdir/$uname";
                   10874:     } elsif (defined($alternateRoot)) {
                   10875:         $dirRoot = $alternateRoot;
1.751     banghart 10876:     }
1.253     stredwic 10877: 
                   10878:     if($udom) {
                   10879:         if($uname) {
1.1135    raeburn  10880:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10881:             if ($uhome eq 'no_host') {
                   10882:                 return ([],'no_host');
                   10883:             }
1.955     raeburn  10884:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10885:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10886:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10887:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10888:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10889:             } else {
                   10890:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10891:             }
1.605     matthew  10892:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10893:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10894:                 @listing_results = split(/:/,$listing);
                   10895:             } else {
                   10896:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10897:             }
1.1135    raeburn  10898:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10899:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10900:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10901:                 return ([],$listing);
                   10902:             } else {
                   10903:                 return (\@listing_results);
1.1135    raeburn  10904:             }
1.955     raeburn  10905:         } elsif(!$alternateRoot) {
1.1136    raeburn  10906:             my (%allusers,%listerror);
1.841     albertel 10907: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10908:  	    foreach my $tryserver (keys(%servers)) {
                   10909:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10910:                                   &escape($udom),$tryserver);
                   10911:                 if ($listing eq 'unknown_cmd') {
                   10912: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10913: 				      $udom, $tryserver);
                   10914:                 } else {
                   10915:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10916:                 }
1.841     albertel 10917: 		if ($listing eq 'unknown_cmd') {
                   10918: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10919: 				      $udom, $tryserver);
                   10920: 		    @listing_results = split(/:/,$listing);
                   10921: 		} else {
                   10922: 		    @listing_results =
                   10923: 			map { &unescape($_); } split(/:/,$listing);
                   10924: 		}
1.1136    raeburn  10925:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10926:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10927:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10928:                     $listerror{$tryserver} = $listing;
                   10929:                 } else {
1.841     albertel 10930: 		    foreach my $line (@listing_results) {
                   10931: 			my ($entry) = split(/&/,$line,2);
                   10932: 			$allusers{$entry} = 1;
                   10933: 		    }
                   10934: 		}
1.253     stredwic 10935:             }
1.1136    raeburn  10936:             my @alluserslist=();
1.800     albertel 10937:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10938:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10939:             }
1.1172.2.80  raeburn  10940:             if (!%listerror) {
                   10941:                 # no errors
                   10942:                 return (\@alluserslist);
                   10943:             } elsif (scalar(keys(%servers)) == 1) {
                   10944:                 # one library server, one error
                   10945:                 my ($key) = keys(%listerror);
                   10946:                 return (\@alluserslist, $listerror{$key});
                   10947:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10948:                 # con_lost indicates that we might miss data from at least one
                   10949:                 # library server
                   10950:                 return (\@alluserslist, 'con_lost');
                   10951:             } else {
                   10952:                 # multiple library servers and no con_lost -> data should be
                   10953:                 # complete.
                   10954:                 return (\@alluserslist);
                   10955:             }
                   10956: 
1.253     stredwic 10957:         } else {
1.1136    raeburn  10958:             return ([],'missing username');
1.253     stredwic 10959:         }
1.955     raeburn  10960:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10961:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10962:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10963:         return (\@all_domains);
1.955     raeburn  10964:     } else {
1.1136    raeburn  10965:         return ([],'missing domain');
1.275     stredwic 10966:     }
                   10967: }
                   10968: 
                   10969: # --------------------------------------------- GetFileTimestamp
                   10970: # This function utilizes dirlist and returns the date stamp for
                   10971: # when it was last modified.  It will also return an error of -1
                   10972: # if an error occurs
                   10973: 
                   10974: sub GetFileTimestamp {
1.955     raeburn  10975:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10976:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10977:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10978:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10979:                                     undef,$getuserdir);
                   10980:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10981:         return -1;
                   10982:     }
                   10983:     if (ref($fileref) eq 'ARRAY') {
                   10984:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10985:         # @stats contains first the filename, then the stat output
                   10986:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10987:     } else {
                   10988:         return -1;
1.253     stredwic 10989:     }
1.26      www      10990: }
                   10991: 
1.712     albertel 10992: sub stat_file {
                   10993:     my ($uri) = @_;
1.787     albertel 10994:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10995: 
1.955     raeburn  10996:     my ($udom,$uname,$file);
1.712     albertel 10997:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10998: 	($udom,$uname,$file) =
1.811     albertel 10999: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11000: 	$file = 'userfiles/'.$file;
                   11001:     }
                   11002:     if ($uri =~ m-^/res/-) {
                   11003: 	($udom,$uname) = 
1.807     albertel 11004: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11005: 	$file = $uri;
                   11006:     }
                   11007: 
                   11008:     if (!$udom || !$uname || !$file) {
                   11009: 	# unable to handle the uri
                   11010: 	return ();
                   11011:     }
1.956     raeburn  11012:     my $getpropath;
                   11013:     if ($file =~ /^userfiles\//) {
                   11014:         $getpropath = 1;
                   11015:     }
1.1136    raeburn  11016:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11017:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11018:         return ();
                   11019:     } else {
                   11020:         if (ref($listref) eq 'ARRAY') {
                   11021:             my @stats = split('&',$listref->[0]);
                   11022: 	    shift(@stats); #filename is first
                   11023: 	    return @stats;
                   11024:         }
1.712     albertel 11025:     }
                   11026:     return ();
                   11027: }
                   11028: 
1.26      www      11029: # -------------------------------------------------------- Value of a Condition
                   11030: 
1.713     albertel 11031: # gets the value of a specific preevaluated condition
                   11032: #    stored in the string  $env{user.state.<cid>}
                   11033: # or looks up a condition reference in the bighash and if if hasn't
                   11034: # already been evaluated recurses into docondval to get the value of
                   11035: # the condition, then memoizing it to 
                   11036: #   $env{user.state.<cid>.<condition>}
1.40      www      11037: sub directcondval {
                   11038:     my $number=shift;
1.620     albertel 11039:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11040: 	&Apache::lonuserstate::evalstate();
                   11041:     }
1.713     albertel 11042:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11043: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11044:     } elsif ($number =~ /^_/) {
                   11045: 	my $sub_condition;
                   11046: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11047: 		&GDBM_READER(),0640)) {
                   11048: 	    $sub_condition=$bighash{'conditions'.$number};
                   11049: 	    untie(%bighash);
                   11050: 	}
                   11051: 	my $value = &docondval($sub_condition);
1.949     raeburn  11052: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11053: 	return $value;
                   11054:     }
1.620     albertel 11055:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11056:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11057:     } else {
                   11058:        return 2;
                   11059:     }
                   11060: }
                   11061: 
1.713     albertel 11062: # get the collection of conditions for this resource
1.26      www      11063: sub condval {
                   11064:     my $condidx=shift;
1.54      www      11065:     my $allpathcond='';
1.713     albertel 11066:     foreach my $cond (split(/\|/,$condidx)) {
                   11067: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11068: 	    $allpathcond.=
                   11069: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11070: 	}
1.191     harris41 11071:     }
1.54      www      11072:     $allpathcond=~s/\|$//;
1.713     albertel 11073:     return &docondval($allpathcond);
                   11074: }
                   11075: 
                   11076: #evaluates an expression of conditions
                   11077: sub docondval {
                   11078:     my ($allpathcond) = @_;
                   11079:     my $result=0;
                   11080:     if ($env{'request.course.id'}
                   11081: 	&& defined($allpathcond)) {
                   11082: 	my $operand='|';
                   11083: 	my @stack;
                   11084: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11085: 	    if ($chunk eq '(') {
                   11086: 		push @stack,($operand,$result);
                   11087: 	    } elsif ($chunk eq ')') {
                   11088: 		my $before=pop @stack;
                   11089: 		if (pop @stack eq '&') {
                   11090: 		    $result=$result>$before?$before:$result;
                   11091: 		} else {
                   11092: 		    $result=$result>$before?$result:$before;
                   11093: 		}
                   11094: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11095: 		$operand=$chunk;
                   11096: 	    } else {
                   11097: 		my $new=directcondval($chunk);
                   11098: 		if ($operand eq '&') {
                   11099: 		    $result=$result>$new?$new:$result;
                   11100: 		} else {
                   11101: 		    $result=$result>$new?$result:$new;
                   11102: 		}
                   11103: 	    }
                   11104: 	}
1.26      www      11105:     }
                   11106:     return $result;
1.421     albertel 11107: }
                   11108: 
                   11109: # ---------------------------------------------------- Devalidate courseresdata
                   11110: 
                   11111: sub devalidatecourseresdata {
                   11112:     my ($coursenum,$coursedomain)=@_;
                   11113:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11114:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11115: }
                   11116: 
1.763     www      11117: 
1.200     www      11118: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11119: #
                   11120: #  Parameters:
                   11121: #      $coursenum    - Number of the course.
                   11122: #      $coursedomain - Domain at which the course was created.
                   11123: #  Returns:
                   11124: #     A hash of the course parameters along (I think) with timestamps
                   11125: #     and version info.
1.877     foxr     11126: 
1.624     albertel 11127: sub get_courseresdata {
                   11128:     my ($coursenum,$coursedomain)=@_;
1.200     www      11129:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11130:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11131:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11132:     my %dumpreply;
1.417     albertel 11133:     unless (defined($cached)) {
1.624     albertel 11134: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11135: 	$result=\%dumpreply;
1.251     albertel 11136: 	my ($tmp) = keys(%dumpreply);
                   11137: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11138: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11139: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11140: 	    return $tmp;
1.416     albertel 11141: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11142: 	    $result=undef;
1.599     albertel 11143: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11144: 	}
                   11145:     }
1.624     albertel 11146:     return $result;
                   11147: }
                   11148: 
1.633     albertel 11149: sub devalidateuserresdata {
                   11150:     my ($uname,$udom)=@_;
                   11151:     my $hashid="$udom:$uname";
                   11152:     &devalidate_cache_new('userres',$hashid);
                   11153: }
                   11154: 
1.624     albertel 11155: sub get_userresdata {
                   11156:     my ($uname,$udom)=@_;
                   11157:     #most student don\'t have any data set, check if there is some data
                   11158:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11159: 
                   11160:     my $hashid="$udom:$uname";
                   11161:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11162:     if (!defined($cached)) {
                   11163: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11164: 	$result=\%resourcedata;
                   11165: 	&do_cache_new('userres',$hashid,$result,600);
                   11166:     }
                   11167:     my ($tmp)=keys(%$result);
                   11168:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11169: 	return $result;
                   11170:     }
                   11171:     #error 2 occurs when the .db doesn't exist
                   11172:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11173:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11174: 	    &logthis("<font color=\"blue\">WARNING:".
                   11175: 		     " Trying to get resource data for ".
                   11176: 		     $uname." at ".$udom.": ".
                   11177: 		     $tmp."</font>");
                   11178:         }
1.624     albertel 11179:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11180: 	#&EXT_cache_set($udom,$uname);
                   11181: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11182: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11183:     }
                   11184:     return $tmp;
                   11185: }
1.879     foxr     11186: #----------------------------------------------- resdata - return resource data
                   11187: #  Purpose:
                   11188: #    Return resource data for either users or for a course.
                   11189: #  Parameters:
                   11190: #     $name      - Course/user name.
                   11191: #     $domain    - Name of the domain the user/course is registered on.
                   11192: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11193: #     @which     - Array of names of resources desired.
                   11194: #  Returns:
                   11195: #     The value of the first reasource in @which that is found in the
                   11196: #     resource hash.
                   11197: #  Exceptional Conditions:
                   11198: #     If the $type passed in is not valid (not the string 'course' or 
                   11199: #     'user', an undefined  reference is returned.
                   11200: #     If none of the resources are found, an undef is returned
1.624     albertel 11201: sub resdata {
                   11202:     my ($name,$domain,$type,@which)=@_;
                   11203:     my $result;
                   11204:     if ($type eq 'course') {
                   11205: 	$result=&get_courseresdata($name,$domain);
                   11206:     } elsif ($type eq 'user') {
                   11207: 	$result=&get_userresdata($name,$domain);
                   11208:     }
                   11209:     if (!ref($result)) { return $result; }    
1.251     albertel 11210:     foreach my $item (@which) {
1.927     albertel 11211: 	if (defined($result->{$item->[0]})) {
                   11212: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11213: 	}
1.250     albertel 11214:     }
1.291     albertel 11215:     return undef;
1.200     www      11216: }
                   11217: 
1.1172.2.31  raeburn  11218: sub get_numsuppfiles {
                   11219:     my ($cnum,$cdom,$ignorecache)=@_;
                   11220:     my $hashid=$cnum.':'.$cdom;
                   11221:     my ($suppcount,$cached);
                   11222:     unless ($ignorecache) {
                   11223:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11224:     }
                   11225:     unless (defined($cached)) {
                   11226:         my $chome=&homeserver($cnum,$cdom);
                   11227:         unless ($chome eq 'no_host') {
                   11228:             ($suppcount,my $errors) = (0,0);
                   11229:             my $suppmap = 'supplemental.sequence';
                   11230:             ($suppcount,$errors) =
                   11231:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11232:         }
                   11233:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11234:     }
                   11235:     return $suppcount;
                   11236: }
                   11237: 
1.379     matthew  11238: #
                   11239: # EXT resource caching routines
                   11240: #
                   11241: 
                   11242: sub clear_EXT_cache_status {
1.383     albertel 11243:     &delenv('cache.EXT.');
1.379     matthew  11244: }
                   11245: 
                   11246: sub EXT_cache_status {
                   11247:     my ($target_domain,$target_user) = @_;
1.383     albertel 11248:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11249:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11250:         # We know already the user has no data
                   11251:         return 1;
                   11252:     } else {
                   11253:         return 0;
                   11254:     }
                   11255: }
                   11256: 
                   11257: sub EXT_cache_set {
                   11258:     my ($target_domain,$target_user) = @_;
1.383     albertel 11259:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11260:     #&appenv({$cachename => time});
1.379     matthew  11261: }
                   11262: 
1.28      www      11263: # --------------------------------------------------------- Value of a Variable
1.58      www      11264: sub EXT {
1.715     albertel 11265: 
1.1172.2.28  raeburn  11266:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11267:     unless ($varname) { return ''; }
1.218     albertel 11268:     #get real user name/domain, courseid and symb
                   11269:     my $courseid;
1.359     albertel 11270:     my $publicuser;
1.427     www      11271:     if ($symbparm) {
                   11272: 	$symbparm=&get_symb_from_alias($symbparm);
                   11273:     }
1.218     albertel 11274:     if (!($uname && $udom)) {
1.790     albertel 11275:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11276:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11277:     } else {
1.620     albertel 11278: 	$courseid=$env{'request.course.id'};
1.218     albertel 11279:     }
1.48      www      11280:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11281:     my $rest;
1.320     albertel 11282:     if (defined($therest[0])) {
1.48      www      11283:        $rest=join('.',@therest);
                   11284:     } else {
                   11285:        $rest='';
                   11286:     }
1.320     albertel 11287: 
1.57      www      11288:     my $qualifierrest=$qualifier;
                   11289:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11290:     my $spacequalifierrest=$space;
                   11291:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11292:     if ($realm eq 'user') {
1.48      www      11293: # --------------------------------------------------------------- user.resource
                   11294: 	if ($space eq 'resource') {
1.651     albertel 11295: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11296: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11297: 		 &&
1.744     albertel 11298: 		 ($symbparm eq &symbread()) ) {	
                   11299: 		# if we are in the middle of processing the resource the
                   11300: 		# get the value we are planning on committing
                   11301:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11302:                     return $Apache::lonhomework::results{$qualifierrest};
                   11303:                 } else {
                   11304:                     return $Apache::lonhomework::history{$qualifierrest};
                   11305:                 }
1.335     albertel 11306: 	    } else {
1.359     albertel 11307: 		my %restored;
1.620     albertel 11308: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11309: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11310: 		} else {
                   11311: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11312: 		}
1.335     albertel 11313: 		return $restored{$qualifierrest};
                   11314: 	    }
1.48      www      11315: # ----------------------------------------------------------------- user.access
                   11316:         } elsif ($space eq 'access') {
1.218     albertel 11317: 	    # FIXME - not supporting calls for a specific user
1.48      www      11318:             return &allowed($qualifier,$rest);
                   11319: # ------------------------------------------ user.preferences, user.environment
                   11320:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11321: 	    if (($uname eq $env{'user.name'}) &&
                   11322: 		($udom eq $env{'user.domain'})) {
                   11323: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11324: 	    } else {
1.359     albertel 11325: 		my %returnhash;
                   11326: 		if (!$publicuser) {
                   11327: 		    %returnhash=&userenvironment($udom,$uname,
                   11328: 						 $qualifierrest);
                   11329: 		}
1.218     albertel 11330: 		return $returnhash{$qualifierrest};
                   11331: 	    }
1.48      www      11332: # ----------------------------------------------------------------- user.course
                   11333:         } elsif ($space eq 'course') {
1.218     albertel 11334: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11335:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11336: # ------------------------------------------------------------------- user.role
                   11337:         } elsif ($space eq 'role') {
1.218     albertel 11338: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11339:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11340:             if ($qualifier eq 'value') {
                   11341: 		return $role;
                   11342:             } elsif ($qualifier eq 'extent') {
                   11343:                 return $where;
                   11344:             }
                   11345: # ----------------------------------------------------------------- user.domain
                   11346:         } elsif ($space eq 'domain') {
1.218     albertel 11347:             return $udom;
1.48      www      11348: # ------------------------------------------------------------------- user.name
                   11349:         } elsif ($space eq 'name') {
1.218     albertel 11350:             return $uname;
1.48      www      11351: # ---------------------------------------------------- Any other user namespace
1.29      www      11352:         } else {
1.359     albertel 11353: 	    my %reply;
                   11354: 	    if (!$publicuser) {
                   11355: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11356: 	    }
                   11357: 	    return $reply{$qualifierrest};
1.48      www      11358:         }
1.236     www      11359:     } elsif ($realm eq 'query') {
                   11360: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11361:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11362: 						[$spacequalifierrest]);
1.620     albertel 11363: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11364:    } elsif ($realm eq 'request') {
1.48      www      11365: # ------------------------------------------------------------- request.browser
                   11366:         if ($space eq 'browser') {
1.1145    bisitz   11367:             return $env{'browser.'.$qualifier};
1.57      www      11368: # ------------------------------------------------------------ request.filename
                   11369:         } else {
1.620     albertel 11370:             return $env{'request.'.$spacequalifierrest};
1.29      www      11371:         }
1.28      www      11372:     } elsif ($realm eq 'course') {
1.48      www      11373: # ---------------------------------------------------------- course.description
1.620     albertel 11374:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11375:     } elsif ($realm eq 'resource') {
1.165     www      11376: 
1.620     albertel 11377: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11378: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11379: 	}
1.693     albertel 11380: 
1.1172.2.30  raeburn  11381:         if ($qualifier eq '') {
                   11382: 	    if ($space eq 'title') {
                   11383: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11384: 	        return &gettitle($symbparm);
                   11385: 	    }
1.693     albertel 11386: 	
1.1172.2.30  raeburn  11387: 	    if ($space eq 'map') {
                   11388: 	        my ($map) = &decode_symb($symbparm);
                   11389: 	        return &symbread($map);
                   11390: 	    }
                   11391:             if ($space eq 'maptitle') {
                   11392:                 my ($map) = &decode_symb($symbparm);
                   11393:                 return &gettitle($map);
                   11394:             }
                   11395: 	    if ($space eq 'filename') {
                   11396: 	        if ($symbparm) {
                   11397: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11398: 	        }
                   11399: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11400: 	    }
1.1172.2.30  raeburn  11401: 
                   11402:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11403:                 if ($space eq 'visibleparts') {
                   11404:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11405:                     my $item;
                   11406:                     if (ref($navmap)) {
                   11407:                         my $res = $navmap->getBySymb($symbparm);
                   11408:                         my $parts = $res->parts();
                   11409:                         if (ref($parts) eq 'ARRAY') {
                   11410:                             $item = join(',',@{$parts});
                   11411:                         }
                   11412:                         undef($navmap);
                   11413:                     }
                   11414:                     return $item;
                   11415:                 }
                   11416:             }
                   11417:         }
1.693     albertel 11418: 
                   11419: 	my ($section, $group, @groups);
1.593     albertel 11420: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11421:         if (($courseid eq '') && ($cid)) {
                   11422:             $courseid = $cid;
                   11423:         }
                   11424: 	if (($symbparm && $courseid) && 
                   11425: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11426: 
1.218     albertel 11427: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11428: 
1.60      www      11429: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11430: 	    my $symbp=$symbparm;
1.735     albertel 11431: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11432: 
                   11433: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11434: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11435: 
1.620     albertel 11436: 	    if (($env{'user.name'} eq $uname) &&
                   11437: 		($env{'user.domain'} eq $udom)) {
                   11438: 		$section=$env{'request.course.sec'};
1.733     raeburn  11439:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11440:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11441: 	    } else {
1.539     albertel 11442: 		if (! defined($usection)) {
1.551     albertel 11443: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11444: 		} else {
                   11445: 		    $section = $usection;
                   11446: 		}
1.733     raeburn  11447:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11448: 	    }
                   11449: 
                   11450: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11451: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11452: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11453: 
1.593     albertel 11454: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11455: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11456: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11457: 
1.60      www      11458: # ----------------------------------------------------------- first, check user
1.624     albertel 11459: 
                   11460: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11461: 				       ([$courselevelr,'resource'],
                   11462: 					[$courselevelm,'map'     ],
                   11463: 					[$courselevel, 'course'  ]));
1.931     albertel 11464: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11465: 
1.594     albertel 11466: # ------------------------------------------------ second, check some of course
1.684     raeburn  11467:             my $coursereply;
1.691     raeburn  11468:             if (@groups > 0) {
                   11469:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11470:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11471:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11472:             }
1.96      www      11473: 
1.684     raeburn  11474: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11475: 				  $env{'course.'.$courseid.'.domain'},
                   11476: 				  'course',
                   11477: 				  ([$seclevelr,   'resource'],
                   11478: 				   [$seclevelm,   'map'     ],
                   11479: 				   [$seclevel,    'course'  ],
                   11480: 				   [$courselevelr,'resource']));
                   11481: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11482: 
1.60      www      11483: # ------------------------------------------------------ third, check map parms
1.218     albertel 11484: 	    my %parmhash=();
                   11485: 	    my $thisparm='';
                   11486: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11487: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11488: 		    &GDBM_READER(),0640)) {
1.218     albertel 11489: 		$thisparm=$parmhash{$symbparm};
                   11490: 		untie(%parmhash);
                   11491: 	    }
1.927     albertel 11492: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11493: 	}
1.594     albertel 11494: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11495: 
1.218     albertel 11496: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11497: 	my $filename;
                   11498: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11499: 	if ($symbparm) {
1.409     www      11500: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11501: 	} else {
1.620     albertel 11502: 	    $filename=$env{'request.filename'};
1.282     albertel 11503: 	}
                   11504: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11505: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11506: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11507: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11508: 
1.927     albertel 11509: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11510: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11511: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11512: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11513: 				     $env{'course.'.$courseid.'.domain'},
                   11514: 				     'course',
1.927     albertel 11515: 				     ([$courselevelm,'map'   ],
                   11516: 				      [$courselevel, 'course']));
                   11517: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11518: 	}
1.145     www      11519: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11520: 	unless ($space eq '0') {
1.336     albertel 11521: 	    my @parts=split(/_/,$space);
                   11522: 	    my $id=pop(@parts);
                   11523: 	    my $part=join('_',@parts);
                   11524: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11525: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11526: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11527: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11528: 	}
1.395     albertel 11529: 	if ($recurse) { return undef; }
                   11530: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11531: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11532: # ---------------------------------------------------- Any other user namespace
                   11533:     } elsif ($realm eq 'environment') {
                   11534: # ----------------------------------------------------------------- environment
1.620     albertel 11535: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11536: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11537: 	} else {
1.770     albertel 11538: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11539: 		return '';
                   11540: 	    }
1.219     albertel 11541: 	    my %returnhash=&userenvironment($udom,$uname,
                   11542: 					    $spacequalifierrest);
                   11543: 	    return $returnhash{$spacequalifierrest};
                   11544: 	}
1.28      www      11545:     } elsif ($realm eq 'system') {
1.48      www      11546: # ----------------------------------------------------------------- system.time
                   11547: 	if ($space eq 'time') {
                   11548: 	    return time;
                   11549:         }
1.696     albertel 11550:     } elsif ($realm eq 'server') {
                   11551: # ----------------------------------------------------------------- system.time
                   11552: 	if ($space eq 'name') {
                   11553: 	    return $ENV{'SERVER_NAME'};
                   11554:         }
1.28      www      11555:     }
1.48      www      11556:     return '';
1.61      www      11557: }
                   11558: 
1.927     albertel 11559: sub get_reply {
                   11560:     my ($reply_value) = @_;
1.940     raeburn  11561:     if (ref($reply_value) eq 'ARRAY') {
                   11562:         if (wantarray) {
                   11563: 	    return @$reply_value;
                   11564:         }
                   11565:         return $reply_value->[0];
                   11566:     } else {
                   11567:         return $reply_value;
1.927     albertel 11568:     }
                   11569: }
                   11570: 
1.691     raeburn  11571: sub check_group_parms {
                   11572:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11573:     my @groupitems = ();
                   11574:     my $resultitem;
1.927     albertel 11575:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11576:     foreach my $group (@{$groups}) {
                   11577:         foreach my $level (@levels) {
1.927     albertel 11578:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11579:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11580:         }
                   11581:     }
                   11582:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11583:                             $env{'course.'.$courseid.'.domain'},
                   11584:                                      'course',@groupitems);
                   11585:     return $coursereply;
                   11586: }
                   11587: 
                   11588: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11589:     my ($courseid,@groups) = @_;
                   11590:     @groups = sort(@groups);
1.691     raeburn  11591:     return @groups;
                   11592: }
                   11593: 
1.395     albertel 11594: sub packages_tab_default {
                   11595:     my ($uri,$varname)=@_;
                   11596:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11597: 
                   11598:     my (@extension,@specifics,$do_default);
                   11599:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11600: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11601: 	if ($pack_type eq 'default') {
                   11602: 	    $do_default=1;
                   11603: 	} elsif ($pack_type eq 'extension') {
                   11604: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11605: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11606: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11607: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11608: 	}
                   11609:     }
                   11610:     # first look for a package that matches the requested part id
                   11611:     foreach my $package (@specifics) {
                   11612: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11613: 	next if ($pack_part ne $part);
                   11614: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11615: 	    return $packagetab{"$pack_type&$name&default"};
                   11616: 	}
                   11617:     }
                   11618:     # look for any possible matching non extension_ package
                   11619:     foreach my $package (@specifics) {
                   11620: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11621: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11622: 	    return $packagetab{"$pack_type&$name&default"};
                   11623: 	}
1.585     albertel 11624: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11625: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11626: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11627: 	}
                   11628:     }
1.738     albertel 11629:     # look for any posible extension_ match
                   11630:     foreach my $package (@extension) {
                   11631: 	my ($package,$pack_type)=@{$package};
                   11632: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11633: 	    return $packagetab{"$pack_type&$name&default"};
                   11634: 	}
                   11635: 	if (defined($packagetab{$package."&$name&default"})) {
                   11636: 	    return $packagetab{$package."&$name&default"};
                   11637: 	}
                   11638:     }
                   11639:     # look for a global default setting
                   11640:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11641: 	return $packagetab{"default&$name&default"};
                   11642:     }
1.395     albertel 11643:     return undef;
                   11644: }
                   11645: 
1.334     albertel 11646: sub add_prefix_and_part {
                   11647:     my ($prefix,$part)=@_;
                   11648:     my $keyroot;
                   11649:     if (defined($prefix) && $prefix !~ /^__/) {
                   11650: 	# prefix that has a part already
                   11651: 	$keyroot=$prefix;
                   11652:     } elsif (defined($prefix)) {
                   11653: 	# prefix that is missing a part
                   11654: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11655:     } else {
                   11656: 	# no prefix at all
                   11657: 	if (defined($part)) { $keyroot='_'.$part; }
                   11658:     }
                   11659:     return $keyroot;
                   11660: }
                   11661: 
1.71      www      11662: # ---------------------------------------------------------------- Get metadata
                   11663: 
1.599     albertel 11664: my %metaentry;
1.1070    www      11665: my %importedpartids;
1.1172.2.99  raeburn  11666: my %importedrespids;
1.71      www      11667: sub metadata {
1.176     www      11668:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11669:     $uri=&declutter($uri);
1.288     albertel 11670:     # if it is a non metadata possible uri return quickly
1.529     albertel 11671:     if (($uri eq '') || 
                   11672: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11673: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11674:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11675: 	return undef;
                   11676:     }
1.1172.2.49  raeburn  11677:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11678: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11679: 	return undef;
1.288     albertel 11680:     }
1.73      www      11681:     my $filename=$uri;
                   11682:     $uri=~s/\.meta$//;
1.172     www      11683: #
                   11684: # Is the metadata already cached?
1.177     www      11685: # Look at timestamp of caching
1.172     www      11686: # Everything is cached by the main uri, libraries are never directly cached
                   11687: #
1.428     albertel 11688:     if (!defined($liburi)) {
1.599     albertel 11689: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11690: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11691:     }
                   11692:     {
1.1069    www      11693: # Imported parts would go here
1.1172.2.99  raeburn  11694:         my @origfiletagids=();
1.1069    www      11695:         my $importedparts=0;
1.1172.2.99  raeburn  11696: 
                   11697: # Imported responseids would go here
                   11698:         my $importedresponses=0;
1.172     www      11699: #
                   11700: # Is this a recursive call for a library?
                   11701: #
1.599     albertel 11702: #	if (! exists($metacache{$uri})) {
                   11703: #	    $metacache{$uri}={};
                   11704: #	}
1.924     albertel 11705: 	my $cachetime = 60*60;
1.171     www      11706:         if ($liburi) {
                   11707: 	    $liburi=&declutter($liburi);
                   11708:             $filename=$liburi;
1.401     bowersj2 11709:         } else {
1.599     albertel 11710: 	    &devalidate_cache_new('meta',$uri);
                   11711: 	    undef(%metaentry);
1.401     bowersj2 11712: 	}
1.140     www      11713:         my %metathesekeys=();
1.73      www      11714:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11715: 	my $metastring;
1.1140    www      11716: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11717: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11718: 	    $metastring = 
1.929     albertel 11719: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11720: 					  ('grade_target' => 'meta'));
                   11721: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11722: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11723:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11724: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11725: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11726: 	    $metastring=&getfile($file);
1.489     albertel 11727: 	}
1.208     albertel 11728:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11729:         my $token;
1.140     www      11730:         undef %metathesekeys;
1.71      www      11731:         while ($token=$parser->get_token) {
1.339     albertel 11732: 	    if ($token->[0] eq 'S') {
                   11733: 		if (defined($token->[2]->{'package'})) {
1.172     www      11734: #
                   11735: # This is a package - get package info
                   11736: #
1.339     albertel 11737: 		    my $package=$token->[2]->{'package'};
                   11738: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11739: 		    if (defined($token->[2]->{'id'})) { 
                   11740: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11741: 		    }
1.599     albertel 11742: 		    if ($metaentry{':packages'}) {
                   11743: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11744: 		    } else {
1.599     albertel 11745: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11746: 		    }
1.736     albertel 11747: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11748: 			my $part=$keyroot;
                   11749: 			$part=~s/^\_//;
1.736     albertel 11750: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11751: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11752: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11753: 			    # ignore package.tab specified default values
                   11754:                             # here &package_tab_default() will fetch those
                   11755: 			    if ($subp eq 'default') { next; }
1.736     albertel 11756: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11757: 			    my $unikey;
                   11758: 			    if ($pack =~ /_0$/) {
                   11759: 				$unikey='parameter_0_'.$name;
                   11760: 				$part=0;
                   11761: 			    } else {
                   11762: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11763: 			    }
1.339     albertel 11764: 			    if ($subp eq 'display') {
                   11765: 				$value.=' [Part: '.$part.']';
                   11766: 			    }
1.599     albertel 11767: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11768: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11769: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11770: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11771: 			    }
1.599     albertel 11772: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11773: 				$metaentry{':'.$unikey}=
                   11774: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11775: 			    }
1.339     albertel 11776: 			}
                   11777: 		    }
                   11778: 		} else {
1.172     www      11779: #
                   11780: # This is not a package - some other kind of start tag
1.339     albertel 11781: #
                   11782: 		    my $entry=$token->[1];
1.1068    www      11783: 		    my $unikey='';
1.175     www      11784: 
1.339     albertel 11785: 		    if ($entry eq 'import') {
1.175     www      11786: #
                   11787: # Importing a library here
1.339     albertel 11788: #
1.1067    www      11789:                         my $location=$parser->get_text('/import');
                   11790:                         my $dir=$filename;
                   11791:                         $dir=~s|[^/]*$||;
                   11792:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11793: 
                   11794:                         my $importid=$token->[2]->{'id'};
1.1068    www      11795:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11796: #
                   11797: # Check metadata for imported file to
                   11798: # see if it contained response items
                   11799: #
                   11800:                         my %currmetaentry = %metaentry;
                   11801:                         my $libresponseorder = &metadata($location,'responseorder');
                   11802:                         my $origfile;
                   11803:                         if ($libresponseorder ne '') {
                   11804:                             if ($#origfiletagids<0) {
                   11805:                                 undef(%importedrespids);
                   11806:                                 undef(%importedpartids);
                   11807:                             }
                   11808:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11809:                             if (@{$importedrespids{$importid}} > 0) {
                   11810:                                 $importedresponses = 1;
                   11811: # We need to get the original file and the imported file to get the response order correct
                   11812: # Load and inspect original file
                   11813:                                 if ($#origfiletagids<0) {
                   11814:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11815:                                     $origfile=&getfile($origfilelocation);
                   11816:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11817:                                 }
                   11818:                             }
                   11819:                         }
                   11820: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11821: # hash populated for imported library file
                   11822:                         %metaentry = %currmetaentry;
                   11823:                         undef(%currmetaentry);
1.1068    www      11824:                         if ($importmode eq 'problem') {
1.1069    www      11825: # Import as problem/response
1.1068    www      11826:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11827:                         } elsif ($importmode eq 'part') {
                   11828: # Import as part(s)
1.1069    www      11829:                            $importedparts=1;
                   11830: # We need to get the original file and the imported file to get the part order correct
                   11831: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11832: # Load and inspect original file if we didn't do that already
                   11833:                            if ($#origfiletagids<0) {
                   11834:                                undef(%importedrespids);
                   11835:                                undef(%importedpartids);
                   11836:                                if ($origfile eq '') {
                   11837:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11838:                                    $origfile=&getfile($origfilelocation);
                   11839:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11840:                                }
1.1070    www      11841:                            }
                   11842: 
1.1069    www      11843: # Load and inspect imported file
                   11844:                            my $impfile=&getfile($location);
                   11845:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11846:                            if ($#impfilepartids>=0) {
                   11847: # This problem had parts
1.1070    www      11848:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11849:                            } else {
                   11850: # Importing by turning a single problem into a problem part
                   11851: # It gets the import-tags ID as part-ID
                   11852:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11853:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11854:                            }
1.1068    www      11855:                         } else {
                   11856: # Normal import
                   11857:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11858:                            if (defined($token->[2]->{'id'})) {
                   11859:                               $unikey.='_'.$token->[2]->{'id'};
                   11860:                            }
1.1067    www      11861:                         }
                   11862: 
1.339     albertel 11863: 			if ($depthcount<20) {
1.736     albertel 11864: 			    my $metadata = 
                   11865: 				&metadata($uri,'keys', $location,$unikey,
                   11866: 					  $depthcount+1);
                   11867: 			    foreach my $meta (split(',',$metadata)) {
                   11868: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11869: 				$metathesekeys{$meta}=1;
1.339     albertel 11870: 			    }
1.1068    www      11871: 			
                   11872:                         }
1.1067    www      11873: 		    } else {
                   11874: #
                   11875: # Not importing, some other kind of non-package, non-library start tag
                   11876: # 
                   11877:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11878:                         if (defined($token->[2]->{'id'})) {
                   11879:                             $unikey.='_'.$token->[2]->{'id'};
                   11880:                         }
1.339     albertel 11881: 			if (defined($token->[2]->{'name'})) { 
                   11882: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11883: 			}
                   11884: 			$metathesekeys{$unikey}=1;
1.736     albertel 11885: 			foreach my $param (@{$token->[3]}) {
                   11886: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11887: 				$token->[2]->{$param};
1.339     albertel 11888: 			}
                   11889: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11890: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11891: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11892: 		 # only ws inside the tag, and not in default, so use default
                   11893: 		 # as value
1.599     albertel 11894: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11895: 			} elsif ( $internaltext =~ /\S/ ) {
                   11896: 		  # something interesting inside the tag
                   11897: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11898: 			} else {
1.908     albertel 11899: 		  # no interesting values, don't set a default
1.339     albertel 11900: 			}
1.172     www      11901: # end of not-a-package not-a-library import
1.339     albertel 11902: 		    }
1.172     www      11903: # end of not-a-package start tag
1.339     albertel 11904: 		}
1.172     www      11905: # the next is the end of "start tag"
1.339     albertel 11906: 	    }
                   11907: 	}
1.483     albertel 11908: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11909: 	$extension = lc($extension);
                   11910: 	if ($extension eq 'htm') { $extension='html'; }
                   11911: 
1.737     albertel 11912: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11913: 	    #no specific packages #how's our extension
                   11914: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11915: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11916: 					 \%metathesekeys);
                   11917: 	}
1.883     albertel 11918: 
                   11919: 	if (!exists($metaentry{':packages'})
                   11920: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11921: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11922: 		#no specific packages well let's get default then
                   11923: 		if ($key!~/^default&/) { next; }
1.488     albertel 11924: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11925: 					     \%metathesekeys);
                   11926: 	    }
                   11927: 	}
1.338     www      11928: # are there custom rights to evaluate
1.599     albertel 11929: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11930: 
1.338     www      11931:     #
                   11932:     # Importing a rights file here
1.339     albertel 11933:     #
                   11934: 	    unless ($depthcount) {
1.599     albertel 11935: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11936: 		my $dir=$filename;
                   11937: 		$dir=~s|[^/]*$||;
                   11938: 		$location=&filelocation($dir,$location);
1.736     albertel 11939: 		my $rights_metadata =
                   11940: 		    &metadata($uri,'keys',$location,'_rights',
                   11941: 			      $depthcount+1);
                   11942: 		foreach my $rights (split(',',$rights_metadata)) {
                   11943: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11944: 		    $metathesekeys{$rights}=1;
1.339     albertel 11945: 		}
                   11946: 	    }
                   11947: 	}
1.737     albertel 11948: 	# uniqifiy package listing
                   11949: 	my %seen;
                   11950: 	my @uniq_packages =
                   11951: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11952: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11953: 
1.1172.2.99  raeburn  11954:         if (($importedresponses) || ($importedparts)) {
                   11955:             if ($importedparts) {
1.1070    www      11956: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11957:                 $metaentry{':partorder'}='';
                   11958:                 $metathesekeys{'partorder'}=1;
                   11959:             }
                   11960:             if ($importedresponses) {
                   11961: # We had imported responses and need to rebuild responseorder
                   11962:                 $metaentry{':responseorder'}='';
                   11963:                 $metathesekeys{'responseorder'}=1;
                   11964:             }
                   11965:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11966:                 my $origid = $origfiletagids[$index+1];
                   11967:                 if ($origfiletagids[$index] eq 'part') {
                   11968: # Original part, part of the problem
                   11969:                     if ($importedparts) {
                   11970:                         $metaentry{':partorder'}.=','.$origid;
                   11971:                     }
                   11972:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11973:                     if ($importedparts) {
                   11974: # We have imported parts at this position
                   11975:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11976:                     }
                   11977:                     if ($importedresponses) {
                   11978: # We have imported responses at this position
                   11979:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11980:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11981:                         }
                   11982:                     }
                   11983:                 } else {
                   11984: # Original response item, part of the problem
                   11985:                     if ($importedresponses) {
                   11986:                         $metaentry{':responseorder'}.=','.$origid;
                   11987:                     }
                   11988:                 }
                   11989:             }
                   11990:             if ($importedparts) {
                   11991:                 $metaentry{':partorder'}=~s/^\,//;
                   11992:             }
                   11993:             if ($importedresponses) {
                   11994:                 $metaentry{':responseorder'}=~s/^\,//;
                   11995:             }
1.1070    www      11996:         }
                   11997: 
1.737     albertel 11998: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11999: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12000: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12001: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12002: # this is the end of "was not already recently cached
1.71      www      12003:     }
1.599     albertel 12004:     return $metaentry{':'.$what};
1.261     albertel 12005: }
                   12006: 
1.488     albertel 12007: sub metadata_create_package_def {
1.483     albertel 12008:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12009:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12010:     if ($subp eq 'default') { next; }
                   12011:     
1.599     albertel 12012:     if (defined($metaentry{':packages'})) {
                   12013: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12014:     } else {
1.599     albertel 12015: 	$metaentry{':packages'}=$package;
1.483     albertel 12016:     }
                   12017:     my $value=$packagetab{$key};
                   12018:     my $unikey;
                   12019:     $unikey='parameter_0_'.$name;
1.599     albertel 12020:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12021:     $$metathesekeys{$unikey}=1;
1.599     albertel 12022:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12023: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12024:     }
1.599     albertel 12025:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12026: 	$metaentry{':'.$unikey}=
                   12027: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12028:     }
                   12029: }
                   12030: 
1.261     albertel 12031: sub metadata_generate_part0 {
                   12032:     my ($metadata,$metacache,$uri) = @_;
                   12033:     my %allnames;
1.737     albertel 12034:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12035: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12036: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12037: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12038: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12039: 	    $allnames{$name}=$part;
                   12040: 	  }
                   12041: 	}
                   12042:     }
                   12043:     foreach my $name (keys(%allnames)) {
                   12044:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12045:       my $key=":parameter_0_$name";
1.261     albertel 12046:       $$metacache{"$key.part"}='0';
                   12047:       $$metacache{"$key.name"}=$name;
1.428     albertel 12048:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12049: 					   $allnames{$name}.'_'.$name.
                   12050: 					   '.type'};
1.428     albertel 12051:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12052: 			     '.display'};
1.644     www      12053:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12054:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12055:       $$metacache{"$key.display"}=$olddis;
                   12056:     }
1.71      www      12057: }
                   12058: 
1.764     albertel 12059: # ------------------------------------------------------ Devalidate title cache
                   12060: 
                   12061: sub devalidate_title_cache {
                   12062:     my ($url)=@_;
                   12063:     if (!$env{'request.course.id'}) { return; }
                   12064:     my $symb=&symbread($url);
                   12065:     if (!$symb) { return; }
                   12066:     my $key=$env{'request.course.id'}."\0".$symb;
                   12067:     &devalidate_cache_new('title',$key);
                   12068: }
                   12069: 
1.1014    droeschl 12070: # ------------------------------------------------- Get the title of a course
                   12071: 
                   12072: sub current_course_title {
                   12073:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12074: }
1.301     www      12075: # ------------------------------------------------- Get the title of a resource
                   12076: 
                   12077: sub gettitle {
                   12078:     my $urlsymb=shift;
                   12079:     my $symb=&symbread($urlsymb);
1.534     albertel 12080:     if ($symb) {
1.620     albertel 12081: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12082: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12083: 	if (defined($cached)) { 
                   12084: 	    return $result;
                   12085: 	}
1.534     albertel 12086: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12087: 	my $title='';
1.907     albertel 12088: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12089: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12090: 	} else {
                   12091: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12092: 		    &GDBM_READER(),0640)) {
                   12093: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12094: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12095: 		untie(%bighash);
                   12096: 	    }
1.534     albertel 12097: 	}
                   12098: 	$title=~s/\&colon\;/\:/gs;
                   12099: 	if ($title) {
1.1159    www      12100: # Remember both $symb and $title for dynamic metadata
                   12101:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12102:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12103: # Cache this title and then return it
1.599     albertel 12104: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12105: 	}
                   12106: 	$urlsymb=$url;
                   12107:     }
                   12108:     my $title=&metadata($urlsymb,'title');
                   12109:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12110:     return $title;
1.301     www      12111: }
1.613     albertel 12112: 
1.614     albertel 12113: sub get_slot {
                   12114:     my ($which,$cnum,$cdom)=@_;
                   12115:     if (!$cnum || !$cdom) {
1.790     albertel 12116: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12117: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12118: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12119:     }
1.703     albertel 12120:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12121:     my %slotinfo;
                   12122:     if (exists($remembered{$key})) {
                   12123: 	$slotinfo{$which} = $remembered{$key};
                   12124:     } else {
                   12125: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12126: 	&Apache::lonhomework::showhash(%slotinfo);
                   12127: 	my ($tmp)=keys(%slotinfo);
                   12128: 	if ($tmp=~/^error:/) { return (); }
                   12129: 	$remembered{$key} = $slotinfo{$which};
                   12130:     }
1.616     albertel 12131:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12132: 	return %{$slotinfo{$which}};
                   12133:     }
                   12134:     return $slotinfo{$which};
1.614     albertel 12135: }
1.1150    raeburn  12136: 
                   12137: sub get_reservable_slots {
                   12138:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12139:     my $now = time;
                   12140:     my $reservable_info;
                   12141:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12142:     if (exists($remembered{$key})) {
                   12143:         $reservable_info = $remembered{$key};
                   12144:     } else {
                   12145:         my %resv;
                   12146:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12147:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12148:         $reservable_info = \%resv;
                   12149:         $remembered{$key} = $reservable_info;
                   12150:     }
                   12151:     return $reservable_info;
                   12152: }
                   12153: 
                   12154: sub get_course_slots {
                   12155:     my ($cnum,$cdom) = @_;
                   12156:     my $hashid=$cnum.':'.$cdom;
                   12157:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12158:     if (defined($cached)) {
                   12159:         if (ref($result) eq 'HASH') {
                   12160:             return %{$result};
                   12161:         }
                   12162:     } else {
                   12163:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12164:         my ($tmp) = keys(%slots);
                   12165:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12166:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12167:             return %slots;
                   12168:         }
                   12169:     }
                   12170:     return;
                   12171: }
                   12172: 
                   12173: sub devalidate_slots_cache {
                   12174:     my ($cnum,$cdom)=@_;
                   12175:     my $hashid=$cnum.':'.$cdom;
                   12176:     &devalidate_cache_new('allslots',$hashid);
                   12177: }
                   12178: 
1.1172.2.8  raeburn  12179: sub get_coursechange {
                   12180:     my ($cdom,$cnum) = @_;
                   12181:     if ($cdom eq '' || $cnum eq '') {
                   12182:         return unless ($env{'request.course.id'});
                   12183:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12184:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12185:     }
                   12186:     my $hashid=$cdom.'_'.$cnum;
                   12187:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12188:     if ((defined($cached)) && ($change ne '')) {
                   12189:         return $change;
                   12190:     } else {
                   12191:         my %crshash;
                   12192:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12193:         if ($crshash{'internal.contentchange'} eq '') {
                   12194:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12195:             if ($change eq '') {
                   12196:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12197:                 $change = $crshash{'internal.created'};
                   12198:             }
                   12199:         } else {
                   12200:             $change = $crshash{'internal.contentchange'};
                   12201:         }
                   12202:         my $cachetime = 600;
                   12203:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12204:     }
                   12205:     return $change;
                   12206: }
                   12207: 
                   12208: sub devalidate_coursechange_cache {
                   12209:     my ($cnum,$cdom)=@_;
                   12210:     my $hashid=$cnum.':'.$cdom;
                   12211:     &devalidate_cache_new('crschange',$hashid);
                   12212: }
                   12213: 
1.31      www      12214: # ------------------------------------------------- Update symbolic store links
                   12215: 
                   12216: sub symblist {
                   12217:     my ($mapname,%newhash)=@_;
1.438     www      12218:     $mapname=&deversion(&declutter($mapname));
1.31      www      12219:     my %hash;
1.620     albertel 12220:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12221:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12222:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12223: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12224: 		next if ($url eq 'last_known'
                   12225: 			 && $env{'form.no_update_last_known'});
                   12226: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12227: 						    $newhash{$url}->[1],
                   12228: 						    $newhash{$url}->[0]);
1.191     harris41 12229:             }
1.31      www      12230:             if (untie(%hash)) {
                   12231: 		return 'ok';
                   12232:             }
                   12233:         }
                   12234:     }
                   12235:     return 'error';
1.212     www      12236: }
                   12237: 
                   12238: # --------------------------------------------------------------- Verify a symb
                   12239: 
                   12240: sub symbverify {
1.1172.2.11  raeburn  12241:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12242:     my $thisfn=$thisurl;
1.439     www      12243:     $thisfn=&declutter($thisfn);
1.215     www      12244: # direct jump to resource in page or to a sequence - will construct own symbs
                   12245:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12246: # check URL part
1.409     www      12247:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12248: 
1.431     www      12249:     unless ($url eq $thisfn) { return 0; }
1.213     www      12250: 
1.216     www      12251:     $symb=&symbclean($symb);
1.510     www      12252:     $thisurl=&deversion($thisurl);
1.439     www      12253:     $thisfn=&deversion($thisfn);
1.213     www      12254: 
                   12255:     my %bighash;
                   12256:     my $okay=0;
1.431     www      12257: 
1.620     albertel 12258:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12259:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  12260:         my $noclutter;
1.1032    raeburn  12261:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12262:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12263:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12264:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12265:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12266:                 $noclutter = 1;
                   12267:             }
                   12268:         }
                   12269:         my $ids;
                   12270:         if ($noclutter) {
                   12271:             $ids=$bighash{'ids_'.$thisurl};
                   12272:         } else {
                   12273:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12274:         }
1.1102    raeburn  12275:         unless ($ids) {
1.1172.2.13  raeburn  12276:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12277:             $ids=$bighash{$idkey};
1.216     www      12278:         }
                   12279:         if ($ids) {
                   12280: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12281:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12282:                 $symb =~ s/\?.+$//;
                   12283:             }
1.800     albertel 12284: 	    foreach my $id (split(/\,/,$ids)) {
                   12285: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12286:                if (
                   12287:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12288:    eq $symb) {
1.1172.2.11  raeburn  12289:                    if (ref($encstate)) {
                   12290:                        $$encstate = $bighash{'encrypted_'.$id};
                   12291:                    }
1.1172.2.13  raeburn  12292:                    if (($env{'request.role.adv'}) ||
                   12293:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12294:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12295:                        $okay=1;
                   12296:                        last;
                   12297:                    }
                   12298:                }
                   12299:            }
1.216     www      12300:         }
1.213     www      12301: 	untie(%bighash);
                   12302:     }
                   12303:     return $okay;
1.31      www      12304: }
                   12305: 
1.210     www      12306: # --------------------------------------------------------------- Clean-up symb
                   12307: 
                   12308: sub symbclean {
                   12309:     my $symb=shift;
1.568     albertel 12310:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12311: # remove version from map
                   12312:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12313: 
1.210     www      12314: # remove version from URL
                   12315:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12316: 
1.507     www      12317: # remove wrapper
                   12318: 
1.510     www      12319:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12320:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12321:     return $symb;
1.409     www      12322: }
                   12323: 
                   12324: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12325: 
                   12326: sub encode_symb {
                   12327:     my ($map,$resid,$url)=@_;
                   12328:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12329: }
1.409     www      12330: 
                   12331: sub decode_symb {
1.568     albertel 12332:     my $symb=shift;
                   12333:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12334:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12335:     return (&fixversion($map),$resid,&fixversion($url));
                   12336: }
                   12337: 
                   12338: sub fixversion {
                   12339:     my $fn=shift;
1.609     banghart 12340:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12341:     my %bighash;
                   12342:     my $uri=&clutter($fn);
1.620     albertel 12343:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12344: # is this cached?
1.599     albertel 12345:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12346:     if (defined($cached)) { return $result; }
                   12347: # unfortunately not cached, or expired
1.620     albertel 12348:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12349: 	    &GDBM_READER(),0640)) {
                   12350:  	if ($bighash{'version_'.$uri}) {
                   12351:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12352:  	    unless (($version eq 'mostrecent') || 
                   12353: 		    ($version==&getversion($uri))) {
1.440     www      12354:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12355:  	    }
                   12356:  	}
                   12357:  	untie %bighash;
1.413     www      12358:     }
1.599     albertel 12359:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12360: }
                   12361: 
                   12362: sub deversion {
                   12363:     my $url=shift;
                   12364:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12365:     return $url;
1.210     www      12366: }
                   12367: 
1.31      www      12368: # ------------------------------------------------------ Return symb list entry
                   12369: 
                   12370: sub symbread {
1.1172.2.66  raeburn  12371:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12372:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12373:     if (defined($env{$cache_str})) {
                   12374:         if ($ignorecachednull) {
                   12375:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12376:         } else {
                   12377:             return $env{$cache_str};
                   12378:         }
                   12379:     }
1.242     www      12380: # no filename provided? try from environment
1.1172.2.54  raeburn  12381:     unless ($thisfn) {
1.620     albertel 12382:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12383:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12384:         }
                   12385:         $thisfn=$env{'request.filename'};
1.44      www      12386:     }
1.569     albertel 12387:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12388: # is that filename actually a symb? Verify, clean, and return
                   12389:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12390: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12391: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12392: 	}
1.242     www      12393:     }
1.44      www      12394:     $thisfn=declutter($thisfn);
1.31      www      12395:     my %hash;
1.37      www      12396:     my %bighash;
                   12397:     my $syval='';
1.620     albertel 12398:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12399:         my $targetfn = $thisfn;
1.609     banghart 12400:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12401:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12402:         }
1.687     albertel 12403: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12404: 	    $targetfn=$1;
                   12405: 	}
1.620     albertel 12406:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12407:                       &GDBM_READER(),0640)) {
1.481     raeburn  12408: 	    $syval=$hash{$targetfn};
1.37      www      12409:             untie(%hash);
                   12410:         }
                   12411: # ---------------------------------------------------------- There was an entry
                   12412:         if ($syval) {
1.601     albertel 12413: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12414: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12415: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12416: 		    #return $env{$cache_str}='';
1.601     albertel 12417: 		#}    
                   12418: 		#$syval.=$1;
                   12419: 	    #}
1.37      www      12420:         } else {
                   12421: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12422:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12423:                             &GDBM_READER(),0640)) {
1.37      www      12424: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12425:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12426:               unless ($ids) { 
                   12427:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12428:               }
                   12429:               unless ($ids) {
                   12430: # alias?
                   12431: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12432:               }
1.37      www      12433:               if ($ids) {
                   12434: # ------------------------------------------------------------------- Has ID(s)
                   12435:                  my @possibilities=split(/\,/,$ids);
1.39      www      12436:                  if ($#possibilities==0) {
                   12437: # ----------------------------------------------- There is only one possibility
1.37      www      12438: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12439: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12440: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12441:                      if (ref($possibles) eq 'HASH') {
                   12442:                          $possibles->{$syval} = 1;
                   12443:                      }
                   12444:                      if ($checkforblock) {
                   12445:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12446:                          if (@blockers) {
                   12447:                              $syval = '';
                   12448:                              return;
                   12449:                          }
                   12450:                      }
                   12451:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12452: # ------------------------------------------ There is more than one possibility
                   12453:                      my $realpossible=0;
1.800     albertel 12454:                      foreach my $id (@possibilities) {
                   12455: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12456:                          my $canaccess;
                   12457:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12458:                              $canaccess = 1;
                   12459:                          } else {
                   12460:                              $canaccess = &allowed('bre',$file);
                   12461:                          }
                   12462:                          if ($canaccess) {
                   12463:          		     my ($mapid,$resid)=split(/\./,$id);
                   12464:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12465:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12466:                                                              $resid,$thisfn);
                   12467:                                  if (ref($possibles) eq 'HASH') {
                   12468:                                      $possibles->{$syval} = 1;
                   12469:                                  }
                   12470:                                  if ($checkforblock) {
                   12471:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12472:                                      unless (@blockers > 0) {
                   12473:                                          $syval = $poss_syval;
                   12474:                                          $realpossible++;
                   12475:                                      }
                   12476:                                  } else {
                   12477:                                      $syval = $poss_syval;
                   12478:                                      $realpossible++;
                   12479:                                  }
                   12480:                              }
1.39      www      12481: 			 }
1.191     harris41 12482:                      }
1.39      www      12483: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12484:                  } else {
                   12485:                      $syval='';
1.37      www      12486:                  }
                   12487: 	      }
1.1172.2.66  raeburn  12488:               untie(%bighash);
1.481     raeburn  12489:            }
1.31      www      12490:         }
1.62      www      12491:         if ($syval) {
1.620     albertel 12492: 	    return $env{$cache_str}=$syval;
1.62      www      12493:         }
1.31      www      12494:     }
1.949     raeburn  12495:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12496:     return $env{$cache_str}='';
1.31      www      12497: }
                   12498: 
                   12499: # ---------------------------------------------------------- Return random seed
                   12500: 
1.32      www      12501: sub numval {
                   12502:     my $txt=shift;
                   12503:     $txt=~tr/A-J/0-9/;
                   12504:     $txt=~tr/a-j/0-9/;
                   12505:     $txt=~tr/K-T/0-9/;
                   12506:     $txt=~tr/k-t/0-9/;
                   12507:     $txt=~tr/U-Z/0-5/;
                   12508:     $txt=~tr/u-z/0-5/;
                   12509:     $txt=~s/\D//g;
1.564     albertel 12510:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12511:     return int($txt);
1.368     albertel 12512: }
                   12513: 
1.484     albertel 12514: sub numval2 {
                   12515:     my $txt=shift;
                   12516:     $txt=~tr/A-J/0-9/;
                   12517:     $txt=~tr/a-j/0-9/;
                   12518:     $txt=~tr/K-T/0-9/;
                   12519:     $txt=~tr/k-t/0-9/;
                   12520:     $txt=~tr/U-Z/0-5/;
                   12521:     $txt=~tr/u-z/0-5/;
                   12522:     $txt=~s/\D//g;
                   12523:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12524:     my $total;
                   12525:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12526:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12527:     return int($total);
                   12528: }
                   12529: 
1.575     albertel 12530: sub numval3 {
                   12531:     use integer;
                   12532:     my $txt=shift;
                   12533:     $txt=~tr/A-J/0-9/;
                   12534:     $txt=~tr/a-j/0-9/;
                   12535:     $txt=~tr/K-T/0-9/;
                   12536:     $txt=~tr/k-t/0-9/;
                   12537:     $txt=~tr/U-Z/0-5/;
                   12538:     $txt=~tr/u-z/0-5/;
                   12539:     $txt=~s/\D//g;
                   12540:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12541:     my $total;
                   12542:     foreach my $val (@txts) { $total+=$val; }
                   12543:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12544:     return $total;
                   12545: }
                   12546: 
1.675     albertel 12547: sub digest {
                   12548:     my ($data)=@_;
                   12549:     my $digest=&Digest::MD5::md5($data);
                   12550:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12551:     my ($e,$f);
                   12552:     {
                   12553:         use integer;
                   12554:         $e=($a+$b);
                   12555:         $f=($c+$d);
                   12556:         if ($_64bit) {
                   12557:             $e=(($e<<32)>>32);
                   12558:             $f=(($f<<32)>>32);
                   12559:         }
                   12560:     }
                   12561:     if (wantarray) {
                   12562: 	return ($e,$f);
                   12563:     } else {
                   12564: 	my $g;
                   12565: 	{
                   12566: 	    use integer;
                   12567: 	    $g=($e+$f);
                   12568: 	    if ($_64bit) {
                   12569: 		$g=(($g<<32)>>32);
                   12570: 	    }
                   12571: 	}
                   12572: 	return $g;
                   12573:     }
                   12574: }
                   12575: 
1.368     albertel 12576: sub latest_rnd_algorithm_id {
1.675     albertel 12577:     return '64bit5';
1.366     albertel 12578: }
1.32      www      12579: 
1.503     albertel 12580: sub get_rand_alg {
                   12581:     my ($courseid)=@_;
1.790     albertel 12582:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12583:     if ($courseid) {
1.620     albertel 12584: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12585:     }
                   12586:     return &latest_rnd_algorithm_id();
                   12587: }
                   12588: 
1.562     albertel 12589: sub validCODE {
                   12590:     my ($CODE)=@_;
                   12591:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12592:     return 0;
                   12593: }
                   12594: 
1.491     albertel 12595: sub getCODE {
1.620     albertel 12596:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12597:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12598: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12599: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12600: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12601:     }
                   12602:     return undef;
                   12603: }
1.1133    foxr     12604: #
                   12605: #  Determines the random seed for a specific context:
                   12606: #
                   12607: # parameters:
                   12608: #   symb      - in course context the symb for the seed.
                   12609: #   course_id - The course id of the form domain_coursenum.
                   12610: #   domain    - Domain for the user.
                   12611: #   course    - Course for the user.
                   12612: #   cenv      - environment of the course.
                   12613: #
                   12614: # NOTE:
                   12615: #   All parameters are picked out of the environment if missing
                   12616: #   or not defined.
                   12617: #   If a symb cannot be determined the current time is used instead.
                   12618: #
                   12619: #  For a given well defined symb, courside, domain, username,
                   12620: #  and course environment, the seed is reproducible.
                   12621: #
1.31      www      12622: sub rndseed {
1.1133    foxr     12623:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12624:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12625:     if (!defined($symb)) {
1.366     albertel 12626: 	unless ($symb=$wsymb) { return time; }
                   12627:     }
1.1146    foxr     12628:     if (!defined $courseid) { 
                   12629: 	$courseid=$wcourseid; 
                   12630:     }
                   12631:     if (!defined $domain) { $domain=$wdomain; }
                   12632:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12633: 
                   12634:     my $which;
                   12635:     if (defined($cenv->{'rndseed'})) {
                   12636: 	$which = $cenv->{'rndseed'};
                   12637:     } else {
                   12638: 	$which =&get_rand_alg($courseid);
                   12639:     }
1.491     albertel 12640:     if (defined(&getCODE())) {
1.675     albertel 12641: 	if ($which eq '64bit5') {
                   12642: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12643: 	} elsif ($which eq '64bit4') {
1.575     albertel 12644: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12645: 	} else {
                   12646: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12647: 	}
1.675     albertel 12648:     } elsif ($which eq '64bit5') {
                   12649: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12650:     } elsif ($which eq '64bit4') {
                   12651: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12652:     } elsif ($which eq '64bit3') {
                   12653: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12654:     } elsif ($which eq '64bit2') {
                   12655: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12656:     } elsif ($which eq '64bit') {
                   12657: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12658:     }
                   12659:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12660: }
                   12661: 
                   12662: sub rndseed_32bit {
                   12663:     my ($symb,$courseid,$domain,$username)=@_;
                   12664:     {
                   12665: 	use integer;
                   12666: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12667: 	my $symbseed=numval($symb) << 22;
                   12668: 	my $namechck=unpack("%32C*",$username) << 17;
                   12669: 	my $nameseed=numval($username) << 12;
                   12670: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12671: 	my $courseseed=unpack("%32C*",$courseid);
                   12672: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12673: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12674: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12675: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12676: 	return $num;
                   12677:     }
                   12678: }
                   12679: 
                   12680: sub rndseed_64bit {
                   12681:     my ($symb,$courseid,$domain,$username)=@_;
                   12682:     {
                   12683: 	use integer;
                   12684: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12685: 	my $symbseed=numval($symb) << 10;
                   12686: 	my $namechck=unpack("%32S*",$username);
                   12687: 	
                   12688: 	my $nameseed=numval($username) << 21;
                   12689: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12690: 	my $courseseed=unpack("%32S*",$courseid);
                   12691: 	
                   12692: 	my $num1=$symbchck+$symbseed+$namechck;
                   12693: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12694: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12695: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12696: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12697: 	return "$num1,$num2";
1.155     albertel 12698:     }
1.366     albertel 12699: }
                   12700: 
1.443     albertel 12701: sub rndseed_64bit2 {
                   12702:     my ($symb,$courseid,$domain,$username)=@_;
                   12703:     {
                   12704: 	use integer;
                   12705: 	# strings need to be an even # of cahracters long, it it is odd the
                   12706:         # last characters gets thrown away
                   12707: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12708: 	my $symbseed=numval($symb) << 10;
                   12709: 	my $namechck=unpack("%32S*",$username.' ');
                   12710: 	
                   12711: 	my $nameseed=numval($username) << 21;
1.501     albertel 12712: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12713: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12714: 	
                   12715: 	my $num1=$symbchck+$symbseed+$namechck;
                   12716: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12717: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12718: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12719: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12720: 	return "$num1,$num2";
                   12721:     }
                   12722: }
                   12723: 
                   12724: sub rndseed_64bit3 {
                   12725:     my ($symb,$courseid,$domain,$username)=@_;
                   12726:     {
                   12727: 	use integer;
                   12728: 	# strings need to be an even # of cahracters long, it it is odd the
                   12729:         # last characters gets thrown away
                   12730: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12731: 	my $symbseed=numval2($symb) << 10;
                   12732: 	my $namechck=unpack("%32S*",$username.' ');
                   12733: 	
                   12734: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12735: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12736: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12737: 	
                   12738: 	my $num1=$symbchck+$symbseed+$namechck;
                   12739: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12740: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12741: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12742: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12743: 	
1.503     albertel 12744: 	return "$num1:$num2";
1.443     albertel 12745:     }
                   12746: }
                   12747: 
1.575     albertel 12748: sub rndseed_64bit4 {
                   12749:     my ($symb,$courseid,$domain,$username)=@_;
                   12750:     {
                   12751: 	use integer;
                   12752: 	# strings need to be an even # of cahracters long, it it is odd the
                   12753:         # last characters gets thrown away
                   12754: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12755: 	my $symbseed=numval3($symb) << 10;
                   12756: 	my $namechck=unpack("%32S*",$username.' ');
                   12757: 	
                   12758: 	my $nameseed=numval3($username) << 21;
                   12759: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12760: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12761: 	
                   12762: 	my $num1=$symbchck+$symbseed+$namechck;
                   12763: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12764: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12765: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12766: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12767: 	
1.575     albertel 12768: 	return "$num1:$num2";
                   12769:     }
                   12770: }
                   12771: 
1.675     albertel 12772: sub rndseed_64bit5 {
                   12773:     my ($symb,$courseid,$domain,$username)=@_;
                   12774:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12775:     return "$num1:$num2";
                   12776: }
                   12777: 
1.366     albertel 12778: sub rndseed_CODE_64bit {
                   12779:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12780:     {
1.366     albertel 12781: 	use integer;
1.443     albertel 12782: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12783: 	my $symbseed=numval2($symb);
1.491     albertel 12784: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12785: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12786: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12787: 	my $num1=$symbseed+$CODEchck;
                   12788: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12789: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12790: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12791: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12792: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12793: 	return "$num1:$num2";
1.366     albertel 12794:     }
                   12795: }
                   12796: 
1.575     albertel 12797: sub rndseed_CODE_64bit4 {
                   12798:     my ($symb,$courseid,$domain,$username)=@_;
                   12799:     {
                   12800: 	use integer;
                   12801: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12802: 	my $symbseed=numval3($symb);
                   12803: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12804: 	my $CODEseed=numval3(&getCODE());
                   12805: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12806: 	my $num1=$symbseed+$CODEchck;
                   12807: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12808: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12809: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12810: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12811: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12812: 	return "$num1:$num2";
                   12813:     }
                   12814: }
                   12815: 
1.675     albertel 12816: sub rndseed_CODE_64bit5 {
                   12817:     my ($symb,$courseid,$domain,$username)=@_;
                   12818:     my $code = &getCODE();
                   12819:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12820:     return "$num1:$num2";
                   12821: }
                   12822: 
1.366     albertel 12823: sub setup_random_from_rndseed {
                   12824:     my ($rndseed)=@_;
1.503     albertel 12825:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12826: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12827:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12828:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12829:         } else {
                   12830:             &Math::Random::random_set_seed($num1,$num2);
                   12831:         }
1.366     albertel 12832:     } else {
                   12833: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12834:     }
1.36      albertel 12835: }
                   12836: 
1.474     albertel 12837: sub latest_receipt_algorithm_id {
1.835     albertel 12838:     return 'receipt3';
1.474     albertel 12839: }
                   12840: 
1.480     www      12841: sub recunique {
                   12842:     my $fucourseid=shift;
                   12843:     my $unique;
1.835     albertel 12844:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12845: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12846: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12847:     } else {
                   12848: 	$unique=$perlvar{'lonReceipt'};
                   12849:     }
                   12850:     return unpack("%32C*",$unique);
                   12851: }
                   12852: 
                   12853: sub recprefix {
                   12854:     my $fucourseid=shift;
                   12855:     my $prefix;
1.835     albertel 12856:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12857: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12858: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12859:     } else {
                   12860: 	$prefix=$perlvar{'lonHostID'};
                   12861:     }
                   12862:     return unpack("%32C*",$prefix);
                   12863: }
                   12864: 
1.76      www      12865: sub ireceipt {
1.474     albertel 12866:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12867: 
                   12868:     my $return =&recprefix($fucourseid).'-';
                   12869: 
                   12870:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12871: 	$env{'request.state'} eq 'construct') {
                   12872: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12873: 	return $return;
                   12874:     }
                   12875: 
1.76      www      12876:     my $cuname=unpack("%32C*",$funame);
                   12877:     my $cudom=unpack("%32C*",$fudom);
                   12878:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12879:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12880:     my $cunique=&recunique($fucourseid);
1.474     albertel 12881:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12882:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12883: 
1.790     albertel 12884: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12885: 			       
                   12886: 	$return.= ($cunique%$cuname+
                   12887: 		   $cunique%$cudom+
                   12888: 		   $cusymb%$cuname+
                   12889: 		   $cusymb%$cudom+
                   12890: 		   $cucourseid%$cuname+
                   12891: 		   $cucourseid%$cudom+
                   12892: 		   $cpart%$cuname+
                   12893: 		   $cpart%$cudom);
                   12894:     } else {
                   12895: 	$return.= ($cunique%$cuname+
                   12896: 		   $cunique%$cudom+
                   12897: 		   $cusymb%$cuname+
                   12898: 		   $cusymb%$cudom+
                   12899: 		   $cucourseid%$cuname+
                   12900: 		   $cucourseid%$cudom);
                   12901:     }
                   12902:     return $return;
1.76      www      12903: }
                   12904: 
                   12905: sub receipt {
1.474     albertel 12906:     my ($part)=@_;
1.790     albertel 12907:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12908:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12909: }
1.260     ng       12910: 
1.790     albertel 12911: sub whichuser {
                   12912:     my ($passedsymb)=@_;
                   12913:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12914:     if (defined($env{'form.grade_symb'})) {
                   12915: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12916: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12917: 	if (!$allowed &&
                   12918: 	    exists($env{'request.course.sec'}) &&
                   12919: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12920: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12921: 			      '/'.$env{'request.course.sec'});
                   12922: 	}
                   12923: 	if ($allowed) {
                   12924: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12925: 	    $courseid=$tmp_courseid;
                   12926: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12927: 	    ($name)=&get_env_multiple('form.grade_username');
                   12928: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12929: 	}
                   12930:     }
                   12931:     if (!$passedsymb) {
                   12932: 	$symb=&symbread();
                   12933:     } else {
                   12934: 	$symb=$passedsymb;
                   12935:     }
                   12936:     $courseid=$env{'request.course.id'};
                   12937:     $domain=$env{'user.domain'};
                   12938:     $name=$env{'user.name'};
                   12939:     if ($name eq 'public' && $domain eq 'public') {
                   12940: 	if (!defined($env{'form.username'})) {
                   12941: 	    $env{'form.username'}.=time.rand(10000000);
                   12942: 	}
                   12943: 	$name.=$env{'form.username'};
                   12944:     }
                   12945:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12946: 
                   12947: }
                   12948: 
1.36      albertel 12949: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12950: # returns either the contents of the file or 
                   12951: # -1 if the file doesn't exist
1.481     raeburn  12952: #
                   12953: # if the target is a file that was uploaded via DOCS, 
                   12954: # a check will be made to see if a current copy exists on the local server,
                   12955: # if it does this will be served, otherwise a copy will be retrieved from
                   12956: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12957: # the local server.   
1.472     albertel 12958: 
1.36      albertel 12959: sub getfile {
1.538     albertel 12960:     my ($file) = @_;
1.609     banghart 12961:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12962:     &repcopy($file);
                   12963:     return &readfile($file);
                   12964: }
                   12965: 
                   12966: sub repcopy_userfile {
                   12967:     my ($file)=@_;
1.1142    raeburn  12968:     my $londocroot = $perlvar{'lonDocRoot'};
                   12969:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12970:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12971:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12972: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12973:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12974:     if (-e "$file") {
1.828     www      12975: # we already have a local copy, check it out
1.538     albertel 12976: 	my @fileinfo = stat($file);
1.828     www      12977: 	my $rtncode;
                   12978: 	my $info;
1.538     albertel 12979: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12980: 	if ($lwpresp ne 'ok') {
1.828     www      12981: # there is no such file anymore, even though we had a local copy
1.482     albertel 12982: 	    if ($rtncode eq '404') {
1.538     albertel 12983: 		unlink($file);
1.482     albertel 12984: 	    }
                   12985: 	    return -1;
                   12986: 	}
                   12987: 	if ($info < $fileinfo[9]) {
1.828     www      12988: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12989: 	    return 'ok';
1.828     www      12990: 	} else {
                   12991: # the file is outdated, get rid of it
                   12992: 	    unlink($file);
1.482     albertel 12993: 	}
1.828     www      12994:     }
                   12995: # one way or the other, at this point, we don't have the file
                   12996: # construct the correct path for the file
                   12997:     my @parts = ($cdom,$cnum); 
                   12998:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12999: 	push @parts, split(/\//,$1);
                   13000:     }
                   13001:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13002:     foreach my $part (@parts) {
                   13003: 	$path .= '/'.$part;
                   13004: 	if (!-e $path) {
                   13005: 	    mkdir($path,0770);
1.482     albertel 13006: 	}
                   13007:     }
1.828     www      13008: # now the path exists for sure
                   13009: # get a user agent
                   13010:     my $ua=new LWP::UserAgent;
                   13011:     my $transferfile=$file.'.in.transfer';
                   13012: # FIXME: this should flock
                   13013:     if (-e $transferfile) { return 'ok'; }
                   13014:     my $request;
                   13015:     $uri=~s/^\///;
1.980     raeburn  13016:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13017:     my $hostname = &hostname($homeserver);
1.980     raeburn  13018:     my $protocol = $protocol{$homeserver};
                   13019:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13020:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13021:     my $response=$ua->request($request,$transferfile);
                   13022: # did it work?
                   13023:     if ($response->is_error()) {
                   13024: 	unlink($transferfile);
                   13025: 	&logthis("Userfile repcopy failed for $uri");
                   13026: 	return -1;
                   13027:     }
                   13028: # worked, rename the transfer file
                   13029:     rename($transferfile,$file);
1.607     raeburn  13030:     return 'ok';
1.481     raeburn  13031: }
                   13032: 
1.517     albertel 13033: sub tokenwrapper {
                   13034:     my $uri=shift;
1.980     raeburn  13035:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13036:     $uri=~s|^/||;
1.620     albertel 13037:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13038:     my $token=$1;
1.552     albertel 13039:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13040:     if ($udom && $uname && $file) {
                   13041: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13042:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13043:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13044:         my $hostname = &hostname($homeserver);
1.980     raeburn  13045:         my $protocol = $protocol{$homeserver};
                   13046:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13047:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13048:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13049:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13050:     } else {
                   13051:         return '/adm/notfound.html';
                   13052:     }
                   13053: }
                   13054: 
1.828     www      13055: # call with reqtype HEAD: get last modification time
                   13056: # call with reqtype GET: get the file contents
                   13057: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13058: #
1.481     raeburn  13059: sub getuploaded {
                   13060:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13061:     $uri=~s/^\///;
1.980     raeburn  13062:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13063:     my $hostname = &hostname($homeserver);
1.980     raeburn  13064:     my $protocol = $protocol{$homeserver};
                   13065:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13066:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13067:     my $ua=new LWP::UserAgent;
                   13068:     my $request=new HTTP::Request($reqtype,$uri);
                   13069:     my $response=$ua->request($request);
                   13070:     $$rtncode = $response->code;
1.482     albertel 13071:     if (! $response->is_success()) {
                   13072: 	return 'failed';
                   13073:     }      
                   13074:     if ($reqtype eq 'HEAD') {
1.486     www      13075: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13076:     } elsif ($reqtype eq 'GET') {
                   13077: 	$$info = $response->content;
1.472     albertel 13078:     }
1.482     albertel 13079:     return 'ok';
1.36      albertel 13080: }
                   13081: 
1.481     raeburn  13082: sub readfile {
                   13083:     my $file = shift;
                   13084:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13085:     my $fh;
1.1172.2.96  raeburn  13086:     open($fh,"<",$file);
1.481     raeburn  13087:     my $a='';
1.800     albertel 13088:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13089:     return $a;
                   13090: }
                   13091: 
1.36      albertel 13092: sub filelocation {
1.590     banghart 13093:     my ($dir,$file) = @_;
                   13094:     my $location;
                   13095:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13096: 
                   13097:     if ($file =~ m-^/adm/-) {
                   13098: 	$file=~s-^/adm/wrapper/-/-;
                   13099: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13100:     }
1.882     albertel 13101: 
1.1139    www      13102:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13103:         $location = $file;
1.609     banghart 13104:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13105:         my ($udom,$uname,$filename)=
1.811     albertel 13106:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13107:         my $home=&homeserver($uname,$udom);
                   13108:         my $is_me=0;
                   13109:         my @ids=&current_machine_ids();
                   13110:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13111:         if ($is_me) {
1.1117    foxr     13112:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13113:         } else {
                   13114:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13115:   	      $udom.'/'.$uname.'/'.$filename;
                   13116:         }
1.882     albertel 13117:     } elsif ($file =~ m-^/adm/-) {
                   13118: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13119:     } else {
                   13120:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13121:         $file=~s:^/(res|priv)/:/:;
                   13122:         my $space=$1;
1.590     banghart 13123:         if ( !( $file =~ m:^/:) ) {
                   13124:             $location = $dir. '/'.$file;
                   13125:         } else {
1.1142    raeburn  13126:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13127:         }
1.59      albertel 13128:     }
1.590     banghart 13129:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13130:     while ($location=~m{/\.\./}) {
                   13131: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13132: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13133: 	} else {
                   13134: 	    $location=~ s{/\.\./}{/}g;
                   13135: 	}
                   13136:     } #remove dir/..
1.590     banghart 13137:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13138:     return $location;
1.46      www      13139: }
1.36      albertel 13140: 
1.46      www      13141: sub hreflocation {
                   13142:     my ($dir,$file)=@_;
1.980     raeburn  13143:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13144: 	$file=filelocation($dir,$file);
1.700     albertel 13145:     } elsif ($file=~m-^/adm/-) {
                   13146: 	$file=~s-^/adm/wrapper/-/-;
                   13147: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13148:     }
                   13149:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13150: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13151:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13152: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13153: 	        {/uploaded/$1/$2/}x;
1.46      www      13154:     }
1.913     albertel 13155:     if ($file=~ m{^/userfiles/}) {
                   13156: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13157:     }
1.462     albertel 13158:     return $file;
1.465     albertel 13159: }
                   13160: 
1.1139    www      13161: 
                   13162: 
                   13163: 
                   13164: 
1.465     albertel 13165: sub current_machine_domains {
1.853     albertel 13166:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13167: }
                   13168: 
                   13169: sub machine_domains {
                   13170:     my ($hostname) = @_;
1.465     albertel 13171:     my @domains;
1.838     albertel 13172:     my %hostname = &all_hostnames();
1.465     albertel 13173:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13174: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13175: 	if ($hostname eq $name) {
1.844     albertel 13176: 	    push(@domains,&host_domain($id));
1.465     albertel 13177: 	}
                   13178:     }
                   13179:     return @domains;
                   13180: }
                   13181: 
                   13182: sub current_machine_ids {
1.853     albertel 13183:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13184: }
                   13185: 
                   13186: sub machine_ids {
                   13187:     my ($hostname) = @_;
                   13188:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13189:     my @ids;
1.888     albertel 13190:     my %name_to_host = &all_names();
1.889     albertel 13191:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13192: 	return @{ $name_to_host{$hostname} };
                   13193:     }
                   13194:     return;
1.31      www      13195: }
                   13196: 
1.824     raeburn  13197: sub additional_machine_domains {
                   13198:     my @domains;
1.1172.2.96  raeburn  13199:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13200:     while( my $line = <$fh>) {
                   13201:         $line =~ s/\s//g;
                   13202:         push(@domains,$line);
                   13203:     }
                   13204:     return @domains;
                   13205: }
                   13206: 
                   13207: sub default_login_domain {
                   13208:     my $domain = $perlvar{'lonDefDomain'};
                   13209:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13210:     foreach my $posdom (&current_machine_domains(),
                   13211:                         &additional_machine_domains()) {
                   13212:         if (lc($posdom) eq lc($testdomain)) {
                   13213:             $domain=$posdom;
                   13214:             last;
                   13215:         }
                   13216:     }
                   13217:     return $domain;
                   13218: }
                   13219: 
1.1172.2.106  raeburn  13220: sub shared_institution {
                   13221:     my ($dom) = @_;
                   13222:     my $same_intdom;
                   13223:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13224:     if ($hostintdom ne '') {
                   13225:         my %iphost = &get_iphost();
                   13226:         my $primary_id = &domain($dom,'primary');
                   13227:         my $primary_ip = &get_host_ip($primary_id);
                   13228:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13229:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13230:                 my $intdom = &internet_dom($id);
                   13231:                 if ($intdom eq $hostintdom) {
                   13232:                     $same_intdom = 1;
                   13233:                     last;
                   13234:                 }
                   13235:             }
                   13236:         }
                   13237:     }
                   13238:     return $same_intdom;
                   13239: }
                   13240: 
1.1172.2.120  raeburn  13241: sub uses_sts {
                   13242:     my ($ignore_cache) = @_;
                   13243:     my $lonhost = $perlvar{'lonHostID'};
                   13244:     my $hostname = &hostname($lonhost);
                   13245:     my $sts_on;
                   13246:     if ($protocol{$lonhost} eq 'https') {
                   13247:         my $cachetime = 12*3600;
                   13248:         if (!$ignore_cache) {
                   13249:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13250:             if (defined($cached)) {
                   13251:                 return $sts_on;
                   13252:             }
                   13253:         }
1.1172.2.121! raeburn  13254:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13255:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13256:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121! raeburn  13257:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13258:         if ($response->is_success) {
                   13259:             my $has_sts = $response->header('Strict-Transport-Security');
                   13260:             if ($has_sts eq '') {
                   13261:                 $sts_on = 0;
                   13262:             } else {
                   13263:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13264:                     my $maxage = $1;
                   13265:                     if ($maxage) {
                   13266:                         $sts_on = 1;
                   13267:                     } else {
                   13268:                         $sts_on = 0;
                   13269:                     }
                   13270:                 } else {
                   13271:                     $sts_on = 0;
                   13272:                 }
                   13273:             }
                   13274:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13275:         }
                   13276:     }
                   13277:     return;
                   13278: }
                   13279: 
1.31      www      13280: # ------------------------------------------------------------- Declutters URLs
                   13281: 
                   13282: sub declutter {
                   13283:     my $thisfn=shift;
1.569     albertel 13284:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13285:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13286:         $thisfn=~s{^/home/httpd/html}{};
                   13287:     }
1.31      www      13288:     $thisfn=~s/^\///;
1.697     albertel 13289:     $thisfn=~s|^adm/wrapper/||;
                   13290:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13291:     $thisfn=~s/^res\///;
1.1172    bisitz   13292:     $thisfn=~s/^priv\///;
1.1032    raeburn  13293:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13294:         $thisfn=~s/\?.+$//;
                   13295:     }
1.268     www      13296:     return $thisfn;
                   13297: }
                   13298: 
                   13299: # ------------------------------------------------------------- Clutter up URLs
                   13300: 
                   13301: sub clutter {
                   13302:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13303:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13304: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13305:        $thisfn='/res'.$thisfn; 
                   13306:     }
1.1031    raeburn  13307:     if ($thisfn !~m|^/adm|) {
                   13308: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13309: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13310: 	} else {
                   13311: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13312: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13313: 	    if ($embstyle eq 'ssi'
                   13314: 		|| ($embstyle eq 'hdn')
                   13315: 		|| ($embstyle eq 'rat')
                   13316: 		|| ($embstyle eq 'prv')
                   13317: 		|| ($embstyle eq 'ign')) {
                   13318: 		#do nothing with these
                   13319: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13320: 		|| ($embstyle eq 'emb')
                   13321: 		|| ($embstyle eq 'wrp')) {
                   13322: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13323: 	    } elsif ($embstyle eq 'unk'
                   13324: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13325: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13326: 	    } else {
1.718     www      13327: #		&logthis("Got a blank emb style");
1.695     albertel 13328: 	    }
1.694     albertel 13329: 	}
                   13330:     }
1.31      www      13331:     return $thisfn;
1.12      www      13332: }
                   13333: 
1.787     albertel 13334: sub clutter_with_no_wrapper {
                   13335:     my $uri = &clutter(shift);
                   13336:     if ($uri =~ m-^/adm/-) {
                   13337: 	$uri =~ s-^/adm/wrapper/-/-;
                   13338: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13339:     }
                   13340:     return $uri;
                   13341: }
                   13342: 
1.557     albertel 13343: sub freeze_escape {
                   13344:     my ($value)=@_;
                   13345:     if (ref($value)) {
                   13346: 	$value=&nfreeze($value);
                   13347: 	return '__FROZEN__'.&escape($value);
                   13348:     }
                   13349:     return &escape($value);
                   13350: }
                   13351: 
1.11      www      13352: 
1.557     albertel 13353: sub thaw_unescape {
                   13354:     my ($value)=@_;
                   13355:     if ($value =~ /^__FROZEN__/) {
                   13356: 	substr($value,0,10,undef);
                   13357: 	$value=&unescape($value);
                   13358: 	return &thaw($value);
                   13359:     }
                   13360:     return &unescape($value);
                   13361: }
                   13362: 
1.436     albertel 13363: sub correct_line_ends {
                   13364:     my ($result)=@_;
                   13365:     $$result =~s/\r\n/\n/mg;
                   13366:     $$result =~s/\r/\n/mg;
1.415     albertel 13367: }
1.1       albertel 13368: # ================================================================ Main Program
                   13369: 
1.184     www      13370: sub goodbye {
1.204     albertel 13371:    &logthis("Starting Shut down");
1.443     albertel 13372: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13373:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13374: #converted
1.599     albertel 13375: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13376:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13377: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13378: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13379: #1.1 only
1.870     albertel 13380: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13381: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13382: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13383: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13384:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13385:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13386:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13387:    &flushcourselogs();
                   13388:    &logthis("Shutting down");
                   13389: }
                   13390: 
1.852     albertel 13391: sub get_dns {
1.1172.2.17  raeburn  13392:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13393:     if (!$ignore_cache) {
                   13394: 	my ($content,$cached)=
                   13395: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13396: 	if ($cached) {
1.1172.2.17  raeburn  13397: 	    &$func($content,$hashref);
1.869     albertel 13398: 	    return;
                   13399: 	}
                   13400:     }
                   13401: 
                   13402:     my %alldns;
1.1172.2.96  raeburn  13403:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13404:         foreach my $dns (<$config>) {
                   13405: 	    next if ($dns !~ /^\^(\S*)/x);
                   13406:             my $line = $1;
                   13407:             my ($host,$protocol) = split(/:/,$line);
                   13408:             if ($protocol ne 'https') {
                   13409:                 $protocol = 'http';
                   13410:             }
                   13411: 	    $alldns{$host} = $protocol;
1.979     raeburn  13412:         }
1.1172.2.96  raeburn  13413:         close($config);
1.869     albertel 13414:     }
                   13415:     while (%alldns) {
1.1172.2.52  raeburn  13416: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13417: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13418:         $ua->timeout(30);
1.979     raeburn  13419: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13420: 	my $response=$ua->request($request);
1.979     raeburn  13421:         delete($alldns{$dns});
1.852     albertel 13422: 	next if ($response->is_error());
                   13423: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13424:         unless ($nocache) {
1.1172.2.23  raeburn  13425: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13426:         }
                   13427: 	&$func(\@content,$hashref);
1.869     albertel 13428: 	return;
1.852     albertel 13429:     }
1.871     albertel 13430:     my $which = (split('/',$url))[3];
                   13431:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13432:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13433:         my @content = <$config>;
                   13434:         &$func(\@content,$hashref);
                   13435:     }
1.1172.2.17  raeburn  13436:     return;
                   13437: }
                   13438: 
                   13439: # ------------------------------------------------------Get DNS checksums file
                   13440: sub parse_dns_checksums_tab {
                   13441:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13442:     my $lonhost = $perlvar{'lonHostID'};
                   13443:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13444:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13445:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13446:     my $webconfdir = '/etc/httpd/conf';
                   13447:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13448:         $webconfdir = '/etc/apache2';
                   13449:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13450:         if ($1 >= 10) {
                   13451:             $webconfdir = '/etc/apache2';
                   13452:         }
                   13453:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13454:         if ($1 >= 10.0) {
                   13455:             $webconfdir = '/etc/apache2';
                   13456:         }
                   13457:     }
1.1172.2.17  raeburn  13458:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13459:     my (%chksum,%revnum);
                   13460:     if (ref($lines) eq 'ARRAY') {
                   13461:         chomp(@{$lines});
1.1172.2.34  raeburn  13462:         my $version = shift(@{$lines});
                   13463:         if ($version eq $release) {
1.1172.2.17  raeburn  13464:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13465:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13466:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13467:                     if ($webconfdir eq '/etc/apache2') {
                   13468:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13469:                     }
                   13470:                 }
1.1172.2.34  raeburn  13471:                 $chksum{$file} = $shasum;
                   13472:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13473:             }
                   13474:             if (ref($hashref) eq 'HASH') {
                   13475:                 %{$hashref} = (
                   13476:                                 sums     => \%chksum,
                   13477:                                 versions => \%revnum,
                   13478:                               );
                   13479:             }
                   13480:         }
                   13481:     }
1.869     albertel 13482:     return;
1.852     albertel 13483: }
1.1172.2.17  raeburn  13484: 
                   13485: sub fetch_dns_checksums {
                   13486:     my %checksums;
1.1172.2.34  raeburn  13487:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13488:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13489:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13490:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13491:              \%checksums);
                   13492:     return \%checksums;
                   13493: }
                   13494: 
1.327     albertel 13495: # ------------------------------------------------------------ Read domain file
                   13496: {
1.852     albertel 13497:     my $loaded;
1.846     albertel 13498:     my %domain;
                   13499: 
1.852     albertel 13500:     sub parse_domain_tab {
                   13501: 	my ($lines) = @_;
                   13502: 	foreach my $line (@$lines) {
                   13503: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13504: 
1.846     albertel 13505: 	    chomp($line);
1.852     albertel 13506: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13507: 	    my %this_domain;
                   13508: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13509: 			       'lang_def', 'city', 'longi', 'lati',
                   13510: 			       'primary') {
                   13511: 		$this_domain{$field} = shift(@elements);
                   13512: 	    }
                   13513: 	    $domain{$name} = \%this_domain;
1.852     albertel 13514: 	}
                   13515:     }
1.864     albertel 13516: 
                   13517:     sub reset_domain_info {
                   13518: 	undef($loaded);
                   13519: 	undef(%domain);
                   13520:     }
                   13521: 
1.852     albertel 13522:     sub load_domain_tab {
1.1172.2.70  raeburn  13523: 	my ($ignore_cache,$nocache) = @_;
                   13524: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13525: 	my $fh;
1.1172.2.96  raeburn  13526: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13527: 	    my @lines = <$fh>;
                   13528: 	    &parse_domain_tab(\@lines);
1.448     albertel 13529: 	}
1.852     albertel 13530: 	close($fh);
                   13531: 	$loaded = 1;
1.327     albertel 13532:     }
1.846     albertel 13533: 
                   13534:     sub domain {
1.852     albertel 13535: 	&load_domain_tab() if (!$loaded);
                   13536: 
1.846     albertel 13537: 	my ($name,$what) = @_;
                   13538: 	return if ( !exists($domain{$name}) );
                   13539: 
                   13540: 	if (!$what) {
                   13541: 	    return $domain{$name}{'description'};
                   13542: 	}
                   13543: 	return $domain{$name}{$what};
                   13544:     }
1.974     raeburn  13545: 
                   13546:     sub domain_info {
                   13547:         &load_domain_tab() if (!$loaded);
                   13548:         return %domain;
                   13549:     }
                   13550: 
1.327     albertel 13551: }
                   13552: 
                   13553: 
1.1       albertel 13554: # ------------------------------------------------------------- Read hosts file
                   13555: {
1.838     albertel 13556:     my %hostname;
1.844     albertel 13557:     my %hostdom;
1.845     albertel 13558:     my %libserv;
1.852     albertel 13559:     my $loaded;
1.888     albertel 13560:     my %name_to_host;
1.1074    raeburn  13561:     my %internetdom;
1.1107    raeburn  13562:     my %LC_dns_serv;
1.852     albertel 13563: 
                   13564:     sub parse_hosts_tab {
                   13565: 	my ($file) = @_;
                   13566: 	foreach my $configline (@$file) {
                   13567: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13568:             chomp($configline);
                   13569: 	    if ($configline =~ /^\^/) {
                   13570:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13571:                     $LC_dns_serv{$1} = 1;
                   13572:                 }
                   13573:                 next;
                   13574:             }
1.1074    raeburn  13575: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13576: 	    $name=~s/\s//g;
                   13577: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13578:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13579:                     my $curr = $hostname{$id};
                   13580:                     my $skip;
                   13581:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13582:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13583:                             $skip = 1;
                   13584:                         } else {
                   13585:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13586:                         }
                   13587:                     }
                   13588:                     unless ($skip) {
                   13589:                         push(@{$name_to_host{$name}},$id);
                   13590:                     }
                   13591:                 } else {
                   13592:                     push(@{$name_to_host{$name}},$id);
                   13593:                 }
1.852     albertel 13594: 		$hostname{$id}=$name;
                   13595: 		$hostdom{$id}=$domain;
                   13596: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13597:                 if (defined($protocol)) {
                   13598:                     if ($protocol eq 'https') {
                   13599:                         $protocol{$id} = $protocol;
                   13600:                     } else {
                   13601:                         $protocol{$id} = 'http'; 
                   13602:                     }
1.968     raeburn  13603:                 } else {
1.969     raeburn  13604:                     $protocol{$id} = 'http';
1.968     raeburn  13605:                 }
1.1074    raeburn  13606:                 if (defined($intdom)) {
                   13607:                     $internetdom{$id} = $intdom;
                   13608:                 }
1.852     albertel 13609: 	    }
                   13610: 	}
                   13611:     }
1.864     albertel 13612:     
                   13613:     sub reset_hosts_info {
1.897     albertel 13614: 	&purge_remembered();
1.864     albertel 13615: 	&reset_domain_info();
                   13616: 	&reset_hosts_ip_info();
1.892     albertel 13617: 	undef(%name_to_host);
1.864     albertel 13618: 	undef(%hostname);
                   13619: 	undef(%hostdom);
                   13620: 	undef(%libserv);
                   13621: 	undef($loaded);
                   13622:     }
1.1       albertel 13623: 
1.852     albertel 13624:     sub load_hosts_tab {
1.1172.2.70  raeburn  13625: 	my ($ignore_cache,$nocache) = @_;
                   13626: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13627: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13628: 	my @config = <$config>;
                   13629: 	&parse_hosts_tab(\@config);
                   13630: 	close($config);
                   13631: 	$loaded=1;
1.1       albertel 13632:     }
1.852     albertel 13633: 
1.838     albertel 13634:     sub hostname {
1.852     albertel 13635: 	&load_hosts_tab() if (!$loaded);
                   13636: 
1.838     albertel 13637: 	my ($lonid) = @_;
                   13638: 	return $hostname{$lonid};
                   13639:     }
1.845     albertel 13640: 
1.838     albertel 13641:     sub all_hostnames {
1.852     albertel 13642: 	&load_hosts_tab() if (!$loaded);
                   13643: 
1.838     albertel 13644: 	return %hostname;
                   13645:     }
1.845     albertel 13646: 
1.888     albertel 13647:     sub all_names {
1.1172.2.70  raeburn  13648:         my ($ignore_cache,$nocache) = @_;
                   13649: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13650: 
                   13651: 	return %name_to_host;
                   13652:     }
                   13653: 
1.974     raeburn  13654:     sub all_host_domain {
                   13655:         &load_hosts_tab() if (!$loaded);
                   13656:         return %hostdom;
                   13657:     }
                   13658: 
1.845     albertel 13659:     sub is_library {
1.852     albertel 13660: 	&load_hosts_tab() if (!$loaded);
                   13661: 
1.845     albertel 13662: 	return exists($libserv{$_[0]});
                   13663:     }
                   13664: 
                   13665:     sub all_library {
1.852     albertel 13666: 	&load_hosts_tab() if (!$loaded);
                   13667: 
1.845     albertel 13668: 	return %libserv;
                   13669:     }
                   13670: 
1.1062    droeschl 13671:     sub unique_library {
                   13672: 	#2x reverse removes all hostnames that appear more than once
                   13673:         my %unique = reverse &all_library();
                   13674:         return reverse %unique;
                   13675:     }
                   13676: 
1.841     albertel 13677:     sub get_servers {
1.852     albertel 13678: 	&load_hosts_tab() if (!$loaded);
                   13679: 
1.841     albertel 13680: 	my ($domain,$type) = @_;
                   13681: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13682: 	                                          : %hostname;
                   13683: 	my %result;
1.842     albertel 13684: 	if (ref($domain) eq 'ARRAY') {
                   13685: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13686: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13687: 		    $result{$host} = $hostname;
                   13688: 		}
                   13689: 	    }
                   13690: 	} else {
                   13691: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13692: 		if ($hostdom{$host} eq $domain) {
                   13693: 		    $result{$host} = $hostname;
                   13694: 		}
1.841     albertel 13695: 	    }
                   13696: 	}
                   13697: 	return %result;
                   13698:     }
1.845     albertel 13699: 
1.1062    droeschl 13700:     sub get_unique_servers {
                   13701:         my %unique = reverse &get_servers(@_);
                   13702: 	return reverse %unique;
                   13703:     }
                   13704: 
1.844     albertel 13705:     sub host_domain {
1.852     albertel 13706: 	&load_hosts_tab() if (!$loaded);
                   13707: 
1.844     albertel 13708: 	my ($lonid) = @_;
                   13709: 	return $hostdom{$lonid};
                   13710:     }
                   13711: 
1.841     albertel 13712:     sub all_domains {
1.852     albertel 13713: 	&load_hosts_tab() if (!$loaded);
                   13714: 
1.841     albertel 13715: 	my %seen;
                   13716: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13717: 	return @uniq;
                   13718:     }
1.1074    raeburn  13719: 
                   13720:     sub internet_dom {
                   13721:         &load_hosts_tab() if (!$loaded);
                   13722: 
                   13723:         my ($lonid) = @_;
                   13724:         return $internetdom{$lonid};
                   13725:     }
1.1107    raeburn  13726: 
                   13727:     sub is_LC_dns {
                   13728:         &load_hosts_tab() if (!$loaded);
                   13729: 
                   13730:         my ($hostname) = @_;
                   13731:         return exists($LC_dns_serv{$hostname});
                   13732:     }
                   13733: 
1.1       albertel 13734: }
                   13735: 
1.847     albertel 13736: { 
                   13737:     my %iphost;
1.856     albertel 13738:     my %name_to_ip;
                   13739:     my %lonid_to_ip;
1.869     albertel 13740: 
1.847     albertel 13741:     sub get_hosts_from_ip {
                   13742: 	my ($ip) = @_;
                   13743: 	my %iphosts = &get_iphost();
                   13744: 	if (ref($iphosts{$ip})) {
                   13745: 	    return @{$iphosts{$ip}};
                   13746: 	}
                   13747: 	return;
1.839     albertel 13748:     }
1.864     albertel 13749:     
                   13750:     sub reset_hosts_ip_info {
                   13751: 	undef(%iphost);
                   13752: 	undef(%name_to_ip);
                   13753: 	undef(%lonid_to_ip);
                   13754:     }
1.856     albertel 13755: 
                   13756:     sub get_host_ip {
                   13757: 	my ($lonid) = @_;
                   13758: 	if (exists($lonid_to_ip{$lonid})) {
                   13759: 	    return $lonid_to_ip{$lonid};
                   13760: 	}
                   13761: 	my $name=&hostname($lonid);
                   13762:    	my $ip = gethostbyname($name);
                   13763: 	return if (!$ip || length($ip) ne 4);
                   13764: 	$ip=inet_ntoa($ip);
                   13765: 	$name_to_ip{$name}   = $ip;
                   13766: 	$lonid_to_ip{$lonid} = $ip;
                   13767: 	return $ip;
                   13768:     }
1.847     albertel 13769:     
                   13770:     sub get_iphost {
1.1172.2.70  raeburn  13771: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13772: 
1.869     albertel 13773: 	if (!$ignore_cache) {
                   13774: 	    if (%iphost) {
                   13775: 		return %iphost;
                   13776: 	    }
                   13777: 	    my ($ip_info,$cached)=
                   13778: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13779: 	    if ($cached) {
                   13780: 		%iphost      = %{$ip_info->[0]};
                   13781: 		%name_to_ip  = %{$ip_info->[1]};
                   13782: 		%lonid_to_ip = %{$ip_info->[2]};
                   13783: 		return %iphost;
                   13784: 	    }
                   13785: 	}
1.894     albertel 13786: 
                   13787: 	# get yesterday's info for fallback
                   13788: 	my %old_name_to_ip;
                   13789: 	my ($ip_info,$cached)=
                   13790: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13791: 	if ($cached) {
                   13792: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13793: 	}
                   13794: 
1.1172.2.70  raeburn  13795: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13796: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13797: 	    my $ip;
                   13798: 	    if (!exists($name_to_ip{$name})) {
                   13799: 		$ip = gethostbyname($name);
                   13800: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13801: 		    if (defined($old_name_to_ip{$name})) {
                   13802: 			$ip = $old_name_to_ip{$name};
                   13803: 			&logthis("Can't find $name defaulting to old $ip");
                   13804: 		    } else {
                   13805: 			&logthis("Name $name no IP found");
                   13806: 			next;
                   13807: 		    }
                   13808: 		} else {
                   13809: 		    $ip=inet_ntoa($ip);
1.847     albertel 13810: 		}
                   13811: 		$name_to_ip{$name} = $ip;
                   13812: 	    } else {
                   13813: 		$ip = $name_to_ip{$name};
1.653     albertel 13814: 	    }
1.888     albertel 13815: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13816: 		$lonid_to_ip{$id} = $ip;
                   13817: 	    }
                   13818: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13819: 	}
1.1172.2.70  raeburn  13820:         unless ($nocache) {
                   13821: 	    &do_cache_new('iphost','iphost',
                   13822: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13823: 		          48*60*60);
                   13824:         }
1.869     albertel 13825: 
1.847     albertel 13826: 	return %iphost;
1.598     albertel 13827:     }
                   13828: 
1.992     raeburn  13829:     #
                   13830:     #  Given a DNS returns the loncapa host name for that DNS 
                   13831:     # 
                   13832:     sub host_from_dns {
                   13833:         my ($dns) = @_;
                   13834:         my @hosts;
                   13835:         my $ip;
                   13836: 
1.993     raeburn  13837:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13838:             $ip = $name_to_ip{$dns};
                   13839:         }
                   13840:         if (!$ip) {
                   13841:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13842:             if (length($ip) == 4) { 
                   13843: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13844:             }
                   13845:         }
                   13846:         if ($ip) {
                   13847: 	    @hosts = get_hosts_from_ip($ip);
                   13848: 	    return $hosts[0];
                   13849:         }
                   13850:         return undef;
1.986     foxr     13851:     }
1.992     raeburn  13852: 
1.1074    raeburn  13853:     sub get_internet_names {
                   13854:         my ($lonid) = @_;
                   13855:         return if ($lonid eq '');
                   13856:         my ($idnref,$cached)=
                   13857:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13858:         if ($cached) {
                   13859:             return $idnref;
                   13860:         }
                   13861:         my $ip = &get_host_ip($lonid);
                   13862:         my @hosts = &get_hosts_from_ip($ip);
                   13863:         my %iphost = &get_iphost();
                   13864:         my (@idns,%seen);
                   13865:         foreach my $id (@hosts) {
                   13866:             my $dom = &host_domain($id);
                   13867:             my $prim_id = &domain($dom,'primary');
                   13868:             my $prim_ip = &get_host_ip($prim_id);
                   13869:             next if ($seen{$prim_ip});
                   13870:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13871:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13872:                     my $intdom = &internet_dom($id);
                   13873:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13874:                         push(@idns,$intdom);
                   13875:                     }
                   13876:                 }
                   13877:             }
                   13878:             $seen{$prim_ip} = 1;
                   13879:         }
1.1172.2.23  raeburn  13880:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13881:     }
                   13882: 
1.986     foxr     13883: }
                   13884: 
1.1079    raeburn  13885: sub all_loncaparevs {
1.1172.2.39  raeburn  13886:     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 2.11);
1.1079    raeburn  13887: }
                   13888: 
1.1172.2.27  raeburn  13889: # ------------------------------------------------------- Read loncaparev table
                   13890: {
                   13891:     sub load_loncaparevs {
                   13892:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13893:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13894:                 while (my $configline=<$config>) {
                   13895:                     chomp($configline);
                   13896:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13897:                     $loncaparevs{$hostid}=$loncaparev;
                   13898:                 }
                   13899:                 close($config);
                   13900:             }
                   13901:         }
                   13902:     }
                   13903: }
                   13904: 
                   13905: # ----------------------------------------------------- Read serverhostID table
                   13906: {
                   13907:     sub load_serverhomeIDs {
                   13908:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13909:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13910:                 while (my $configline=<$config>) {
                   13911:                     chomp($configline);
                   13912:                     my ($name,$id)=split(/:/,$configline);
                   13913:                     $serverhomeIDs{$name}=$id;
                   13914:                 }
                   13915:                 close($config);
                   13916:             }
                   13917:         }
                   13918:     }
                   13919: }
                   13920: 
                   13921: 
1.862     albertel 13922: BEGIN {
                   13923: 
                   13924: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13925:     unless ($readit) {
                   13926: {
                   13927:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13928:     %perlvar = (%perlvar,%{$configvars});
                   13929: }
                   13930: 
                   13931: 
1.1       albertel 13932: # ------------------------------------------------------ Read spare server file
                   13933: {
1.1172.2.96  raeburn  13934:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13935: 
                   13936:     while (my $configline=<$config>) {
                   13937:        chomp($configline);
1.284     matthew  13938:        if ($configline) {
1.784     albertel 13939: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13940: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13941: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13942:        }
                   13943:     }
1.448     albertel 13944:     close($config);
1.1       albertel 13945: }
1.11      www      13946: # ------------------------------------------------------------ Read permissions
                   13947: {
1.1172.2.96  raeburn  13948:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13949: 
                   13950:     while (my $configline=<$config>) {
1.448     albertel 13951: 	chomp($configline);
                   13952: 	if ($configline) {
                   13953: 	    my ($role,$perm)=split(/ /,$configline);
                   13954: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13955: 	}
1.11      www      13956:     }
1.448     albertel 13957:     close($config);
1.11      www      13958: }
                   13959: 
                   13960: # -------------------------------------------- Read plain texts for permissions
                   13961: {
1.1172.2.96  raeburn  13962:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13963: 
                   13964:     while (my $configline=<$config>) {
1.448     albertel 13965: 	chomp($configline);
                   13966: 	if ($configline) {
1.742     raeburn  13967: 	    my ($short,@plain)=split(/:/,$configline);
                   13968:             %{$prp{$short}} = ();
                   13969: 	    if (@plain > 0) {
                   13970:                 $prp{$short}{'std'} = $plain[0];
                   13971:                 for (my $i=1; $i<@plain; $i++) {
                   13972:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13973:                 }
                   13974:             }
1.448     albertel 13975: 	}
1.135     www      13976:     }
1.448     albertel 13977:     close($config);
1.135     www      13978: }
                   13979: 
                   13980: # ---------------------------------------------------------- Read package table
                   13981: {
1.1172.2.96  raeburn  13982:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13983: 
                   13984:     while (my $configline=<$config>) {
1.483     albertel 13985: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13986: 	chomp($configline);
                   13987: 	my ($short,$plain)=split(/:/,$configline);
                   13988: 	my ($pack,$name)=split(/\&/,$short);
                   13989: 	if ($plain ne '') {
                   13990: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13991: 	    $packagetab{$short}=$plain; 
                   13992: 	}
1.11      www      13993:     }
1.448     albertel 13994:     close($config);
1.329     matthew  13995: }
                   13996: 
1.1172.2.27  raeburn  13997: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13998: 
1.1172.2.27  raeburn  13999: &load_loncaparevs();
                   14000: 
                   14001: # ------------------------------------------------------- Read serverhostID table
                   14002: 
                   14003: &load_serverhomeIDs();
1.1074    raeburn  14004: 
1.1172.2.27  raeburn  14005: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14006: {
                   14007:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14008:     if (-e $file) {
                   14009:         my $parser = HTML::LCParser->new($file);
                   14010:         while (my $token = $parser->get_token()) {
                   14011:             if ($token->[0] eq 'S') {
                   14012:                 my $item = $token->[1];
                   14013:                 my $name = $token->[2]{'name'};
                   14014:                 my $value = $token->[2]{'value'};
                   14015:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14016:                     my $release = $parser->get_text();
                   14017:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14018:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14019:                 }
                   14020:             }
                   14021:         }
                   14022:     }
1.1073    raeburn  14023: }
                   14024: 
1.1138    raeburn  14025: # ---------------------------------------------------------- Read managers table
                   14026: {
                   14027:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14028:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14029:             while (my $configline=<$config>) {
                   14030:                 chomp($configline);
                   14031:                 next if ($configline =~ /^\#/);
                   14032:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14033:                     $managerstab{$configline} = 1;
                   14034:                 }
                   14035:             }
                   14036:             close($config);
                   14037:         }
                   14038:     }
                   14039: }
                   14040: 
1.329     matthew  14041: # ------------- set up temporary directory
                   14042: {
1.1117    foxr     14043:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14044: 
1.11      www      14045: }
                   14046: 
1.1172.2.104  raeburn  14047: # ------------- set default texengine (domain default overrides this)
                   14048: {
                   14049:     $deftex = LONCAPA::texengine();
                   14050: }
                   14051: 
1.1172.2.114  raeburn  14052: # ------------- set default minimum length for passwords for internal auth users
                   14053: {
                   14054:     $passwdmin = LONCAPA::passwd_min();
                   14055: }
                   14056: 
1.794     albertel 14057: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14058: 				'compress_threshold'=> 20_000,
                   14059:  			        });
1.185     www      14060: 
1.281     www      14061: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14062: $dumpcount=0;
1.958     www      14063: $locknum=0;
1.22      www      14064: 
1.163     harris41 14065: &logtouch();
1.672     albertel 14066: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14067: $readit=1;
1.564     albertel 14068:     {
                   14069: 	use integer;
                   14070: 	my $test=(2**32)+1;
1.568     albertel 14071: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14072: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14073:     }
1.195     www      14074: }
1.1       albertel 14075: }
1.179     www      14076: 
1.1       albertel 14077: 1;
1.191     harris41 14078: __END__
                   14079: 
1.243     albertel 14080: =pod
                   14081: 
1.191     harris41 14082: =head1 NAME
                   14083: 
1.243     albertel 14084: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14085: 
                   14086: =head1 SYNOPSIS
                   14087: 
1.243     albertel 14088: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14089: 
                   14090:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14091: 
1.243     albertel 14092: Common parameters:
                   14093: 
                   14094: =over 4
                   14095: 
                   14096: =item *
                   14097: 
                   14098: $uname : an internal username (if $cname expecting a course Id specifically)
                   14099: 
                   14100: =item *
                   14101: 
                   14102: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14103: 
                   14104: =item *
                   14105: 
                   14106: $symb : a resource instance identifier
                   14107: 
                   14108: =item *
                   14109: 
                   14110: $namespace : the name of a .db file that contains the data needed or
                   14111: being set.
                   14112: 
                   14113: =back
                   14114: 
1.394     bowersj2 14115: =head1 OVERVIEW
1.191     harris41 14116: 
1.394     bowersj2 14117: lonnet provides subroutines which interact with the
                   14118: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14119: about classes, users, and resources.
1.243     albertel 14120: 
                   14121: For many of these objects you can also use this to store data about
                   14122: them or modify them in various ways.
1.191     harris41 14123: 
1.394     bowersj2 14124: =head2 Symbs
1.191     harris41 14125: 
1.394     bowersj2 14126: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14127: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14128: map, the resource number of the resource in the map, and the URL of
                   14129: the resource itself. The latter is somewhat redundant, but might help
                   14130: if maps change.
                   14131: 
                   14132: An example is
                   14133: 
                   14134:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14135: 
                   14136: The respective map entry is
                   14137: 
                   14138:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14139:   title="Problem 2">
                   14140:  </resource>
                   14141: 
                   14142: Symbs are used by the random number generator, as well as to store and
                   14143: restore data specific to a certain instance of for example a problem.
                   14144: 
                   14145: =head2 Storing And Retrieving Data
                   14146: 
                   14147: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14148: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14149: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14150: is is the non-critical message twin of cstore. These functions are for
                   14151: handlers to store a perl hash to a user's permanent data space in an
                   14152: easy manner, and to retrieve it again on another call. It is expected
                   14153: that a handler would use this once at the beginning to retrieve data,
                   14154: and then again once at the end to send only the new data back.
                   14155: 
                   14156: The data is stored in the user's data directory on the user's
                   14157: homeserver under the ID of the course.
                   14158: 
                   14159: The hash that is returned by restore will have all of the previous
                   14160: value for all of the elements of the hash.
                   14161: 
                   14162: Example:
                   14163: 
                   14164:  #creating a hash
                   14165:  my %hash;
                   14166:  $hash{'foo'}='bar';
                   14167: 
                   14168:  #storing it
                   14169:  &Apache::lonnet::cstore(\%hash);
                   14170: 
                   14171:  #changing a value
                   14172:  $hash{'foo'}='notbar';
                   14173: 
                   14174:  #adding a new value
                   14175:  $hash{'bar'}='foo';
                   14176:  &Apache::lonnet::cstore(\%hash);
                   14177: 
                   14178:  #retrieving the hash
                   14179:  my %history=&Apache::lonnet::restore();
                   14180: 
                   14181:  #print the hash
                   14182:  foreach my $key (sort(keys(%history))) {
                   14183:    print("\%history{$key} = $history{$key}");
                   14184:  }
                   14185: 
                   14186: Will print out:
1.191     harris41 14187: 
1.394     bowersj2 14188:  %history{1:foo} = bar
                   14189:  %history{1:keys} = foo:timestamp
                   14190:  %history{1:timestamp} = 990455579
                   14191:  %history{2:bar} = foo
                   14192:  %history{2:foo} = notbar
                   14193:  %history{2:keys} = foo:bar:timestamp
                   14194:  %history{2:timestamp} = 990455580
                   14195:  %history{bar} = foo
                   14196:  %history{foo} = notbar
                   14197:  %history{timestamp} = 990455580
                   14198:  %history{version} = 2
                   14199: 
                   14200: Note that the special hash entries C<keys>, C<version> and
                   14201: C<timestamp> were added to the hash. C<version> will be equal to the
                   14202: total number of versions of the data that have been stored. The
                   14203: C<timestamp> attribute will be the UNIX time the hash was
                   14204: stored. C<keys> is available in every historical section to list which
                   14205: keys were added or changed at a specific historical revision of a
                   14206: hash.
                   14207: 
                   14208: B<Warning>: do not store the hash that restore returns directly. This
                   14209: will cause a mess since it will restore the historical keys as if the
                   14210: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14211: 
1.394     bowersj2 14212: Calling convention:
1.191     harris41 14213: 
1.1172.2.27  raeburn  14214:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14215:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14216: 
1.394     bowersj2 14217: For more detailed information, see lonnet specific documentation.
1.191     harris41 14218: 
1.394     bowersj2 14219: =head1 RETURN MESSAGES
1.191     harris41 14220: 
1.394     bowersj2 14221: =over 4
1.191     harris41 14222: 
1.394     bowersj2 14223: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14224: 
1.394     bowersj2 14225: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14226: when the connection is brought back up
1.191     harris41 14227: 
1.394     bowersj2 14228: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14229: for later delivery
1.191     harris41 14230: 
1.967     bisitz   14231: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14232: 
1.394     bowersj2 14233: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14234: that was requested
1.191     harris41 14235: 
1.243     albertel 14236: =back
1.191     harris41 14237: 
1.243     albertel 14238: =head1 PUBLIC SUBROUTINES
1.191     harris41 14239: 
1.243     albertel 14240: =head2 Session Environment Functions
1.191     harris41 14241: 
1.243     albertel 14242: =over 4
1.191     harris41 14243: 
1.394     bowersj2 14244: =item * 
                   14245: X<appenv()>
1.949     raeburn  14246: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14247: the user envirnoment file, and will be restored for each access this
1.620     albertel 14248: user makes during this session, also modifies the %env for the current
1.949     raeburn  14249: process. Optional rolesarrayref - if defined contains a reference to an array
                   14250: of roles which are exempt from the restriction on modifying user.role entries 
                   14251: in the user's environment.db and in %env.    
1.191     harris41 14252: 
                   14253: =item *
1.394     bowersj2 14254: X<delenv()>
1.987     raeburn  14255: B<delenv($delthis,$regexp)>: removes all items from the session
                   14256: environment file that begin with $delthis. If the 
                   14257: optional second arg - $regexp - is true, $delthis is treated as a 
                   14258: regular expression, otherwise \Q$delthis\E is used. 
                   14259: The values are also deleted from the current processes %env.
1.191     harris41 14260: 
1.795     albertel 14261: =item * get_env_multiple($name) 
                   14262: 
                   14263: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14264: values may be defined and end up as an array ref.
                   14265: 
                   14266: returns an array of values
                   14267: 
1.243     albertel 14268: =back
                   14269: 
                   14270: =head2 User Information
1.191     harris41 14271: 
1.243     albertel 14272: =over 4
1.191     harris41 14273: 
                   14274: =item *
1.394     bowersj2 14275: X<queryauthenticate()>
                   14276: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14277: authentication scheme
                   14278: 
                   14279: =item *
1.394     bowersj2 14280: X<authenticate()>
1.1073    raeburn  14281: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14282: authenticate user from domain's lib servers (first use the current
                   14283: one). C<$upass> should be the users password.
1.1073    raeburn  14284: $checkdefauth is optional (value is 1 if a check should be made to
                   14285:    authenticate user using default authentication method, and allow
                   14286:    account creation if username does not have account in the domain).
                   14287: $clientcancheckhost is optional (value is 1 if checking whether the
                   14288:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14289: 
                   14290: =item *
1.394     bowersj2 14291: X<homeserver()>
                   14292: B<homeserver($uname,$udom)>: find the server which has
                   14293: the user's directory and files (there must be only one), this caches
                   14294: the answer, and also caches if there is a borken connection.
1.191     harris41 14295: 
                   14296: =item *
1.394     bowersj2 14297: X<idget()>
                   14298: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14299: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14300: username, and only 1 username per ID in a specific domain) (returns
                   14301: hash: id=>name,id=>name)
1.191     harris41 14302: 
                   14303: =item *
1.394     bowersj2 14304: X<idrget()>
                   14305: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14306: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14307: 
                   14308: =item *
1.394     bowersj2 14309: X<idput()>
                   14310: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14311: 
                   14312: =item *
1.394     bowersj2 14313: X<rolesinit()>
1.1169    droeschl 14314: B<rolesinit($udom,$username)>: get user privileges.
                   14315: returns user role, first access and timer interval hashes
1.243     albertel 14316: 
                   14317: =item *
1.1171    droeschl 14318: X<privileged()>
                   14319: B<privileged($username,$domain)>: returns a true if user has a
                   14320: privileged and active role (i.e. su or dc), false otherwise.
                   14321: 
                   14322: =item *
1.551     albertel 14323: X<getsection()>
                   14324: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14325: course $cname, return section name/number or '' for "not in course"
                   14326: and '-1' for "no section"
                   14327: 
                   14328: =item *
1.394     bowersj2 14329: X<userenvironment()>
                   14330: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14331: passed in @what from the requested user's environment, returns a hash
                   14332: 
1.858     raeburn  14333: =item * 
                   14334: X<userlog_query()>
1.859     albertel 14335: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14336: activity.log file. %filters defines filters applied when parsing the
                   14337: log file. These can be start or end timestamps, or the type of action
                   14338: - log to look for Login or Logout events, check for Checkin or
                   14339: Checkout, role for role selection. The response is in the form
                   14340: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14341: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14342: 
1.243     albertel 14343: =back
                   14344: 
                   14345: =head2 User Roles
                   14346: 
                   14347: =over 4
                   14348: 
                   14349: =item *
                   14350: 
1.1172.2.65  raeburn  14351: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14352: returns codes for allowed actions.
                   14353: 
                   14354: The first argument is required, all others are optional.
                   14355: 
                   14356: $priv is the privilege being checked.
                   14357: $uri contains additional information about what is being checked for access (e.g.,
                   14358: URL, course ID etc.).
                   14359: $symb is the unique resource instance identifier in a course; if needed,
                   14360: but not provided, it will be retrieved via a call to &symbread().
                   14361: $role is the role for which a priv is being checked (only used if priv is evb).
                   14362: $clientip is the user's IP address (only used when checking for access to portfolio
                   14363: files).
                   14364: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14365: prevents recursive calls to &allowed.
                   14366: 
1.243     albertel 14367:  F: full access
                   14368:  U,I,K: authentication modes (cxx only)
                   14369:  '': forbidden
                   14370:  1: user needs to choose course
                   14371:  2: browse allowed
1.766     albertel 14372:  A: passphrase authentication needed
1.1172.2.65  raeburn  14373:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14374: 
                   14375: =item *
                   14376: 
1.1172.2.13  raeburn  14377: constructaccess($url,$setpriv) : check for access to construction space URL
                   14378: 
                   14379: See if the owner domain and name in the URL match those in the
                   14380: expected environment.  If so, return three element list
                   14381: ($ownername,$ownerdomain,$ownerhome).
                   14382: 
                   14383: Otherwise return the null string.
                   14384: 
                   14385: If second argument 'setpriv' is true, it assigns the privileges,
                   14386: and returns the same three element list, unless the owner has
                   14387: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14388: in which case the null string is returned.
                   14389: 
                   14390: =item *
                   14391: 
1.1172.2.84  raeburn  14392: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14393: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14394: for system, domain, and course level. $uname and $udom are optional (current
                   14395: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14396: 
                   14397: =item *
                   14398: 
1.988     raeburn  14399: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14400: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14401: $type is Course (default) or Community.
1.988     raeburn  14402: If $forcedefault evaluates to true, text returned will be default 
                   14403: text for $type. Otherwise, if this is a course, the text returned 
                   14404: will be a custom name for the role (if defined in the course's 
                   14405: environment).  If no custom name is defined the default is returned.
                   14406:    
1.832     raeburn  14407: =item *
                   14408: 
1.1172.2.23  raeburn  14409: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14410: All arguments are optional. Returns a hash of a roles, either for
                   14411: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14412: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14413: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14414: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14415: For each key, value is set to colon-separated start and end times for
                   14416: the role.  If no username and domain are specified, will default to
1.934     raeburn  14417: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14418: of role statuses (active, future or previous), roles 
                   14419: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14420: to restrict the list of roles reported. If no array ref is 
                   14421: provided for types, will default to return only active roles.
1.834     albertel 14422: 
1.1172.2.13  raeburn  14423: =item *
                   14424: 
                   14425: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14426: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14427: 
                   14428: Additional optional arguments are: $type (if role checking is to be restricted
                   14429: to certain user status types -- previous (expired roles), active (currently
                   14430: available roles) or future (roles available in the future), and
                   14431: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14432: have active Domain Coordinator role in course's domain or in additional
                   14433: domains (specified in 'Domains to check for privileged users' in course
                   14434: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14435: 
                   14436: =item *
                   14437: 
                   14438: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14439: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14440: $possdomains and $possroles are optional array refs -- to domains to check and
                   14441: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14442: users' roles.db to check for a dc or su role in any domain. This can be
                   14443: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14444: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14445: this then allows &privileged_by_domain() to be used, which caches the identity
                   14446: of privileged users, eliminating the need for repeated calls to &dump().
                   14447: 
                   14448: =item *
                   14449: 
                   14450: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14451: where the outer hash keys are domains specified in the $possdomains array ref,
                   14452: next inner hash keys are privileged roles specified in the $roles array ref,
                   14453: and the innermost hash contains key = value pairs for username:domain = end:start
                   14454: for active or future "privileged" users with that role in that domain. To avoid
                   14455: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14456: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14457: 
1.243     albertel 14458: =back
                   14459: 
                   14460: =head2 User Modification
                   14461: 
                   14462: =over 4
                   14463: 
                   14464: =item *
                   14465: 
1.957     raeburn  14466: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14467: user for the level given by URL.  Optional start and end dates (leave empty
                   14468: string or zero for "no date")
1.191     harris41 14469: 
                   14470: =item *
                   14471: 
1.243     albertel 14472: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14473: change a users, password, possible return values are: ok,
                   14474: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14475: refused
1.191     harris41 14476: 
                   14477: =item *
                   14478: 
1.243     albertel 14479: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14480: 
                   14481: =item *
                   14482: 
1.1058    raeburn  14483: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14484:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14485: 
                   14486: will update user information (firstname,middlename,lastname,generation,
                   14487: permanentemail), and if forceid is true, student/employee ID also.
                   14488: A user's institutional affiliation(s) can also be updated.
                   14489: User information fields will not be overwritten with empty entries 
                   14490: unless the field is included in the $candelete array reference.
                   14491: This array is included when a single user is modified via "Manage Users",
                   14492: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14493: 
                   14494: =item *
                   14495: 
1.286     matthew  14496: modifystudent
                   14497: 
1.957     raeburn  14498: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14499: The course id is resolved based on the current user's environment.  
                   14500: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14501: associated with a course.
                   14502: 
1.297     matthew  14503: This call is essentially a wrapper for lonnet::modifyuser and
                   14504: lonnet::modify_student_enrollment
1.286     matthew  14505: 
                   14506: Inputs: 
                   14507: 
                   14508: =over 4
                   14509: 
1.957     raeburn  14510: =item B<$udom> Student's loncapa domain
1.286     matthew  14511: 
1.957     raeburn  14512: =item B<$uname> Student's loncapa login name
1.286     matthew  14513: 
1.964     bisitz   14514: =item B<$uid> Student/Employee ID
1.286     matthew  14515: 
1.957     raeburn  14516: =item B<$umode> Student's authentication mode
1.286     matthew  14517: 
1.957     raeburn  14518: =item B<$upass> Student's password
1.286     matthew  14519: 
1.957     raeburn  14520: =item B<$first> Student's first name
1.286     matthew  14521: 
1.957     raeburn  14522: =item B<$middle> Student's middle name
1.286     matthew  14523: 
1.957     raeburn  14524: =item B<$last> Student's last name
1.286     matthew  14525: 
1.957     raeburn  14526: =item B<$gene> Student's generation
1.286     matthew  14527: 
1.957     raeburn  14528: =item B<$usec> Student's section in course
1.286     matthew  14529: 
                   14530: =item B<$end> Unix time of the roles expiration
                   14531: 
                   14532: =item B<$start> Unix time of the roles start date
                   14533: 
                   14534: =item B<$forceid> If defined, allow $uid to be changed
                   14535: 
                   14536: =item B<$desiredhome> server to use as home server for student
                   14537: 
1.957     raeburn  14538: =item B<$email> Student's permanent e-mail address
                   14539: 
                   14540: =item B<$type> Type of enrollment (auto or manual)
                   14541: 
1.963     raeburn  14542: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14543: 
                   14544: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14545: 
1.963     raeburn  14546: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14547: 
1.963     raeburn  14548: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14549: 
1.1172.2.19  raeburn  14550: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14551: 
                   14552: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957     raeburn  14553: 
1.286     matthew  14554: =back
1.297     matthew  14555: 
                   14556: =item *
                   14557: 
                   14558: modify_student_enrollment
                   14559: 
1.1172.2.31  raeburn  14560: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14561: 'role.request.course' must be defined for this function to proceed.
                   14562: 
                   14563: Inputs:
                   14564: 
                   14565: =over 4
                   14566: 
1.1172.2.31  raeburn  14567: =item $udom, student's domain
1.297     matthew  14568: 
1.1172.2.31  raeburn  14569: =item $uname, student's name
1.297     matthew  14570: 
1.1172.2.31  raeburn  14571: =item $uid, student's user id
1.297     matthew  14572: 
1.1172.2.31  raeburn  14573: =item $first, student's first name
1.297     matthew  14574: 
                   14575: =item $middle
                   14576: 
                   14577: =item $last
                   14578: 
                   14579: =item $gene
                   14580: 
                   14581: =item $usec
                   14582: 
                   14583: =item $end
                   14584: 
                   14585: =item $start
                   14586: 
1.957     raeburn  14587: =item $type
                   14588: 
                   14589: =item $locktype
                   14590: 
                   14591: =item $cid
                   14592: 
                   14593: =item $selfenroll
                   14594: 
                   14595: =item $context
                   14596: 
1.1172.2.19  raeburn  14597: =item $credits, number of credits student will earn from this class
                   14598: 
1.1172.2.76  raeburn  14599: =item $instsec, institutional course section code for student
                   14600: 
1.297     matthew  14601: =back
                   14602: 
1.191     harris41 14603: 
                   14604: =item *
                   14605: 
1.243     albertel 14606: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14607: custom role; give a custom role to a user for the level given by URL.  Specify
                   14608: name and domain of role author, and role name
1.191     harris41 14609: 
                   14610: =item *
                   14611: 
1.243     albertel 14612: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14613: 
                   14614: =item *
                   14615: 
1.243     albertel 14616: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14617: 
                   14618: =back
                   14619: 
                   14620: =head2 Course Infomation
                   14621: 
                   14622: =over 4
1.191     harris41 14623: 
                   14624: =item *
                   14625: 
1.1118    foxr     14626: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14627: specified course id, including all environment settings for the
                   14628: course, the description of the course will be in the hash under the
                   14629: key 'description'
1.191     harris41 14630: 
1.1118    foxr     14631: $options is an optional parameter that if supplied is a hash reference that controls
                   14632: what how this function works.  It has the following key/values:
                   14633: 
                   14634: =over 4
                   14635: 
                   14636: =item freshen_cache
                   14637: 
                   14638: If defined, and the environment cache for the course is valid, it is 
                   14639: returned in the returned hash.
                   14640: 
                   14641: =item one_time
                   14642: 
                   14643: If defined, the last cache time is set to _now_
                   14644: 
                   14645: =item user
                   14646: 
                   14647: If defined, the supplied username is used instead of the current user.
                   14648: 
                   14649: 
                   14650: =back
                   14651: 
1.191     harris41 14652: =item *
                   14653: 
1.624     albertel 14654: resdata($name,$domain,$type,@which) : request for current parameter
                   14655: setting for a specific $type, where $type is either 'course' or 'user',
                   14656: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14657: answers for 10 minutes.
1.243     albertel 14658: 
1.877     foxr     14659: =item *
                   14660: 
                   14661: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14662: data base, returning a hash that is keyed by the resource name and has
                   14663: values that are the resource value.  I believe that the timestamps and
                   14664: versions are also returned.
                   14665: 
1.1172.2.31  raeburn  14666: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14667: supplemental content area. This routine caches the number of files for
                   14668: 10 minutes.
                   14669: 
1.243     albertel 14670: =back
                   14671: 
                   14672: =head2 Course Modification
                   14673: 
                   14674: =over 4
1.191     harris41 14675: 
                   14676: =item *
                   14677: 
1.243     albertel 14678: writecoursepref($courseid,%prefs) : write preferences (environment
                   14679: database) for a course
1.191     harris41 14680: 
                   14681: =item *
                   14682: 
1.1011    raeburn  14683: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14684: 
                   14685: =item *
                   14686: 
1.1038    raeburn  14687: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14688: 
1.1167    droeschl 14689: =item *
                   14690: 
                   14691: is_course($courseid), is_course($cdom, $cnum)
                   14692: 
                   14693: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14694: two component version $cdom, $cnum. It checks if the specified course exists.
                   14695: 
                   14696: Returns:
                   14697:     undef if the course doesn't exist, otherwise
                   14698:     in scalar context the combined courseid.
                   14699:     in list context the two components of the course identifier, domain and 
                   14700:     courseid.    
                   14701: 
1.243     albertel 14702: =back
                   14703: 
1.1172.2.109  raeburn  14704: =head2 Bubblesheet Configuration
                   14705: 
                   14706: =over 4
                   14707: 
                   14708: =item *
                   14709: 
                   14710: get_scantron_config($which)
                   14711: 
                   14712: $which - the name of the configuration to parse from the file.
                   14713: 
                   14714: Parses and returns the bubblesheet configuration line selected as a
                   14715: hash of configuration file fields.
                   14716: 
                   14717: 
                   14718: Returns:
                   14719:     If the named configuration is not in the file, an empty
                   14720:     hash is returned.
                   14721: 
                   14722:     a hash with the fields
                   14723:       name         - internal name for the this configuration setup
                   14724:       description  - text to display to operator that describes this config
                   14725:       CODElocation - if 0 or the string 'none'
                   14726:                           - no CODE exists for this config
                   14727:                      if -1 || the string 'letter'
                   14728:                           - a CODE exists for this config and is
                   14729:                             a string of letters
                   14730:                      Unsupported value (but planned for future support)
                   14731:                           if a positive integer
                   14732:                                - The CODE exists as the first n items from
                   14733:                                  the question section of the form
                   14734:                           if the string 'number'
                   14735:                                - The CODE exists for this config and is
                   14736:                                  a string of numbers
                   14737:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14738:                      the CODE starts
                   14739:       CODElength  - length of the CODE
                   14740:       IDstart     - column where the student/employee ID starts
                   14741:       IDlength    - length of the student/employee ID info
                   14742:       Qstart      - column where the information from the bubbled
                   14743:                     'questions' start
                   14744:       Qlength     - number of columns comprising a single bubble line from
                   14745:                     the sheet. (usually either 1 or 10)
                   14746:       Qon         - either a single character representing the character used
                   14747:                     to signal a bubble was chosen in the positional setup, or
                   14748:                     the string 'letter' if the letter of the chosen bubble is
                   14749:                     in the final, or 'number' if a number representing the
                   14750:                     chosen bubble is in the file (1->A 0->J)
                   14751:       Qoff        - the character used to represent that a bubble was
                   14752:                     left blank
                   14753:       PaperID     - if the scanning process generates a unique number for each
                   14754:                     sheet scanned the column that this ID number starts in
                   14755:       PaperIDlength - number of columns that comprise the unique ID number
                   14756:                       for the sheet of paper
                   14757:       FirstName   - column that the first name starts in
                   14758:       FirstNameLength - number of columns that the first name spans
                   14759:       LastName    - column that the last name starts in
                   14760:       LastNameLength - number of columns that the last name spans
                   14761:       BubblesPerRow - number of bubbles available in each row used to
                   14762:                       bubble an answer. (If not specified, 10 assumed).
                   14763: 
                   14764: 
                   14765: =item *
                   14766: 
                   14767: get_scantronformat_file($cdom)
                   14768: 
                   14769: $cdom - the course's domain (optional); if not supplied, uses
                   14770: domain for current $env{'request.course.id'}.
                   14771: 
                   14772: Returns an array containing lines from the scantron format file for
                   14773: the domain of the course.
                   14774: 
                   14775: If a url for a custom.tab file is listed in domain's configuration.db,
                   14776: lines are from this file.
                   14777: 
                   14778: Otherwise, if a default.tab has been published in RES space by the
                   14779: domainconfig user, lines are from this file.
                   14780: 
                   14781: Otherwise, fall back to getting lines from the legacy file on the
                   14782: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14783: 
                   14784: =back
                   14785: 
1.243     albertel 14786: =head2 Resource Subroutines
                   14787: 
                   14788: =over 4
1.191     harris41 14789: 
                   14790: =item *
                   14791: 
1.243     albertel 14792: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14793: 
                   14794: =item *
                   14795: 
1.243     albertel 14796: repcopy($filename) : subscribes to the requested file, and attempts to
                   14797: replicate from the owning library server, Might return
1.607     raeburn  14798: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14799: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14800: resource. Expects the local filesystem pathname
                   14801: (/home/httpd/html/res/....)
                   14802: 
                   14803: =back
                   14804: 
                   14805: =head2 Resource Information
                   14806: 
                   14807: =over 4
1.191     harris41 14808: 
                   14809: =item *
                   14810: 
1.1172.2.28  raeburn  14811: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14812: and returns the value of a variety of different possible values,
                   14813: $varname should be a request string, and the other parameters can be
                   14814: used to specify who and what one is asking about. Ordinarily, $cid 
                   14815: does not need to be specified, as it is retrived from 
                   14816: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14817: within lonuserstate::loadmap() when initializing a course, before
                   14818: $env{'request.course.id'} has been set, so it needs to be provided
                   14819: in that one case.
1.243     albertel 14820: 
                   14821: Possible values for $varname are environment.lastname (or other item
                   14822: from the envirnment hash), user.name (or someother aspect about the
                   14823: user), resource.0.maxtries (or some other part and parameter of a
                   14824: resource)
1.204     albertel 14825: 
                   14826: =item *
                   14827: 
1.243     albertel 14828: directcondval($number) : get current value of a condition; reads from a state
                   14829: string
1.204     albertel 14830: 
                   14831: =item *
                   14832: 
1.243     albertel 14833: condval($condidx) : value of condition index based on state
1.204     albertel 14834: 
                   14835: =item *
                   14836: 
1.243     albertel 14837: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14838: resource's metadata, $what should be either a specific key, or either
                   14839: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14840: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14841: 
                   14842: this function automatically caches all requests
1.191     harris41 14843: 
                   14844: =item *
                   14845: 
1.243     albertel 14846: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14847: network of library servers; returns file handle of where SQL and regex results
                   14848: will be stored for query
1.191     harris41 14849: 
                   14850: =item *
                   14851: 
1.1172.2.66  raeburn  14852: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14853: return symbolic list entry (all arguments optional).
                   14854: 
                   14855: Args: filename is the filename (including path) for the file for which a symb
                   14856: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14857: to check access status if more than one resource was found in the bighash
                   14858: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14859: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14860: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14861: cause possible symbs to be checked to determine if they are subject to content
                   14862: blocking, if so they will not be included as possible symbs; possibles is a
                   14863: ref to a hash, which, as a side effect, will be populated with all possible
                   14864: symbs (content blocking not tested).
                   14865: 
1.243     albertel 14866: returns the data handle
1.191     harris41 14867: 
                   14868: =item *
                   14869: 
1.1172.2.17  raeburn  14870: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14871: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14872: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14873: on failure, user must be in a course, as it assumes the existence of
                   14874: the course initial hash, and uses $env('request.course.id'}.  The third
                   14875: arg is an optional reference to a scalar.  If this arg is passed in the
                   14876: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14877: encrypted; otherwise it will be null.
1.243     albertel 14878: 
1.191     harris41 14879: =item *
                   14880: 
1.243     albertel 14881: symbclean($symb) : removes versions numbers from a symb, returns the
                   14882: cleaned symb
1.191     harris41 14883: 
                   14884: =item *
                   14885: 
1.243     albertel 14886: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14887: course map, user must be in a course for it to work.
1.191     harris41 14888: 
                   14889: =item *
                   14890: 
1.243     albertel 14891: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14892: 
                   14893: =item *
                   14894: 
1.243     albertel 14895: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14896: a random seed, all arguments are optional, if they aren't sent it uses the
                   14897: environment to derive them. Note: if symb isn't sent and it can't get one
                   14898: from &symbread it will use the current time as its return value
1.191     harris41 14899: 
                   14900: =item *
                   14901: 
1.243     albertel 14902: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14903: unfakeable, receipt
1.191     harris41 14904: 
                   14905: =item *
                   14906: 
1.620     albertel 14907: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14908: 
                   14909: =item *
                   14910: 
1.243     albertel 14911: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14912: 
                   14913: =item *
                   14914: 
1.243     albertel 14915: 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 14916: 
                   14917: =item *
                   14918: 
1.243     albertel 14919: 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 14920: 
                   14921: =item *
                   14922: 
1.243     albertel 14923: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14924: 
                   14925: =item *
                   14926: 
1.243     albertel 14927: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14928: forcing spreadsheet to reevaluate the resource scores next time.
                   14929: 
1.1172.2.13  raeburn  14930: =item *
                   14931: 
                   14932: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14933: when viewing in course context.
                   14934: 
                   14935:  input: six args -- filename (decluttered), course number, course domain,
                   14936:                     url, symb (if registered) and group (if this is a
                   14937:                     group item -- e.g., bulletin board, group page etc.).
                   14938: 
                   14939:  output: array of five scalars --
                   14940:          $cfile -- url for file editing if editable on current server
                   14941:          $home -- homeserver of resource (i.e., for author if published,
                   14942:                                           or course if uploaded.).
                   14943:          $switchserver --  1 if server switch will be needed.
                   14944:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14945:          $forceview -- 1 if icon/link should be to go to view mode
                   14946: 
                   14947: =item *
                   14948: 
                   14949: is_course_upload($file,$cnum,$cdom)
                   14950: 
                   14951: Used in course context to determine if current file was uploaded to
                   14952: the course (i.e., would be found in /userfiles/docs on the course's
                   14953: homeserver.
                   14954: 
                   14955:   input: 3 args -- filename (decluttered), course number and course domain.
                   14956:   output: boolean -- 1 if file was uploaded.
                   14957: 
1.243     albertel 14958: =back
                   14959: 
                   14960: =head2 Storing/Retreiving Data
                   14961: 
                   14962: =over 4
1.191     harris41 14963: 
                   14964: =item *
                   14965: 
1.1172.2.64  raeburn  14966: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14967: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14968: the remaining args aren't required and if they aren't passed or are '' they will
                   14969: be derived from the env (with the exception of $laststore, which is an
                   14970: optional arg used when a user's submission is stored in grading).
                   14971: $laststore is $version=$timestamp, where $version is the most recent version
                   14972: number retrieved for the corresponding $symb in the $namespace db file, and
                   14973: $timestamp is the timestamp for that transaction (UNIX time).
                   14974: $laststore is currently only passed when cstore() is called by
                   14975: structuretags::finalize_storage().
1.191     harris41 14976: 
                   14977: =item *
                   14978: 
1.1172.2.64  raeburn  14979: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14980: but uses critical subroutine
1.191     harris41 14981: 
                   14982: =item *
                   14983: 
1.243     albertel 14984: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14985: all args are optional
1.191     harris41 14986: 
                   14987: =item *
                   14988: 
1.717     albertel 14989: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14990: dumps the complete (or key matching regexp) namespace into a hash
                   14991: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14992: normally &store()ed into
                   14993: 
                   14994: $range should be either an integer '100' (give me the first 100
                   14995:                                            matching records)
                   14996:               or be  two integers sperated by a - with no spaces
                   14997:                  '30-50' (give me the 30th through the 50th matching
                   14998:                           records)
                   14999: 
                   15000: 
                   15001: =item *
                   15002: 
1.1172.2.59  raeburn  15003: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15004: replaces a &store() version of data with a replacement set of data
                   15005: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15006: reference. If $tolog is true, the transaction is logged in the courselog
                   15007: with an action=PUTSTORE.
1.717     albertel 15008: 
                   15009: =item *
                   15010: 
1.243     albertel 15011: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15012: works very similar to store/cstore, but all data is stored in a
                   15013: temporary location and can be reset using tmpreset, $storehash should
                   15014: be a hash reference, returns nothing on success
1.191     harris41 15015: 
                   15016: =item *
                   15017: 
1.243     albertel 15018: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15019: similar to restore, but all data is stored in a temporary location and
                   15020: can be reset using tmpreset. Returns a hash of values on success,
                   15021: error string otherwise.
1.191     harris41 15022: 
                   15023: =item *
                   15024: 
1.243     albertel 15025: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15026: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15027: 
                   15028: =item *
                   15029: 
1.243     albertel 15030: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15031: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15032: 
                   15033: =item *
                   15034: 
1.243     albertel 15035: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15036: namesp ($udom and $uname are optional)
1.191     harris41 15037: 
                   15038: =item *
                   15039: 
1.702     albertel 15040: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15041: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15042: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15043: 
1.702     albertel 15044: $range should be either an integer '100' (give me the first 100
                   15045:                                            matching records)
                   15046:               or be  two integers sperated by a - with no spaces
                   15047:                  '30-50' (give me the 30th through the 50th matching
                   15048:                           records)
1.449     matthew  15049: =item *
                   15050: 
                   15051: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15052: $store can be a scalar, an array reference, or if the amount to be 
                   15053: incremented is > 1, a hash reference.
                   15054: 
                   15055: ($udom and $uname are optional)
1.191     harris41 15056: 
                   15057: =item *
                   15058: 
1.243     albertel 15059: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15060: ($udom and $uname are optional)
1.191     harris41 15061: 
                   15062: =item *
                   15063: 
1.243     albertel 15064: cput($namespace,$storehash,$udom,$uname) : critical put
                   15065: ($udom and $uname are optional)
1.191     harris41 15066: 
                   15067: =item *
                   15068: 
1.748     albertel 15069: newput($namespace,$storehash,$udom,$uname) :
                   15070: 
                   15071: Attempts to store the items in the $storehash, but only if they don't
                   15072: currently exist, if this succeeds you can be certain that you have 
                   15073: successfully created a new key value pair in the $namespace db.
                   15074: 
                   15075: 
                   15076: Args:
                   15077:  $namespace: name of database to store values to
                   15078:  $storehash: hashref to store to the db
                   15079:  $udom: (optional) domain of user containing the db
                   15080:  $uname: (optional) name of user caontaining the db
                   15081: 
                   15082: Returns:
                   15083:  'ok' -> succeeded in storing all keys of $storehash
                   15084:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15085:                         least <key> already existed in the db (other
                   15086:                         requested keys may also already exist)
1.967     bisitz   15087:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15088:  'con_lost' -> unable to contact request server
                   15089:  'refused' -> action was not allowed by remote machine
                   15090: 
                   15091: 
                   15092: =item *
                   15093: 
1.243     albertel 15094: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15095: reference filled in from namesp (encrypts the return communication)
                   15096: ($udom and $uname are optional)
1.191     harris41 15097: 
                   15098: =item *
                   15099: 
1.243     albertel 15100: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15101: critical subroutine
                   15102: 
1.806     raeburn  15103: =item *
                   15104: 
1.860     raeburn  15105: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15106: array reference filled in from namespace found in domain level on either
                   15107: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15108: 
                   15109: =item *
                   15110: 
1.860     raeburn  15111: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15112: domain level either on specified domain server ($uhome) or primary domain 
                   15113: server ($udom and $uhome are optional)
1.806     raeburn  15114: 
1.943     raeburn  15115: =item * 
                   15116: 
1.1172.2.35  raeburn  15117: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15118: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15119: the target domain.
                   15120: 
                   15121: May also include additional key => value pairs for the following groups:
                   15122: 
                   15123: =over
                   15124: 
                   15125: =item
                   15126: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15127: 
                   15128: =over
                   15129: 
                   15130: =item defaultquota, authorquota
                   15131: 
                   15132: =back
                   15133: 
                   15134: =item
                   15135: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15136: portfolio for users).
                   15137: 
                   15138: =over
                   15139: 
                   15140: =item
                   15141: aboutme, blog, webdav, portfolio
                   15142: 
                   15143: =back
                   15144: 
                   15145: =item
                   15146: requestcourses: ability to request courses, and how requests are processed.
                   15147: 
                   15148: =over
                   15149: 
                   15150: =item
1.1172.2.37  raeburn  15151: official, unofficial, community, textbook
1.1172.2.35  raeburn  15152: 
                   15153: =back
                   15154: 
                   15155: =item
                   15156: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15157: 
                   15158: =over
                   15159: 
                   15160: =item
1.1172.2.44  raeburn  15161: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15162: 
                   15163: =back
                   15164: 
                   15165: =item
                   15166: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15167: for course's uploaded content.
                   15168: 
                   15169: =over
                   15170: 
                   15171: =item
1.1172.2.68  raeburn  15172: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15173: communityquota, textbookquota
1.1172.2.35  raeburn  15174: 
                   15175: =back
                   15176: 
                   15177: =item
                   15178: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15179: on your servers.
                   15180: 
                   15181: =over
                   15182: 
                   15183: =item
                   15184: remotesessions, hostedsessions
                   15185: 
                   15186: =back
                   15187: 
                   15188: =back
                   15189: 
                   15190: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15191: utility to create a configuration.db file on a domain's primary library server
                   15192: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15193: -- corresponding values are authentication type (internal, krb4, krb5,
                   15194: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15195: will be available. Values are retrieved from cache (if current), unless the
                   15196: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15197: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15198: 
                   15199: Typical usage:
1.943     raeburn  15200: 
1.1172.2.35  raeburn  15201: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15202: 
1.243     albertel 15203: =back
                   15204: 
                   15205: =head2 Network Status Functions
                   15206: 
                   15207: =over 4
1.191     harris41 15208: 
                   15209: =item *
                   15210: 
1.1137    raeburn  15211: dirlist() : return directory list based on URI (first arg).
                   15212: 
                   15213: Inputs: 1 required, 5 optional.
                   15214: 
                   15215: =over
                   15216: 
                   15217: =item 
                   15218: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15219: 
                   15220: =item
                   15221: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15222: 
                   15223: =item
                   15224: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15225: 
                   15226: =item
                   15227: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15228: 
                   15229: =item
                   15230: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15231: 
                   15232: =item 
                   15233: $alternateRoot - path to prepend in place of path from $uri.
                   15234: 
                   15235: =back
                   15236: 
                   15237: Returns: Array of up to two items.
                   15238: 
                   15239: =over
                   15240: 
                   15241: a reference to an array of files/subdirectories
                   15242: 
                   15243: =over
                   15244: 
                   15245: Each element in the array of files/subdirectories is a & separated list of
                   15246: item name and the result of running stat on the item.  If dirlist was requested
                   15247: for a file instead of a directory, the item name will be ''. For a directory 
                   15248: listing, if the item is a metadata file, the element will end &N&M 
                   15249: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15250: default copyright set (1).  
                   15251: 
                   15252: =back
                   15253: 
                   15254: a scalar containing error condition (if encountered).
                   15255: 
                   15256: =over
                   15257: 
                   15258: =item 
                   15259: no_host (no homeserver identified for $username:$domain).
                   15260: 
                   15261: =item 
                   15262: no_such_host (server contacted for listing not identified as valid host).
                   15263: 
                   15264: =item 
                   15265: con_lost (connection to remote server failed).
                   15266: 
                   15267: =item 
                   15268: refused (invalid $username:$domain received on lond side).
                   15269: 
                   15270: =item 
                   15271: no_such_dir (directory at specified path on lond side does not exist). 
                   15272: 
                   15273: =item 
                   15274: empty (directory at specified path on lond side is empty).
                   15275: 
                   15276: =over
                   15277: 
                   15278: This is currently not encountered because the &ls3, &ls2, 
                   15279: &ls (_handler) routines on the lond side do not filter out
                   15280: . and .. from a directory listing. 
                   15281: 
                   15282: =back
                   15283: 
                   15284: =back
                   15285: 
                   15286: =back
1.191     harris41 15287: 
                   15288: =item *
                   15289: 
1.243     albertel 15290: spareserver() : find server with least workload from spare.tab
                   15291: 
1.986     foxr     15292: 
                   15293: =item *
                   15294: 
                   15295: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15296: if there is no corresponding loncapa host.
                   15297: 
1.243     albertel 15298: =back
                   15299: 
1.986     foxr     15300: 
1.243     albertel 15301: =head2 Apache Request
                   15302: 
                   15303: =over 4
1.191     harris41 15304: 
                   15305: =item *
                   15306: 
1.243     albertel 15307: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15308: localhost, posts hash
                   15309: 
                   15310: =back
                   15311: 
                   15312: =head2 Data to String to Data
                   15313: 
                   15314: =over 4
1.191     harris41 15315: 
                   15316: =item *
                   15317: 
1.243     albertel 15318: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15319: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15320: 
                   15321: =item *
                   15322: 
1.243     albertel 15323: hashref2str($hashref) : convert a hashref into a string complete with
                   15324: escaping and '=' and '&' separators, supports elements that are
                   15325: arrayrefs and hashrefs
1.191     harris41 15326: 
                   15327: =item *
                   15328: 
1.243     albertel 15329: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15330: with escaping and '&' separators, supports elements that are arrayrefs
                   15331: and hashrefs
1.191     harris41 15332: 
                   15333: =item *
                   15334: 
1.243     albertel 15335: str2hash($string) : convert string to hash using unescaping and
                   15336: splitting on '=' and '&', supports elements that are arrayrefs and
                   15337: hashrefs
1.191     harris41 15338: 
                   15339: =item *
                   15340: 
1.243     albertel 15341: str2array($string) : convert string to hash using unescaping and
                   15342: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15343: 
                   15344: =back
                   15345: 
                   15346: =head2 Logging Routines
                   15347: 
                   15348: 
                   15349: These routines allow one to make log messages in the lonnet.log and
                   15350: lonnet.perm logfiles.
1.191     harris41 15351: 
1.1119    foxr     15352: =over 4
                   15353: 
1.191     harris41 15354: =item *
                   15355: 
1.243     albertel 15356: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15357: 
                   15358: =item *
                   15359: 
1.243     albertel 15360: logthis() : append message to the normal lonnet.log file, it gets
                   15361: preiodically rolled over and deleted.
1.191     harris41 15362: 
                   15363: =item *
                   15364: 
1.243     albertel 15365: logperm() : append a permanent message to lonnet.perm.log, this log
                   15366: file never gets deleted by any automated portion of the system, only
                   15367: messages of critical importance should go in here.
                   15368: 
1.1119    foxr     15369: 
1.243     albertel 15370: =back
                   15371: 
                   15372: =head2 General File Helper Routines
                   15373: 
                   15374: =over 4
1.191     harris41 15375: 
                   15376: =item *
                   15377: 
1.481     raeburn  15378: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15379: (a) files in /uploaded
                   15380:   (i) If a local copy of the file exists - 
                   15381:       compares modification date of local copy with last-modified date for 
                   15382:       definitive version stored on home server for course. If local copy is 
                   15383:       stale, requests a new version from the home server and stores it. 
                   15384:       If the original has been removed from the home server, then local copy 
                   15385:       is unlinked.
                   15386:   (ii) If local copy does not exist -
                   15387:       requests the file from the home server and stores it. 
                   15388:   
                   15389:   If $caller is 'uploadrep':  
                   15390:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15391:     for request for files originally uploaded via DOCS. 
                   15392:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15393:   
                   15394:   Otherwise:
                   15395:      This indicates a call from the content generation phase of the request.
                   15396:      -  returns the entire contents of the file or -1.
                   15397:      
                   15398: (b) files in /res
                   15399:    - returns the entire contents of a file or -1; 
                   15400:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15401: 
1.712     albertel 15402: 
                   15403: =item *
                   15404: 
                   15405: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15406:                   reference
                   15407: 
                   15408: returns either a stat() list of data about the file or an empty list
                   15409: if the file doesn't exist or couldn't find out about it (connection
                   15410: problems or user unknown)
                   15411: 
1.191     harris41 15412: =item *
                   15413: 
1.243     albertel 15414: filelocation($dir,$file) : returns file system location of a file
                   15415: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15416: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15417: and a file of ../bob will become /a/bob)
1.191     harris41 15418: 
                   15419: =item *
                   15420: 
                   15421: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15422: filelocation except for hrefs
                   15423: 
                   15424: =item *
                   15425: 
1.1172.2.49  raeburn  15426: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15427: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15428: 
1.243     albertel 15429: =back
                   15430: 
1.608     albertel 15431: =head2 Usererfile file routines (/uploaded*)
                   15432: 
                   15433: =over 4
                   15434: 
                   15435: =item *
                   15436: 
                   15437: userfileupload(): main rotine for putting a file in a user or course's
                   15438:                   filespace, arguments are,
                   15439: 
1.620     albertel 15440:  formname - required - this is the name of the element in $env where the
1.608     albertel 15441:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15442:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15443:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15444:  context - if coursedoc, store the file in the course of the active role
                   15445:              of the current user; 
                   15446:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15447:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15448:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15449:          if undefined, it will be placed in "unknown"
                   15450: 
                   15451:  (This routine calls clean_filename() to remove any dangerous
                   15452:  characters from the filename, and then calls finuserfileupload() to
                   15453:  complete the transaction)
                   15454: 
                   15455:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15456:  and /adm/notfound.html if unsuccessful
                   15457: 
                   15458: =item *
                   15459: 
                   15460: clean_filename(): routine for cleaing a filename up for storage in
                   15461:                  userfile space, argument is:
                   15462: 
                   15463:  filename - proposed filename
                   15464: 
                   15465: returns: the new clean filename
                   15466: 
                   15467: =item *
                   15468: 
1.1090    raeburn  15469: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15470: userspace, probably shouldn't be called directly
                   15471: 
                   15472:   docuname: username or courseid of destination for the file
                   15473:   docudom: domain of user/course of destination for the file
                   15474:   formname: same as for userfileupload()
1.1090    raeburn  15475:   fname: filename (including subdirectories) for the file
                   15476:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15477:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15478:   allfiles: reference to hash used to store objects found by parser
                   15479:   codebase: reference to hash used for codebases of java objects found by parser
                   15480:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15481:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15482:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15483:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15484:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15485:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15486:   mimetype: reference to scalar to accommodate mime type determined
                   15487:             from File::MMagic if $parser = parse.
1.608     albertel 15488: 
                   15489:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15490:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15491:  was 'overwrite').
                   15492:  
1.608     albertel 15493: 
                   15494: =item *
                   15495: 
                   15496: renameuserfile(): renames an existing userfile to a new name
                   15497: 
                   15498:   Args:
                   15499:    docuname: username or courseid of destination for the file
                   15500:    docudom: domain of user/course of destination for the file
                   15501:    old: current file name (including any subdirs under userfiles)
                   15502:    new: desired file name (including any subdirs under userfiles)
                   15503: 
                   15504: =item *
                   15505: 
                   15506: mkdiruserfile(): creates a directory is a userfiles dir
                   15507: 
                   15508:   Args:
                   15509:    docuname: username or courseid of destination for the file
                   15510:    docudom: domain of user/course of destination for the file
                   15511:    dir: dir to create (including any subdirs under userfiles)
                   15512: 
                   15513: =item *
                   15514: 
                   15515: removeuserfile(): removes a file that exists in userfiles
                   15516: 
                   15517:   Args:
                   15518:    docuname: username or courseid of destination for the file
                   15519:    docudom: domain of user/course of destination for the file
                   15520:    fname: filname to delete (including any subdirs under userfiles)
                   15521: 
                   15522: =item *
                   15523: 
                   15524: removeuploadedurl(): convience function for removeuserfile()
                   15525: 
                   15526:   Args:
                   15527:    url:  a full /uploaded/... url to delete
                   15528: 
1.747     albertel 15529: =item * 
                   15530: 
                   15531: get_portfile_permissions():
                   15532:   Args:
                   15533:     domain: domain of user or course contain the portfolio files
                   15534:     user: name of user or num of course contain the portfolio files
                   15535:   Returns:
                   15536:     hashref of a dump of the proper file_permissions.db
                   15537:    
                   15538: 
                   15539: =item * 
                   15540: 
                   15541: get_access_controls():
                   15542: 
                   15543: Args:
                   15544:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15545:   group: (optional) the group you want the files associated with
                   15546:   file: (optional) the file you want access info on
                   15547: 
                   15548: Returns:
1.749     raeburn  15549:     a hash (keys are file names) of hashes containing
                   15550:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15551:         values are XML containing access control settings (see below) 
1.747     albertel 15552: 
                   15553: Internal notes:
                   15554: 
1.749     raeburn  15555:  access controls are stored in file_permissions.db as key=value pairs.
                   15556:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15557:         where scope -> public,guest,course,group,domains or users.
                   15558:               end -> UNIX time for end of access (0 -> no end date)
                   15559:               start -> UNIX time for start of access
                   15560: 
                   15561:     value -> XML description of access control
                   15562:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15563:             <start></start>
                   15564:             <end></end>
                   15565: 
                   15566:             <password></password>  for scope type = guest
                   15567: 
                   15568:             <domain></domain>     for scope type = course or group
                   15569:             <number></number>
                   15570:             <roles id="">
                   15571:              <role></role>
                   15572:              <access></access>
                   15573:              <section></section>
                   15574:              <group></group>
                   15575:             </roles>
                   15576: 
                   15577:             <dom></dom>         for scope type = domains
                   15578: 
                   15579:             <users>             for scope type = users
                   15580:              <user>
                   15581:               <uname></uname>
                   15582:               <udom></udom>
                   15583:              </user>
                   15584:             </users>
                   15585:            </scope> 
                   15586:               
                   15587:  Access data is also aggregated for each file in an additional key=value pair:
                   15588:  key -> path to file/file_name\0accesscontrol 
                   15589:  value -> reference to hash
                   15590:           hash contains key = value pairs
                   15591:           where key = uniqueID:scope_end_start
                   15592:                 value = UNIX time record was last updated
                   15593: 
                   15594:           Used to improve speed of look-ups of access controls for each file.  
                   15595:  
                   15596:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15597: 
1.1172.2.13  raeburn  15598: =item *
                   15599: 
1.749     raeburn  15600: modify_access_controls():
                   15601: 
                   15602: Modifies access controls for a portfolio file
                   15603: Args
                   15604: 1. file name
                   15605: 2. reference to hash of required changes,
                   15606: 3. domain
                   15607: 4. username
                   15608:   where domain,username are the domain of the portfolio owner 
                   15609:   (either a user or a course) 
                   15610: 
                   15611: Returns:
                   15612: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15613: 2. result of deletions ('ok' or 'error', with error message).
                   15614: 3. reference to hash of any new or updated access controls.
                   15615: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15616:    key = integer (inbound ID)
1.1172.2.13  raeburn  15617:    value = uniqueID
                   15618: 
                   15619: =item *
                   15620: 
                   15621: get_timebased_id():
                   15622: 
                   15623: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15624: course via the Course Editor (e.g., folders, composite pages,
                   15625: group bulletin boards).
                   15626: 
                   15627: Args: (first three required; six others optional)
                   15628: 
                   15629: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15630:    docssequence, or name of group
                   15631: 
                   15632: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15633:    e.g., num, boardids
                   15634: 
                   15635: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15636:    file will be named nohist_namespace.db
                   15637: 
                   15638: 4. cdom: domain of course; default is current course domain from %env
                   15639: 
                   15640: 5. cnum: course number; default is current course number from %env
                   15641: 
                   15642: 6. idtype: set to concat if an additional digit is to be appended to the
                   15643:    unix timestamp to form the suffix, if the plain timestamp is already
                   15644:    in use.  Default is to not do this, but simply increment the unix
                   15645:    timestamp by 1 until a unique key is obtained.
                   15646: 
                   15647: 7. who: holder of locking key; defaults to user:domain for user.
                   15648: 
                   15649: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15650:    retrying); default is 3.
                   15651: 
                   15652: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15653: 
                   15654: Returns:
                   15655: 
                   15656: 1. suffix obtained (numeric)
                   15657: 
                   15658: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15659: 
                   15660: 3. error: contains (localized) error message if an error occurred.
                   15661: 
1.747     albertel 15662: 
1.608     albertel 15663: =back
                   15664: 
1.243     albertel 15665: =head2 HTTP Helper Routines
                   15666: 
                   15667: =over 4
                   15668: 
1.191     harris41 15669: =item *
                   15670: 
                   15671: escape() : unpack non-word characters into CGI-compatible hex codes
                   15672: 
                   15673: =item *
                   15674: 
                   15675: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15676: 
1.243     albertel 15677: =back
                   15678: 
                   15679: =head1 PRIVATE SUBROUTINES
                   15680: 
                   15681: =head2 Underlying communication routines (Shouldn't call)
                   15682: 
                   15683: =over 4
                   15684: 
                   15685: =item *
                   15686: 
                   15687: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15688: 
                   15689: =item *
                   15690: 
                   15691: reply() : uses subreply to send a message to remote machine, logs all failures
                   15692: 
                   15693: =item *
                   15694: 
                   15695: critical() : passes a critical message to another server; if cannot
                   15696: get through then place message in connection buffer directory and
                   15697: returns con_delayed, if incapable of saving message, returns
                   15698: con_failed
                   15699: 
                   15700: =item *
                   15701: 
                   15702: reconlonc() : tries to reconnect lonc client processes.
                   15703: 
                   15704: =back
                   15705: 
                   15706: =head2 Resource Access Logging
                   15707: 
                   15708: =over 4
                   15709: 
                   15710: =item *
                   15711: 
                   15712: flushcourselogs() : flush (save) buffer logs and access logs
                   15713: 
                   15714: =item *
                   15715: 
                   15716: courselog($what) : save message for course in hash
                   15717: 
                   15718: =item *
                   15719: 
                   15720: courseacclog($what) : save message for course using &courselog().  Perform
                   15721: special processing for specific resource types (problems, exams, quizzes, etc).
                   15722: 
1.191     harris41 15723: =item *
                   15724: 
                   15725: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15726: as a PerlChildExitHandler
1.243     albertel 15727: 
                   15728: =back
                   15729: 
                   15730: =head2 Other
                   15731: 
                   15732: =over 4
                   15733: 
                   15734: =item *
                   15735: 
                   15736: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15737: 
                   15738: =back
                   15739: 
                   15740: =cut
1.877     foxr     15741: 

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