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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .9(raebu    4:20): # $Id: lonnet.pm,v 1.1172.2.118.2.8 2020/10/01 13:19:14 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.118.  .3(raebu  266:20):                     my $hostname = &hostname($lonhost);
1.1073    raeburn   267:                     my $protocol = $protocol{$lonhost};
                    268:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu  269:20):                     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.118.  .3(raebu  960:20):                 my $protocol = 'http';
                    961:20):                 if ($protocol{$spare_server} eq 'https') {
                    962:20):                     $protocol = $protocol{$spare_server};
                    963:20):                 }
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.1172.2.118.  .5(raebu 1165:20): sub get_course_sessions {
                   1166:20):     my ($cnum,$cdom,$lastactivity) = @_;
                   1167:20):     my %servers = &internet_dom_servers($cdom);
                   1168:20):     my %returnhash;
                   1169:20):     foreach my $server (sort(keys(%servers))) {
                   1170:20):         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1171:20):         my @pairs=split(/\&/,$rep);
                   1172:20):         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1173:20):             foreach my $item (@pairs) {
                   1174:20):                 my ($key,$value)=split(/=/,$item,2);
                   1175:20):                 $key = &unescape($key);
                   1176:20):                 next if ($key =~ /^error: 2 /);
                   1177:20):                 if (exists($returnhash{$key})) {
                   1178:20):                     next if ($value < $returnhash{$key});
                   1179:20):                 }
                   1180:20):                 $returnhash{$key}=$value;
                   1181:20):             }
                   1182:20):         }
                   1183:20):     }
                   1184:20):     return %returnhash;
                   1185:20): }
                   1186:20): 
1.202     matthew  1187: # --------------------------------------------- Try to change a user's password
                   1188: 
                   1189: sub changepass {
1.799     raeburn  1190:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1191:     $currentpass = &escape($currentpass);
                   1192:     $newpass     = &escape($newpass);
1.1030    raeburn  1193:     my $lonhost = $perlvar{'lonHostID'};
                   1194:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1195: 		       $server);
                   1196:     if (! $answer) {
                   1197: 	&logthis("No reply on password change request to $server ".
                   1198: 		 "by $uname in domain $udom.");
                   1199:     } elsif ($answer =~ "^ok") {
                   1200:         &logthis("$uname in $udom successfully changed their password ".
                   1201: 		 "on $server.");
                   1202:     } elsif ($answer =~ "^pwchange_failure") {
                   1203: 	&logthis("$uname in $udom was unable to change their password ".
                   1204: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1205: 		 "or pwchange");
                   1206:     } elsif ($answer =~ "^non_authorized") {
                   1207:         &logthis("$uname in $udom did not get their password correct when ".
                   1208: 		 "attempting to change it on $server.");
                   1209:     } elsif ($answer =~ "^auth_mode_error") {
                   1210:         &logthis("$uname in $udom attempted to change their password despite ".
                   1211: 		 "not being locally or internally authenticated on $server.");
                   1212:     } elsif ($answer =~ "^unknown_user") {
                   1213:         &logthis("$uname in $udom attempted to change their password ".
                   1214: 		 "on $server but were unable to because $server is not ".
                   1215: 		 "their home server.");
                   1216:     } elsif ($answer =~ "^refused") {
                   1217: 	&logthis("$server refused to change $uname in $udom password because ".
                   1218: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1219:     } elsif ($answer =~ "invalid_client") {
                   1220:         &logthis("$server refused to change $uname in $udom password because ".
                   1221:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1222:     } elsif ($answer =~ "^prioruse") {
                   1223:        &logthis("$server refused to change $uname in $udom password because ".
                   1224:                 "the password had been used before");
1.202     matthew  1225:     }
                   1226:     return $answer;
1.1       albertel 1227: }
                   1228: 
1.169     harris41 1229: # ----------------------- Try to determine user's current authentication scheme
                   1230: 
                   1231: sub queryauthenticate {
                   1232:     my ($uname,$udom)=@_;
1.456     albertel 1233:     my $uhome=&homeserver($uname,$udom);
                   1234:     if (!$uhome) {
                   1235: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1236: 	return 'no_host';
                   1237:     }
                   1238:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1239:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1240: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1241:     }
1.456     albertel 1242:     return $answer;
1.169     harris41 1243: }
                   1244: 
1.1       albertel 1245: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1246: 
1.1       albertel 1247: sub authenticate {
1.1073    raeburn  1248:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1249:     $upass=&escape($upass);
                   1250:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1251:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1252:     my $newhome;
1.836     www      1253:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1254: # Maybe the machine was offline and only re-appeared again recently?
                   1255:         &reconlonc();
                   1256: # One more
1.952     raeburn  1257: 	$uhome=&homeserver($uname,$udom,1);
                   1258:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1259:             if (defined(&domain($udom,'primary'))) {
                   1260:                 $newhome=&domain($udom,'primary');
                   1261:             }
                   1262:             if ($newhome ne '') {
                   1263:                 $uhome = $newhome;
                   1264:             }
                   1265:         }
1.836     www      1266: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1267: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1268: 	    return 'no_host';
                   1269:         }
1.1       albertel 1270:     }
1.1073    raeburn  1271:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1272:     if ($answer eq 'authorized') {
1.952     raeburn  1273:         if ($newhome) {
                   1274:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1275:             return 'no_account_on_host'; 
                   1276:         } else {
                   1277:             &logthis("User $uname at $udom authorized by $uhome");
                   1278:             return $uhome;
                   1279:         }
1.471     albertel 1280:     }
                   1281:     if ($answer eq 'non_authorized') {
                   1282: 	&logthis("User $uname at $udom rejected by $uhome");
                   1283: 	return 'no_host'; 
1.9       www      1284:     }
1.471     albertel 1285:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1286:     return 'no_host';
                   1287: }
                   1288: 
1.1073    raeburn  1289: sub can_host_session {
1.1074    raeburn  1290:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1291:     my $canhost = 1;
1.1074    raeburn  1292:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1293:     if (ref($remotesessions) eq 'HASH') {
                   1294:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1295:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1296:                 $canhost = 0;
                   1297:             } else {
                   1298:                 $canhost = 1;
                   1299:             }
                   1300:         }
                   1301:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1302:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1303:                 $canhost = 1;
                   1304:             } else {
                   1305:                 $canhost = 0;
                   1306:             }
                   1307:         }
                   1308:         if ($canhost) {
                   1309:             if ($remotesessions->{'version'} ne '') {
                   1310:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1311:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1312:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1313:                         my $major = $1;
                   1314:                         my $minor = $2;
                   1315:                         if (($major < $reqmajor ) ||
                   1316:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1317:                             $canhost = 0;
                   1318:                         }
                   1319:                     } else {
                   1320:                         $canhost = 0;
                   1321:                     }
                   1322:                 }
                   1323:             }
                   1324:         }
                   1325:     }
                   1326:     if ($canhost) {
                   1327:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1328:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1329:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1330:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1331:                 if (($uint_dom ne '') && 
                   1332:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1333:                     $canhost = 0;
                   1334:                 } else {
                   1335:                     $canhost = 1;
                   1336:                 }
                   1337:             }
                   1338:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1339:                 if (($uint_dom ne '') && 
                   1340:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1341:                     $canhost = 1;
                   1342:                 } else {
                   1343:                     $canhost = 0;
                   1344:                 }
                   1345:             }
                   1346:         }
                   1347:     }
                   1348:     return $canhost;
                   1349: }
                   1350: 
1.1083    raeburn  1351: sub spare_can_host {
                   1352:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1353:     my $canhost=1;
1.1172.2.62  raeburn  1354:     my $try_server_hostname = &hostname($try_server);
                   1355:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1356:     my $serverhomedom = &host_domain($serverhomeID);
                   1357:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1358:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1359:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1360:             $canhost = 0;
                   1361:         }
                   1362:     }
                   1363:     if (($canhost) && ($uint_dom)) {
                   1364:         my @intdoms;
                   1365:         my $internet_names = &get_internet_names($try_server);
                   1366:         if (ref($internet_names) eq 'ARRAY') {
                   1367:             @intdoms = @{$internet_names};
                   1368:         }
                   1369:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1370:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1371:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1372:                                          $remotesessions,
                   1373:                                          $defdomdefaults{'hostedsessions'});
                   1374:         }
1.1083    raeburn  1375:     }
                   1376:     return $canhost;
                   1377: }
                   1378: 
1.1123    raeburn  1379: sub this_host_spares {
                   1380:     my ($dom) = @_;
1.1126    raeburn  1381:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1382:     my @hosts = &current_machine_ids();
                   1383:     foreach my $lonhost (@hosts) {
                   1384:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1385:             $dom_in_use = $dom;
                   1386:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1387:             last;
                   1388:         }
                   1389:     }
1.1126    raeburn  1390:     if ($dom_in_use ne '') {
                   1391:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1392:     }
                   1393:     if (ref($result) ne 'HASH') {
                   1394:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1395:         $dom_in_use = &host_domain($lonhost_in_use);
                   1396:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1397:         if (ref($result) ne 'HASH') {
                   1398:             $result = \%spareid;
                   1399:         }
                   1400:     }
                   1401:     return $result;
                   1402: }
                   1403: 
                   1404: sub spares_for_offload  {
                   1405:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1406:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1407:     if (defined($cached)) {
                   1408:         return $result;
                   1409:     } else {
1.1126    raeburn  1410:         my $cachetime = 60*60*24;
                   1411:         my %domconfig =
                   1412:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1413:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1414:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1415:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1416:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1417:                 }
                   1418:             }
                   1419:         }
                   1420:     }
1.1126    raeburn  1421:     return;
1.1123    raeburn  1422: }
                   1423: 
1.1129    raeburn  1424: sub get_lonbalancer_config {
                   1425:     my ($servers) = @_;
                   1426:     my ($currbalancer,$currtargets);
                   1427:     if (ref($servers) eq 'HASH') {
                   1428:         foreach my $server (keys(%{$servers})) {
                   1429:             my %what = (
                   1430:                          spareid => 1,
                   1431:                          perlvar => 1,
                   1432:                        );
                   1433:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1434:             if ($result eq 'ok') {
                   1435:                 if (ref($returnhash) eq 'HASH') {
                   1436:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1437:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1438:                             $currbalancer = $server;
                   1439:                             $currtargets = {};
                   1440:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1441:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1442:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1443:                                 }
                   1444:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1445:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1446:                                 }
                   1447:                             }
                   1448:                             last;
                   1449:                         }
                   1450:                     }
                   1451:                 }
                   1452:             }
                   1453:         }
                   1454:     }
                   1455:     return ($currbalancer,$currtargets);
                   1456: }
                   1457: 
                   1458: sub check_loadbalancing {
1.1172.2.88  raeburn  1459:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1460:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1461:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1462:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1463:     my @hosts = &current_machine_ids();
1.1129    raeburn  1464:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1465:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1466:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1467:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1468:     my $domneedscache; 
1.1129    raeburn  1469:     my $cachetime = 60*60*24;
                   1470: 
                   1471:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1472:         $dom_in_use = $udom;
                   1473:         $homeintdom = 1;
                   1474:     } else {
                   1475:         $dom_in_use = $serverhomedom;
                   1476:     }
                   1477:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1478:     unless (defined($cached)) {
                   1479:         my %domconfig =
                   1480:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1481:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1482:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1483:         } else {
                   1484:             $domneedscache = $dom_in_use;
1.1129    raeburn  1485:         }
                   1486:     }
                   1487:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1488:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1489:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1490:         if ($is_balancer) {
                   1491:             if (ref($currrules) eq 'HASH') {
                   1492:                 if ($homeintdom) {
                   1493:                     if ($uname ne '') {
                   1494:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1495:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1496:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1497:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1498:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1499:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1500:                             }
                   1501:                         }
                   1502:                         if ($rule_in_effect eq '') {
                   1503:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1504:                             if ($userenv{'inststatus'} ne '') {
                   1505:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1506:                                 my ($othertitle,$usertypes,$types) =
                   1507:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1508:                                 if (ref($types) eq 'ARRAY') {
                   1509:                                     foreach my $type (@{$types}) {
                   1510:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1511:                                             if (exists($currrules->{$type})) {
                   1512:                                                 $rule_in_effect = $currrules->{$type};
                   1513:                                             }
                   1514:                                         }
                   1515:                                     }
                   1516:                                 }
                   1517:                             } else {
                   1518:                                 if (exists($currrules->{'default'})) {
                   1519:                                     $rule_in_effect = $currrules->{'default'};
                   1520:                                 }
                   1521:                             }
                   1522:                         }
                   1523:                     } else {
                   1524:                         if (exists($currrules->{'default'})) {
                   1525:                             $rule_in_effect = $currrules->{'default'};
                   1526:                         }
                   1527:                     }
                   1528:                 } else {
                   1529:                     if ($currrules->{'_LC_external'} ne '') {
                   1530:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1531:                     }
                   1532:                 }
                   1533:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1534:                                                        $uname,$udom);
                   1535:             }
                   1536:         }
                   1537:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1538:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1539:         unless (defined($cached)) {
                   1540:             my %domconfig =
                   1541:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1542:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1543:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1544:             } else {
                   1545:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1546:             }
                   1547:         }
                   1548:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1549:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1550:                 &check_balancer_result($result,@hosts);
                   1551:             if ($is_balancer) {
1.1129    raeburn  1552:                 if (ref($currrules) eq 'HASH') {
                   1553:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1554:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1555:                     }
                   1556:                 }
                   1557:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1558:                                                        $uname,$udom);
                   1559:             }
                   1560:         } else {
                   1561:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1562:                 $is_balancer = 1;
                   1563:                 $offloadto = &this_host_spares($dom_in_use);
                   1564:             }
1.1172.2.75  raeburn  1565:             unless (defined($cached)) {
                   1566:                 $domneedscache = $serverhomedom;
                   1567:             }
1.1129    raeburn  1568:         }
                   1569:     } else {
                   1570:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1571:             $is_balancer = 1;
                   1572:             $offloadto = &this_host_spares($dom_in_use);
                   1573:         }
1.1172.2.75  raeburn  1574:         unless (defined($cached)) {
                   1575:             $domneedscache = $serverhomedom;
                   1576:         }
                   1577:     }
                   1578:     if ($domneedscache) {
                   1579:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1580:     }
1.1172.2.5  raeburn  1581:     if ($is_balancer) {
                   1582:         my $lowest_load = 30000;
                   1583:         if (ref($offloadto) eq 'HASH') {
                   1584:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1585:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1586:                     ($otherserver,$lowest_load) =
                   1587:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1588:                 }
1.1129    raeburn  1589:             }
1.1172.2.5  raeburn  1590:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1591: 
1.1172.2.5  raeburn  1592:             if (!$found_server) {
                   1593:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1594:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1595:                         ($otherserver,$lowest_load) =
                   1596:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1597:                     }
                   1598:                 }
                   1599:             }
                   1600:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1601:             if (@{$offloadto} == 1) {
                   1602:                 $otherserver = $offloadto->[0];
                   1603:             } elsif (@{$offloadto} > 1) {
                   1604:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1605:                     ($otherserver,$lowest_load) =
                   1606:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1607:                 }
                   1608:             }
                   1609:         }
1.1172.2.88  raeburn  1610:         unless ($caller eq 'login') {
                   1611:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1612:                 $is_balancer = 0;
                   1613:                 if ($uname ne '' && $udom ne '') {
                   1614:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1615:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1616:                                  'user.loadbalcheck.time' => time});
                   1617:                     }
1.1172.2.5  raeburn  1618:                 }
1.1129    raeburn  1619:             }
                   1620:         }
1.1172.2.107  raeburn  1621:         unless ($homeintdom) {
                   1622:             undef($setcookie);
                   1623:         }
1.1129    raeburn  1624:     }
1.1172.2.107  raeburn  1625:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1626: }
                   1627: 
1.1172.2.12  raeburn  1628: sub check_balancer_result {
                   1629:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1630:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1631:     if (ref($result) eq 'HASH') {
                   1632:         if ($result->{'lonhost'} ne '') {
                   1633:             my $currbalancer = $result->{'lonhost'};
                   1634:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1635:                 $is_balancer = 1;
                   1636:                 $currtargets = $result->{'targets'};
                   1637:                 $currrules = $result->{'rules'};
                   1638:             }
                   1639:         } else {
                   1640:             foreach my $key (keys(%{$result})) {
                   1641:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1642:                     (ref($result->{$key}) eq 'HASH')) {
                   1643:                     $is_balancer = 1;
                   1644:                     $currrules = $result->{$key}{'rules'};
                   1645:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1646:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1647:                     last;
                   1648:                 }
                   1649:             }
                   1650:         }
                   1651:     }
1.1172.2.107  raeburn  1652:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1653: }
                   1654: 
1.1129    raeburn  1655: sub get_loadbalancer_targets {
                   1656:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1657:     my $offloadto;
1.1172.2.4  raeburn  1658:     if ($rule_in_effect eq 'none') {
                   1659:         return [$perlvar{'lonHostID'}];
                   1660:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1661:         $offloadto = $currtargets;
                   1662:     } else {
                   1663:         if ($rule_in_effect eq 'homeserver') {
                   1664:             my $homeserver = &homeserver($uname,$udom);
                   1665:             if ($homeserver ne 'no_host') {
                   1666:                 $offloadto = [$homeserver];
                   1667:             }
                   1668:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1669:             my %domconfig =
                   1670:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1671:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1672:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1673:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1674:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1675:                     }
                   1676:                 }
                   1677:             } else {
1.1172.2.7  raeburn  1678:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1679:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1680:                 if (&hostname($remotebalancer) ne '') {
                   1681:                     $offloadto = [$remotebalancer];
                   1682:                 }
                   1683:             }
                   1684:         } elsif (&hostname($rule_in_effect) ne '') {
                   1685:             $offloadto = [$rule_in_effect];
                   1686:         }
                   1687:     }
                   1688:     return $offloadto;
                   1689: }
                   1690: 
1.1127    raeburn  1691: sub internet_dom_servers {
                   1692:     my ($dom) = @_;
                   1693:     my (%uniqservers,%servers);
                   1694:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1695:     my @machinedoms = &machine_domains($primaryserver);
                   1696:     foreach my $mdom (@machinedoms) {
                   1697:         my %currservers = %servers;
                   1698:         my %server = &get_servers($mdom);
                   1699:         %servers = (%currservers,%server);
                   1700:     }
                   1701:     my %by_hostname;
                   1702:     foreach my $id (keys(%servers)) {
                   1703:         push(@{$by_hostname{$servers{$id}}},$id);
                   1704:     }
                   1705:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1706:         if (@{$by_hostname{$hostname}} > 1) {
                   1707:             my $match = 0;
                   1708:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1709:                 if (&host_domain($id) eq $dom) {
                   1710:                     $uniqservers{$id} = $hostname;
                   1711:                     $match = 1;
                   1712:                 }
                   1713:             }
                   1714:             unless ($match) {
                   1715:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1716:             }
                   1717:         } else {
                   1718:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1719:         }
                   1720:     }
                   1721:     return %uniqservers;
                   1722: }
                   1723: 
1.1       albertel 1724: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1725: 
1.599     albertel 1726: my %homecache;
1.1       albertel 1727: sub homeserver {
1.230     stredwic 1728:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1729:     my $index="$uname:$udom";
1.426     albertel 1730: 
1.599     albertel 1731:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1732: 
                   1733:     my %servers = &get_servers($udom,'library');
                   1734:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1735:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1736: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1737: 
                   1738: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1739: 	if ($answer eq 'found') {
                   1740: 	    delete($badServerCache{$tryserver}); 
                   1741: 	    return $homecache{$index}=$tryserver;
                   1742: 	} elsif ($answer eq 'no_host') {
                   1743: 	    $badServerCache{$tryserver}=1;
                   1744: 	}
1.1       albertel 1745:     }    
                   1746:     return 'no_host';
1.70      www      1747: }
                   1748: 
                   1749: # ------------------------------------- Find the usernames behind a list of IDs
                   1750: 
                   1751: sub idget {
                   1752:     my ($udom,@ids)=@_;
                   1753:     my %returnhash=();
                   1754:     
1.841     albertel 1755:     my %servers = &get_servers($udom,'library');
                   1756:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1757: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1758: 	$idlist=~tr/A-Z/a-z/; 
                   1759: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1760: 	my @answer=();
                   1761: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1762: 	    @answer=split(/\&/,$reply);
                   1763: 	}                    ;
                   1764: 	my $i;
                   1765: 	for ($i=0;$i<=$#ids;$i++) {
                   1766: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1767: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1768: 	    } 
                   1769: 	}
                   1770:     } 
1.70      www      1771:     return %returnhash;
                   1772: }
                   1773: 
                   1774: # ------------------------------------- Find the IDs behind a list of usernames
                   1775: 
                   1776: sub idrget {
                   1777:     my ($udom,@unames)=@_;
                   1778:     my %returnhash=();
1.800     albertel 1779:     foreach my $uname (@unames) {
                   1780:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1781:     }
1.70      www      1782:     return %returnhash;
                   1783: }
                   1784: 
                   1785: # ------------------------------- Store away a list of names and associated IDs
                   1786: 
                   1787: sub idput {
                   1788:     my ($udom,%ids)=@_;
                   1789:     my %servers=();
1.800     albertel 1790:     foreach my $uname (keys(%ids)) {
                   1791: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1792:         my $uhom=&homeserver($uname,$udom);
1.70      www      1793:         if ($uhom ne 'no_host') {
1.800     albertel 1794:             my $id=&escape($ids{$uname});
1.70      www      1795:             $id=~tr/A-Z/a-z/;
1.800     albertel 1796:             my $esc_unam=&escape($uname);
1.70      www      1797: 	    if ($servers{$uhom}) {
1.800     albertel 1798: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1799:             } else {
1.800     albertel 1800:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1801:             }
                   1802:         }
1.191     harris41 1803:     }
1.800     albertel 1804:     foreach my $server (keys(%servers)) {
                   1805:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1806:     }
1.344     www      1807: }
                   1808: 
1.1172.2.30  raeburn  1809: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1810: 
                   1811: sub iddel {
                   1812:     my ($udom,$idshashref,$uhome)=@_;
                   1813:     my %result=();
                   1814:     unless (ref($idshashref) eq 'HASH') {
                   1815:         return %result;
                   1816:     }
                   1817:     my %servers=();
                   1818:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1819:         my $uhom;
                   1820:         if ($uhome) {
                   1821:             $uhom = $uhome;
                   1822:         } else {
                   1823:             $uhom=&homeserver($uname,$udom);
                   1824:         }
                   1825:         if ($uhom ne 'no_host') {
                   1826:             if ($servers{$uhom}) {
                   1827:                 $servers{$uhom}.='&'.&escape($id);
                   1828:             } else {
                   1829:                 $servers{$uhom}=&escape($id);
                   1830:             }
                   1831:         }
                   1832:     }
                   1833:     foreach my $server (keys(%servers)) {
                   1834:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1835:     }
                   1836:     return %result;
                   1837: }
                   1838: 
1.1023    raeburn  1839: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1840: sub dump_dom {
1.1165    droeschl 1841:     my ($namespace, $udom, $regexp) = @_;
                   1842: 
                   1843:     $udom ||= $env{'user.domain'};
                   1844: 
                   1845:     return () unless $udom;
                   1846: 
                   1847:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1848: }
                   1849: 
1.1023    raeburn  1850: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1851: 
                   1852: sub get_dom {
1.860     raeburn  1853:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1854:     return if ($udom eq 'public');
1.806     raeburn  1855:     my $items='';
                   1856:     foreach my $item (@$storearr) {
                   1857:         $items.=&escape($item).'&';
                   1858:     }
                   1859:     $items=~s/\&$//;
1.860     raeburn  1860:     if (!$udom) {
                   1861:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1862:         return if ($udom eq 'public');
1.860     raeburn  1863:         if (defined(&domain($udom,'primary'))) {
                   1864:             $uhome=&domain($udom,'primary');
                   1865:         } else {
1.874     albertel 1866:             undef($uhome);
1.860     raeburn  1867:         }
                   1868:     } else {
                   1869:         if (!$uhome) {
                   1870:             if (defined(&domain($udom,'primary'))) {
                   1871:                 $uhome=&domain($udom,'primary');
                   1872:             }
                   1873:         }
                   1874:     }
                   1875:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.118.  .1(raebu 1876:20):         my $rep;
                   1877:20):         if ($namespace =~ /^enc/) {
                   1878:20):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1879:20):         } else {
                   1880:20):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1881:20):         }
1.866     raeburn  1882:         my %returnhash;
1.875     albertel 1883:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1884:             return %returnhash;
                   1885:         }
1.806     raeburn  1886:         my @pairs=split(/\&/,$rep);
                   1887:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1888:             return @pairs;
                   1889:         }
                   1890:         my $i=0;
                   1891:         foreach my $item (@$storearr) {
                   1892:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1893:             $i++;
                   1894:         }
                   1895:         return %returnhash;
                   1896:     } else {
1.880     banghart 1897:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1898:     }
                   1899: }
                   1900: 
                   1901: # -------------------------------------------- put items in domain db files 
                   1902: 
                   1903: sub put_dom {
1.860     raeburn  1904:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1905:     if (!$udom) {
                   1906:         $udom=$env{'user.domain'};
                   1907:         if (defined(&domain($udom,'primary'))) {
                   1908:             $uhome=&domain($udom,'primary');
                   1909:         } else {
1.874     albertel 1910:             undef($uhome);
1.860     raeburn  1911:         }
                   1912:     } else {
                   1913:         if (!$uhome) {
                   1914:             if (defined(&domain($udom,'primary'))) {
                   1915:                 $uhome=&domain($udom,'primary');
                   1916:             }
                   1917:         }
                   1918:     } 
                   1919:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1920:         my $items='';
                   1921:         foreach my $item (keys(%$storehash)) {
                   1922:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1923:         }
                   1924:         $items=~s/\&$//;
1.1172.2.118.  .1(raebu 1925:20):         if ($namespace =~ /^enc/) {
                   1926:20):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1927:20):         } else {
                   1928:20):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1929:20):         }
1.806     raeburn  1930:     } else {
1.860     raeburn  1931:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1932:     }
                   1933: }
                   1934: 
1.1023    raeburn  1935: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1936: sub newput_dom {
1.1023    raeburn  1937:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1938:     my $result;
                   1939:     if (!$udom) {
                   1940:         $udom=$env{'user.domain'};
                   1941:     }
1.1023    raeburn  1942:     if ($udom) {
                   1943:         my $uname = &get_domainconfiguser($udom);
                   1944:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1945:     }
                   1946:     return $result;
                   1947: }
                   1948: 
1.1023    raeburn  1949: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1950: sub del_dom {
1.1023    raeburn  1951:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1952:     if (ref($storearr) eq 'ARRAY') {
                   1953:         if (!$udom) {
                   1954:             $udom=$env{'user.domain'};
                   1955:         }
1.1023    raeburn  1956:         if ($udom) {
                   1957:             my $uname = &get_domainconfiguser($udom); 
                   1958:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1959:         }
                   1960:     }
                   1961: }
                   1962: 
1.1023    raeburn  1963: # ----------------------------------construct domainconfig user for a domain 
                   1964: sub get_domainconfiguser {
                   1965:     my ($udom) = @_;
                   1966:     return $udom.'-domainconfig';
                   1967: }
                   1968: 
1.837     raeburn  1969: sub retrieve_inst_usertypes {
                   1970:     my ($udom) = @_;
                   1971:     my (%returnhash,@order);
1.989     raeburn  1972:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1973:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1974:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1975:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1976:     } else {
                   1977:         if (defined(&domain($udom,'primary'))) {
                   1978:             my $uhome=&domain($udom,'primary');
                   1979:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1980:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1981:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1982:                 return (\%returnhash,\@order);
                   1983:             }
                   1984:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1985:             my @pairs=split(/\&/,$hashitems);
                   1986:             foreach my $item (@pairs) {
                   1987:                 my ($key,$value)=split(/=/,$item,2);
                   1988:                 $key = &unescape($key);
                   1989:                 next if ($key =~ /^error: 2 /);
                   1990:                 $returnhash{$key}=&thaw_unescape($value);
                   1991:             }
                   1992:             my @esc_order = split(/\&/,$orderitems);
                   1993:             foreach my $item (@esc_order) {
                   1994:                 push(@order,&unescape($item));
                   1995:             }
                   1996:         } else {
1.1172.2.44  raeburn  1997:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1998:         }
1.1172.2.44  raeburn  1999:         return (\%returnhash,\@order);
1.837     raeburn  2000:     }
                   2001: }
                   2002: 
1.868     raeburn  2003: sub is_domainimage {
                   2004:     my ($url) = @_;
1.1172.2.74  raeburn  2005:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2006:         if (&domain($1) ne '') {
                   2007:             return '1';
                   2008:         }
                   2009:     }
                   2010:     return;
                   2011: }
                   2012: 
1.899     raeburn  2013: sub inst_directory_query {
                   2014:     my ($srch) = @_;
                   2015:     my $udom = $srch->{'srchdomain'};
                   2016:     my %results;
                   2017:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2018:     my $outcome;
1.899     raeburn  2019:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2020:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2021:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2022:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2023:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2024:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2025:                     (($major == 2) && ($minor < 11)) ||
                   2026:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2027:                     return;
                   2028:                 }
                   2029:             }
                   2030:         }
1.904     albertel 2031: 	my $queryid=&reply("querysend:instdirsearch:".
                   2032: 			   &escape($srch->{'srchby'}).':'.
                   2033: 			   &escape($srch->{'srchterm'}).':'.
                   2034: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2035: 	my $host=&hostname($homeserver);
                   2036: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2037: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2038: 	    return;
                   2039: 	}
                   2040: 	my $response = &get_query_reply($queryid);
                   2041: 	my $maxtries = 5;
                   2042: 	my $tries = 1;
                   2043: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2044: 	    $response = &get_query_reply($queryid);
                   2045: 	    $tries ++;
                   2046: 	}
                   2047: 
                   2048:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2049:             if ($response eq 'unavailable') {
                   2050:                 $outcome = $response;
                   2051:             } else {
                   2052:                 $outcome = 'ok';
                   2053:                 my @matches = split(/\n/,$response);
                   2054:                 foreach my $match (@matches) {
                   2055:                     my ($key,$value) = split(/=/,$match);
                   2056:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2057:                 }
1.899     raeburn  2058:             }
                   2059:         }
                   2060:     }
1.909     raeburn  2061:     return ($outcome,%results);
1.899     raeburn  2062: }
                   2063: 
                   2064: sub usersearch {
                   2065:     my ($srch) = @_;
                   2066:     my $dom = $srch->{'srchdomain'};
                   2067:     my %results;
                   2068:     my %libserv = &all_library();
                   2069:     my $query = 'usersearch';
                   2070:     foreach my $tryserver (keys(%libserv)) {
                   2071:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2072:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2073:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2074:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.118.  .2(raebu 2075:20):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2076:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2077:                              (($major == 2) && ($minor < 11)) ||
                   2078:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2079:                 }
                   2080:             }
1.899     raeburn  2081:             my $host=&hostname($tryserver);
                   2082:             my $queryid=
1.911     raeburn  2083:                 &reply("querysend:".&escape($query).':'.
                   2084:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2085:                        &escape($srch->{'srchtype'}).':'.
                   2086:                        &escape($srch->{'srchterm'}),$tryserver);
                   2087:             if ($queryid !~/^\Q$host\E\_/) {
                   2088:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2089:                 next;
1.899     raeburn  2090:             }
                   2091:             my $reply = &get_query_reply($queryid);
                   2092:             my $maxtries = 1;
                   2093:             my $tries = 1;
                   2094:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2095:                 $reply = &get_query_reply($queryid);
                   2096:                 $tries ++;
                   2097:             }
                   2098:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2099:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2100:             } else {
1.911     raeburn  2101:                 my @matches;
                   2102:                 if ($reply =~ /\n/) {
                   2103:                     @matches = split(/\n/,$reply);
                   2104:                 } else {
                   2105:                     @matches = split(/\&/,$reply);
                   2106:                 }
1.899     raeburn  2107:                 foreach my $match (@matches) {
                   2108:                     my ($uname,$udom,%userhash);
1.911     raeburn  2109:                     foreach my $entry (split(/:/,$match)) {
                   2110:                         my ($key,$value) =
                   2111:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2112:                         $userhash{$key} = $value;
                   2113:                         if ($key eq 'username') {
                   2114:                             $uname = $value;
                   2115:                         } elsif ($key eq 'domain') {
                   2116:                             $udom = $value;
1.911     raeburn  2117:                         }
1.899     raeburn  2118:                     }
                   2119:                     $results{$uname.':'.$udom} = \%userhash;
                   2120:                 }
                   2121:             }
                   2122:         }
                   2123:     }
                   2124:     return %results;
                   2125: }
                   2126: 
1.912     raeburn  2127: sub get_instuser {
                   2128:     my ($udom,$uname,$id) = @_;
                   2129:     my $homeserver = &domain($udom,'primary');
                   2130:     my ($outcome,%results);
                   2131:     if ($homeserver ne '') {
                   2132:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2133:                            &escape($id).':'.&escape($udom),$homeserver);
                   2134:         my $host=&hostname($homeserver);
                   2135:         if ($queryid !~/^\Q$host\E\_/) {
                   2136:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2137:             return;
                   2138:         }
                   2139:         my $response = &get_query_reply($queryid);
                   2140:         my $maxtries = 5;
                   2141:         my $tries = 1;
                   2142:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2143:             $response = &get_query_reply($queryid);
                   2144:             $tries ++;
                   2145:         }
                   2146:         if (!&error($response) && $response ne 'refused') {
                   2147:             if ($response eq 'unavailable') {
                   2148:                 $outcome = $response;
                   2149:             } else {
                   2150:                 $outcome = 'ok';
                   2151:                 my @matches = split(/\n/,$response);
                   2152:                 foreach my $match (@matches) {
                   2153:                     my ($key,$value) = split(/=/,$match);
                   2154:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2155:                 }
                   2156:             }
                   2157:         }
                   2158:     }
                   2159:     my %userinfo;
                   2160:     if (ref($results{$uname}) eq 'HASH') {
                   2161:         %userinfo = %{$results{$uname}};
                   2162:     } 
                   2163:     return ($outcome,%userinfo);
                   2164: }
                   2165: 
1.1172.2.69  raeburn  2166: sub get_multiple_instusers {
                   2167:     my ($udom,$users,$caller) = @_;
                   2168:     my ($outcome,$results);
                   2169:     if (ref($users) eq 'HASH') {
                   2170:         my $count = keys(%{$users});
                   2171:         my $requested = &freeze_escape($users);
                   2172:         my $homeserver = &domain($udom,'primary');
                   2173:         if ($homeserver ne '') {
                   2174:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2175:             my $host=&hostname($homeserver);
                   2176:             if ($queryid !~/^\Q$host\E\_/) {
                   2177:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2178:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2179:                 return ($outcome,$results);
                   2180:             }
                   2181:             my $response = &get_query_reply($queryid);
                   2182:             my $maxtries = 5;
                   2183:             if ($count > 100) {
                   2184:                 $maxtries = 1+int($count/20);
                   2185:             }
                   2186:             my $tries = 1;
                   2187:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2188:                 $response = &get_query_reply($queryid);
                   2189:                 $tries ++;
                   2190:             }
                   2191:             if ($response eq '') {
                   2192:                 $results = {};
                   2193:                 foreach my $key (keys(%{$users})) {
                   2194:                     my ($uname,$id);
                   2195:                     if ($caller eq 'id') {
                   2196:                         $id = $key;
                   2197:                     } else {
                   2198:                         $uname = $key;
                   2199:                     }
                   2200:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2201:                     $outcome = $resp;
                   2202:                     if ($resp eq 'ok') {
                   2203:                         %{$results} = (%{$results}, %info);
                   2204:                     } else {
                   2205:                         last;
                   2206:                     }
                   2207:                 }
                   2208:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2209:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2210:                     $outcome = $response;
                   2211:                 } else {
                   2212:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2213:                     if ($outcome eq 'ok') {
                   2214:                         $results = &thaw_unescape($userdata);
                   2215:                     }
                   2216:                 }
                   2217:             }
                   2218:         }
                   2219:     }
                   2220:     return ($outcome,$results);
                   2221: }
                   2222: 
1.912     raeburn  2223: sub inst_rulecheck {
1.923     raeburn  2224:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2225:     my %returnhash;
                   2226:     if ($udom ne '') {
                   2227:         if (ref($rules) eq 'ARRAY') {
                   2228:             @{$rules} = map {&escape($_);} (@{$rules});
                   2229:             my $rulestr = join(':',@{$rules});
                   2230:             my $homeserver=&domain($udom,'primary');
                   2231:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2232:                 my $response;
                   2233:                 if ($item eq 'username') {                
                   2234:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2235:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2236:                                               $homeserver));
1.923     raeburn  2237:                 } elsif ($item eq 'id') {
                   2238:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2239:                                               ':'.&escape($id).':'.$rulestr,
                   2240:                                               $homeserver));
1.945     raeburn  2241:                 } elsif ($item eq 'selfcreate') {
                   2242:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2243:                                                &escape($udom).':'.&escape($uname).
                   2244:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2245:                 }
1.912     raeburn  2246:                 if ($response ne 'refused') {
                   2247:                     my @pairs=split(/\&/,$response);
                   2248:                     foreach my $item (@pairs) {
                   2249:                         my ($key,$value)=split(/=/,$item,2);
                   2250:                         $key = &unescape($key);
                   2251:                         next if ($key =~ /^error: 2 /);
                   2252:                         $returnhash{$key}=&thaw_unescape($value);
                   2253:                     }
                   2254:                 }
                   2255:             }
                   2256:         }
                   2257:     }
                   2258:     return %returnhash;
                   2259: }
                   2260: 
                   2261: sub inst_userrules {
1.923     raeburn  2262:     my ($udom,$check) = @_;
1.912     raeburn  2263:     my (%ruleshash,@ruleorder);
                   2264:     if ($udom ne '') {
                   2265:         my $homeserver=&domain($udom,'primary');
                   2266:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2267:             my $response;
                   2268:             if ($check eq 'id') {
                   2269:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2270:                                  $homeserver);
1.943     raeburn  2271:             } elsif ($check eq 'email') {
                   2272:                 $response=&reply('instemailrules:'.&escape($udom),
                   2273:                                  $homeserver);
1.923     raeburn  2274:             } else {
                   2275:                 $response=&reply('instuserrules:'.&escape($udom),
                   2276:                                  $homeserver);
                   2277:             }
1.912     raeburn  2278:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2279:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2280:                 ($response ne 'no_such_host')) {
                   2281:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2282:                 my @pairs=split(/\&/,$hashitems);
                   2283:                 foreach my $item (@pairs) {
                   2284:                     my ($key,$value)=split(/=/,$item,2);
                   2285:                     $key = &unescape($key);
                   2286:                     next if ($key =~ /^error: 2 /);
                   2287:                     $ruleshash{$key}=&thaw_unescape($value);
                   2288:                 }
                   2289:                 my @esc_order = split(/\&/,$orderitems);
                   2290:                 foreach my $item (@esc_order) {
                   2291:                     push(@ruleorder,&unescape($item));
                   2292:                 }
                   2293:             }
                   2294:         }
                   2295:     }
                   2296:     return (\%ruleshash,\@ruleorder);
                   2297: }
                   2298: 
1.976     raeburn  2299: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2300: 
                   2301: sub get_domain_defaults {
1.1172.2.35  raeburn  2302:     my ($domain,$ignore_cache) = @_;
                   2303:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2304:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2305:     unless ($ignore_cache) {
                   2306:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2307:         if (defined($cached)) {
                   2308:             if (ref($result) eq 'HASH') {
                   2309:                 return %{$result};
                   2310:             }
1.943     raeburn  2311:         }
                   2312:     }
                   2313:     my %domdefaults;
                   2314:     my %domconfig =
1.989     raeburn  2315:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2316:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2317:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2318:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2319:                                   'coursecategories','autoenroll',
                   2320:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2321:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2322:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2323:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2324:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2325:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2326:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2327:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2328:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2329:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2330:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2331:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2332:     } else {
                   2333:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2334:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2335:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2336:     }
1.976     raeburn  2337:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2338:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2339:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2340:         } else {
                   2341:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2342:         }
1.1172.2.6  raeburn  2343:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2344:         foreach my $item (@usertools) {
                   2345:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2346:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2347:             }
                   2348:         }
1.1172.2.29  raeburn  2349:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2350:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2351:         }
1.976     raeburn  2352:     }
1.985     raeburn  2353:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2354:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2355:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2356:         }
                   2357:     }
1.1172.2.9  raeburn  2358:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2359:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2360:     }
1.989     raeburn  2361:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2362:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2363:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2364:         }
                   2365:     }
1.1047    raeburn  2366:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2367:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2368:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2369:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2370:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2371:         }
1.1172.2.41  raeburn  2372:         foreach my $type (@coursetypes) {
                   2373:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2374:                 unless ($type eq 'community') {
                   2375:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2376:                 }
                   2377:             }
                   2378:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2379:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2380:             }
1.1172.2.60  raeburn  2381:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2382:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2383:                     $domdefaults{$type.'postsubtimeout'} =
                   2384:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2385:                 }
                   2386:             }
1.1172.2.30  raeburn  2387:         }
1.1172.2.67  raeburn  2388:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2389:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2390:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2391:                 if (@clonecodes) {
                   2392:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2393:                 }
                   2394:             }
                   2395:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2396:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2397:         }
1.1172.2.103  raeburn  2398:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2399:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2400:         }
1.1047    raeburn  2401:     }
1.1073    raeburn  2402:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2403:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2404:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2405:         }
                   2406:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2407:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2408:         }
1.1172.2.62  raeburn  2409:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2410:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2411:         }
1.1073    raeburn  2412:     }
1.1172.2.41  raeburn  2413:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2414:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2415:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2416:                             'approval','limit');
                   2417:             foreach my $type (@coursetypes) {
                   2418:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2419:                     my @mgrdc = ();
                   2420:                     foreach my $item (@settings) {
                   2421:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2422:                             push(@mgrdc,$item);
                   2423:                         }
                   2424:                     }
                   2425:                     if (@mgrdc) {
                   2426:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2427:                     }
                   2428:                 }
                   2429:             }
                   2430:         }
                   2431:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2432:             foreach my $type (@coursetypes) {
                   2433:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2434:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2435:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2436:                     }
                   2437:                 }
                   2438:             }
                   2439:         }
                   2440:     }
1.1172.2.46  raeburn  2441:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2442:         $domdefaults{'catauth'} = 'std';
                   2443:         $domdefaults{'catunauth'} = 'std';
                   2444:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2445:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2446:         }
                   2447:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2448:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2449:         }
                   2450:     }
1.1172.2.76  raeburn  2451:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2452:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2453:     }
1.1172.2.89  raeburn  2454:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2455:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2456:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2457:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2458:         }
                   2459:     }
1.1172.2.23  raeburn  2460:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2461:     return %domdefaults;
                   2462: }
                   2463: 
1.1172.2.106  raeburn  2464: sub get_dom_cats {
                   2465:     my ($dom) = @_;
                   2466:     return unless (&domain($dom));
                   2467:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2468:     unless (defined($cached)) {
                   2469:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2470:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2471:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2472:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2473:             } else {
                   2474:                 $cats = {};
                   2475:             }
                   2476:         } else {
                   2477:             $cats = {};
                   2478:         }
                   2479:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2480:     }
                   2481:     return $cats;
                   2482: }
                   2483: 
                   2484: sub get_dom_instcats {
                   2485:     my ($dom) = @_;
                   2486:     return unless (&domain($dom));
                   2487:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2488:     unless (defined($cached)) {
                   2489:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2490:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2491:         if ($totcodes > 0) {
                   2492:             my $caller = 'global';
                   2493:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2494:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2495:                 $instcats = {
                   2496:                                 codes => \%codes,
                   2497:                                 codetitles => \@codetitles,
                   2498:                                 cat_titles => \%cat_titles,
                   2499:                                 cat_order => \%cat_order,
                   2500:                             };
                   2501:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2502:             }
                   2503:         }
                   2504:     }
                   2505:     return $instcats;
                   2506: }
                   2507: 
                   2508: sub retrieve_instcodes {
                   2509:     my ($coursecodes,$dom) = @_;
                   2510:     my $totcodes;
                   2511:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2512:     foreach my $course (keys(%courses)) {
                   2513:         if (ref($courses{$course}) eq 'HASH') {
                   2514:             if ($courses{$course}{'inst_code'} ne '') {
                   2515:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2516:                 $totcodes ++;
                   2517:             }
                   2518:         }
                   2519:     }
                   2520:     return $totcodes;
                   2521: }
                   2522: 
1.1172.2.113  raeburn  2523: # --------------------------------------------- Get domain config for passwords
                   2524: 
                   2525: sub get_passwdconf {
                   2526:     my ($dom) = @_;
                   2527:     my (%passwdconf,$gotconf,$lookup);
                   2528:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2529:     if (defined($cached)) {
                   2530:         if (ref($result) eq 'HASH') {
                   2531:             %passwdconf = %{$result};
                   2532:             $gotconf = 1;
                   2533:         }
                   2534:     }
                   2535:     unless ($gotconf) {
                   2536:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2537:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2538:             %passwdconf = %{$domconfig{'passwords'}};
                   2539:         }
                   2540:         my $cachetime = 24*60*60;
                   2541:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2542:     }
                   2543:     return %passwdconf;
                   2544: }
                   2545: 
1.1172.2.118.  .1(raebu 2546:20): sub course_portal_url {
                   2547:20):     my ($cnum,$cdom) = @_;
                   2548:20):     my $chome = &homeserver($cnum,$cdom);
                   2549:20):     my $hostname = &hostname($chome);
                   2550:20):     my $protocol = $protocol{$chome};
                   2551:20):     $protocol = 'http' if ($protocol ne 'https');
                   2552:20):     my %domdefaults = &get_domain_defaults($cdom);
                   2553:20):     my $firsturl;
                   2554:20):     if ($domdefaults{'portal_def'}) {
                   2555:20):         $firsturl = $domdefaults{'portal_def'};
                   2556:20):     } else {
                   2557:20):         $firsturl = $protocol.'://'.$hostname;
                   2558:20):     }
                   2559:20):     return $firsturl;
                   2560:20): }
                   2561:20): 
1.344     www      2562: # --------------------------------------------------- Assign a key to a student
                   2563: 
                   2564: sub assign_access_key {
1.364     www      2565: #
                   2566: # a valid key looks like uname:udom#comments
                   2567: # comments are being appended
                   2568: #
1.498     www      2569:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2570:     $kdom=
1.620     albertel 2571:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2572:     $knum=
1.620     albertel 2573:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2574:     $cdom=
1.620     albertel 2575:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2576:     $cnum=
1.620     albertel 2577:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2578:     $udom=$env{'user.name'} unless (defined($udom));
                   2579:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2580:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2581:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2582:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2583:                                                   # assigned to this person
                   2584:                                                   # - this should not happen,
1.345     www      2585:                                                   # unless something went wrong
                   2586:                                                   # the first time around
                   2587: # ready to assign
1.364     www      2588:         $logentry=$1.'; '.$logentry;
1.496     www      2589:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2590:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2591: # key now belongs to user
1.346     www      2592: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2593:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2594:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2595:                 return 'ok';
                   2596:             } else {
                   2597:                 return 
                   2598:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2599: 	    }
                   2600:         } else {
                   2601:             return 'error: Could not assign key, try again later.';
                   2602:         }
1.364     www      2603:     } elsif (!$existing{$ckey}) {
1.345     www      2604: # the key does not exist
                   2605: 	return 'error: The key does not exist';
                   2606:     } else {
                   2607: # the key is somebody else's
                   2608: 	return 'error: The key is already in use';
                   2609:     }
1.344     www      2610: }
                   2611: 
1.364     www      2612: # ------------------------------------------ put an additional comment on a key
                   2613: 
                   2614: sub comment_access_key {
                   2615: #
                   2616: # a valid key looks like uname:udom#comments
                   2617: # comments are being appended
                   2618: #
                   2619:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2620:     $cdom=
1.620     albertel 2621:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2622:     $cnum=
1.620     albertel 2623:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2624:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2625:     if ($existing{$ckey}) {
                   2626:         $existing{$ckey}.='; '.$logentry;
                   2627: # ready to assign
1.367     www      2628:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2629:                                                  $cdom,$cnum) eq 'ok') {
                   2630: 	    return 'ok';
                   2631:         } else {
                   2632: 	    return 'error: Count not store comment.';
                   2633:         }
                   2634:     } else {
                   2635: # the key does not exist
                   2636: 	return 'error: The key does not exist';
                   2637:     }
                   2638: }
                   2639: 
1.344     www      2640: # ------------------------------------------------------ Generate a set of keys
                   2641: 
                   2642: sub generate_access_keys {
1.364     www      2643:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2644:     $cdom=
1.620     albertel 2645:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2646:     $cnum=
1.620     albertel 2647:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2648:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2649:     unless (($cdom) && ($cnum)) { return 0; }
                   2650:     if ($number>10000) { return 0; }
                   2651:     sleep(2); # make sure don't get same seed twice
                   2652:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2653:     my $total=0;
                   2654:     for (my $i=1;$i<=$number;$i++) {
                   2655:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2656:                   sprintf("%lx",int(100000*rand)).'-'.
                   2657:                   sprintf("%lx",int(100000*rand));
                   2658:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2659:        $newkey=~s/0/h/g; # and also 0 and O
                   2660:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2661:        if ($existing{$newkey}) {
                   2662:            $i--;
                   2663:        } else {
1.364     www      2664: 	  if (&put('accesskeys',
                   2665:               { $newkey => '# generated '.localtime().
1.620     albertel 2666:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2667:                            '; '.$logentry },
                   2668: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2669:               $total++;
                   2670: 	  }
                   2671:        }
                   2672:     }
1.620     albertel 2673:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2674:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2675:     return $total;
                   2676: }
                   2677: 
                   2678: # ------------------------------------------------------- Validate an accesskey
                   2679: 
                   2680: sub validate_access_key {
                   2681:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2682:     $cdom=
1.620     albertel 2683:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2684:     $cnum=
1.620     albertel 2685:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2686:     $udom=$env{'user.domain'} unless (defined($udom));
                   2687:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2688:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2689:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2690: }
                   2691: 
                   2692: # ------------------------------------- Find the section of student in a course
1.652     albertel 2693: sub devalidate_getsection_cache {
                   2694:     my ($udom,$unam,$courseid)=@_;
                   2695:     my $hashid="$udom:$unam:$courseid";
                   2696:     &devalidate_cache_new('getsection',$hashid);
                   2697: }
1.298     matthew  2698: 
1.815     albertel 2699: sub courseid_to_courseurl {
                   2700:     my ($courseid) = @_;
                   2701:     #already url style courseid
                   2702:     return $courseid if ($courseid =~ m{^/});
                   2703: 
                   2704:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2705: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2706: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2707: 	return "/$cdom/$cnum";
                   2708:     }
                   2709: 
                   2710:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2711:     if (exists($courseinfo{'num'})) {
                   2712: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2713:     }
                   2714: 
                   2715:     return undef;
                   2716: }
                   2717: 
1.298     matthew  2718: sub getsection {
                   2719:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2720:     my $cachetime=1800;
1.551     albertel 2721: 
                   2722:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2723:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2724:     if (defined($cached)) { return $result; }
                   2725: 
1.298     matthew  2726:     my %Pending; 
                   2727:     my %Expired;
                   2728:     #
                   2729:     # Each role can either have not started yet (pending), be active, 
                   2730:     #    or have expired.
                   2731:     #
                   2732:     # If there is an active role, we are done.
                   2733:     #
                   2734:     # If there is more than one role which has not started yet, 
                   2735:     #     choose the one which will start sooner
                   2736:     # If there is one role which has not started yet, return it.
                   2737:     #
                   2738:     # If there is more than one expired role, choose the one which ended last.
                   2739:     # If there is a role which has expired, return it.
                   2740:     #
1.815     albertel 2741:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2742:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2743:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2744:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2745:         my $section=$1;
                   2746:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2747:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2748:         my $now=time;
1.548     albertel 2749:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2750:             $Expired{$end}=$section;
                   2751:             next;
                   2752:         }
1.548     albertel 2753:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2754:             $Pending{$start}=$section;
                   2755:             next;
                   2756:         }
1.599     albertel 2757:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2758:     }
                   2759:     #
                   2760:     # Presumedly there will be few matching roles from the above
                   2761:     # loop and the sorting time will be negligible.
                   2762:     if (scalar(keys(%Pending))) {
                   2763:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2764:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2765:     } 
                   2766:     if (scalar(keys(%Expired))) {
                   2767:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2768:         my $time = pop(@sorted);
1.599     albertel 2769:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2770:     }
1.599     albertel 2771:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2772: }
1.70      www      2773: 
1.599     albertel 2774: sub save_cache {
                   2775:     &purge_remembered();
1.722     albertel 2776:     #&Apache::loncommon::validate_page();
1.620     albertel 2777:     undef(%env);
1.780     albertel 2778:     undef($env_loaded);
1.599     albertel 2779: }
1.452     albertel 2780: 
1.599     albertel 2781: my $to_remember=-1;
                   2782: my %remembered;
                   2783: my %accessed;
                   2784: my $kicks=0;
                   2785: my $hits=0;
1.849     albertel 2786: sub make_key {
                   2787:     my ($name,$id) = @_;
1.872     albertel 2788:     if (length($id) > 65 
                   2789: 	&& length(&escape($id)) > 200) {
                   2790: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2791:     }
1.849     albertel 2792:     return &escape($name.':'.$id);
                   2793: }
                   2794: 
1.599     albertel 2795: sub devalidate_cache_new {
                   2796:     my ($name,$id,$debug) = @_;
                   2797:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2798:     my $remembered_id=$name.':'.$id;
1.849     albertel 2799:     $id=&make_key($name,$id);
1.599     albertel 2800:     $memcache->delete($id);
1.1172.2.81  raeburn  2801:     delete($remembered{$remembered_id});
                   2802:     delete($accessed{$remembered_id});
1.599     albertel 2803: }
                   2804: 
                   2805: sub is_cached_new {
                   2806:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2807:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2808:                                      # keys in %remembered hash, which persists for
                   2809:                                      # duration of request (no restriction on key length).
                   2810:     if (exists($remembered{$remembered_id})) {
                   2811: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2812: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2813: 	$hits++;
1.1172.2.81  raeburn  2814: 	return ($remembered{$remembered_id},1);
1.599     albertel 2815:     }
1.1172.2.81  raeburn  2816:     $id=&make_key($name,$id);
1.599     albertel 2817:     my $value = $memcache->get($id);
                   2818:     if (!(defined($value))) {
                   2819: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2820: 	return (undef,undef);
1.416     albertel 2821:     }
1.599     albertel 2822:     if ($value eq '__undef__') {
                   2823: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2824: 	$value=undef;
                   2825:     }
1.1172.2.81  raeburn  2826:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2827:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2828:     return ($value,1);
                   2829: }
                   2830: 
                   2831: sub do_cache_new {
                   2832:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2833:     my $remembered_id=$name.':'.$id;
1.849     albertel 2834:     $id=&make_key($name,$id);
1.599     albertel 2835:     my $setvalue=$value;
                   2836:     if (!defined($setvalue)) {
                   2837: 	$setvalue='__undef__';
                   2838:     }
1.623     albertel 2839:     if (!defined($time) ) {
                   2840: 	$time=600;
                   2841:     }
1.599     albertel 2842:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2843:     my $result = $memcache->set($id,$setvalue,$time);
                   2844:     if (! $result) {
1.872     albertel 2845: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2846: 	$memcache->disconnect_all();
1.872     albertel 2847:     }
1.600     albertel 2848:     # need to make a copy of $value
1.1172.2.81  raeburn  2849:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2850:     return $value;
                   2851: }
                   2852: 
                   2853: sub make_room {
1.1172.2.81  raeburn  2854:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2855: 
1.1172.2.81  raeburn  2856:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2857:                                     : $value;
1.599     albertel 2858:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2859:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2860:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2861:     my $to_kick;
                   2862:     my $max_time=0;
                   2863:     foreach my $other (keys(%accessed)) {
                   2864: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2865: 	    $to_kick=$other;
                   2866: 	    $max_time=&tv_interval($accessed{$other});
                   2867: 	}
                   2868:     }
                   2869:     delete($remembered{$to_kick});
                   2870:     delete($accessed{$to_kick});
                   2871:     $kicks++;
                   2872:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2873:     return;
                   2874: }
                   2875: 
1.599     albertel 2876: sub purge_remembered {
1.604     albertel 2877:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2878:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2879:     undef(%remembered);
                   2880:     undef(%accessed);
1.428     albertel 2881: }
1.70      www      2882: # ------------------------------------- Read an entry from a user's environment
                   2883: 
                   2884: sub userenvironment {
                   2885:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2886:     my $items;
                   2887:     foreach my $item (@what) {
                   2888:         $items.=&escape($item).'&';
                   2889:     }
                   2890:     $items=~s/\&$//;
1.70      www      2891:     my %returnhash=();
1.1009    raeburn  2892:     my $uhome = &homeserver($unam,$udom);
                   2893:     unless ($uhome eq 'no_host') {
                   2894:         my @answer=split(/\&/, 
                   2895:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2896:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2897:             return %returnhash;
                   2898:         }
1.1009    raeburn  2899:         my $i;
                   2900:         for ($i=0;$i<=$#what;$i++) {
                   2901: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2902:         }
1.70      www      2903:     }
                   2904:     return %returnhash;
1.1       albertel 2905: }
                   2906: 
1.617     albertel 2907: # ---------------------------------------------------------- Get a studentphoto
                   2908: sub studentphoto {
                   2909:     my ($udom,$unam,$ext) = @_;
                   2910:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2911:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2912:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2913:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2914:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2915:             } else {
                   2916:                 my ($result,$perm_reqd)=
1.707     albertel 2917: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2918:                 if ($result eq 'ok') {
                   2919:                     if (!($perm_reqd eq 'yes')) {
                   2920:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2921:                     }
                   2922:                 }
                   2923:             }
                   2924:         }
                   2925:     } else {
                   2926:         my ($result,$perm_reqd) = 
1.707     albertel 2927: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2928:         if ($result eq 'ok') {
                   2929:             if (!($perm_reqd eq 'yes')) {
                   2930:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2931:             }
                   2932:         }
                   2933:     }
                   2934:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2935: }
                   2936: 
                   2937: sub retrievestudentphoto {
                   2938:     my ($udom,$unam,$ext,$type) = @_;
                   2939:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2940:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2941:     if ($ret eq 'ok') {
                   2942:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2943:         if ($type eq 'thumbnail') {
                   2944:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2945:         }
                   2946:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2947:         return $tokenurl;
                   2948:     } else {
                   2949:         if ($type eq 'thumbnail') {
                   2950:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2951:         } else { 
                   2952:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2953:         }
1.617     albertel 2954:     }
                   2955: }
                   2956: 
1.263     www      2957: # -------------------------------------------------------------------- New chat
                   2958: 
                   2959: sub chatsend {
1.724     raeburn  2960:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2961:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2962:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2963:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2964:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2965: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2966: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2967: }
                   2968: 
                   2969: # ------------------------------------------ Find current version of a resource
                   2970: 
                   2971: sub getversion {
                   2972:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2973:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2974:     return &currentversion(&filelocation('',$fname));
                   2975: }
                   2976: 
                   2977: sub currentversion {
                   2978:     my $fname=shift;
                   2979:     my $author=$fname;
                   2980:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2981:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2982:     my $home=&homeserver($uname,$udom);
1.292     www      2983:     if ($home eq 'no_host') { 
                   2984:         return -1; 
                   2985:     }
1.1112    www      2986:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2987:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2988: 	return -1;
                   2989:     }
1.1112    www      2990:     return $answer;
1.263     www      2991: }
                   2992: 
1.1111    www      2993: #
                   2994: # Return special version number of resource if set by override, empty otherwise
                   2995: #
                   2996: sub usedversion {
                   2997:     my $fname=shift;
                   2998:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2999:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3000:     if ($urlversion) { return $urlversion; }
                   3001:     return '';
                   3002: }
                   3003: 
1.1       albertel 3004: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3005: 
1.1       albertel 3006: sub subscribe {
                   3007:     my $fname=shift;
1.761     raeburn  3008:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3009:     $fname=~s/[\n\r]//g;
1.1       albertel 3010:     my $author=$fname;
                   3011:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3012:     my ($udom,$uname)=split(/\//,$author);
                   3013:     my $home=homeserver($uname,$udom);
1.335     albertel 3014:     if ($home eq 'no_host') {
                   3015:         return 'not_found';
1.1       albertel 3016:     }
                   3017:     my $answer=reply("sub:$fname",$home);
1.64      www      3018:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3019: 	$answer.=' by '.$home;
                   3020:     }
1.1       albertel 3021:     return $answer;
                   3022: }
                   3023:     
1.8       www      3024: # -------------------------------------------------------------- Replicate file
                   3025: 
                   3026: sub repcopy {
                   3027:     my $filename=shift;
1.23      www      3028:     $filename=~s/\/+/\//g;
1.1142    raeburn  3029:     my $londocroot = $perlvar{'lonDocRoot'};
                   3030:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3031:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3032:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3033: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3034: 	return &repcopy_userfile($filename);
                   3035:     }
1.532     albertel 3036:     $filename=~s/[\n\r]//g;
1.8       www      3037:     my $transname="$filename.in.transfer";
1.828     www      3038: # FIXME: this should flock
1.607     raeburn  3039:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3040:     my $remoteurl=subscribe($filename);
1.64      www      3041:     if ($remoteurl =~ /^con_lost by/) {
                   3042: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3043:            return 'unavailable';
1.8       www      3044:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3045: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3046: 	   return 'not_found';
1.64      www      3047:     } elsif ($remoteurl =~ /^rejected by/) {
                   3048: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3049:            return 'forbidden';
1.20      www      3050:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3051:            return 'ok';
1.8       www      3052:     } else {
1.290     www      3053:         my $author=$filename;
                   3054:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3055:         my ($udom,$uname)=split(/\//,$author);
                   3056:         my $home=homeserver($uname,$udom);
                   3057:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3058:            my @parts=split(/\//,$filename);
                   3059:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3060:            if ($path ne "$londocroot/res") {
1.8       www      3061:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3062: 	       return 'bad_request';
1.8       www      3063:            }
                   3064:            my $count;
                   3065:            for ($count=5;$count<$#parts;$count++) {
                   3066:                $path.="/$parts[$count]";
                   3067:                if ((-e $path)!=1) {
                   3068: 		   mkdir($path,0777);
                   3069:                }
                   3070:            }
                   3071:            my $ua=new LWP::UserAgent;
                   3072:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3073:            my $response=$ua->request($request,$transname);
                   3074:            if ($response->is_error()) {
                   3075: 	       unlink($transname);
                   3076:                my $message=$response->status_line;
1.672     albertel 3077:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3078:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3079:                return 'unavailable';
1.8       www      3080:            } else {
1.16      www      3081: 	       if ($remoteurl!~/\.meta$/) {
                   3082:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3083:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3084:                   if ($mresponse->is_error()) {
                   3085: 		      unlink($filename.'.meta');
                   3086:                       &logthis(
1.672     albertel 3087:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3088:                   }
                   3089: 	       }
1.8       www      3090:                rename($transname,$filename);
1.607     raeburn  3091:                return 'ok';
1.8       www      3092:            }
1.290     www      3093:        }
1.8       www      3094:     }
1.330     www      3095: }
                   3096: 
1.1172.2.118.  .5(raebu 3097:20): # ------------------------------------------------- Unsubscribe from a resource
                   3098:20): 
                   3099:20): sub unsubscribe {
                   3100:20):     my ($fname) = @_;
                   3101:20):     my $answer;
                   3102:20):     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3103:20):     $fname=~s/[\n\r]//g;
                   3104:20):     my $author=$fname;
                   3105:20):     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3106:20):     my ($udom,$uname)=split(/\//,$author);
                   3107:20):     my $home=homeserver($uname,$udom);
                   3108:20):     if ($home eq 'no_host') {
                   3109:20):         $answer = 'no_host';
                   3110:20):     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3111:20):         $answer = 'home';
                   3112:20):     } else {
          .7(raebu 3113:20):         $answer = reply("unsub:$fname",$home);
          .5(raebu 3114:20):     }
                   3115:20):     return $answer;
                   3116:20): }
                   3117:20): 
1.330     www      3118: # ------------------------------------------------ Get server side include body
                   3119: sub ssi_body {
1.381     albertel 3120:     my ($filelink,%form)=@_;
1.606     matthew  3121:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3122:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3123:     }
1.953     www      3124:     my $output='';
                   3125:     my $response;
1.980     raeburn  3126:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3127:        ($output,$response)=&externalssi($filelink);
1.953     www      3128:     } else {
1.1004    droeschl 3129:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3130:        $filelink .= 'inhibitmenu=yes';
1.953     www      3131:        ($output,$response)=&ssi($filelink,%form);
                   3132:     }
1.778     albertel 3133:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3134:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3135:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3136:     if (wantarray) {
                   3137:         return ($output, $response);
                   3138:     } else {
                   3139:         return $output;
                   3140:     }
1.8       www      3141: }
                   3142: 
1.15      www      3143: # --------------------------------------------------------- Server Side Include
                   3144: 
1.782     albertel 3145: sub absolute_url {
                   3146:     my ($host_name) = @_;
                   3147:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3148:     if ($host_name eq '') {
                   3149: 	$host_name = $ENV{'SERVER_NAME'};
                   3150:     }
                   3151:     return $protocol.$host_name;
                   3152: }
                   3153: 
1.942     foxr     3154: #
                   3155: #   Server side include.
                   3156: # Parameters:
                   3157: #  fn     Possibly encrypted resource name/id.
                   3158: #  form   Hash that describes how the rendering should be done
                   3159: #         and other things.
1.944     foxr     3160: # Returns:
1.950     raeburn  3161: #   Scalar context: The content of the response.
                   3162: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3163: #     
1.15      www      3164: sub ssi {
                   3165: 
1.944     foxr     3166:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3167:     my ($request,$response);
1.711     albertel 3168: 
                   3169:     $form{'no_update_last_known'}=1;
1.895     albertel 3170:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3171:     if (%form) {
1.782     albertel 3172:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3173:       $request->content(join('&',map {
                   3174:             my $name = escape($_);
                   3175:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3176:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3177:             : &escape($form{$_}) );
                   3178:         } keys(%form)));
1.23      www      3179:     } else {
1.782     albertel 3180:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3181:     }
                   3182: 
1.15      www      3183:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3184: 
1.1172.2.101  raeburn  3185:     if (($env{'request.course.id'}) &&
                   3186:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3187:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3188:         ($form{'grade_symb'} ne '') &&
                   3189:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3190:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3191:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3192:             my $ua=new LWP::UserAgent;
                   3193:             $ua->local_address('127.0.0.1');
                   3194:             $response = $ua->request($request);
                   3195:         } else {
                   3196:             {
                   3197:                 require LWP::Protocol::http;
                   3198:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3199:                 my $ua=new LWP::UserAgent;
                   3200:                 $response = $ua->request($request);
                   3201:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3202:             }
                   3203:         }
                   3204:     } else {
                   3205:         my $ua=new LWP::UserAgent;
                   3206:         $response = $ua->request($request);
                   3207:     }
1.944     foxr     3208:     if (wantarray) {
1.1172.2.3  raeburn  3209: 	return ($response->content, $response);
1.944     foxr     3210:     } else {
1.1172.2.3  raeburn  3211: 	return $response->content;
1.942     foxr     3212:     }
1.324     www      3213: }
                   3214: 
                   3215: sub externalssi {
                   3216:     my ($url)=@_;
                   3217:     my $ua=new LWP::UserAgent;
                   3218:     my $request=new HTTP::Request('GET',$url);
                   3219:     my $response=$ua->request($request);
1.954     raeburn  3220:     if (wantarray) {
                   3221:         return ($response->content, $response);
                   3222:     } else {
                   3223:         return $response->content;
                   3224:     }
1.15      www      3225: }
1.254     www      3226: 
1.1172.2.98  raeburn  3227: # If the local copy of a replicated resource is outdated, trigger a
                   3228: # connection from the homeserver to flush the delayed queue. If no update
                   3229: # happens, remove local copies of outdated resource (and corresponding
                   3230: # metadata file).
                   3231: 
                   3232: sub remove_stale_resfile {
                   3233:     my ($url) = @_;
                   3234:     my $removed;
                   3235:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3236:         my $audom = $1;
                   3237:         my $auname = $2;
                   3238:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3239:             my $homeserver = &homeserver($auname,$audom);
                   3240:             unless (($homeserver eq 'no_host') ||
                   3241:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3242:                 my $fname = &filelocation('',$url);
                   3243:                 if (-e $fname) {
                   3244:                     my $hostname = &hostname($homeserver);
                   3245:                     if ($hostname) {
1.1172.2.118.  .3(raebu 3246:20):                         my $protocol = $protocol{$homeserver};
                   3247:20):                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3248:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.118.  .3(raebu 3249:20):                         my $ua=new LWP::UserAgent;
                   3250:20):                         $ua->timeout(5);
1.1172.2.98  raeburn  3251:                         my $request=new HTTP::Request('HEAD',$uri);
                   3252:                         my $response=$ua->request($request);
                   3253:                         if ($response->is_success()) {
                   3254:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3255:                             my $locmodtime = (stat($fname))[9];
                   3256:                             if ($locmodtime < $remmodtime) {
                   3257:                                 my $stale;
                   3258:                                 my $answer = &reply('pong',$homeserver);
                   3259:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3260:                                     sleep(0.2);
                   3261:                                     $locmodtime = (stat($fname))[9];
                   3262:                                     if ($locmodtime < $remmodtime) {
                   3263:                                         my $posstransfer = $fname.'.in.transfer';
                   3264:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3265:                                             $removed = 1;
                   3266:                                         } else {
                   3267:                                             $stale = 1;
                   3268:                                         }
                   3269:                                     } else {
                   3270:                                         $removed = 1;
                   3271:                                     }
                   3272:                                 } else {
                   3273:                                     $stale = 1;
                   3274:                                 }
                   3275:                                 if ($stale) {
1.1172.2.118.  .5(raebu 3276:20):                                     if (unlink($fname)) {
                   3277:20):                                         if ($uri!~/\.meta$/) {
                   3278:20):                                             if (-e $fname.'.meta') {
                   3279:20):                                                 unlink($fname.'.meta');
                   3280:20):                                             }
                   3281:20):                                         }
                   3282:20):                                         my $unsubresult = &unsubscribe($fname);
                   3283:20):                                         unless ($unsubresult eq 'ok') {
                   3284:20):                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3285:20):                                         }
                   3286:20):                                         $removed = 1;
1.1172.2.98  raeburn  3287:                                     }
                   3288:                                 }
                   3289:                             }
                   3290:                         }
                   3291:                     }
                   3292:                 }
                   3293:             }
                   3294:         }
                   3295:     }
                   3296:     return $removed;
                   3297: }
                   3298: 
1.492     albertel 3299: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3300: 
                   3301: sub allowuploaded {
                   3302:     my ($srcurl,$url)=@_;
                   3303:     $url=&clutter(&declutter($url));
                   3304:     my $dir=$url;
                   3305:     $dir=~s/\/[^\/]+$//;
                   3306:     my %httpref=();
                   3307:     my $httpurl=&hreflocation('',$url);
                   3308:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3309:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3310: }
1.477     raeburn  3311: 
1.1172.2.13  raeburn  3312: #
                   3313: # Determine if the current user should be able to edit a particular resource,
                   3314: # when viewing in course context.
                   3315: # (a) When viewing resource used to determine if "Edit" item is included in
                   3316: #     Functions.
                   3317: # (b) When displaying folder contents in course editor, used to determine if
                   3318: #     "Edit" link will be displayed alongside resource.
                   3319: #
                   3320: #  input: six args -- filename (decluttered), course number, course domain,
                   3321: #                   url, symb (if registered) and group (if this is a group
                   3322: #                   item -- e.g., bulletin board, group page etc.).
                   3323: #  output: array of five scalars --
                   3324: #          $cfile -- url for file editing if editable on current server
                   3325: #          $home -- homeserver of resource (i.e., for author if published,
                   3326: #                                           or course if uploaded.).
                   3327: #          $switchserver --  1 if server switch will be needed.
                   3328: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3329: #          $forceview -- 1 if icon/link should be to go to view mode
                   3330: #
                   3331: 
                   3332: sub can_edit_resource {
                   3333:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3334:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3335: #
                   3336: # For aboutme pages user can only edit his/her own.
                   3337: #
                   3338:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3339:         my ($sdom,$sname) = ($1,$2);
                   3340:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3341:             $home = $env{'user.home'};
                   3342:             $cfile = $resurl;
                   3343:             if ($env{'form.forceedit'}) {
                   3344:                 $forceview = 1;
                   3345:             } else {
                   3346:                 $forceedit = 1;
                   3347:             }
                   3348:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3349:         } else {
                   3350:             return;
                   3351:         }
                   3352:     }
                   3353: 
                   3354:     if ($env{'request.course.id'}) {
                   3355:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3356:         if ($group ne '') {
                   3357: # if this is a group homepage or group bulletin board, check group privs
                   3358:             my $allowed = 0;
                   3359:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3360:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3361:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3362:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3363:                     $allowed = 1;
                   3364:                 }
                   3365:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3366:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3367:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3368:                     $allowed = 1;
                   3369:                 }
                   3370:             }
                   3371:             if ($allowed) {
                   3372:                 $home=&homeserver($cnum,$cdom);
                   3373:                 if ($env{'form.forceedit'}) {
                   3374:                     $forceview = 1;
                   3375:                 } else {
                   3376:                     $forceedit = 1;
                   3377:                 }
                   3378:                 $cfile = $resurl;
                   3379:             } else {
                   3380:                 return;
                   3381:             }
                   3382:         } else {
1.1172.2.15  raeburn  3383:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3384:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3385:                     return;
                   3386:                 }
                   3387:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3388: #
                   3389: # No edit allowed where CC has switched to student role.
                   3390: #
                   3391:                 return;
                   3392:             }
                   3393:         }
                   3394:     }
                   3395: 
                   3396:     if ($file ne '') {
                   3397:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3398:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3399:                 $uploaded = 1;
                   3400:                 $incourse = 1;
                   3401:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3402:                     $cfile = &hreflocation('',$file);
                   3403:                     if ($env{'form.forceedit'}) {
                   3404:                         $forceview = 1;
                   3405:                     } else {
                   3406:                         $forceedit = 1;
                   3407:                     }
                   3408:                 }
                   3409:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3410:                 $incourse = 1;
                   3411:                 if ($env{'form.forceedit'}) {
                   3412:                     $forceview = 1;
                   3413:                 } else {
                   3414:                     $forceedit = 1;
                   3415:                 }
                   3416:                 $cfile = $resurl;
                   3417:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3418:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3419:                     $incourse = 1;
                   3420:                     if ($env{'form.forceedit'}) {
                   3421:                         $forceview = 1;
                   3422:                     } else {
                   3423:                         $forceedit = 1;
                   3424:                     }
                   3425:                     $cfile = $resurl;
                   3426:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3427:                     $incourse = 1;
                   3428:                     $cfile = $resurl.'/smpedit';
                   3429:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3430:                     $incourse = 1;
                   3431:                     if ($env{'form.forceedit'}) {
                   3432:                         $forceview = 1;
                   3433:                     } else {
                   3434:                         $forceedit = 1;
                   3435:                     }
                   3436:                     $cfile = $resurl;
1.1172.2.118.  .5(raebu 3437:20):                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3438:20):                     my ($map,$id,$res) = &decode_symb($symb);
                   3439:20):                     if ($map =~ /\.page$/) {
                   3440:20):                         $incourse = 1;
                   3441:20):                         if ($env{'form.forceedit'}) {
                   3442:20):                             $forceview = 1;
                   3443:20):                             $cfile = $map;
                   3444:20):                         } else {
                   3445:20):                             $forceedit = 1;
                   3446:20):                             $cfile =  '/adm/wrapper'.$resurl;
                   3447:20):                         }
                   3448:20):                     }
          .1(raebu 3449:20):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3450:20):                     $incourse = 1;
                   3451:20):                     if ($env{'form.forceedit'}) {
                   3452:20):                         $forceview = 1;
                   3453:20):                     } else {
                   3454:20):                         $forceedit = 1;
                   3455:20):                     }
                   3456:20):                     $cfile = $resurl;
1.1172.2.15  raeburn  3457:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3458:                     $incourse = 1;
                   3459:                     if ($env{'form.forceedit'}) {
                   3460:                         $forceview = 1;
                   3461:                     } else {
                   3462:                         $forceedit = 1;
                   3463:                     }
                   3464:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3465:                 }
                   3466:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3467:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3468:                 if (&is_on_map($template)) {
                   3469:                     $incourse = 1;
                   3470:                     $forceview = 1;
                   3471:                     $cfile = $template;
                   3472:                 }
                   3473:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3474:                 $incourse = 1;
                   3475:                 if ($env{'form.forceedit'}) {
                   3476:                     $forceview = 1;
                   3477:                 } else {
                   3478:                     $forceedit = 1;
                   3479:                 }
                   3480:                 $cfile = $resurl;
1.1172.2.118.  .1(raebu 3481:20):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3482:20):                 $incourse = 1;
                   3483:20):                 if ($env{'form.forceedit'}) {
                   3484:20):                     $forceview = 1;
                   3485:20):                 } else {
                   3486:20):                     $forceedit = 1;
                   3487:20):                 }
                   3488:20):                 $cfile = $resurl;
1.1172.2.13  raeburn  3489:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3490:                 $incourse = 1;
                   3491:                 $forceview = 1;
                   3492:                 if ($symb) {
                   3493:                     my ($map,$id,$res)=&decode_symb($symb);
                   3494:                     $env{'request.symb'} = $symb;
                   3495:                     $cfile = &clutter($res);
                   3496:                 } else {
                   3497:                     $cfile = $env{'form.suppurl'};
1.1172.2.118.  .1(raebu 3498:20):                     my $escfile = &unescape($cfile);
                   3499:20):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3500:20):                         $cfile = '/adm/wrapper'.$escfile;
                   3501:20):                     } else {
                   3502:20):                         $escfile =~ s{^http://}{};
                   3503:20):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3504:20):                     }
1.1172.2.13  raeburn  3505:                 }
1.1172.2.31  raeburn  3506:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3507:                 if ($env{'form.forceedit'}) {
                   3508:                     $forceview = 1;
                   3509:                 } else {
                   3510:                     $forceedit = 1;
                   3511:                 }
                   3512:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3513:             }
                   3514:         }
                   3515:         if ($uploaded || $incourse) {
                   3516:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3517:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3518:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3519:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3520:             # Check that the user has permission to edit this resource
                   3521:             my $setpriv = 1;
                   3522:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3523:             if (defined($cfudom)) {
                   3524:                 $home=&homeserver($cfuname,$cfudom);
                   3525:                 $cfile=$file;
                   3526:             }
                   3527:         }
                   3528:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3529:             (($home ne '') && ($home ne 'no_host'))) {
                   3530:             my @ids=&current_machine_ids();
                   3531:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3532:                 $switchserver=1;
                   3533:             }
                   3534:         }
                   3535:     }
                   3536:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3537: }
                   3538: 
                   3539: sub is_course_upload {
                   3540:     my ($file,$cnum,$cdom) = @_;
                   3541:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3542:     $uploadpath =~ s{^\/}{};
                   3543:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3544:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3545:         return 1;
                   3546:     }
                   3547:     return;
                   3548: }
                   3549: 
                   3550: sub in_course {
                   3551:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3552:     if ($hideprivileged) {
                   3553:         my $skipuser;
1.1172.2.23  raeburn  3554:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3555:         my @possdoms = ($cdom);
                   3556:         if ($coursehash{'checkforpriv'}) {
                   3557:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3558:         }
                   3559:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3560:             $skipuser = 1;
                   3561:             if ($coursehash{'nothideprivileged'}) {
                   3562:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3563:                     my $user;
                   3564:                     if ($item =~ /:/) {
                   3565:                         $user = $item;
                   3566:                     } else {
                   3567:                         $user = join(':',split(/[\@]/,$item));
                   3568:                     }
                   3569:                     if ($user eq $uname.':'.$udom) {
                   3570:                         undef($skipuser);
                   3571:                         last;
                   3572:                     }
                   3573:                 }
                   3574:             }
                   3575:             if ($skipuser) {
                   3576:                 return 0;
                   3577:             }
                   3578:         }
                   3579:     }
                   3580:     $type ||= 'any';
                   3581:     if (!defined($cdom) || !defined($cnum)) {
                   3582:         my $cid  = $env{'request.course.id'};
                   3583:         $cdom = $env{'course.'.$cid.'.domain'};
                   3584:         $cnum = $env{'course.'.$cid.'.num'};
                   3585:     }
                   3586:     my $typesref;
                   3587:     if (($type eq 'any') || ($type eq 'all')) {
                   3588:         $typesref = ['active','previous','future'];
                   3589:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3590:         $typesref = [$type];
                   3591:     }
                   3592:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3593:                               $typesref,undef,[$cdom]);
                   3594:     my ($tmp) = keys(%roles);
                   3595:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3596:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3597:     if (@course_roles > 0) {
                   3598:         return 1;
                   3599:     }
                   3600:     return 0;
                   3601: }
                   3602: 
1.478     albertel 3603: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3604: # input: action, courseID, current domain, intended
1.637     raeburn  3605: #        path to file, source of file, instruction to parse file for objects,
                   3606: #        ref to hash for embedded objects,
                   3607: #        ref to hash for codebase of java objects.
1.1095    raeburn  3608: #        reference to scalar to accommodate mime type determined
                   3609: #          from File::MMagic if $parser = parse.
1.637     raeburn  3610: #
1.485     raeburn  3611: # output: url to file (if action was uploaddoc), 
                   3612: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3613: #
1.478     albertel 3614: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3615: # course.
1.477     raeburn  3616: #
1.478     albertel 3617: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3618: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3619: #          course's home server.
1.477     raeburn  3620: #
1.478     albertel 3621: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3622: #          be copied from $source (current location) to 
                   3623: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3624: #         and will then be copied to
                   3625: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3626: #         course's home server.
1.485     raeburn  3627: #
1.481     raeburn  3628: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3629: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3630: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3631: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3632: #         in course's home server.
1.637     raeburn  3633: #
1.477     raeburn  3634: 
                   3635: sub process_coursefile {
1.1095    raeburn  3636:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3637:         $mimetype)=@_;
1.477     raeburn  3638:     my $fetchresult;
1.638     albertel 3639:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3640:     if ($action eq 'propagate') {
1.638     albertel 3641:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3642: 			     $home);
1.481     raeburn  3643:     } else {
1.477     raeburn  3644:         my $fpath = '';
                   3645:         my $fname = $file;
1.478     albertel 3646:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3647:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3648:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3649:         if ($action eq 'copy') {
                   3650:             if ($source eq '') {
                   3651:                 $fetchresult = 'no source file';
                   3652:                 return $fetchresult;
                   3653:             } else {
                   3654:                 my $destination = $filepath.'/'.$fname;
                   3655:                 rename($source,$destination);
                   3656:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3657:                                  $home);
1.481     raeburn  3658:             }
                   3659:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3660:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3661:             print $fh $env{'form.'.$source};
1.481     raeburn  3662:             close($fh);
1.637     raeburn  3663:             if ($parser eq 'parse') {
1.1024    raeburn  3664:                 my $mm = new File::MMagic;
1.1095    raeburn  3665:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3666:                 if ($type eq 'text/html') {
1.1024    raeburn  3667:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3668:                     unless ($parse_result eq 'ok') {
                   3669:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3670:                     }
1.637     raeburn  3671:                 }
1.1095    raeburn  3672:                 if (ref($mimetype)) {
                   3673:                     $$mimetype = $type;
                   3674:                 } 
1.637     raeburn  3675:             }
1.477     raeburn  3676:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3677:                                  $home);
1.481     raeburn  3678:             if ($fetchresult eq 'ok') {
                   3679:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3680:             } else {
                   3681:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3682:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3683:                 return '/adm/notfound.html';
                   3684:             }
1.477     raeburn  3685:         }
                   3686:     }
1.485     raeburn  3687:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3688:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3689:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3690:     }
                   3691:     return $fetchresult;
                   3692: }
                   3693: 
1.637     raeburn  3694: sub build_filepath {
                   3695:     my ($fpath) = @_;
                   3696:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3697:     unless ($fpath eq '') {
                   3698:         my @parts=split('/',$fpath);
                   3699:         foreach my $part (@parts) {
                   3700:             $filepath.= '/'.$part;
                   3701:             if ((-e $filepath)!=1) {
                   3702:                 mkdir($filepath,0777);
                   3703:             }
                   3704:         }
                   3705:     }
                   3706:     return $filepath;
                   3707: }
                   3708: 
                   3709: sub store_edited_file {
1.638     albertel 3710:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3711:     my $file = $primary_url;
                   3712:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3713:     my $fpath = '';
                   3714:     my $fname = $file;
                   3715:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3716:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3717:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3718:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3719:     print $fh $content;
                   3720:     close($fh);
1.638     albertel 3721:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3722:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3723: 			  $home);
1.637     raeburn  3724:     if ($$fetchresult eq 'ok') {
                   3725:         return '/uploaded/'.$fpath.'/'.$fname;
                   3726:     } else {
1.638     albertel 3727:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3728: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3729:         return '/adm/notfound.html';
                   3730:     }
                   3731: }
                   3732: 
1.531     albertel 3733: sub clean_filename {
1.831     albertel 3734:     my ($fname,$args)=@_;
1.315     www      3735: # Replace Windows backslashes by forward slashes
1.257     www      3736:     $fname=~s/\\/\//g;
1.831     albertel 3737:     if (!$args->{'keep_path'}) {
                   3738:         # Get rid of everything but the actual filename
                   3739: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3740:     }
1.315     www      3741: # Replace spaces by underscores
                   3742:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3743: # Transliterate non-ascii text to ascii
                   3744:     my $lang = &Apache::lonlocal::current_language();
                   3745:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3746: # Replace all other weird characters by nothing
1.831     albertel 3747:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3748: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3749: # numbers
                   3750:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3751:     return $fname;
                   3752: }
1.1172.2.110  raeburn  3753: 
1.1051    raeburn  3754: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3755: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3756: # image with the same aspect ratio as the original, but with dimensions which do 
                   3757: # not exceed $resizewidth and $resizeheight.
                   3758:  
1.984     neumanie 3759: sub resizeImage {
1.1051    raeburn  3760:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3761:     my $ima = Image::Magick->new;
                   3762:     my $resized;
                   3763:     if (-e $img_path) {
                   3764:         $ima->Read($img_path);
                   3765:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3766:             my $width = $ima->Get('width');
                   3767:             my $height = $ima->Get('height');
                   3768:             if ($width > $resizewidth) {
                   3769: 	        my $factor = $width/$resizewidth;
                   3770:                 my $newheight = $height/$factor;
                   3771:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3772:                 $resized = 1;
                   3773:             }
                   3774:         }
                   3775:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3776:             my $width = $ima->Get('width');
                   3777:             my $height = $ima->Get('height');
                   3778:             if ($height > $resizeheight) {
                   3779:                 my $factor = $height/$resizeheight;
                   3780:                 my $newwidth = $width/$factor;
                   3781:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3782:                 $resized = 1;
                   3783:             }
                   3784:         }
                   3785:         if ($resized) {
                   3786:             $ima->Write($img_path);
                   3787:         }
                   3788:     }
                   3789:     return;
1.977     amueller 3790: }
                   3791: 
1.608     albertel 3792: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3793: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3794: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3795: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3796: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3797: #                   if 'coursedoc': upload to the current course
                   3798: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3799: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3800: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3801: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3802: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3803: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3804: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3805: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3806: #        $allfiles - reference to hash for embedded objects
                   3807: #        $codebase - reference to hash for codebase of java objects
                   3808: #        $desuname - username for permanent storage of uploaded file
                   3809: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3810: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3811: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3812: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3813: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3814: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3815: #                    from File::MMagic.
1.858     raeburn  3816: # 
1.686     albertel 3817: # output: url of file in userspace, or error: <message> 
                   3818: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3819: 
1.531     albertel 3820: sub userfileupload {
1.1090    raeburn  3821:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3822:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3823:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3824:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3825:     $fname=&clean_filename($fname);
1.1090    raeburn  3826:     # See if there is anything left
1.257     www      3827:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3828:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3829:     if ($fname =~ /^\./) {
                   3830:         my ($s,$usec) = &gettimeofday();
                   3831:         while (length($usec) < 6) {
                   3832:             $usec = '0'.$usec;
                   3833:         }
                   3834:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3835:     }
1.1090    raeburn  3836:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3837:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3838:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3839:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3840:         my $now = time;
1.1090    raeburn  3841:         my $filepath;
1.1095    raeburn  3842:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3843:              $filepath = 'tmp/helprequests/'.$now;
                   3844:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3845:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3846:                          '_'.$env{'user.domain'}.'/pending';
                   3847:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3848:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3849:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3850:                 $docudom = $destudom;
                   3851:             } else {
                   3852:                 $docudom = $env{'user.domain'};
                   3853:             }
1.1172.2.96  raeburn  3854:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3855:                 $docuname = $destuname;
                   3856:             } else {
                   3857:                 $docuname = $env{'user.name'};
                   3858:             }
                   3859:             if (exists($env{'form.group'})) {
                   3860:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3861:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3862:             }
                   3863:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3864:             if ($context eq 'canceloverwrite') {
                   3865:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3866:                 if (-e  $tempfile) {
                   3867:                     my @info = stat($tempfile);
                   3868:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3869:                         unlink($tempfile);
                   3870:                     }
                   3871:                 }
                   3872:                 return;
1.523     raeburn  3873:             }
                   3874:         }
1.1090    raeburn  3875:         # Create the directory if not present
1.741     raeburn  3876:         my @parts=split(/\//,$filepath);
                   3877:         my $fullpath = $perlvar{'lonDaemons'};
                   3878:         for (my $i=0;$i<@parts;$i++) {
                   3879:             $fullpath .= '/'.$parts[$i];
                   3880:             if ((-e $fullpath)!=1) {
                   3881:                 mkdir($fullpath,0777);
                   3882:             }
                   3883:         }
1.1172.2.96  raeburn  3884:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3885:         print $fh $env{'form.'.$formname};
                   3886:         close($fh);
1.1090    raeburn  3887:         if ($context eq 'existingfile') {
                   3888:             my @info = stat($fullpath.'/'.$fname);
                   3889:             return ($fullpath.'/'.$fname,$info[9]);
                   3890:         } else {
                   3891:             return $fullpath.'/'.$fname;
                   3892:         }
1.523     raeburn  3893:     }
1.995     raeburn  3894:     if ($subdir eq 'scantron') {
                   3895:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3896:     } else {
1.995     raeburn  3897:         $fname="$subdir/$fname";
                   3898:     }
1.1090    raeburn  3899:     if ($context eq 'coursedoc') {
1.638     albertel 3900: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3901: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3902:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3903:             return &finishuserfileupload($docuname,$docudom,
                   3904: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3905: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3906:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3907:         } else {
1.1172.2.21  raeburn  3908:             if ($env{'form.folder'}) {
                   3909:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3910:             }
1.638     albertel 3911:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3912: 				       $fname,$formname,$parser,
1.1095    raeburn  3913: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3914:         }
1.719     banghart 3915:     } elsif (defined($destuname)) {
                   3916:         my $docuname=$destuname;
                   3917:         my $docudom=$destudom;
1.860     raeburn  3918: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3919: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3920:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3921:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3922:     } else {
1.638     albertel 3923:         my $docuname=$env{'user.name'};
                   3924:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3925:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3926:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3927:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3928:         }
1.860     raeburn  3929: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3930: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3931:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3932:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3933:     }
1.271     www      3934: }
                   3935: 
                   3936: sub finishuserfileupload {
1.860     raeburn  3937:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3938:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3939:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3940:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3941:   
1.860     raeburn  3942:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3943:     $file=$fname;
                   3944:     if ($fname=~m|/|) {
                   3945:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3946: 	$path.=$fnamepath.'/';
                   3947:     }
1.259     www      3948:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3949:     my $count;
                   3950:     for ($count=4;$count<=$#parts;$count++) {
                   3951:         $filepath.="/$parts[$count]";
                   3952:         if ((-e $filepath)!=1) {
                   3953: 	    mkdir($filepath,0777);
                   3954:         }
                   3955:     }
1.984     neumanie 3956: 
1.258     www      3957: # Save the file
                   3958:     {
1.1172.2.96  raeburn  3959: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3960: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3961: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3962: 	    return '/adm/notfound.html';
                   3963: 	}
1.1090    raeburn  3964:         if ($context eq 'overwrite') {
1.1117    foxr     3965:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3966:             my $target = $filepath.'/'.$file;
                   3967:             if (-e $source) {
                   3968:                 my @info = stat($source);
                   3969:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3970:                     unless (&File::Copy::move($source,$target)) {
                   3971:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3972:                         return "Moving from $source failed";
                   3973:                     }
                   3974:                 } else {
                   3975:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3976:                 }
                   3977:             } else {
                   3978:                 return "Temporary file: $source missing";
                   3979:             }
                   3980:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3981: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3982: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3983: 	    return '/adm/notfound.html';
                   3984: 	}
1.570     albertel 3985: 	close(FH);
1.1051    raeburn  3986:         if ($resizewidth && $resizeheight) {
                   3987:             my $mm = new File::MMagic;
                   3988:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3989:             if ($mime_type =~ m{^image/}) {
                   3990: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3991:             }  
1.977     amueller 3992: 	}
1.258     www      3993:     }
1.1152    raeburn  3994:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3995:         if (ref($mimetype)) {
                   3996:             if ($$mimetype eq '') {
                   3997:                 my $mm = new File::MMagic;
                   3998:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3999:                 $$mimetype = $type;
                   4000:             }
                   4001:         }
                   4002:     }
1.1172.2.109  raeburn  4003:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4004:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4005:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4006:                                                        $allfiles,$codebase);
                   4007:             unless ($parse_result eq 'ok') {
                   4008:                 &logthis('Failed to parse '.$filepath.$file.
                   4009: 	   	         ' for embedded media: '.$parse_result); 
                   4010:             }
1.637     raeburn  4011:         }
1.1172.2.109  raeburn  4012:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4013:         my $format = $env{'form.scantron_format'};
                   4014:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4015:     }
1.860     raeburn  4016:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4017:         my $input = $filepath.'/'.$file;
                   4018:         my $output = $filepath.'/'.'tn-'.$file;
                   4019:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4020:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4021:         system({$args[0]} @args);
1.860     raeburn  4022:         if (-e $filepath.'/'.'tn-'.$file) {
                   4023:             $fetchthumb  = 1; 
                   4024:         }
                   4025:     }
1.858     raeburn  4026:  
1.259     www      4027: # Notify homeserver to grep it
                   4028: #
1.984     neumanie 4029:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4030:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4031:     if ($fetchresult eq 'ok') {
1.860     raeburn  4032:         if ($fetchthumb) {
                   4033:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4034:             if ($thumbresult ne 'ok') {
                   4035:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4036:                          $docuhome.': '.$thumbresult);
                   4037:             }
                   4038:         }
1.259     www      4039: #
1.258     www      4040: # Return the URL to it
1.494     albertel 4041:         return '/uploaded/'.$path.$file;
1.263     www      4042:     } else {
1.494     albertel 4043:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4044: 		 ': '.$fetchresult);
1.263     www      4045:         return '/adm/notfound.html';
1.858     raeburn  4046:     }
1.493     albertel 4047: }
                   4048: 
1.637     raeburn  4049: sub extract_embedded_items {
1.961     raeburn  4050:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4051:     my @state = ();
1.1164    raeburn  4052:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4053:     my %javafiles = (
                   4054:                       codebase => '',
                   4055:                       code => '',
                   4056:                       archive => ''
                   4057:                     );
                   4058:     my %mediafiles = (
                   4059:                       src => '',
                   4060:                       movie => '',
                   4061:                      );
1.648     raeburn  4062:     my $p;
                   4063:     if ($content) {
                   4064:         $p = HTML::LCParser->new($content);
                   4065:     } else {
1.961     raeburn  4066:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4067:     }
1.641     albertel 4068:     while (my $t=$p->get_token()) {
1.640     albertel 4069: 	if ($t->[0] eq 'S') {
                   4070: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4071: 	    push(@state, $tagname);
1.648     raeburn  4072:             if (lc($tagname) eq 'allow') {
                   4073:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4074:             }
1.640     albertel 4075: 	    if (lc($tagname) eq 'img') {
                   4076: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4077: 	    }
1.886     albertel 4078: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4079:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4080: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4081:                 }
1.886     albertel 4082: 	    }
1.645     raeburn  4083:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4084:                 my $src;
1.645     raeburn  4085:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4086:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4087:                 } else {
1.1164    raeburn  4088:                     if ($attr->{'src'} ne '') {
                   4089:                         $src = $attr->{'src'};
                   4090:                         &add_filetype($allfiles,$src,'src');
                   4091:                     }
                   4092:                 }
                   4093:                 my $text = $p->get_trimmed_text();
                   4094:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4095:                     my @swfargs = split(/,/,$1);
                   4096:                     foreach my $item (@swfargs) {
                   4097:                         $item =~ s/["']//g;
                   4098:                         $item =~ s/^\s+//;
                   4099:                         $item =~ s/\s+$//;
                   4100:                     }
                   4101:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4102:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4103:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4104:                         } else {
                   4105:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4106:                         }
                   4107:                     }
1.645     raeburn  4108:                 }
                   4109:             }
                   4110:             if (lc($tagname) eq 'link') {
                   4111:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4112:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4113:                 }
                   4114:             }
1.640     albertel 4115: 	    if (lc($tagname) eq 'object' ||
                   4116: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4117: 		foreach my $item (keys(%javafiles)) {
                   4118: 		    $javafiles{$item} = '';
                   4119: 		}
1.1164    raeburn  4120:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4121:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4122:                 }
1.640     albertel 4123: 	    }
                   4124: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4125: 		my $name = lc($attr->{'name'});
                   4126: 		foreach my $item (keys(%javafiles)) {
                   4127: 		    if ($name eq $item) {
                   4128: 			$javafiles{$item} = $attr->{'value'};
                   4129: 			last;
                   4130: 		    }
                   4131: 		}
1.1164    raeburn  4132:                 my $pathfrom;
1.640     albertel 4133: 		foreach my $item (keys(%mediafiles)) {
                   4134: 		    if ($name eq $item) {
1.1164    raeburn  4135:                         $pathfrom = $attr->{'value'};
                   4136:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4137: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4138: 			last;
                   4139: 		    }
                   4140: 		}
1.1164    raeburn  4141:                 if ($name eq 'flashvars') {
                   4142:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4143:                 }
                   4144:                 if ($pathfrom ne '') {
                   4145:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4146:                                          $pathfrom);
                   4147:                 }
1.640     albertel 4148: 	    }
                   4149: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4150: 		foreach my $item (keys(%javafiles)) {
                   4151: 		    if ($attr->{$item}) {
                   4152: 			$javafiles{$item} = $attr->{$item};
                   4153: 			last;
                   4154: 		    }
                   4155: 		}
                   4156: 		foreach my $item (keys(%mediafiles)) {
                   4157: 		    if ($attr->{$item}) {
                   4158: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4159: 			last;
                   4160: 		    }
                   4161: 		}
1.1164    raeburn  4162:                 if (lc($tagname) eq 'embed') {
                   4163:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4164:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4165:                                              $attr->{'src'});
                   4166:                     }
                   4167:                 }
1.640     albertel 4168: 	    }
1.1172.2.35  raeburn  4169:             if (lc($tagname) eq 'iframe') {
                   4170:                 my $src = $attr->{'src'} ;
                   4171:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4172:                     &add_filetype($allfiles,$src,'src');
                   4173:                 } elsif ($src =~ m{^/}) {
                   4174:                     if ($env{'request.course.id'}) {
                   4175:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4176:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4177:                         my $url = &hreflocation('',$fullpath);
                   4178:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4179:                             my $relpath = $1;
                   4180:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4181:                                 &add_filetype($allfiles,$1,'src');
                   4182:                             }
                   4183:                         }
                   4184:                     }
                   4185:                 }
                   4186:             }
1.1164    raeburn  4187:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4188:                 pop(@state);
1.1164    raeburn  4189:             }
1.640     albertel 4190: 	} elsif ($t->[0] eq 'E') {
                   4191: 	    my ($tagname) = ($t->[1]);
                   4192: 	    if ($javafiles{'codebase'} ne '') {
                   4193: 		$javafiles{'codebase'} .= '/';
                   4194: 	    }  
                   4195: 	    if (lc($tagname) eq 'applet' ||
                   4196: 		lc($tagname) eq 'object' ||
                   4197: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4198: 		) {
                   4199: 		foreach my $item (keys(%javafiles)) {
                   4200: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4201: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4202: 			&add_filetype($allfiles,$file,$item);
                   4203: 		    }
                   4204: 		}
                   4205: 	    } 
                   4206: 	    pop @state;
                   4207: 	}
                   4208:     }
1.1164    raeburn  4209:     foreach my $id (sort(keys(%flashvars))) {
                   4210:         if ($shockwave{$id} ne '') {
                   4211:             my @pairs = split(/\&/,$flashvars{$id});
                   4212:             foreach my $pair (@pairs) {
                   4213:                 my ($key,$value) = split(/\=/,$pair);
                   4214:                 if ($key eq 'thumb') {
                   4215:                     &add_filetype($allfiles,$value,$key);
                   4216:                 } elsif ($key eq 'content') {
                   4217:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4218:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4219:                     if ($ext ne '') {
                   4220:                         &add_filetype($allfiles,$path.$value,$ext);
                   4221:                     }
                   4222:                 }
                   4223:             }
                   4224:         }
                   4225:     }
1.637     raeburn  4226:     return 'ok';
                   4227: }
                   4228: 
1.639     albertel 4229: sub add_filetype {
                   4230:     my ($allfiles,$file,$type)=@_;
                   4231:     if (exists($allfiles->{$file})) {
                   4232: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4233: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4234: 	}
                   4235:     } else {
                   4236: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4237:     }
                   4238: }
                   4239: 
1.1164    raeburn  4240: sub embedded_dependency {
                   4241:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4242:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4243:         if (($identifier ne '') &&
                   4244:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4245:             ($pathfrom ne '')) {
                   4246:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4247:             foreach my $dep (@{$related->{$identifier}}) {
                   4248:                 &add_filetype($allfiles,$path.$dep,'object');
                   4249:             }
                   4250:         }
                   4251:     }
                   4252:     return;
                   4253: }
                   4254: 
1.1172.2.109  raeburn  4255: sub bubblesheet_converter {
                   4256:     my ($cdom,$fullpath,$config,$format) = @_;
                   4257:     if ((&domain($cdom) ne '') &&
                   4258:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4259:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4260:         my (%csvcols,%csvoptions);
                   4261:         if (ref($config->{'fields'}) eq 'HASH') {
                   4262:             %csvcols = %{$config->{'fields'}};
                   4263:         }
                   4264:         if (ref($config->{'options'}) eq 'HASH') {
                   4265:             %csvoptions = %{$config->{'options'}};
                   4266:         }
                   4267:         my %csvbynum = reverse(%csvcols);
                   4268:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4269:         if (keys(%scantronconf)) {
                   4270:             my %bynum = (
                   4271:                           $scantronconf{CODEstart} => 'CODEstart',
                   4272:                           $scantronconf{IDstart}   => 'IDstart',
                   4273:                           $scantronconf{PaperID}   => 'PaperID',
                   4274:                           $scantronconf{FirstName} => 'FirstName',
                   4275:                           $scantronconf{LastName}  => 'LastName',
                   4276:                           $scantronconf{Qstart}    => 'Qstart',
                   4277:                         );
                   4278:             my @ordered;
                   4279:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4280:                 push(@ordered,$bynum{$item});
                   4281:             }
                   4282:             my %mapstart = (
                   4283:                               CODEstart => 'CODE',
                   4284:                               IDstart   => 'ID',
                   4285:                               PaperID   => 'PaperID',
                   4286:                               FirstName => 'FirstName',
                   4287:                               LastName  => 'LastName',
                   4288:                               Qstart    => 'FirstQuestion',
                   4289:                            );
                   4290:             my %maplength = (
                   4291:                               CODEstart => 'CODElength',
                   4292:                               IDstart   => 'IDlength',
                   4293:                               PaperID   => 'PaperIDlength',
                   4294:                               FirstName => 'FirstNamelength',
                   4295:                               LastName  => 'LastNamelength',
                   4296:             );
                   4297:             if (open(my $fh,'<',$fullpath)) {
                   4298:                 my $output;
                   4299:                 my %lettdig = &letter_to_digits();
                   4300:                 my %diglett = reverse(%lettdig);
                   4301:                 my $numletts = scalar(keys(%lettdig));
                   4302:                 my $num = 0;
                   4303:                 while (my $line=<$fh>) {
                   4304:                     $num ++;
                   4305:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4306:                     $line =~ s{[\r\n]+$}{};
                   4307:                     my %found;
                   4308:                     my @values = split(/,/,$line);
                   4309:                     my ($qstart,$record);
                   4310:                     for (my $i=0; $i<@values; $i++) {
                   4311:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4312:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4313:                             if ($values[$i] eq '') {
                   4314:                                 $values[$i] = $scantronconf{'Qoff'};
                   4315:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4316:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4317:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4318:                                 }
                   4319:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4320:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4321:                                     $values[$i] = $diglett{$values[$i]};
                   4322:                                 }
                   4323:                             } else {
                   4324:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4325:                                     my $digit;
                   4326:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4327:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4328:                                         if ($values[$i] eq 'J') {
                   4329:                                             $digit += $numletts;
                   4330:                                         }
                   4331:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4332:                                         $digit = $values[$i]-1;
                   4333:                                         if ($values[$i] eq '0') {
                   4334:                                             $digit += $numletts;
                   4335:                                         }
                   4336:                                     }
                   4337:                                     my $qval='';
                   4338:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4339:                                         if ($j == $digit) {
                   4340:                                             $qval .= $scantronconf{'Qon'};
                   4341:                                         } else {
                   4342:                                             $qval .= $scantronconf{'Qoff'};
                   4343:                                         }
                   4344:                                     }
                   4345:                                     $values[$i] = $qval;
                   4346:                                 }
                   4347:                             }
                   4348:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4349:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4350:                             }
                   4351:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4352:                             if ($numblank > 0) {
                   4353:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4354:                             }
                   4355:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4356:                                 $qstart = $i;
                   4357:                                 $found{$csvbynum{$i}} = $values[$i];
                   4358:                             } else {
                   4359:                                 $found{'FirstQuestion'} .= $values[$i];
                   4360:                             }
                   4361:                         } elsif (exists($csvbynum{$i})) {
                   4362:                             if ($csvoptions{'rem'}) {
                   4363:                                 $values[$i] =~ s/^\s+//;
                   4364:                             }
                   4365:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4366:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4367:                                     $values[$i] = '0'.$values[$i];
                   4368:                                 }
                   4369:                             }
                   4370:                             $found{$csvbynum{$i}} = $values[$i];
                   4371:                         }
                   4372:                     }
                   4373:                     foreach my $item (@ordered) {
                   4374:                         my $currlength = 1+length($record);
                   4375:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4376:                         if ($numspaces > 0) {
                   4377:                             $record .= (' ' x $numspaces);
                   4378:                         }
                   4379:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4380:                             unless ($item eq 'Qstart') {
                   4381:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4382:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4383:                                 }
                   4384:                             }
                   4385:                             $record .= $found{$mapstart{$item}};
                   4386:                         }
                   4387:                     }
                   4388:                     $output .= "$record\n";
                   4389:                 }
                   4390:                 close($fh);
                   4391:                 if ($output) {
                   4392:                     if (open(my $fh,'>',$fullpath)) {
                   4393:                         print $fh $output;
                   4394:                         close($fh);
                   4395:                     }
                   4396:                 }
                   4397:             }
                   4398:         }
                   4399:         return;
                   4400:     }
                   4401: }
                   4402: 
                   4403: sub letter_to_digits {
                   4404:     my %lettdig = (
                   4405:                     A => 1,
                   4406:                     B => 2,
                   4407:                     C => 3,
                   4408:                     D => 4,
                   4409:                     E => 5,
                   4410:                     F => 6,
                   4411:                     G => 7,
                   4412:                     H => 8,
                   4413:                     I => 9,
                   4414:                     J => 0,
                   4415:                   );
                   4416:     return %lettdig;
                   4417: }
                   4418: 
                   4419: sub get_scantron_config {
                   4420:     my ($which,$cdom) = @_;
                   4421:     my @lines = &get_scantronformat_file($cdom);
                   4422:     my %config;
                   4423:     #FIXME probably should move to XML it has already gotten a bit much now
                   4424:     foreach my $line (@lines) {
                   4425:         my ($name,$descrip)=split(/:/,$line);
                   4426:         if ($name ne $which ) { next; }
                   4427:         chomp($line);
                   4428:         my @config=split(/:/,$line);
                   4429:         $config{'name'}=$config[0];
                   4430:         $config{'description'}=$config[1];
                   4431:         $config{'CODElocation'}=$config[2];
                   4432:         $config{'CODEstart'}=$config[3];
                   4433:         $config{'CODElength'}=$config[4];
                   4434:         $config{'IDstart'}=$config[5];
                   4435:         $config{'IDlength'}=$config[6];
                   4436:         $config{'Qstart'}=$config[7];
                   4437:         $config{'Qlength'}=$config[8];
                   4438:         $config{'Qoff'}=$config[9];
                   4439:         $config{'Qon'}=$config[10];
                   4440:         $config{'PaperID'}=$config[11];
                   4441:         $config{'PaperIDlength'}=$config[12];
                   4442:         $config{'FirstName'}=$config[13];
                   4443:         $config{'FirstNamelength'}=$config[14];
                   4444:         $config{'LastName'}=$config[15];
                   4445:         $config{'LastNamelength'}=$config[16];
                   4446:         $config{'BubblesPerRow'}=$config[17];
                   4447:         last;
                   4448:     }
                   4449:     return %config;
                   4450: }
                   4451: 
                   4452: sub get_scantronformat_file {
                   4453:     my ($cdom) = @_;
                   4454:     if ($cdom eq '') {
                   4455:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4456:     }
                   4457:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4458:     my $gottab = 0;
                   4459:     my @lines;
                   4460:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4461:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4462:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4463:             if ($formatfile ne '-1') {
                   4464:                 @lines = split("\n",$formatfile,-1);
                   4465:                 $gottab = 1;
                   4466:             }
                   4467:         }
                   4468:     }
                   4469:     if (!$gottab) {
                   4470:         my $confname = $cdom.'-domainconfig';
                   4471:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4472:         my $formatfile = &getfile($default);
                   4473:         if ($formatfile ne '-1') {
                   4474:             @lines = split("\n",$formatfile,-1);
                   4475:             $gottab = 1;
                   4476:         }
                   4477:     }
                   4478:     if (!$gottab) {
                   4479:         my @domains = &current_machine_domains();
                   4480:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4481:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4482:                 @lines = <$fh>;
                   4483:                 close($fh);
                   4484:             }
                   4485:         } else {
                   4486:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4487:                 @lines = <$fh>;
                   4488:                 close($fh);
                   4489:             }
                   4490:         }
                   4491:     }
                   4492:     return @lines;
                   4493: }
                   4494: 
1.493     albertel 4495: sub removeuploadedurl {
1.984     neumanie 4496:     my ($url)=@_;	
                   4497:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4498:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4499: }
                   4500: 
                   4501: sub removeuserfile {
                   4502:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4503:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4504:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4505:     if ($result eq 'ok') {	
1.798     raeburn  4506:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4507:             my $metafile = $fname.'.meta';
                   4508:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4509: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4510:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4511:             my $sqlresult = 
1.823     albertel 4512:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4513:                                         'portfolio_metadata',$group,
                   4514:                                         'delete');
1.798     raeburn  4515:         }
                   4516:     }
                   4517:     return $result;
1.257     www      4518: }
1.15      www      4519: 
1.530     albertel 4520: sub mkdiruserfile {
                   4521:     my ($docuname,$docudom,$dir)=@_;
                   4522:     my $home=&homeserver($docuname,$docudom);
                   4523:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4524: }
                   4525: 
1.531     albertel 4526: sub renameuserfile {
                   4527:     my ($docuname,$docudom,$old,$new)=@_;
                   4528:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4529:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4530:                         &escape("$old").':'.&escape("$new"),$home);
                   4531:     if ($result eq 'ok') {
                   4532:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4533:             my $oldmeta = $old.'.meta';
                   4534:             my $newmeta = $new.'.meta';
                   4535:             my $metaresult = 
                   4536:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4537: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4538:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4539:             my $sqlresult = 
1.823     albertel 4540:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4541:                                         'portfolio_metadata',$group,
                   4542:                                         'delete');
1.798     raeburn  4543:         }
                   4544:     }
                   4545:     return $result;
1.531     albertel 4546: }
                   4547: 
1.14      www      4548: # ------------------------------------------------------------------------- Log
                   4549: 
                   4550: sub log {
                   4551:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4552:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4553: }
                   4554: 
                   4555: # ------------------------------------------------------------------ Course Log
1.352     www      4556: #
                   4557: # This routine flushes several buffers of non-mission-critical nature
                   4558: #
1.157     www      4559: 
                   4560: sub flushcourselogs {
1.352     www      4561:     &logthis('Flushing log buffers');
                   4562: #
                   4563: # course logs
                   4564: # This is a log of all transactions in a course, which can be used
                   4565: # for data mining purposes
                   4566: #
                   4567: # It also collects the courseid database, which lists last transaction
                   4568: # times and course titles for all courseids
                   4569: #
                   4570:     my %courseidbuffer=();
1.921     raeburn  4571:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4572:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4573: 		          &escape($courselogs{$crsid}),
                   4574: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4575: 	    delete $courselogs{$crsid};
                   4576:         } else {
                   4577:             &logthis('Failed to flush log buffer for '.$crsid);
                   4578:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4579:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4580:                         " exceeded maximum size, deleting.</font>");
                   4581:                delete $courselogs{$crsid};
                   4582:             }
1.352     www      4583:         }
1.920     raeburn  4584:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4585:             'description' => $coursedescrbuf{$crsid},
                   4586:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4587:             'type'        => $coursetypebuf{$crsid},
                   4588:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4589:         };
1.191     harris41 4590:     }
1.352     www      4591: #
                   4592: # Write course id database (reverse lookup) to homeserver of courses 
                   4593: # Is used in pickcourse
                   4594: #
1.840     albertel 4595:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4596:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4597:                                     $courseidbuffer{$crs_home},
                   4598:                                     $crs_home,'timeonly');
1.352     www      4599:     }
                   4600: #
                   4601: # File accesses
                   4602: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4603: #
1.449     matthew  4604:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4605:         if ($entry =~ /___count$/) {
                   4606:             my ($dom,$name);
1.807     albertel 4607:             ($dom,$name,undef)=
1.811     albertel 4608: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4609:             if (! defined($dom) || $dom eq '' || 
                   4610:                 ! defined($name) || $name eq '') {
1.620     albertel 4611:                 my $cid = $env{'request.course.id'};
                   4612:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4613:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4614:             }
1.450     matthew  4615:             my $value = $accesshash{$entry};
                   4616:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4617:             my %temphash=($url => $value);
1.449     matthew  4618:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4619:             if ($result eq 'ok') {
                   4620:                 delete $accesshash{$entry};
                   4621:             }
                   4622:         } else {
1.811     albertel 4623:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4624:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4625:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4626:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4627:                 delete $accesshash{$entry};
                   4628:             }
1.185     www      4629:         }
1.191     harris41 4630:     }
1.352     www      4631: #
                   4632: # Roles
                   4633: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4634: #
1.800     albertel 4635:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4636:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4637: 	    split(/\:/,$entry);
                   4638:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4639:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4640:                 $rudom,$runame) eq 'ok') {
                   4641: 	    delete $userrolehash{$entry};
                   4642:         }
                   4643:     }
1.662     raeburn  4644: #
1.1172.2.90  raeburn  4645: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4646: #
                   4647:     my %domrolebuffer = ();
1.1000    raeburn  4648:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4649:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4650:         if ($domrolebuffer{$rudom}) {
                   4651:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4652:                       '='.&escape($domainrolehash{$entry});
                   4653:         } else {
                   4654:             $domrolebuffer{$rudom}.=&escape($entry).
                   4655:                       '='.&escape($domainrolehash{$entry});
                   4656:         }
                   4657:         delete $domainrolehash{$entry};
                   4658:     }
                   4659:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4660:         my %servers;
                   4661:         if (defined(&domain($dom,'primary'))) {
                   4662:             my $primary=&domain($dom,'primary');
                   4663:             my $hostname=&hostname($primary);
                   4664:             $servers{$primary} = $hostname;
                   4665:         } else {
                   4666:             %servers = &get_servers($dom,'library');
                   4667:         }
1.841     albertel 4668: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4669: 	    if (&reply('domroleput:'.$dom.':'.
                   4670: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4671: 	        last;
                   4672: 	    } else {
1.841     albertel 4673: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4674: 	    }
1.662     raeburn  4675:         }
                   4676:     }
1.186     www      4677:     $dumpcount++;
1.157     www      4678: }
                   4679: 
                   4680: sub courselog {
                   4681:     my $what=shift;
1.158     www      4682:     $what=time.':'.$what;
1.620     albertel 4683:     unless ($env{'request.course.id'}) { return ''; }
                   4684:     $coursedombuf{$env{'request.course.id'}}=
                   4685:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4686:     $coursenumbuf{$env{'request.course.id'}}=
                   4687:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4688:     $coursehombuf{$env{'request.course.id'}}=
                   4689:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4690:     $coursedescrbuf{$env{'request.course.id'}}=
                   4691:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4692:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4693:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4694:     $courseownerbuf{$env{'request.course.id'}}=
                   4695:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4696:     $coursetypebuf{$env{'request.course.id'}}=
                   4697:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4698:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4699: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4700:     } else {
1.620     albertel 4701: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4702:     }
1.620     albertel 4703:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4704: 	&flushcourselogs();
                   4705:     }
1.158     www      4706: }
                   4707: 
                   4708: sub courseacclog {
                   4709:     my $fnsymb=shift;
1.620     albertel 4710:     unless ($env{'request.course.id'}) { return ''; }
                   4711:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4712:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4713:         $what.=':POST';
1.583     matthew  4714:         # FIXME: Probably ought to escape things....
1.800     albertel 4715: 	foreach my $key (keys(%env)) {
                   4716:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4717:                 my $formitem = $1;
                   4718:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4719:                     $what.=':'.$formitem.'='.$env{$key};
                   4720:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4721:                     $what.=':'.$formitem.'='.$env{$key};
                   4722:                 }
1.158     www      4723:             }
1.191     harris41 4724:         }
1.583     matthew  4725:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4726:         # FIXME: We should not be depending on a form parameter that someone
                   4727:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4728:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4729:             $what.= ':POST';
                   4730:             # FIXME: Probably ought to escape things....
                   4731:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4732:                                  'crsdiscuss') {
1.620     albertel 4733:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4734:             }
                   4735:         }
1.158     www      4736:     }
                   4737:     &courselog($what);
1.149     www      4738: }
                   4739: 
1.185     www      4740: sub countacc {
                   4741:     my $url=&declutter(shift);
1.458     matthew  4742:     return if (! defined($url) || $url eq '');
1.620     albertel 4743:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4744: #
                   4745: # Mark that this url was used in this course
                   4746: #
1.620     albertel 4747:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4748: #
                   4749: # Increase the access count for this resource in this child process
                   4750: #
1.281     www      4751:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4752:     $accesshash{$key}++;
1.185     www      4753: }
1.349     www      4754: 
1.361     www      4755: sub linklog {
                   4756:     my ($from,$to)=@_;
                   4757:     $from=&declutter($from);
                   4758:     $to=&declutter($to);
                   4759:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4760:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4761: }
1.1160    www      4762: 
                   4763: sub statslog {
                   4764:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4765:     if ($users<2) { return; }
                   4766:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4767:             'course'       => $env{'request.course.id'},
                   4768:             'sections'     => '"all"',
                   4769:             'num_students' => $users,
                   4770:             'part'         => $part,
                   4771:             'symb'         => $symb,
                   4772:             'mean_tries'   => $av_attempts,
                   4773:             'deg_of_diff'  => $degdiff});
                   4774:     foreach my $key (keys(%dynstore)) {
                   4775:         $accesshash{$key}=$dynstore{$key};
                   4776:     }
                   4777: }
1.361     www      4778:   
1.349     www      4779: sub userrolelog {
                   4780:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4781:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4782:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4783:        $userrolehash
                   4784:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4785:                     =$tend.':'.$tstart;
1.662     raeburn  4786:     }
1.1169    droeschl 4787:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4788:        $userrolehash
                   4789:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4790:                     =$tend.':'.$tstart;
                   4791:     }
1.1172.2.90  raeburn  4792:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4793:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4794:        $domainrolehash
                   4795:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4796:                     = $tend.':'.$tstart;
                   4797:     }
1.351     www      4798: }
                   4799: 
1.957     raeburn  4800: sub courserolelog {
                   4801:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4802:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4803:         my $cdom = $1;
                   4804:         my $cnum = $2;
                   4805:         my $sec = $3;
                   4806:         my $namespace = 'rolelog';
                   4807:         my %storehash = (
                   4808:                            role    => $trole,
                   4809:                            start   => $tstart,
                   4810:                            end     => $tend,
                   4811:                            selfenroll => $selfenroll,
                   4812:                            context    => $context,
                   4813:                         );
                   4814:         if ($trole eq 'gr') {
                   4815:             $namespace = 'groupslog';
                   4816:             $storehash{'group'} = $sec;
                   4817:         } else {
                   4818:             $storehash{'section'} = $sec;
                   4819:         }
                   4820:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4821:                    $domain,$cnum,$cdom);
                   4822:         if (($trole ne 'st') || ($sec ne '')) {
                   4823:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4824:         }
                   4825:     }
                   4826:     return;
                   4827: }
                   4828: 
1.1172.2.9  raeburn  4829: sub domainrolelog {
                   4830:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4831:     if ($area =~ m{^/($match_domain)/$}) {
                   4832:         my $cdom = $1;
                   4833:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4834:         my $namespace = 'rolelog';
                   4835:         my %storehash = (
                   4836:                            role    => $trole,
                   4837:                            start   => $tstart,
                   4838:                            end     => $tend,
                   4839:                            context => $context,
                   4840:                         );
                   4841:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4842:                    $domain,$domconfiguser,$cdom);
                   4843:     }
                   4844:     return;
                   4845: 
                   4846: }
                   4847: 
                   4848: sub coauthorrolelog {
                   4849:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4850:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4851:         my $audom = $1;
                   4852:         my $auname = $2;
                   4853:         my $namespace = 'rolelog';
                   4854:         my %storehash = (
                   4855:                            role    => $trole,
                   4856:                            start   => $tstart,
                   4857:                            end     => $tend,
                   4858:                            context => $context,
                   4859:                         );
                   4860:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4861:                    $domain,$auname,$audom);
                   4862:     }
                   4863:     return;
                   4864: }
                   4865: 
1.351     www      4866: sub get_course_adv_roles {
1.948     raeburn  4867:     my ($cid,$codes) = @_;
1.620     albertel 4868:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4869:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4870:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4871:     my %nothide=();
1.800     albertel 4872:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4873:         if ($user !~ /:/) {
                   4874: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4875:         } else {
                   4876:             $nothide{$user}=1;
                   4877:         }
1.470     www      4878:     }
1.1172.2.23  raeburn  4879:     my @possdoms = ($coursehash{'domain'});
                   4880:     if ($coursehash{'checkforpriv'}) {
                   4881:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4882:     }
1.351     www      4883:     my %returnhash=();
                   4884:     my %dumphash=
                   4885:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4886:     my $now=time;
1.997     raeburn  4887:     my %privileged;
1.1000    raeburn  4888:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4889: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4890:         if (($tstart) && ($tstart<0)) { next; }
                   4891:         if (($tend) && ($tend<$now)) { next; }
                   4892:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4893:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4894: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4895:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4896:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4897: 	if ($role eq 'cr') { next; }
1.948     raeburn  4898:         if ($codes) {
                   4899:             if ($section) { $role .= ':'.$section; }
                   4900:             if ($returnhash{$role}) {
                   4901:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4902:             } else {
                   4903:                 $returnhash{$role}=$username.':'.$domain;
                   4904:             }
1.351     www      4905:         } else {
1.988     raeburn  4906:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4907:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4908:             if ($returnhash{$key}) {
                   4909: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4910:             } else {
                   4911:                 $returnhash{$key}=$username.':'.$domain;
                   4912:             }
1.351     www      4913:         }
1.948     raeburn  4914:     }
1.400     www      4915:     return %returnhash;
                   4916: }
                   4917: 
                   4918: sub get_my_roles {
1.937     raeburn  4919:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4920:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4921:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4922:     my (%dumphash,%nothide);
1.1086    raeburn  4923:     if ($context eq 'userroles') {
1.1166    raeburn  4924:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4925:     } else {
1.1172.2.23  raeburn  4926:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4927:         if ($hidepriv) {
                   4928:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4929:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4930:                 if ($user !~ /:/) {
                   4931:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4932:                 } else {
                   4933:                     $nothide{$user} = 1;
                   4934:                 }
                   4935:             }
                   4936:         }
1.858     raeburn  4937:     }
1.400     www      4938:     my %returnhash=();
                   4939:     my $now=time;
1.999     raeburn  4940:     my %privileged;
1.800     albertel 4941:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4942:         my ($role,$tend,$tstart);
                   4943:         if ($context eq 'userroles') {
1.1149    raeburn  4944:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4945: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4946:         } else {
                   4947:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4948:         }
1.400     www      4949:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4950:         my $status = 'active';
1.939     raeburn  4951:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4952:             $status = 'previous';
                   4953:         } 
                   4954:         if (($tstart) && ($now<$tstart)) {
                   4955:             $status = 'future';
                   4956:         }
                   4957:         if (ref($types) eq 'ARRAY') {
                   4958:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4959:                 next;
                   4960:             } 
                   4961:         } else {
                   4962:             if ($status ne 'active') {
                   4963:                 next;
                   4964:             }
                   4965:         }
1.867     raeburn  4966:         my ($rolecode,$username,$domain,$section,$area);
                   4967:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4968:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4969:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4970:         } else {
                   4971:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4972:         }
1.832     raeburn  4973:         if (ref($roledoms) eq 'ARRAY') {
                   4974:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4975:                 next;
                   4976:             }
                   4977:         }
                   4978:         if (ref($roles) eq 'ARRAY') {
                   4979:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4980:                 if ($role =~ /^cr\//) {
                   4981:                     if (!grep(/^cr$/,@{$roles})) {
                   4982:                         next;
                   4983:                     }
1.1104    raeburn  4984:                 } elsif ($role =~ /^gr\//) {
                   4985:                     if (!grep(/^gr$/,@{$roles})) {
                   4986:                         next;
                   4987:                     }
1.922     raeburn  4988:                 } else {
                   4989:                     next;
                   4990:                 }
1.832     raeburn  4991:             }
1.867     raeburn  4992:         }
1.937     raeburn  4993:         if ($hidepriv) {
1.1172.2.23  raeburn  4994:             my @privroles = ('dc','su');
1.999     raeburn  4995:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4996:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4997:             } else {
1.1172.2.23  raeburn  4998:                 my $possdoms = [$domain];
                   4999:                 if (ref($roledoms) eq 'ARRAY') {
                   5000:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5001:                 }
1.1172.2.23  raeburn  5002:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5003:                     if (!$nothide{$username.':'.$domain}) {
                   5004:                         next;
                   5005:                     }
                   5006:                 }
1.937     raeburn  5007:             }
                   5008:         }
1.933     raeburn  5009:         if ($withsec) {
                   5010:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5011:                 $tstart.':'.$tend;
                   5012:         } else {
                   5013:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5014:         }
1.832     raeburn  5015:     }
1.373     www      5016:     return %returnhash;
1.399     www      5017: }
                   5018: 
1.1172.2.89  raeburn  5019: sub get_all_adhocroles {
                   5020:     my ($dom) = @_;
                   5021:     my @roles_by_num = ();
                   5022:     my %domdefaults = &get_domain_defaults($dom);
                   5023:     my (%description,%access_in_dom,%access_info);
                   5024:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5025:         my $count = 0;
                   5026:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5027:         my %ordered;
                   5028:         foreach my $role (sort(keys(%domcurrent))) {
                   5029:             my ($order,$desc,$access_in_dom);
                   5030:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5031:                 $order = $domcurrent{$role}{'order'};
                   5032:                 $desc = $domcurrent{$role}{'desc'};
                   5033:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5034:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5035:             }
                   5036:             if ($order eq '') {
                   5037:                 $order = $count;
                   5038:             }
                   5039:             $ordered{$order} = $role;
                   5040:             if ($desc ne '') {
                   5041:                 $description{$role} = $desc;
                   5042:             } else {
                   5043:                 $description{$role}= $role;
                   5044:             }
                   5045:             $count++;
                   5046:         }
                   5047:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5048:             push(@roles_by_num,$ordered{$item});
                   5049:         }
                   5050:     }
                   5051:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5052: }
                   5053: 
                   5054: sub get_my_adhocroles {
                   5055:     my ($cid,$checkreg) = @_;
                   5056:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5057:     if ($env{'request.course.id'} eq $cid) {
                   5058:         $cdom = $env{'course.'.$cid.'.domain'};
                   5059:         $cnum = $env{'course.'.$cid.'.num'};
                   5060:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5061:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5062:         $cdom = $1;
                   5063:         $cnum = $2;
                   5064:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5065:                                      $cdom,$cnum);
                   5066:     }
                   5067:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5068:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5069:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5070:         if ($rosterhash{$user} ne '') {
                   5071:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5072:             return ([],{}) if ($type eq 'auto');
                   5073:         }
                   5074:     }
                   5075:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5076:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5077:             my $then=$env{'user.login.time'};
                   5078:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5079:             if (!$update) {
                   5080:                 $update = $then;
                   5081:             }
                   5082:             my @liveroles;
                   5083:             foreach my $role ('dh','da') {
                   5084:                 if ($env{"user.role.$role./$cdom/"}) {
                   5085:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5086:                     my $limit = $update;
                   5087:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5088:                         $limit = $then;
                   5089:                     }
                   5090:                     my $activerole = 1;
                   5091:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5092:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5093:                     if ($activerole) {
                   5094:                         push(@liveroles,$role);
                   5095:                     }
                   5096:                 }
                   5097:             }
                   5098:             if (@liveroles) {
1.1172.2.89  raeburn  5099:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5100:                     my ($accessref,$accessinfo,%access_in_dom);
                   5101:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5102:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5103:                         if (@{$roles_by_num}) {
                   5104:                             my %settings;
                   5105:                             if ($env{'request.course.id'} eq $cid) {
                   5106:                                 foreach my $envkey (keys(%env)) {
                   5107:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5108:                                         $settings{$1} = $env{$envkey};
                   5109:                                     }
                   5110:                                 }
                   5111:                             } else {
                   5112:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5113:                             }
                   5114:                             my %setincrs;
                   5115:                             if ($settings{'internal.adhocaccess'}) {
                   5116:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5117:                             }
                   5118:                             my @statuses;
                   5119:                             if ($env{'environment.inststatus'}) {
                   5120:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5121:                             }
                   5122:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5123:                             if (ref($accessref) eq 'HASH') {
                   5124:                                 %access_in_dom = %{$accessref};
                   5125:                             }
                   5126:                             foreach my $role (@{$roles_by_num}) {
                   5127:                                 my ($curraccess,@okstatus,@personnel);
                   5128:                                 if ($setincrs{$role}) {
                   5129:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5130:                                     if ($curraccess eq 'status') {
                   5131:                                         @okstatus = split(/\&/,$rest);
                   5132:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5133:                                         @personnel = split(/\&/,$rest);
                   5134:                                     }
                   5135:                                 } else {
                   5136:                                     $curraccess = $access_in_dom{$role};
                   5137:                                     if (ref($accessinfo) eq 'HASH') {
                   5138:                                         if ($curraccess eq 'status') {
                   5139:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5140:                                                 @okstatus = @{$accessinfo->{$role}};
                   5141:                                             }
                   5142:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5143:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5144:                                                 @personnel = @{$accessinfo->{$role}};
                   5145:                                             }
                   5146:                                         }
                   5147:                                     }
                   5148:                                 }
                   5149:                                 if ($curraccess eq 'none') {
                   5150:                                     next;
                   5151:                                 } elsif ($curraccess eq 'all') {
                   5152:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5153:                                 } elsif ($curraccess eq 'dh') {
                   5154:                                     if (grep(/^dh$/,@liveroles)) {
                   5155:                                         push(@possroles,$role);
                   5156:                                     } else {
                   5157:                                         next;
                   5158:                                     }
                   5159:                                 } elsif ($curraccess eq 'da') {
                   5160:                                     if (grep(/^da$/,@liveroles)) {
                   5161:                                         push(@possroles,$role);
                   5162:                                     } else {
                   5163:                                         next;
                   5164:                                     }
1.1172.2.89  raeburn  5165:                                 } elsif ($curraccess eq 'status') {
                   5166:                                     if (@okstatus) {
                   5167:                                         if (!@statuses) {
                   5168:                                             if (grep(/^default$/,@okstatus)) {
                   5169:                                                 push(@possroles,$role);
                   5170:                                             }
                   5171:                                         } else {
                   5172:                                             foreach my $status (@okstatus) {
                   5173:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5174:                                                     push(@possroles,$role);
                   5175:                                                     last;
                   5176:                                                 }
                   5177:                                             }
                   5178:                                         }
                   5179:                                     }
                   5180:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5181:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5182:                                         if ($curraccess eq 'exc') {
                   5183:                                             push(@possroles,$role);
                   5184:                                         }
                   5185:                                     } elsif ($curraccess eq 'inc') {
                   5186:                                         push(@possroles,$role);
                   5187:                                     }
                   5188:                                 }
                   5189:                             }
                   5190:                         }
                   5191:                     }
                   5192:                 }
                   5193:             }
                   5194:         }
                   5195:     }
                   5196:     unless (ref($description) eq 'HASH') {
                   5197:         if (ref($roles_by_num) eq 'ARRAY') {
                   5198:             my %desc;
                   5199:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5200:             $description = \%desc;
                   5201:         } else {
                   5202:             $description = {};
                   5203:         }
                   5204:     }
                   5205:     return (\@possroles,$description);
                   5206: }
                   5207: 
1.399     www      5208: # ----------------------------------------------------- Frontpage Announcements
                   5209: #
                   5210: #
                   5211: 
                   5212: sub postannounce {
                   5213:     my ($server,$text)=@_;
1.844     albertel 5214:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5215:     unless ($text=~/\w/) { $text=''; }
                   5216:     return &reply('setannounce:'.&escape($text),$server);
                   5217: }
                   5218: 
                   5219: sub getannounce {
1.448     albertel 5220: 
1.1172.2.96  raeburn  5221:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5222: 	my $announcement='';
1.800     albertel 5223: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5224: 	close($fh);
1.399     www      5225: 	if ($announcement=~/\w/) { 
                   5226: 	    return 
                   5227:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5228:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5229: 	} else {
                   5230: 	    return '';
                   5231: 	}
                   5232:     } else {
                   5233: 	return '';
                   5234:     }
1.351     www      5235: }
1.353     www      5236: 
                   5237: # ---------------------------------------------------------- Course ID routines
                   5238: # Deal with domain's nohist_courseid.db files
                   5239: #
                   5240: 
                   5241: sub courseidput {
1.921     raeburn  5242:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5243:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5244:     my $outcome;
                   5245:     if ($caller eq 'timeonly') {
                   5246:         my $cids = '';
                   5247:         foreach my $item (keys(%$storehash)) {
                   5248:             $cids.=&escape($item).'&';
                   5249:         }
                   5250:         $cids=~s/\&$//;
                   5251:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5252:                           $coursehome);       
                   5253:     } else {
                   5254:         my $items = '';
                   5255:         foreach my $item (keys(%$storehash)) {
                   5256:             $items.= &escape($item).'='.
                   5257:                      &freeze_escape($$storehash{$item}).'&';
                   5258:         }
                   5259:         $items=~s/\&$//;
                   5260:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5261:                           $coursehome);
1.918     raeburn  5262:     }
                   5263:     if ($outcome eq 'unknown_cmd') {
                   5264:         my $what;
                   5265:         foreach my $cid (keys(%$storehash)) {
                   5266:             $what .= &escape($cid).'=';
1.921     raeburn  5267:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5268:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5269:             }
                   5270:             $what =~ s/\:$/&/;
                   5271:         }
                   5272:         $what =~ s/\&$//;  
                   5273:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5274:     } else {
                   5275:         return $outcome;
                   5276:     }
1.353     www      5277: }
                   5278: 
                   5279: sub courseiddump {
1.921     raeburn  5280:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5281:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5282:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5283:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5284:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5285:     my $as_hash = 1;
                   5286:     my %returnhash;
                   5287:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5288:     my %libserv = &all_library();
                   5289:     foreach my $tryserver (keys(%libserv)) {
                   5290:         if ( (  $hostidflag == 1 
                   5291: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5292: 	     || (!defined($hostidflag)) ) {
                   5293: 
1.918     raeburn  5294: 	    if (($domfilter eq '') ||
                   5295: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5296:                 my $rep;
                   5297:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5298:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5299:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5300:                                 &escape($descfilter), &escape($instcodefilter),
                   5301:                                 &escape($ownerfilter), &escape($coursefilter),
                   5302:                                 &escape($typefilter), &escape($regexp_ok),
                   5303:                                 $as_hash, &escape($selfenrollonly),
                   5304:                                 &escape($catfilter), $showhidden, $caller,
                   5305:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5306:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5307:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5308:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5309:                 } else {
                   5310:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5311:                              $sincefilter.':'.&escape($descfilter).':'.
                   5312:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5313:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5314:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5315:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5316:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5317:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5318:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5319:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5320:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5321:                 }
                   5322: 
1.918     raeburn  5323:                 my @pairs=split(/\&/,$rep);
                   5324:                 foreach my $item (@pairs) {
                   5325:                     my ($key,$value)=split(/\=/,$item,2);
                   5326:                     $key = &unescape($key);
                   5327:                     next if ($key =~ /^error: 2 /);
                   5328:                     my $result = &thaw_unescape($value);
                   5329:                     if (ref($result) eq 'HASH') {
                   5330:                         $returnhash{$key}=$result;
                   5331:                     } else {
1.921     raeburn  5332:                         my @responses = split(/:/,$value);
                   5333:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5334:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5335:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5336:                         }
1.1008    raeburn  5337:                     }
1.353     www      5338:                 }
                   5339:             }
                   5340:         }
                   5341:     }
                   5342:     return %returnhash;
                   5343: }
                   5344: 
1.1055    raeburn  5345: sub courselastaccess {
                   5346:     my ($cdom,$cnum,$hostidref) = @_;
                   5347:     my %returnhash;
                   5348:     if ($cdom && $cnum) {
                   5349:         my $chome = &homeserver($cnum,$cdom);
                   5350:         if ($chome ne 'no_host') {
                   5351:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5352:             &extract_lastaccess(\%returnhash,$rep);
                   5353:         }
                   5354:     } else {
                   5355:         if (!$cdom) { $cdom=''; }
                   5356:         my %libserv = &all_library();
                   5357:         foreach my $tryserver (keys(%libserv)) {
                   5358:             if (ref($hostidref) eq 'ARRAY') {
                   5359:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5360:             } 
                   5361:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5362:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5363:                 &extract_lastaccess(\%returnhash,$rep);
                   5364:             }
                   5365:         }
                   5366:     }
                   5367:     return %returnhash;
                   5368: }
                   5369: 
                   5370: sub extract_lastaccess {
                   5371:     my ($returnhash,$rep) = @_;
                   5372:     if (ref($returnhash) eq 'HASH') {
                   5373:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5374:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5375:                  $rep eq '') {
                   5376:             my @pairs=split(/\&/,$rep);
                   5377:             foreach my $item (@pairs) {
                   5378:                 my ($key,$value)=split(/\=/,$item,2);
                   5379:                 $key = &unescape($key);
                   5380:                 next if ($key =~ /^error: 2 /);
                   5381:                 $returnhash->{$key} = &thaw_unescape($value);
                   5382:             }
                   5383:         }
                   5384:     }
                   5385:     return;
                   5386: }
                   5387: 
1.658     raeburn  5388: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5389: 
                   5390: sub dcmailput {
1.685     raeburn  5391:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5392:     my $status = &Apache::lonnet::critical(
1.740     www      5393:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5394:        &escape($message),$server);
1.662     raeburn  5395:     return $status;
                   5396: }
                   5397: 
1.658     raeburn  5398: sub dcmaildump {
                   5399:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5400:     my %returnhash=();
1.846     albertel 5401: 
                   5402:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5403:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5404:                                                          &escape($enddate).':';
                   5405: 	my @esc_senders=map { &escape($_)} @$senders;
                   5406: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5407: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5408:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5409:             if (($key) && ($value)) {
                   5410:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5411:             }
                   5412:         }
                   5413:     }
                   5414:     return %returnhash;
                   5415: }
1.662     raeburn  5416: # ---------------------------------------------------------- Domain roles
                   5417: 
                   5418: sub get_domain_roles {
                   5419:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5420:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5421:         $startdate = '.';
                   5422:     }
1.1018    raeburn  5423:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5424:         $enddate = '.';
                   5425:     }
1.922     raeburn  5426:     my $rolelist;
                   5427:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5428:         $rolelist = join('&',@{$roles});
1.922     raeburn  5429:     }
1.662     raeburn  5430:     my %personnel = ();
1.841     albertel 5431: 
                   5432:     my %servers = &get_servers($dom,'library');
                   5433:     foreach my $tryserver (keys(%servers)) {
                   5434: 	%{$personnel{$tryserver}}=();
                   5435: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5436: 					    &escape($startdate).':'.
                   5437: 					    &escape($enddate).':'.
                   5438: 					    &escape($rolelist), $tryserver))) {
                   5439: 	    my ($key,$value) = split(/\=/,$line,2);
                   5440: 	    if (($key) && ($value)) {
                   5441: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5442: 	    }
                   5443: 	}
1.662     raeburn  5444:     }
                   5445:     return %personnel;
                   5446: }
1.658     raeburn  5447: 
1.1172.2.89  raeburn  5448: sub get_active_domroles {
                   5449:     my ($dom,$roles) = @_;
                   5450:     return () unless (ref($roles) eq 'ARRAY');
                   5451:     my $now = time;
                   5452:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5453:     my %domroles;
                   5454:     foreach my $server (keys(%dompersonnel)) {
                   5455:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5456:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5457:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5458:         }
                   5459:     }
                   5460:     return %domroles;
                   5461: }
                   5462: 
1.1057    www      5463: # ----------------------------------------------------------- Interval timing 
1.149     www      5464: 
1.1153    www      5465: {
                   5466: # Caches needed for speedup of navmaps
                   5467: # We don't want to cache this for very long at all (5 seconds at most)
                   5468: # 
                   5469: # The user for whom we cache
                   5470: my $cachedkey='';
                   5471: # The cached times for this user
                   5472: my %cachedtimes=();
                   5473: # When this was last done
1.1172.2.66  raeburn  5474: my $cachedtime='';
1.1153    www      5475: 
                   5476: sub load_all_first_access {
1.1172.2.118.  .1(raebu 5477:20):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5478:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118.  .1(raebu 5479:20):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5480:20):         (!$ignorecache)) {
1.1154    raeburn  5481:         return;
                   5482:     }
                   5483:     $cachedtime=time;
                   5484:     $cachedkey=$uname.':'.$udom;
                   5485:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5486: }
                   5487: 
1.504     albertel 5488: sub get_first_access {
1.1172.2.118.  .1(raebu 5489:20):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5490:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5491:     if ($argsymb) { $symb=$argsymb; }
                   5492:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5493:     if ($argmap) { $map = $argmap; }
1.926     albertel 5494:     if ($type eq 'course') {
                   5495: 	$res='course';
                   5496:     } elsif ($type eq 'map') {
1.588     albertel 5497: 	$res=&symbread($map);
                   5498:     } else {
                   5499: 	$res=$symb;
                   5500:     }
1.1172.2.118.  .1(raebu 5501:20):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5502:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5503: }
                   5504: 
                   5505: sub set_first_access {
1.1162    raeburn  5506:     my ($type,$interval)=@_;
1.790     albertel 5507:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5508:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5509:     if ($type eq 'course') {
                   5510: 	$res='course';
                   5511:     } elsif ($type eq 'map') {
1.588     albertel 5512: 	$res=&symbread($map);
                   5513:     } else {
                   5514: 	$res=$symb;
                   5515:     }
1.1153    www      5516:     $cachedkey='';
1.1162    raeburn  5517:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5518:     if ($firstaccess) {
                   5519:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5520:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5521:                  "in $courseid");
                   5522:         return 'already_set';
                   5523:     } else {
1.1162    raeburn  5524:         my $start = time;
                   5525: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5526:                           $udom,$uname);
                   5527:         if ($putres eq 'ok') {
                   5528:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5529:                  $udom,$uname); 
                   5530:             &appenv(
                   5531:                      {
                   5532:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5533:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5534:                      }
                   5535:                   );
1.1172.2.97  raeburn  5536:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5537:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5538:             }
1.1172.2.102  raeburn  5539:         } elsif ($putres ne 'refused') {
                   5540:             &logthis("Result: $putres when attempting to set first access time ".
                   5541:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5542:         }
                   5543:         return $putres;
1.505     albertel 5544:     }
                   5545:     return 'already_set';
1.504     albertel 5546: }
1.1153    www      5547: }
1.1172.2.32  raeburn  5548: 
                   5549: sub checkout {
                   5550:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5551:     my $now=time;
                   5552:     my $lonhost=$perlvar{'lonHostID'};
                   5553:     my $infostr=&escape(
                   5554:                  'CHECKOUTTOKEN&'.
                   5555:                  $tuname.'&'.
                   5556:                  $tudom.'&'.
                   5557:                  $tcrsid.'&'.
                   5558:                  $symb.'&'.
                   5559:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5560:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5561:     if ($token=~/^error\:/) {
                   5562:         &logthis("<font color=\"blue\">WARNING: ".
                   5563:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5564:                  "</font>");
                   5565:         return '';
                   5566:     }
                   5567: 
                   5568:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5569:     $token=~tr/a-z/A-Z/;
                   5570: 
                   5571:     my %infohash=('resource.0.outtoken' => $token,
                   5572:                   'resource.0.checkouttime' => $now,
                   5573:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5574: 
                   5575:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5576:        return '';
                   5577:     } else {
                   5578:         &logthis("<font color=\"blue\">WARNING: ".
                   5579:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5580:                  "</font>");
                   5581:     }
                   5582: 
                   5583:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5584:                          &escape('Checkout '.$infostr.' - '.
                   5585:                                                  $token)) ne 'ok') {
                   5586:         return '';
                   5587:     } else {
                   5588:         &logthis("<font color=\"blue\">WARNING: ".
                   5589:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5590:                  "</font>");
                   5591:     }
                   5592:     return $token;
                   5593: }
                   5594: 
                   5595: # ------------------------------------------------------------ Check in an item
                   5596: 
                   5597: sub checkin {
                   5598:     my $token=shift;
                   5599:     my $now=time;
                   5600:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5601:     $lonhost=~tr/A-Z/a-z/;
                   5602:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5603:     $dtoken=~s/\W/\_/g;
                   5604:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5605:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5606: 
                   5607:     unless (($tuname) && ($tudom)) {
                   5608:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5609:         return '';
                   5610:     }
                   5611: 
                   5612:     unless (&allowed('mgr',$tcrsid)) {
                   5613:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5614:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5615:         return '';
                   5616:     }
                   5617: 
                   5618:     my %infohash=('resource.0.intoken' => $token,
                   5619:                   'resource.0.checkintime' => $now,
                   5620:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5621: 
                   5622:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5623:        return '';
                   5624:     }
                   5625: 
                   5626:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5627:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5628:         return '';
                   5629:     }
                   5630: 
                   5631:     return ($symb,$tuname,$tudom,$tcrsid);
                   5632: }
                   5633: 
1.110     www      5634: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5635: 
                   5636: sub expirespread {
                   5637:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5638:     my $cid=$env{'request.course.id'}; 
1.110     www      5639:     if ($cid) {
                   5640:        my $now=time;
                   5641:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5642:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5643:                             $env{'course.'.$cid.'.num'}.
1.110     www      5644: 	        	    ':nohist_expirationdates:'.
                   5645:                             &escape($key).'='.$now,
1.620     albertel 5646:                             $env{'course.'.$cid.'.home'})
1.110     www      5647:     }
                   5648:     return 'ok';
1.14      www      5649: }
                   5650: 
1.109     www      5651: # ----------------------------------------------------- Devalidate Spreadsheets
                   5652: 
                   5653: sub devalidate {
1.325     www      5654:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5655:     my $cid=$env{'request.course.id'}; 
1.109     www      5656:     if ($cid) {
1.391     matthew  5657:         # delete the stored spreadsheets for
                   5658:         # - the student level sheet of this user in course's homespace
                   5659:         # - the assessment level sheet for this resource 
                   5660:         #   for this user in user's homespace
1.553     albertel 5661: 	# - current conditional state info
1.325     www      5662: 	my $key=$uname.':'.$udom.':';
1.109     www      5663:         my $status=
1.299     matthew  5664: 	    &del('nohist_calculatedsheets',
1.391     matthew  5665: 		 [$key.'studentcalc:'],
1.620     albertel 5666: 		 $env{'course.'.$cid.'.domain'},
                   5667: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5668: 		.' '.
                   5669: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5670: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5671:         unless ($status eq 'ok ok') {
                   5672:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5673:                     $uname.' at '.$udom.' for '.
1.109     www      5674: 		    $symb.': '.$status);
1.133     albertel 5675:         }
1.553     albertel 5676: 	&delenv('user.state.'.$cid);
1.109     www      5677:     }
                   5678: }
                   5679: 
1.265     albertel 5680: sub get_scalar {
                   5681:     my ($string,$end) = @_;
                   5682:     my $value;
                   5683:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5684: 	$value = $1;
                   5685:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5686: 	$value = $1;
                   5687:     }
                   5688:     return &unescape($value);
                   5689: }
                   5690: 
                   5691: sub array2str {
                   5692:   my (@array) = @_;
                   5693:   my $result=&arrayref2str(\@array);
                   5694:   $result=~s/^__ARRAY_REF__//;
                   5695:   $result=~s/__END_ARRAY_REF__$//;
                   5696:   return $result;
                   5697: }
                   5698: 
1.204     albertel 5699: sub arrayref2str {
                   5700:   my ($arrayref) = @_;
1.265     albertel 5701:   my $result='__ARRAY_REF__';
1.204     albertel 5702:   foreach my $elem (@$arrayref) {
1.265     albertel 5703:     if(ref($elem) eq 'ARRAY') {
                   5704:       $result.=&arrayref2str($elem).'&';
                   5705:     } elsif(ref($elem) eq 'HASH') {
                   5706:       $result.=&hashref2str($elem).'&';
                   5707:     } elsif(ref($elem)) {
                   5708:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5709:     } else {
                   5710:       $result.=&escape($elem).'&';
                   5711:     }
                   5712:   }
                   5713:   $result=~s/\&$//;
1.265     albertel 5714:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5715:   return $result;
                   5716: }
                   5717: 
1.168     albertel 5718: sub hash2str {
1.204     albertel 5719:   my (%hash) = @_;
                   5720:   my $result=&hashref2str(\%hash);
1.265     albertel 5721:   $result=~s/^__HASH_REF__//;
                   5722:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5723:   return $result;
                   5724: }
                   5725: 
                   5726: sub hashref2str {
                   5727:   my ($hashref)=@_;
1.265     albertel 5728:   my $result='__HASH_REF__';
1.800     albertel 5729:   foreach my $key (sort(keys(%$hashref))) {
                   5730:     if (ref($key) eq 'ARRAY') {
                   5731:       $result.=&arrayref2str($key).'=';
                   5732:     } elsif (ref($key) eq 'HASH') {
                   5733:       $result.=&hashref2str($key).'=';
                   5734:     } elsif (ref($key)) {
1.265     albertel 5735:       $result.='=';
1.800     albertel 5736:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5737:     } else {
1.1132    raeburn  5738: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5739:     }
                   5740: 
1.800     albertel 5741:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5742:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5743:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5744:       $result.=&hashref2str($hashref->{$key}).'&';
                   5745:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5746:        $result.='&';
1.800     albertel 5747:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5748:     } else {
1.800     albertel 5749:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5750:     }
                   5751:   }
1.168     albertel 5752:   $result=~s/\&$//;
1.265     albertel 5753:   $result .= '__END_HASH_REF__';
1.168     albertel 5754:   return $result;
                   5755: }
                   5756: 
                   5757: sub str2hash {
1.265     albertel 5758:     my ($string)=@_;
                   5759:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5760:     return %$hash;
                   5761: }
                   5762: 
                   5763: sub str2hashref {
1.168     albertel 5764:   my ($string) = @_;
1.265     albertel 5765: 
                   5766:   my %hash;
                   5767: 
                   5768:   if($string !~ /^__HASH_REF__/) {
                   5769:       if (! ($string eq '' || !defined($string))) {
                   5770: 	  $hash{'error'}='Not hash reference';
                   5771:       }
                   5772:       return (\%hash, $string);
                   5773:   }
                   5774: 
                   5775:   $string =~ s/^__HASH_REF__//;
                   5776: 
                   5777:   while($string !~ /^__END_HASH_REF__/) {
                   5778:       #key
                   5779:       my $key='';
                   5780:       if($string =~ /^__HASH_REF__/) {
                   5781:           ($key, $string)=&str2hashref($string);
                   5782:           if(defined($key->{'error'})) {
                   5783:               $hash{'error'}='Bad data';
                   5784:               return (\%hash, $string);
                   5785:           }
                   5786:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5787:           ($key, $string)=&str2arrayref($string);
                   5788:           if($key->[0] eq 'Array reference error') {
                   5789:               $hash{'error'}='Bad data';
                   5790:               return (\%hash, $string);
                   5791:           }
                   5792:       } else {
                   5793:           $string =~ s/^(.*?)=//;
1.267     albertel 5794: 	  $key=&unescape($1);
1.265     albertel 5795:       }
                   5796:       $string =~ s/^=//;
                   5797: 
                   5798:       #value
                   5799:       my $value='';
                   5800:       if($string =~ /^__HASH_REF__/) {
                   5801:           ($value, $string)=&str2hashref($string);
                   5802:           if(defined($value->{'error'})) {
                   5803:               $hash{'error'}='Bad data';
                   5804:               return (\%hash, $string);
                   5805:           }
                   5806:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5807:           ($value, $string)=&str2arrayref($string);
                   5808:           if($value->[0] eq 'Array reference error') {
                   5809:               $hash{'error'}='Bad data';
                   5810:               return (\%hash, $string);
                   5811:           }
                   5812:       } else {
                   5813: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5814:       }
                   5815:       $string =~ s/^&//;
                   5816: 
                   5817:       $hash{$key}=$value;
1.204     albertel 5818:   }
1.265     albertel 5819: 
                   5820:   $string =~ s/^__END_HASH_REF__//;
                   5821: 
                   5822:   return (\%hash, $string);
1.204     albertel 5823: }
                   5824: 
                   5825: sub str2array {
1.265     albertel 5826:     my ($string)=@_;
                   5827:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5828:     return @$array;
                   5829: }
                   5830: 
                   5831: sub str2arrayref {
1.204     albertel 5832:   my ($string) = @_;
1.265     albertel 5833:   my @array;
                   5834: 
                   5835:   if($string !~ /^__ARRAY_REF__/) {
                   5836:       if (! ($string eq '' || !defined($string))) {
                   5837: 	  $array[0]='Array reference error';
                   5838:       }
                   5839:       return (\@array, $string);
                   5840:   }
                   5841: 
                   5842:   $string =~ s/^__ARRAY_REF__//;
                   5843: 
                   5844:   while($string !~ /^__END_ARRAY_REF__/) {
                   5845:       my $value='';
                   5846:       if($string =~ /^__HASH_REF__/) {
                   5847:           ($value, $string)=&str2hashref($string);
                   5848:           if(defined($value->{'error'})) {
                   5849:               $array[0] ='Array reference error';
                   5850:               return (\@array, $string);
                   5851:           }
                   5852:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5853:           ($value, $string)=&str2arrayref($string);
                   5854:           if($value->[0] eq 'Array reference error') {
                   5855:               $array[0] ='Array reference error';
                   5856:               return (\@array, $string);
                   5857:           }
                   5858:       } else {
                   5859: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5860:       }
                   5861:       $string =~ s/^&//;
                   5862: 
                   5863:       push(@array, $value);
1.191     harris41 5864:   }
1.265     albertel 5865: 
                   5866:   $string =~ s/^__END_ARRAY_REF__//;
                   5867: 
                   5868:   return (\@array, $string);
1.168     albertel 5869: }
                   5870: 
1.167     albertel 5871: # -------------------------------------------------------------------Temp Store
                   5872: 
1.168     albertel 5873: sub tmpreset {
                   5874:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5875:   if (!$symb) {
                   5876:     $symb=&symbread();
1.620     albertel 5877:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5878:   }
                   5879:   $symb=escape($symb);
                   5880: 
1.620     albertel 5881:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5882:   $namespace=~s/\//\_/g;
                   5883:   $namespace=~s/\W//g;
                   5884: 
1.620     albertel 5885:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5886:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5887:   if ($domain eq 'public' && $stuname eq 'public') {
                   5888:       $stuname=$ENV{'REMOTE_ADDR'};
                   5889:   }
1.1117    foxr     5890:   my $path=LONCAPA::tempdir();
1.168     albertel 5891:   my %hash;
                   5892:   if (tie(%hash,'GDBM_File',
                   5893: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5894: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5895:     foreach my $key (keys(%hash)) {
1.180     albertel 5896:       if ($key=~ /:$symb/) {
1.168     albertel 5897: 	delete($hash{$key});
                   5898:       }
                   5899:     }
                   5900:   }
                   5901: }
                   5902: 
1.167     albertel 5903: sub tmpstore {
1.168     albertel 5904:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5905: 
                   5906:   if (!$symb) {
                   5907:     $symb=&symbread();
1.620     albertel 5908:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5909:   }
                   5910:   $symb=escape($symb);
                   5911: 
                   5912:   if (!$namespace) {
                   5913:     # I don't think we would ever want to store this for a course.
                   5914:     # it seems this will only be used if we don't have a course.
1.620     albertel 5915:     #$namespace=$env{'request.course.id'};
1.168     albertel 5916:     #if (!$namespace) {
1.620     albertel 5917:       $namespace=$env{'request.state'};
1.168     albertel 5918:     #}
                   5919:   }
                   5920:   $namespace=~s/\//\_/g;
                   5921:   $namespace=~s/\W//g;
1.620     albertel 5922:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5923:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5924:   if ($domain eq 'public' && $stuname eq 'public') {
                   5925:       $stuname=$ENV{'REMOTE_ADDR'};
                   5926:   }
1.168     albertel 5927:   my $now=time;
                   5928:   my %hash;
1.1117    foxr     5929:   my $path=LONCAPA::tempdir();
1.168     albertel 5930:   if (tie(%hash,'GDBM_File',
                   5931: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5932: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5933:     $hash{"version:$symb"}++;
                   5934:     my $version=$hash{"version:$symb"};
                   5935:     my $allkeys=''; 
                   5936:     foreach my $key (keys(%$storehash)) {
                   5937:       $allkeys.=$key.':';
1.591     albertel 5938:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5939:     }
                   5940:     $hash{"$version:$symb:timestamp"}=$now;
                   5941:     $allkeys.='timestamp';
                   5942:     $hash{"$version:keys:$symb"}=$allkeys;
                   5943:     if (untie(%hash)) {
                   5944:       return 'ok';
                   5945:     } else {
                   5946:       return "error:$!";
                   5947:     }
                   5948:   } else {
                   5949:     return "error:$!";
                   5950:   }
                   5951: }
1.167     albertel 5952: 
1.168     albertel 5953: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5954: 
1.168     albertel 5955: sub tmprestore {
                   5956:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5957: 
1.168     albertel 5958:   if (!$symb) {
                   5959:     $symb=&symbread();
1.620     albertel 5960:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5961:   }
                   5962:   $symb=escape($symb);
                   5963: 
1.620     albertel 5964:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5965: 
1.620     albertel 5966:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5967:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5968:   if ($domain eq 'public' && $stuname eq 'public') {
                   5969:       $stuname=$ENV{'REMOTE_ADDR'};
                   5970:   }
1.168     albertel 5971:   my %returnhash;
                   5972:   $namespace=~s/\//\_/g;
                   5973:   $namespace=~s/\W//g;
                   5974:   my %hash;
1.1117    foxr     5975:   my $path=LONCAPA::tempdir();
1.168     albertel 5976:   if (tie(%hash,'GDBM_File',
                   5977: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5978: 	  &GDBM_READER(),0640)) {
1.168     albertel 5979:     my $version=$hash{"version:$symb"};
                   5980:     $returnhash{'version'}=$version;
                   5981:     my $scope;
                   5982:     for ($scope=1;$scope<=$version;$scope++) {
                   5983:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5984:       my @keys=split(/:/,$vkeys);
                   5985:       my $key;
                   5986:       $returnhash{"$scope:keys"}=$vkeys;
                   5987:       foreach $key (@keys) {
1.591     albertel 5988: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5989: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5990:       }
                   5991:     }
1.168     albertel 5992:     if (!(untie(%hash))) {
                   5993:       return "error:$!";
                   5994:     }
                   5995:   } else {
                   5996:     return "error:$!";
                   5997:   }
                   5998:   return %returnhash;
1.167     albertel 5999: }
                   6000: 
1.9       www      6001: # ----------------------------------------------------------------------- Store
                   6002: 
                   6003: sub store {
1.1172.2.64  raeburn  6004:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6005:     my $home='';
                   6006: 
1.168     albertel 6007:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6008: 
1.213     www      6009:     $symb=&symbclean($symb);
1.122     albertel 6010:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6011: 
1.620     albertel 6012:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6013:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6014: 
                   6015:     &devalidate($symb,$stuname,$domain);
1.109     www      6016: 
                   6017:     $symb=escape($symb);
1.187     www      6018:     if (!$namespace) { 
1.620     albertel 6019:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6020:           return ''; 
                   6021:        } 
                   6022:     }
1.620     albertel 6023:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6024: 
                   6025:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6026:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6027: 
1.12      www      6028:     my $namevalue='';
1.800     albertel 6029:     foreach my $key (keys(%$storehash)) {
                   6030:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6031:     }
1.12      www      6032:     $namevalue=~s/\&$//;
1.187     www      6033:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6034:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6035: }
                   6036: 
1.47      www      6037: # -------------------------------------------------------------- Critical Store
                   6038: 
                   6039: sub cstore {
1.1172.2.64  raeburn  6040:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6041:     my $home='';
                   6042: 
1.168     albertel 6043:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6044: 
1.213     www      6045:     $symb=&symbclean($symb);
1.122     albertel 6046:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6047: 
1.620     albertel 6048:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6049:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6050: 
                   6051:     &devalidate($symb,$stuname,$domain);
1.109     www      6052: 
                   6053:     $symb=escape($symb);
1.187     www      6054:     if (!$namespace) { 
1.620     albertel 6055:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6056:           return ''; 
                   6057:        } 
                   6058:     }
1.620     albertel 6059:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6060: 
                   6061:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6062:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6063: 
1.47      www      6064:     my $namevalue='';
1.800     albertel 6065:     foreach my $key (keys(%$storehash)) {
                   6066:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6067:     }
1.47      www      6068:     $namevalue=~s/\&$//;
1.187     www      6069:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6070:     return critical
1.1172.2.64  raeburn  6071:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6072: }
                   6073: 
1.9       www      6074: # --------------------------------------------------------------------- Restore
                   6075: 
                   6076: sub restore {
1.124     www      6077:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6078:     my $home='';
                   6079: 
1.168     albertel 6080:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6081: 
1.122     albertel 6082:     if (!$symb) {
1.1172.2.26  raeburn  6083:         return if ($namespace eq 'courserequests');
                   6084:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6085:     } else {
1.1172.2.26  raeburn  6086:         unless ($namespace eq 'courserequests') {
                   6087:             $symb=&escape(&symbclean($symb));
                   6088:         }
1.122     albertel 6089:     }
1.188     www      6090:     if (!$namespace) { 
1.620     albertel 6091:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6092:           return ''; 
                   6093:        } 
                   6094:     }
1.620     albertel 6095:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6096:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6097:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6098:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6099: 
1.12      www      6100:     my %returnhash=();
1.800     albertel 6101:     foreach my $line (split(/\&/,$answer)) {
                   6102: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6103:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6104:     }
1.75      www      6105:     my $version;
                   6106:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6107:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6108:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6109:        }
1.75      www      6110:     }
1.13      www      6111:     return %returnhash;
1.34      www      6112: }
                   6113: 
                   6114: # ---------------------------------------------------------- Course Description
1.1118    foxr     6115: #
                   6116: #  
1.34      www      6117: 
                   6118: sub coursedescription {
1.731     albertel 6119:     my ($courseid,$args)=@_;
1.34      www      6120:     $courseid=~s/^\///;
1.49      www      6121:     $courseid=~s/\_/\//g;
1.34      www      6122:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6123:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6124:     my $normalid=$cdomain.'_'.$cnum;
                   6125:     # need to always cache even if we get errors otherwise we keep 
                   6126:     # trying and trying and trying to get the course description.
                   6127:     my %envhash=();
                   6128:     my %returnhash=();
1.731     albertel 6129:     
                   6130:     my $expiretime=600;
                   6131:     if ($env{'request.course.id'} eq $normalid) {
                   6132: 	$expiretime=120;
                   6133:     }
                   6134: 
                   6135:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6136:     if (!$args->{'freshen_cache'}
                   6137: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6138: 	foreach my $key (keys(%env)) {
                   6139: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6140: 	    my ($setting) = $1;
                   6141: 	    $returnhash{$setting} = $env{$key};
                   6142: 	}
                   6143: 	return %returnhash;
                   6144:     }
                   6145: 
1.1118    foxr     6146:     # get the data again
                   6147: 
1.731     albertel 6148:     if (!$args->{'one_time'}) {
                   6149: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6150:     }
1.811     albertel 6151: 
1.34      www      6152:     if ($chome ne 'no_host') {
1.302     albertel 6153:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6154:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6155: 	   my $username = $env{'user.name'}; # Defult username
                   6156: 	   if(defined $args->{'user'}) {
                   6157: 	       $username = $args->{'user'};
                   6158: 	   }
1.129     albertel 6159:            $returnhash{'home'}= $chome;
                   6160: 	   $returnhash{'domain'} = $cdomain;
                   6161: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6162:            if (!defined($returnhash{'type'})) {
                   6163:                $returnhash{'type'} = 'Course';
                   6164:            }
1.130     albertel 6165:            while (my ($name,$value) = each %returnhash) {
1.53      www      6166:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6167:            }
1.270     www      6168:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6169:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6170: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6171:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6172:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6173:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6174:        }
                   6175:     }
1.731     albertel 6176:     if (!$args->{'one_time'}) {
1.949     raeburn  6177: 	&appenv(\%envhash);
1.731     albertel 6178:     }
1.302     albertel 6179:     return %returnhash;
1.461     www      6180: }
                   6181: 
1.1080    raeburn  6182: sub update_released_required {
                   6183:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6184:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6185:         $cid = $env{'request.course.id'};
                   6186:         $cdom = $env{'course.'.$cid.'.domain'};
                   6187:         $cnum = $env{'course.'.$cid.'.num'};
                   6188:         $chome = $env{'course.'.$cid.'.home'};
                   6189:     }
                   6190:     if ($needsrelease) {
                   6191:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6192:         my $needsupdate;
                   6193:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6194:             $needsupdate = 1;
                   6195:         } else {
                   6196:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6197:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6198:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6199:                 $needsupdate = 1;
                   6200:             }
                   6201:         }
                   6202:         if ($needsupdate) {
                   6203:             my %needshash = (
                   6204:                              'internal.releaserequired' => $needsrelease,
                   6205:                             );
                   6206:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6207:             if ($putresult eq 'ok') {
                   6208:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6209:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6210:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6211:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6212:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6213:                 }
                   6214:             }
                   6215:         }
                   6216:     }
                   6217:     return;
                   6218: }
                   6219: 
1.461     www      6220: # -------------------------------------------------See if a user is privileged
                   6221: 
                   6222: sub privileged {
1.1172.2.23  raeburn  6223:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6224:     my $now = time;
1.1172.2.23  raeburn  6225:     my $roles;
                   6226:     if (ref($possroles) eq 'ARRAY') {
                   6227:         $roles = $possroles;
                   6228:     } else {
                   6229:         $roles = ['dc','su'];
                   6230:     }
                   6231:     if (ref($possdomains) eq 'ARRAY') {
                   6232:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6233:         foreach my $dom (@{$possdomains}) {
                   6234:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6235:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6236:                 foreach my $role (@{$roles}) {
                   6237:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6238:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6239:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6240:                             return 1 unless (($end && $end < $now) ||
                   6241:                                              ($start && $start > $now));
                   6242:                         }
                   6243:                     }
                   6244:                 }
                   6245:             }
                   6246:         }
                   6247:     } else {
                   6248:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6249:         my $now = time;
1.1170    droeschl 6250: 
1.1172.2.58  raeburn  6251:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6252:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6253:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6254:                 return 1 unless ($tend && $tend < $now)
                   6255:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6256:             }
1.1172.2.23  raeburn  6257:         }
                   6258:     }
1.461     www      6259:     return 0;
1.9       www      6260: }
1.1       albertel 6261: 
1.1172.2.23  raeburn  6262: sub privileged_by_domain {
                   6263:     my ($domains,$roles) = @_;
                   6264:     my %privileged = ();
                   6265:     my $cachetime = 60*60*24;
                   6266:     my $now = time;
                   6267:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6268:         return %privileged;
                   6269:     }
                   6270:     foreach my $dom (@{$domains}) {
                   6271:         next if (ref($privileged{$dom}) eq 'HASH');
                   6272:         my $needroles;
                   6273:         foreach my $role (@{$roles}) {
                   6274:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6275:             if (defined($cached)) {
                   6276:                 if (ref($result) eq 'HASH') {
                   6277:                     $privileged{$dom}{$role} = $result;
                   6278:                 }
                   6279:             } else {
                   6280:                 $needroles = 1;
                   6281:             }
                   6282:         }
                   6283:         if ($needroles) {
                   6284:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6285:             $privileged{$dom} = {};
                   6286:             foreach my $server (keys(%dompersonnel)) {
                   6287:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6288:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6289:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6290:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6291:                         next if ($end && $end < $now);
                   6292:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6293:                             $dompersonnel{$server}{$item};
                   6294:                     }
                   6295:                 }
                   6296:             }
                   6297:             if (ref($privileged{$dom}) eq 'HASH') {
                   6298:                 foreach my $role (@{$roles}) {
                   6299:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6300:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6301:                     } else {
                   6302:                         my %hash = ();
                   6303:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6304:                     }
                   6305:                 }
                   6306:             }
                   6307:         }
                   6308:     }
                   6309:     return %privileged;
                   6310: }
                   6311: 
1.103     harris41 6312: # -------------------------------------------------------- Get user privileges
1.11      www      6313: 
                   6314: sub rolesinit {
1.1169    droeschl 6315:     my ($domain, $username) = @_;
                   6316:     my %userroles = ('user.login.time' => time);
                   6317:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6318: 
                   6319:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6320:     # also, blocking can be triggered by an activating timer
                   6321:     # it's saved in the user's %env.
                   6322:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6323:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6324:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6325:         %timerintchk, %timerintenv);
                   6326: 
1.1162    raeburn  6327:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6328:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6329:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6330:     }
1.1169    droeschl 6331: 
1.1162    raeburn  6332:     foreach my $key (keys(%timerinterval)) {
                   6333:         my ($cid,$rest) = split(/\0/,$key);
                   6334:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6335:     }
1.1169    droeschl 6336: 
1.11      www      6337:     my %allroles=();
1.1162    raeburn  6338:     my %allgroups=();
1.11      www      6339: 
1.1172.2.58  raeburn  6340:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6341:         my $role = $rolesdump{$area};
                   6342:         $area =~ s/\_\w\w$//;
                   6343: 
                   6344:         my ($trole, $tend, $tstart, $group_privs);
                   6345: 
                   6346:         if ($role =~ /^cr/) {
                   6347:         # Custom role, defined by a user 
                   6348:         # e.g., user.role.cr/msu/smith/mynewrole
                   6349:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6350:                 $trole = $1;
                   6351:                 ($tend, $tstart) = split('_', $2);
                   6352:             } else {
                   6353:                 $trole = $role;
                   6354:             }
                   6355:         } elsif ($role =~ m|^gr/|) {
                   6356:         # Role of member in a group, defined within a course/community
                   6357:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6358:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6359:             next if $tstart eq '-1';
                   6360:             ($trole, $group_privs) = split(/\//, $trole);
                   6361:             $group_privs = &unescape($group_privs);
                   6362:         } else {
                   6363:         # Just a normal role, defined in roles.tab
                   6364:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6365:         }
                   6366: 
                   6367:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6368:                  $username);
                   6369:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6370: 
                   6371:         # role expired or not available yet?
                   6372:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6373:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6374: 
                   6375:         next if $area eq '' or $trole eq '';
                   6376: 
                   6377:         my $spec = "$trole.$area";
                   6378:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6379: 
                   6380:         if ($trole =~ /^cr\//) {
                   6381:         # Custom role, defined by a user
                   6382:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6383:         } elsif ($trole eq 'gr') {
                   6384:         # Role of a member in a group, defined within a course/community
                   6385:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6386:             next;
                   6387:         } else {
                   6388:         # Normal role, defined in roles.tab
                   6389:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6390:         }
                   6391: 
                   6392:         my $cid = $tdomain.'_'.$trest;
                   6393:         unless ($firstaccchk{$cid}) {
                   6394:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6395:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6396:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6397:                         $coursetimerstarts{$cid}{$item}; 
                   6398:                 }
                   6399:             }
                   6400:             $firstaccchk{$cid} = 1;
                   6401:         }
                   6402:         unless ($timerintchk{$cid}) {
                   6403:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6404:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6405:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6406:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6407:                 }
1.12      www      6408:             }
1.1169    droeschl 6409:             $timerintchk{$cid} = 1;
1.191     harris41 6410:         }
1.11      www      6411:     }
1.1169    droeschl 6412: 
1.1172.2.91  raeburn  6413:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6414:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6415:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6416:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6417: 
1.1162    raeburn  6418:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6419: }
                   6420: 
1.567     raeburn  6421: sub set_arearole {
1.1172.2.19  raeburn  6422:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6423:     unless ($nolog) {
1.567     raeburn  6424: # log the associated role with the area
1.1172.2.19  raeburn  6425:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6426:     }
1.743     albertel 6427:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6428: }
                   6429: 
                   6430: sub custom_roleprivs {
                   6431:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6432:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6433:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6434:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6435:         my ($rdummy,$roledef)=
                   6436:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6437:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6438:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6439:             if (defined($syspriv)) {
1.1043    raeburn  6440:                 if ($trest =~ /^$match_community$/) {
                   6441:                     $syspriv =~ s/bre\&S//; 
                   6442:                 }
1.567     raeburn  6443:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6444:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6445:             }
                   6446:             if ($tdomain ne '') {
                   6447:                 if (defined($dompriv)) {
                   6448:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6449:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6450:                 }
                   6451:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6452:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6453:                         my $rolename = $1;
                   6454:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6455:                     }
1.567     raeburn  6456:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6457:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6458:                 }
                   6459:             }
                   6460:         }
                   6461:     }
                   6462: }
                   6463: 
1.1172.2.89  raeburn  6464: sub course_adhocrole_privs {
                   6465:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6466:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6467:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6468:         my (%currprivs,%storeprivs);
                   6469:         foreach my $item (split(/:/,$coursepriv)) {
                   6470:             my ($priv,$restrict) = split(/\&/,$item);
                   6471:             $currprivs{$priv} = $restrict;
                   6472:         }
                   6473:         my (%possadd,%possremove,%full);
                   6474:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6475:             my ($priv,$restrict)=split(/\&/,$item);
                   6476:             $full{$priv} = $restrict;
                   6477:         }
                   6478:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6479:              next if ($item eq '');
                   6480:              my ($rule,$rest) = split(/=/,$item);
                   6481:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6482:              foreach my $priv (split(/:/,$rest)) {
                   6483:                  if ($priv ne '') {
                   6484:                      if ($rule eq 'off') {
                   6485:                          $possremove{$priv} = 1;
                   6486:                      } else {
                   6487:                          $possadd{$priv} = 1;
                   6488:                      }
                   6489:                  }
                   6490:              }
                   6491:          }
                   6492:          foreach my $priv (sort(keys(%full))) {
                   6493:              if (exists($currprivs{$priv})) {
                   6494:                  unless (exists($possremove{$priv})) {
                   6495:                      $storeprivs{$priv} = $currprivs{$priv};
                   6496:                  }
                   6497:              } elsif (exists($possadd{$priv})) {
                   6498:                  $storeprivs{$priv} = $full{$priv};
                   6499:              }
                   6500:          }
                   6501:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6502:      }
                   6503:      return $coursepriv;
                   6504: }
                   6505: 
1.678     raeburn  6506: sub group_roleprivs {
                   6507:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6508:     my $access = 1;
                   6509:     my $now = time;
                   6510:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6511:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6512:     if ($access) {
1.811     albertel 6513:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6514:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6515:     }
                   6516: }
1.567     raeburn  6517: 
                   6518: sub standard_roleprivs {
                   6519:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6520:     if (defined($pr{$trole.':s'})) {
                   6521:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6522:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6523:     }
                   6524:     if ($tdomain ne '') {
                   6525:         if (defined($pr{$trole.':d'})) {
                   6526:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6527:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6528:         }
                   6529:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6530:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6531:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6532:         }
                   6533:     }
                   6534: }
                   6535: 
                   6536: sub set_userprivs {
1.1064    raeburn  6537:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6538:     my $author=0;
                   6539:     my $adv=0;
1.1172.2.91  raeburn  6540:     my $rar=0;
1.678     raeburn  6541:     my %grouproles = ();
                   6542:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6543:         my @groupkeys; 
1.1000    raeburn  6544:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6545:             push(@groupkeys,$role);
                   6546:         }
                   6547:         if (ref($groups_roles) eq 'HASH') {
                   6548:             foreach my $key (keys(%{$groups_roles})) {
                   6549:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6550:                     push(@groupkeys,$key);
                   6551:                 }
                   6552:             }
                   6553:         }
                   6554:         if (@groupkeys > 0) {
                   6555:             foreach my $role (@groupkeys) {
                   6556:                 my ($trole,$area,$sec,$extendedarea);
                   6557:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6558:                     $trole = $1;
                   6559:                     $area = $2;
                   6560:                     $sec = $3;
                   6561:                     $extendedarea = $area.$sec;
                   6562:                     if (exists($$allgroups{$area})) {
                   6563:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6564:                             my $spec = $trole.'.'.$extendedarea;
                   6565:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6566:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6567:                         }
1.678     raeburn  6568:                     }
                   6569:                 }
                   6570:             }
                   6571:         }
                   6572:     }
1.800     albertel 6573:     foreach my $group (keys(%grouproles)) {
                   6574:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6575:     }
1.800     albertel 6576:     foreach my $role (keys(%{$allroles})) {
                   6577:         my %thesepriv;
1.941     raeburn  6578:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6579:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6580:             if ($item ne '') {
                   6581:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6582:                 if ($restrictions eq '') {
                   6583:                     $thesepriv{$privilege}='F';
                   6584:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6585:                     $thesepriv{$privilege}.=$restrictions;
                   6586:                 }
                   6587:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6588:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6589:             }
                   6590:         }
                   6591:         my $thesestr='';
1.1104    raeburn  6592:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6593: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6594: 	}
                   6595:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6596:     }
1.1172.2.91  raeburn  6597:     return ($author,$adv,$rar);
1.567     raeburn  6598: }
                   6599: 
1.994     raeburn  6600: sub role_status {
1.1104    raeburn  6601:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6602:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6603:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6604:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6605:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6606:             $$where = '/'.$two;
1.994     raeburn  6607:             $$trolecode=$$role.'.'.$$where;
                   6608:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6609:             $$tstatus='is';
1.1104    raeburn  6610:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6611:                 $$tstatus='future';
1.1034    raeburn  6612:                 if ($$tstart<$now) {
                   6613:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6614:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6615:                             my (%allroles,%allgroups,$group_privs,
                   6616:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6617:                             my %userroles = (
                   6618:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6619:                             );
1.1064    raeburn  6620:                             @rolecodes = ('cm'); 
1.1002    raeburn  6621:                             my $spec=$$role.'.'.$$where;
                   6622:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6623:                             if ($$role =~ /^cr\//) {
                   6624:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6625:                                 push(@rolecodes,'cr');
1.1002    raeburn  6626:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6627:                                 push(@rolecodes,$$role);
1.1002    raeburn  6628:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6629:                                                     $env{'user.name'});
1.1064    raeburn  6630:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6631:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6632:                                 $group_privs = &unescape($group_privs);
                   6633:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6634:                                 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  6635:                                 &get_groups_roles($tdomain,$trest,
                   6636:                                                   \%course_roles,\@rolecodes,
                   6637:                                                   \%groups_roles);
1.1002    raeburn  6638:                             } else {
1.1064    raeburn  6639:                                 push(@rolecodes,$$role);
1.1002    raeburn  6640:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6641:                             }
1.1172.2.91  raeburn  6642:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6643:                                                                    \%groups_roles);
1.1064    raeburn  6644:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6645:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6646:                         }
                   6647:                     }
1.1034    raeburn  6648:                     $$tstatus = 'is';
1.1002    raeburn  6649:                 }
1.994     raeburn  6650:             }
                   6651:             if ($$tend) {
1.1104    raeburn  6652:                 if ($$tend<$update) {
1.994     raeburn  6653:                     $$tstatus='expired';
                   6654:                 } elsif ($$tend<$now) {
                   6655:                     $$tstatus='will_not';
                   6656:                 }
                   6657:             }
                   6658:         }
                   6659:     }
                   6660: }
                   6661: 
1.1104    raeburn  6662: sub get_groups_roles {
                   6663:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6664:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6665:                   (ref($rolecodes) eq 'ARRAY') && 
                   6666:                   (ref($groups_roles) eq 'HASH')); 
                   6667:     if (keys(%{$cdom_courseroles}) > 0) {
                   6668:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6669:         if ($cdom ne '' && $cnum ne '') {
                   6670:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6671:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6672:                     my $crsrole = $1;
                   6673:                     my $crssec = $2;
                   6674:                     if ($crsrole =~ /^cr/) {
                   6675:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6676:                             push(@{$rolecodes},'cr');
                   6677:                         }
                   6678:                     } else {
                   6679:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6680:                             push(@{$rolecodes},$crsrole);
                   6681:                         }
                   6682:                     }
                   6683:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6684:                     if ($crssec ne '') {
                   6685:                         $rolekey .= "/$crssec";
                   6686:                     }
                   6687:                     $rolekey .= './';
                   6688:                     $groups_roles->{$rolekey} = $rolecodes;
                   6689:                 }
                   6690:             }
                   6691:         }
                   6692:     }
                   6693:     return;
                   6694: }
                   6695: 
                   6696: sub delete_env_groupprivs {
                   6697:     my ($where,$courseroles,$possroles) = @_;
                   6698:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6699:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6700:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6701:         %{$courseroles->{$udom}} =
                   6702:             &get_my_roles('','','userroles',['active'],
                   6703:                           $possroles,[$udom],1);
                   6704:     }
                   6705:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6706:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6707:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6708:             my $area = '/'.$cdom.'/'.$cnum;
                   6709:             my $privkey = "user.priv.$crsrole.$area";
                   6710:             if ($crssec ne '') {
                   6711:                 $privkey .= '/'.$crssec;
                   6712:             }
                   6713:             $privkey .= ".$area/$group";
                   6714:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6715:         }
                   6716:     }
                   6717:     return;
                   6718: }
                   6719: 
1.994     raeburn  6720: sub check_adhoc_privs {
1.1172.2.86  raeburn  6721:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6722:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6723:     if ($sec) {
                   6724:         $cckey .= '/'.$sec;
                   6725:     }
1.1172.2.9  raeburn  6726:     my $setprivs;
1.994     raeburn  6727:     if ($env{$cckey}) {
                   6728:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6729:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6730:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6731:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6732:             $setprivs = 1;
1.994     raeburn  6733:         }
                   6734:     } else {
1.1172.2.87  raeburn  6735:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6736:         $setprivs = 1;
1.994     raeburn  6737:     }
1.1172.2.9  raeburn  6738:     return $setprivs;
1.994     raeburn  6739: }
                   6740: 
                   6741: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6742: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6743:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6744:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6745:     if ($sec ne '') {
                   6746:         $area .= '/'.$sec;
                   6747:     }
1.994     raeburn  6748:     my $spec = $role.'.'.$area;
                   6749:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6750:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6751:     my %rolehash = ();
1.1172.2.89  raeburn  6752:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6753:         my $rolename = $1;
1.1172.2.84  raeburn  6754:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6755:         my %domdef = &get_domain_defaults($dcdom);
                   6756:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6757:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6758:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6759:             }
                   6760:         }
1.1172.2.84  raeburn  6761:     } else {
                   6762:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6763:     }
1.1172.2.91  raeburn  6764:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6765:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6766:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6767:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6768:         &appenv( {'request.role'        => $spec,
                   6769:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6770:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6771:                  }
                   6772:                );
                   6773:         my $tadv=0;
                   6774:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6775:         &appenv({'request.role.adv'    => $tadv});
                   6776:     }
1.994     raeburn  6777: }
                   6778: 
1.12      www      6779: # --------------------------------------------------------------- get interface
                   6780: 
                   6781: sub get {
1.131     albertel 6782:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6783:    my $items='';
1.800     albertel 6784:    foreach my $item (@$storearr) {
                   6785:        $items.=&escape($item).'&';
1.191     harris41 6786:    }
1.12      www      6787:    $items=~s/\&$//;
1.620     albertel 6788:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6789:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6790:    my $uhome=&homeserver($uname,$udomain);
                   6791: 
1.133     albertel 6792:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6793:    my @pairs=split(/\&/,$rep);
1.273     albertel 6794:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6795:      return @pairs;
                   6796:    }
1.15      www      6797:    my %returnhash=();
1.42      www      6798:    my $i=0;
1.800     albertel 6799:    foreach my $item (@$storearr) {
                   6800:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6801:       $i++;
1.191     harris41 6802:    }
1.15      www      6803:    return %returnhash;
1.27      www      6804: }
                   6805: 
                   6806: # --------------------------------------------------------------- del interface
                   6807: 
                   6808: sub del {
1.133     albertel 6809:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6810:    my $items='';
1.800     albertel 6811:    foreach my $item (@$storearr) {
                   6812:        $items.=&escape($item).'&';
1.191     harris41 6813:    }
1.984     neumanie 6814: 
1.27      www      6815:    $items=~s/\&$//;
1.620     albertel 6816:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6817:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6818:    my $uhome=&homeserver($uname,$udomain);
                   6819:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6820: }
                   6821: 
                   6822: # -------------------------------------------------------------- dump interface
                   6823: 
1.1172.2.22  raeburn  6824: sub unserialize {
                   6825:     my ($rep, $escapedkeys) = @_;
                   6826: 
                   6827:     return {} if $rep =~ /^error/;
                   6828: 
                   6829:     my %returnhash=();
                   6830:     foreach my $item (split(/\&/,$rep)) {
                   6831:         my ($key, $value) = split(/=/, $item, 2);
                   6832:         $key = unescape($key) unless $escapedkeys;
                   6833:         next if $key =~ /^error: 2 /;
                   6834:         $returnhash{$key} = &thaw_unescape($value);
                   6835:     }
                   6836:     return \%returnhash;
                   6837: }
                   6838: 
                   6839: # see Lond::dump_with_regexp
                   6840: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6841: sub dump {
1.1172.2.22  raeburn  6842:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6843:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6844:     if (!$uname) { $uname=$env{'user.name'}; }
                   6845:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6846: 
1.1172.2.55  raeburn  6847:     if ($regexp) {
                   6848:         $regexp=&escape($regexp);
                   6849:     } else {
                   6850:         $regexp='.';
                   6851:     }
1.1172.2.22  raeburn  6852:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6853:         # user is hosted on this machine
1.1172.2.55  raeburn  6854:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6855:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6856:         return %{&unserialize($reply, $escapedkeys)};
                   6857:     }
1.1166    raeburn  6858:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6859:     my @pairs=split(/\&/,$rep);
                   6860:     my %returnhash=();
1.1098    foxr     6861:     if (!($rep =~ /^error/ )) {
                   6862: 	foreach my $item (@pairs) {
                   6863: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6864:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6865: 	    next if ($key =~ /^error: 2 /);
                   6866: 	    $returnhash{$key}=&thaw_unescape($value);
                   6867: 	}
1.755     albertel 6868:     }
                   6869:     return %returnhash;
1.407     www      6870: }
                   6871: 
1.1098    foxr     6872: 
1.717     albertel 6873: # --------------------------------------------------------- dumpstore interface
                   6874: 
                   6875: sub dumpstore {
                   6876:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6877:    # same as dump but keys must be escaped. They may contain colon separated
                   6878:    # lists of values that may themself contain colons (e.g. symbs).
                   6879:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6880: }
                   6881: 
1.407     www      6882: # -------------------------------------------------------------- keys interface
                   6883: 
                   6884: sub getkeys {
                   6885:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6886:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6887:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6888:    my $uhome=&homeserver($uname,$udomain);
                   6889:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6890:    my @keyarray=();
1.800     albertel 6891:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6892:       next if ($key =~ /^error: 2 /);
1.800     albertel 6893:       push(@keyarray,&unescape($key));
1.407     www      6894:    }
                   6895:    return @keyarray;
1.318     matthew  6896: }
                   6897: 
1.319     matthew  6898: # --------------------------------------------------------------- currentdump
                   6899: sub currentdump {
1.328     matthew  6900:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6901:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6902:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6903:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6904:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6905:    my $rep;
                   6906: 
                   6907:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6908:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6909:                    $courseid)));
                   6910:    } else {
                   6911:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6912:    }
                   6913: 
1.318     matthew  6914:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6915:    #
1.318     matthew  6916:    my %returnhash=();
1.319     matthew  6917:    #
1.1172.2.118.  .1(raebu 6918:20):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6919:        # an old lond will not know currentdump
                   6920:        # Do a dump and make it look like a currentdump
1.822     albertel 6921:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6922:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6923:        my %hash = @tmp;
                   6924:        @tmp=();
1.424     matthew  6925:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6926:    } else {
                   6927:        my @pairs=split(/\&/,$rep);
1.800     albertel 6928:        foreach my $pair (@pairs) {
                   6929:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6930:            my ($symb,$param) = split(/:/,$key);
                   6931:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6932:                                                         &thaw_unescape($value);
1.319     matthew  6933:        }
1.191     harris41 6934:    }
1.12      www      6935:    return %returnhash;
1.424     matthew  6936: }
                   6937: 
                   6938: sub convert_dump_to_currentdump{
                   6939:     my %hash = %{shift()};
                   6940:     my %returnhash;
                   6941:     # Code ripped from lond, essentially.  The only difference
                   6942:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6943:     # we might run in to problems with parameter names =~ /^v\./
                   6944:     while (my ($key,$value) = each(%hash)) {
                   6945:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6946: 	$symb  = &unescape($symb);
                   6947: 	$param = &unescape($param);
1.424     matthew  6948:         next if ($v eq 'version' || $symb eq 'keys');
                   6949:         next if (exists($returnhash{$symb}) &&
                   6950:                  exists($returnhash{$symb}->{$param}) &&
                   6951:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6952:         $returnhash{$symb}->{$param}=$value;
                   6953:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6954:     }
                   6955:     #
                   6956:     # Remove all of the keys in the hashes which keep track of
                   6957:     # the version of the parameter.
                   6958:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6959:         # use a foreach because we are going to delete from the hash.
                   6960:         foreach my $key (keys(%$param_hash)) {
                   6961:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6962:         }
                   6963:     }
                   6964:     return \%returnhash;
1.12      www      6965: }
                   6966: 
1.627     albertel 6967: # ------------------------------------------------------ critical inc interface
                   6968: 
                   6969: sub cinc {
                   6970:     return &inc(@_,'critical');
                   6971: }
                   6972: 
1.449     matthew  6973: # --------------------------------------------------------------- inc interface
                   6974: 
                   6975: sub inc {
1.627     albertel 6976:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6977:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6978:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6979:     my $uhome=&homeserver($uname,$udomain);
                   6980:     my $items='';
                   6981:     if (! ref($store)) {
                   6982:         # got a single value, so use that instead
                   6983:         $items = &escape($store).'=&';
                   6984:     } elsif (ref($store) eq 'SCALAR') {
                   6985:         $items = &escape($$store).'=&';        
                   6986:     } elsif (ref($store) eq 'ARRAY') {
                   6987:         $items = join('=&',map {&escape($_);} @{$store});
                   6988:     } elsif (ref($store) eq 'HASH') {
                   6989:         while (my($key,$value) = each(%{$store})) {
                   6990:             $items.= &escape($key).'='.&escape($value).'&';
                   6991:         }
                   6992:     }
                   6993:     $items=~s/\&$//;
1.627     albertel 6994:     if ($critical) {
                   6995: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6996:     } else {
                   6997: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6998:     }
1.449     matthew  6999: }
                   7000: 
1.12      www      7001: # --------------------------------------------------------------- put interface
                   7002: 
                   7003: sub put {
1.134     albertel 7004:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7005:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7006:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7007:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7008:    my $items='';
1.800     albertel 7009:    foreach my $item (keys(%$storehash)) {
                   7010:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7011:    }
1.12      www      7012:    $items=~s/\&$//;
1.134     albertel 7013:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7014: }
                   7015: 
1.631     albertel 7016: # ------------------------------------------------------------ newput interface
                   7017: 
                   7018: sub newput {
                   7019:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7020:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7021:    if (!$uname) { $uname=$env{'user.name'}; }
                   7022:    my $uhome=&homeserver($uname,$udomain);
                   7023:    my $items='';
                   7024:    foreach my $key (keys(%$storehash)) {
                   7025:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7026:    }
                   7027:    $items=~s/\&$//;
                   7028:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7029: }
                   7030: 
                   7031: # ---------------------------------------------------------  putstore interface
                   7032: 
1.524     raeburn  7033: sub putstore {
1.1172.2.59  raeburn  7034:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7035:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7036:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7037:    my $uhome=&homeserver($uname,$udomain);
                   7038:    my $items='';
1.715     albertel 7039:    foreach my $key (keys(%$storehash)) {
                   7040:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7041:    }
1.715     albertel 7042:    $items=~s/\&$//;
1.716     albertel 7043:    my $esc_symb=&escape($symb);
                   7044:    my $esc_v=&escape($version);
1.715     albertel 7045:    my $reply =
1.716     albertel 7046:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7047: 	      $uhome);
1.1172.2.59  raeburn  7048:    if (($tolog) && ($reply eq 'ok')) {
                   7049:        my $namevalue='';
                   7050:        foreach my $key (keys(%{$storehash})) {
                   7051:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7052:        }
                   7053:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7054:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7055:                      '&version='.$esc_v.
                   7056:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7057:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7058:    }
1.715     albertel 7059:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7060:        # gfall back to way things use to be done
1.715     albertel 7061:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7062: 			    $uname);
1.524     raeburn  7063:    }
1.715     albertel 7064:    return $reply;
                   7065: }
                   7066: 
                   7067: sub old_putstore {
1.716     albertel 7068:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7069:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7070:     if (!$uname) { $uname=$env{'user.name'}; }
                   7071:     my $uhome=&homeserver($uname,$udomain);
                   7072:     my %newstorehash;
1.800     albertel 7073:     foreach my $item (keys(%$storehash)) {
                   7074: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7075: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7076:     }
                   7077:     my $items='';
                   7078:     my %allitems = ();
1.800     albertel 7079:     foreach my $item (keys(%newstorehash)) {
                   7080: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7081: 	    my $key = $1.':keys:'.$2;
                   7082: 	    $allitems{$key} .= $3.':';
                   7083: 	}
1.800     albertel 7084: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7085:     }
1.800     albertel 7086:     foreach my $item (keys(%allitems)) {
                   7087: 	$allitems{$item} =~ s/\:$//;
                   7088: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7089:     }
                   7090:     $items=~s/\&$//;
                   7091:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7092: }
                   7093: 
1.47      www      7094: # ------------------------------------------------------ critical put interface
                   7095: 
                   7096: sub cput {
1.134     albertel 7097:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7099:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7100:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7101:    my $items='';
1.800     albertel 7102:    foreach my $item (keys(%$storehash)) {
                   7103:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7104:    }
1.47      www      7105:    $items=~s/\&$//;
1.134     albertel 7106:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7107: }
                   7108: 
                   7109: # -------------------------------------------------------------- eget interface
                   7110: 
                   7111: sub eget {
1.133     albertel 7112:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7113:    my $items='';
1.800     albertel 7114:    foreach my $item (@$storearr) {
                   7115:        $items.=&escape($item).'&';
1.191     harris41 7116:    }
1.12      www      7117:    $items=~s/\&$//;
1.620     albertel 7118:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7119:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7120:    my $uhome=&homeserver($uname,$udomain);
                   7121:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7122:    my @pairs=split(/\&/,$rep);
                   7123:    my %returnhash=();
1.42      www      7124:    my $i=0;
1.800     albertel 7125:    foreach my $item (@$storearr) {
                   7126:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7127:       $i++;
1.191     harris41 7128:    }
1.12      www      7129:    return %returnhash;
                   7130: }
                   7131: 
1.667     albertel 7132: # ------------------------------------------------------------ tmpput interface
                   7133: sub tmpput {
1.802     raeburn  7134:     my ($storehash,$server,$context)=@_;
1.667     albertel 7135:     my $items='';
1.800     albertel 7136:     foreach my $item (keys(%$storehash)) {
                   7137: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7138:     }
                   7139:     $items=~s/\&$//;
1.802     raeburn  7140:     if (defined($context)) {
                   7141:         $items .= ':'.&escape($context);
                   7142:     }
1.667     albertel 7143:     return &reply("tmpput:$items",$server);
                   7144: }
                   7145: 
                   7146: # ------------------------------------------------------------ tmpget interface
                   7147: sub tmpget {
1.688     albertel 7148:     my ($token,$server)=@_;
                   7149:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7150:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7151:     my %returnhash;
1.1172.2.85  raeburn  7152:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7153:         return %returnhash;
                   7154:     }
1.667     albertel 7155:     foreach my $item (split(/\&/,$rep)) {
                   7156: 	my ($key,$value)=split(/=/,$item);
                   7157: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7158:     }
                   7159:     return %returnhash;
                   7160: }
                   7161: 
1.1113    raeburn  7162: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7163: sub tmpdel {
                   7164:     my ($token,$server)=@_;
                   7165:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7166:     return &reply("tmpdel:$token",$server);
                   7167: }
                   7168: 
1.1172.2.13  raeburn  7169: # ------------------------------------------------------------ get_timebased_id
                   7170: 
                   7171: sub get_timebased_id {
                   7172:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7173:         $maxtries) = @_;
                   7174:     my ($newid,$error,$dellock);
                   7175:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7176:         return ('','ok','invalid call to get suffix');
                   7177:     }
                   7178: 
                   7179: # set defaults for any optional args for which values were not supplied
                   7180:     if ($who eq '') {
                   7181:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7182:     }
                   7183:     if (!$locktries) {
                   7184:         $locktries = 3;
                   7185:     }
                   7186:     if (!$maxtries) {
                   7187:         $maxtries = 10;
                   7188:     }
                   7189: 
                   7190:     if (($cdom eq '') || ($cnum eq '')) {
                   7191:         if ($env{'request.course.id'}) {
                   7192:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7193:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7194:         }
                   7195:         if (($cdom eq '') || ($cnum eq '')) {
                   7196:             return ('','ok','call to get suffix not in course context');
                   7197:         }
                   7198:     }
                   7199: 
                   7200: # construct locking item
                   7201:     my $lockhash = {
                   7202:                       $prefix."\0".'locked_'.$keyid => $who,
                   7203:                    };
                   7204:     my $tries = 0;
                   7205: 
                   7206: # attempt to get lock on nohist_$namespace file
                   7207:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7208:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7209:         $tries ++;
                   7210:         sleep 1;
                   7211:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7212:     }
                   7213: 
                   7214: # attempt to get unique identifier, based on current timestamp
                   7215:     if ($gotlock eq 'ok') {
                   7216:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7217:         my $id = time;
                   7218:         $newid = $id;
1.1172.2.56  raeburn  7219:         if ($idtype eq 'addcode') {
                   7220:             $newid .= &sixnum_code();
                   7221:         }
1.1172.2.13  raeburn  7222:         my $idtries = 0;
                   7223:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7224:             if ($idtype eq 'concat') {
                   7225:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7226:             } elsif ($idtype eq 'addcode') {
                   7227:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7228:             } else {
                   7229:                 $newid ++;
                   7230:             }
                   7231:             $idtries ++;
                   7232:         }
                   7233:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7234:             my %new_item =  (
                   7235:                               $prefix."\0".$newid => $who,
                   7236:                             );
                   7237:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7238:                                                  $cdom,$cnum);
                   7239:             if ($putresult ne 'ok') {
                   7240:                 undef($newid);
                   7241:                 $error = 'error saving new item: '.$putresult;
                   7242:             }
                   7243:         } else {
1.1172.2.56  raeburn  7244:              undef($newid);
1.1172.2.13  raeburn  7245:              $error = ('error: no unique suffix available for the new item ');
                   7246:         }
                   7247: #  remove lock
                   7248:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7249:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7250:     } else {
                   7251:         $error = "error: could not obtain lockfile\n";
                   7252:         $dellock = 'ok';
1.1172.2.58  raeburn  7253:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7254:             $dellock = 'nolock';
                   7255:         }
1.1172.2.13  raeburn  7256:     }
                   7257:     return ($newid,$dellock,$error);
                   7258: }
                   7259: 
1.1172.2.56  raeburn  7260: sub sixnum_code {
                   7261:     my $code;
                   7262:     for (0..6) {
                   7263:         $code .= int( rand(9) );
                   7264:     }
                   7265:     return $code;
                   7266: }
                   7267: 
1.765     albertel 7268: # -------------------------------------------------- portfolio access checking
                   7269: 
                   7270: sub portfolio_access {
1.1172.2.77  raeburn  7271:     my ($requrl,$clientip) = @_;
1.765     albertel 7272:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7273:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7274:     if ($result) {
                   7275:         my %setters;
                   7276:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7277:             my ($startblock,$endblock) =
                   7278:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7279:             if ($startblock && $endblock) {
                   7280:                 return 'B';
                   7281:             }
                   7282:         } else {
                   7283:             my ($startblock,$endblock) =
                   7284:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7285:             if ($startblock && $endblock) {
                   7286:                 return 'B';
                   7287:             }
                   7288:         }
                   7289:     }
1.765     albertel 7290:     if ($result eq 'ok') {
1.766     albertel 7291:        return 'F';
1.765     albertel 7292:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7293:        return 'A';
1.765     albertel 7294:     }
1.766     albertel 7295:     return '';
1.765     albertel 7296: }
                   7297: 
                   7298: sub get_portfolio_access {
1.1172.2.77  raeburn  7299:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7300: 
                   7301:     if (!ref($access_hash)) {
                   7302: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7303: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7304: 						   $file_name);
                   7305: 	$access_hash = $access_controls{$file_name};
                   7306:     }
                   7307: 
1.1172.2.77  raeburn  7308:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7309:     my $now = time;
                   7310:     if (ref($access_hash) eq 'HASH') {
                   7311:         foreach my $key (keys(%{$access_hash})) {
                   7312:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7313:             if ($start > $now) {
                   7314:                 next;
                   7315:             }
                   7316:             if ($end && $end<$now) {
                   7317:                 next;
                   7318:             }
                   7319:             if ($scope eq 'public') {
                   7320:                 $public = $key;
                   7321:                 last;
                   7322:             } elsif ($scope eq 'guest') {
                   7323:                 $guest = $key;
                   7324:             } elsif ($scope eq 'domains') {
                   7325:                 push(@domains,$key);
                   7326:             } elsif ($scope eq 'users') {
                   7327:                 push(@users,$key);
                   7328:             } elsif ($scope eq 'course') {
                   7329:                 push(@courses,$key);
                   7330:             } elsif ($scope eq 'group') {
                   7331:                 push(@groups,$key);
1.1172.2.77  raeburn  7332:             } elsif ($scope eq 'ip') {
                   7333:                 push(@ips,$key);
1.765     albertel 7334:             }
                   7335:         }
                   7336:         if ($public) {
                   7337:             return 'ok';
1.1172.2.77  raeburn  7338:         } elsif (@ips > 0) {
                   7339:             my $allowed;
                   7340:             foreach my $ipkey (@ips) {
                   7341:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7342:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7343:                         $allowed = 1;
                   7344:                         last;
                   7345:                     }
                   7346:                 }
                   7347:             }
                   7348:             if ($allowed) {
                   7349:                 return 'ok';
                   7350:             }
1.765     albertel 7351:         }
                   7352:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7353:             if ($guest) {
                   7354:                 return $guest;
                   7355:             }
                   7356:         } else {
                   7357:             if (@domains > 0) {
                   7358:                 foreach my $domkey (@domains) {
                   7359:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7360:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7361:                             return 'ok';
                   7362:                         }
                   7363:                     }
                   7364:                 }
                   7365:             }
                   7366:             if (@users > 0) {
                   7367:                 foreach my $userkey (@users) {
1.865     raeburn  7368:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7369:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7370:                             if (ref($item) eq 'HASH') {
                   7371:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7372:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7373:                                     return 'ok';
                   7374:                                 }
                   7375:                             }
                   7376:                         }
                   7377:                     } 
1.765     albertel 7378:                 }
                   7379:             }
                   7380:             my %roleshash;
                   7381:             my @courses_and_groups = @courses;
                   7382:             push(@courses_and_groups,@groups); 
                   7383:             if (@courses_and_groups > 0) {
                   7384:                 my (%allgroups,%allroles); 
                   7385:                 my ($start,$end,$role,$sec,$group);
                   7386:                 foreach my $envkey (%env) {
1.1060    raeburn  7387:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7388:                         my $cid = $2.'_'.$3; 
                   7389:                         if ($1 eq 'gr') {
                   7390:                             $group = $4;
                   7391:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7392:                         } else {
                   7393:                             if ($4 eq '') {
                   7394:                                 $sec = 'none';
                   7395:                             } else {
                   7396:                                 $sec = $4;
                   7397:                             }
                   7398:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7399:                         }
1.811     albertel 7400:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7401:                         my $cid = $2.'_'.$3;
                   7402:                         if ($4 eq '') {
                   7403:                             $sec = 'none';
                   7404:                         } else {
                   7405:                             $sec = $4;
                   7406:                         }
                   7407:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7408:                     }
                   7409:                 }
                   7410:                 if (keys(%allroles) == 0) {
                   7411:                     return;
                   7412:                 }
                   7413:                 foreach my $key (@courses_and_groups) {
                   7414:                     my %content = %{$$access_hash{$key}};
                   7415:                     my $cnum = $content{'number'};
                   7416:                     my $cdom = $content{'domain'};
                   7417:                     my $cid = $cdom.'_'.$cnum;
                   7418:                     if (!exists($allroles{$cid})) {
                   7419:                         next;
                   7420:                     }    
                   7421:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7422:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7423:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7424:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7425:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7426:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7427:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7428:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7429:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7430:                                         if (grep/^all$/,@sections) {
                   7431:                                             return 'ok';
                   7432:                                         } else {
                   7433:                                             if (grep/^$sec$/,@sections) {
                   7434:                                                 return 'ok';
                   7435:                                             }
                   7436:                                         }
                   7437:                                     }
                   7438:                                 }
                   7439:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7440:                                     if (grep/^none$/,@groups) {
                   7441:                                         return 'ok';
                   7442:                                     }
                   7443:                                 } else {
                   7444:                                     if (grep/^all$/,@groups) {
                   7445:                                         return 'ok';
                   7446:                                     } 
                   7447:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7448:                                         if (grep/^$group$/,@groups) {
                   7449:                                             return 'ok';
                   7450:                                         }
                   7451:                                     }
                   7452:                                 } 
                   7453:                             }
                   7454:                         }
                   7455:                     }
                   7456:                 }
                   7457:             }
                   7458:             if ($guest) {
                   7459:                 return $guest;
                   7460:             }
                   7461:         }
                   7462:     }
                   7463:     return;
                   7464: }
                   7465: 
                   7466: sub course_group_datechecker {
                   7467:     my ($dates,$now,$status) = @_;
                   7468:     my ($start,$end) = split(/\./,$dates);
                   7469:     if (!$start && !$end) {
                   7470:         return 'ok';
                   7471:     }
                   7472:     if (grep/^active$/,@{$status}) {
                   7473:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7474:             return 'ok';
                   7475:         }
                   7476:     }
                   7477:     if (grep/^previous$/,@{$status}) {
                   7478:         if ($end > $now ) {
                   7479:             return 'ok';
                   7480:         }
                   7481:     }
                   7482:     if (grep/^future$/,@{$status}) {
                   7483:         if ($start > $now) {
                   7484:             return 'ok';
                   7485:         }
                   7486:     }
                   7487:     return; 
                   7488: }
                   7489: 
                   7490: sub parse_portfolio_url {
                   7491:     my ($url) = @_;
                   7492: 
                   7493:     my ($type,$udom,$unum,$group,$file_name);
                   7494:     
1.823     albertel 7495:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7496: 	$type = 1;
                   7497:         $udom = $1;
                   7498:         $unum = $2;
                   7499:         $file_name = $3;
1.823     albertel 7500:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7501: 	$type = 2;
                   7502:         $udom = $1;
                   7503:         $unum = $2;
                   7504:         $group = $3;
                   7505:         $file_name = $3.'/'.$4;
                   7506:     }
                   7507:     if (wantarray) {
                   7508: 	return ($type,$udom,$unum,$file_name,$group);
                   7509:     }
                   7510:     return $type;
                   7511: }
                   7512: 
                   7513: sub is_portfolio_url {
                   7514:     my ($url) = @_;
                   7515:     return scalar(&parse_portfolio_url($url));
                   7516: }
                   7517: 
1.798     raeburn  7518: sub is_portfolio_file {
                   7519:     my ($file) = @_;
1.820     raeburn  7520:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7521:         return 1;
                   7522:     }
                   7523:     return;
                   7524: }
                   7525: 
1.976     raeburn  7526: sub usertools_access {
1.1084    raeburn  7527:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7528:     my ($access,%tools);
                   7529:     if ($context eq '') {
                   7530:         $context = 'tools';
                   7531:     }
                   7532:     if ($context eq 'requestcourses') {
                   7533:         %tools = (
                   7534:                       official   => 1,
                   7535:                       unofficial => 1,
1.1006    raeburn  7536:                       community  => 1,
1.1172.2.37  raeburn  7537:                       textbook   => 1,
1.985     raeburn  7538:                  );
1.1172.2.9  raeburn  7539:     } elsif ($context eq 'requestauthor') {
                   7540:         %tools = (
                   7541:                       requestauthor => 1,
                   7542:                  );
1.985     raeburn  7543:     } else {
                   7544:         %tools = (
                   7545:                       aboutme   => 1,
                   7546:                       blog      => 1,
1.1172.2.6  raeburn  7547:                       webdav    => 1,
1.985     raeburn  7548:                       portfolio => 1,
                   7549:                  );
                   7550:     }
1.976     raeburn  7551:     return if (!defined($tools{$tool}));
                   7552: 
1.1172.2.35  raeburn  7553:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7554:         $udom = $env{'user.domain'};
                   7555:         $uname = $env{'user.name'};
                   7556:     }
                   7557: 
1.978     raeburn  7558:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7559:         if ($action ne 'reload') {
1.985     raeburn  7560:             if ($context eq 'requestcourses') {
                   7561:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7562:             } elsif ($context eq 'requestauthor') {
                   7563:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7564:             } else {
                   7565:                 return $env{'environment.availabletools.'.$tool};
                   7566:             }
                   7567:         }
1.976     raeburn  7568:     }
                   7569: 
1.1172.2.9  raeburn  7570:     my ($toolstatus,$inststatus,$envkey);
                   7571:     if ($context eq 'requestauthor') {
                   7572:         $envkey = $context;
                   7573:     } else {
                   7574:         $envkey = $context.'.'.$tool;
                   7575:     }
1.976     raeburn  7576: 
1.985     raeburn  7577:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7578:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7579:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7580:         $inststatus = $env{'environment.inststatus'};
                   7581:     } else {
1.1084    raeburn  7582:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7583:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7584:             $inststatus = $userenvref->{'inststatus'};
                   7585:         } else {
1.1172.2.9  raeburn  7586:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7587:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7588:             $inststatus = $userenv{'inststatus'};
                   7589:         }
1.976     raeburn  7590:     }
                   7591: 
                   7592:     if ($toolstatus ne '') {
                   7593:         if ($toolstatus) {
                   7594:             $access = 1;
                   7595:         } else {
                   7596:             $access = 0;
                   7597:         }
                   7598:         return $access;
                   7599:     }
                   7600: 
1.1084    raeburn  7601:     my ($is_adv,%domdef);
                   7602:     if (ref($is_advref) eq 'HASH') {
                   7603:         $is_adv = $is_advref->{'is_adv'};
                   7604:     } else {
                   7605:         $is_adv = &is_advanced_user($udom,$uname);
                   7606:     }
                   7607:     if (ref($domdefref) eq 'HASH') {
                   7608:         %domdef = %{$domdefref};
                   7609:     } else {
                   7610:         %domdef = &get_domain_defaults($udom);
                   7611:     }
1.976     raeburn  7612:     if (ref($domdef{$tool}) eq 'HASH') {
                   7613:         if ($is_adv) {
                   7614:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7615:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7616:                     $access = 1;
                   7617:                 } else {
                   7618:                     $access = 0;
                   7619:                 }
                   7620:                 return $access;
                   7621:             }
                   7622:         }
                   7623:         if ($inststatus ne '') {
                   7624:             my ($hasaccess,$hasnoaccess);
                   7625:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7626:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7627:                     if ($domdef{$tool}{$affiliation}) {
                   7628:                         $hasaccess = 1;
                   7629:                     } else {
                   7630:                         $hasnoaccess = 1;
                   7631:                     }
                   7632:                 }
                   7633:             }
                   7634:             if ($hasaccess || $hasnoaccess) {
                   7635:                 if ($hasaccess) {
                   7636:                     $access = 1;
                   7637:                 } elsif ($hasnoaccess) {
                   7638:                     $access = 0; 
                   7639:                 }
                   7640:                 return $access;
                   7641:             }
                   7642:         } else {
                   7643:             if ($domdef{$tool}{'default'} ne '') {
                   7644:                 if ($domdef{$tool}{'default'}) {
                   7645:                     $access = 1;
                   7646:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7647:                     $access = 0;
                   7648:                 }
                   7649:                 return $access;
                   7650:             }
                   7651:         }
                   7652:     } else {
1.1172.2.6  raeburn  7653:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7654:             $access = 1;
                   7655:         } else {
                   7656:             $access = 0;
                   7657:         }
1.976     raeburn  7658:         return $access;
                   7659:     }
                   7660: }
                   7661: 
1.1050    raeburn  7662: sub is_course_owner {
                   7663:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7664:     if (($udom eq '') || ($uname eq '')) {
                   7665:         $udom = $env{'user.domain'};
                   7666:         $uname = $env{'user.name'};
                   7667:     }
                   7668:     unless (($udom eq '') || ($uname eq '')) {
                   7669:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7670:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7671:                 return 1;
                   7672:             } else {
                   7673:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7674:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7675:                     return 1;
                   7676:                 }
                   7677:             }
                   7678:         }
                   7679:     }
                   7680:     return;
                   7681: }
                   7682: 
1.976     raeburn  7683: sub is_advanced_user {
                   7684:     my ($udom,$uname) = @_;
1.1085    raeburn  7685:     if ($udom ne '' && $uname ne '') {
                   7686:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7687:             if (wantarray) {
                   7688:                 return ($env{'user.adv'},$env{'user.author'});
                   7689:             } else {
                   7690:                 return $env{'user.adv'};
                   7691:             }
1.1085    raeburn  7692:         }
                   7693:     }
1.976     raeburn  7694:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7695:     my %allroles;
1.1128    raeburn  7696:     my ($is_adv,$is_author);
1.976     raeburn  7697:     foreach my $role (keys(%roleshash)) {
                   7698:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7699:         my $area = '/'.$tdomain.'/'.$trest;
                   7700:         if ($sec ne '') {
                   7701:             $area .= '/'.$sec;
                   7702:         }
                   7703:         if (($area ne '') && ($trole ne '')) {
                   7704:             my $spec=$trole.'.'.$area;
                   7705:             if ($trole =~ /^cr\//) {
                   7706:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7707:             } elsif ($trole ne 'gr') {
                   7708:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7709:             }
1.1128    raeburn  7710:             if ($trole eq 'au') {
                   7711:                 $is_author = 1;
                   7712:             }
1.976     raeburn  7713:         }
                   7714:     }
                   7715:     foreach my $role (keys(%allroles)) {
                   7716:         last if ($is_adv);
                   7717:         foreach my $item (split(/:/,$allroles{$role})) {
                   7718:             if ($item ne '') {
                   7719:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7720:                 if ($privilege eq 'adv') {
                   7721:                     $is_adv = 1;
                   7722:                     last;
                   7723:                 }
                   7724:             }
                   7725:         }
                   7726:     }
1.1128    raeburn  7727:     if (wantarray) {
                   7728:         return ($is_adv,$is_author);
                   7729:     }
1.976     raeburn  7730:     return $is_adv;
                   7731: }
1.798     raeburn  7732: 
1.1035    raeburn  7733: sub check_can_request {
1.1036    raeburn  7734:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7735:     my $canreq = 0;
                   7736:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7737:     my @options = ('approval','validate','autolimit');
                   7738:     my $optregex = join('|',@options);
                   7739:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7740:         foreach my $type (@{$types}) {
                   7741:             if (&usertools_access($env{'user.name'},
                   7742:                                   $env{'user.domain'},
                   7743:                                   $type,undef,'requestcourses')) {
                   7744:                 $canreq ++;
1.1036    raeburn  7745:                 if (ref($request_domains) eq 'HASH') {
                   7746:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7747:                 }
1.1035    raeburn  7748:                 if ($dom eq $env{'user.domain'}) {
                   7749:                     $can_request->{$type} = 1;
                   7750:                 }
                   7751:             }
                   7752:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7753:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7754:                 if (@curr > 0) {
1.1036    raeburn  7755:                     foreach my $item (@curr) {
                   7756:                         if (ref($request_domains) eq 'HASH') {
                   7757:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7758:                             if ($otherdom ne '') {
                   7759:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7760:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7761:                                         push(@{$request_domains->{$type}},$otherdom);
                   7762:                                     }
                   7763:                                 } else {
                   7764:                                     push(@{$request_domains->{$type}},$otherdom);
                   7765:                                 }
                   7766:                             }
                   7767:                         }
                   7768:                     }
                   7769:                     unless($dom eq $env{'user.domain'}) {
                   7770:                         $canreq ++;
1.1035    raeburn  7771:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7772:                             $can_request->{$type} = 1;
                   7773:                         }
                   7774:                     }
                   7775:                 }
                   7776:             }
                   7777:         }
                   7778:     }
                   7779:     return $canreq;
                   7780: }
                   7781: 
1.341     www      7782: # ---------------------------------------------- Custom access rule evaluation
                   7783: 
                   7784: sub customaccess {
                   7785:     my ($priv,$uri)=@_;
1.807     albertel 7786:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7787:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7788:     $udom = &LONCAPA::clean_domain($udom);
                   7789:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7790:     my $access=0;
1.800     albertel 7791:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7792: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7793: 	if ($type eq 'user') {
                   7794: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7795: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7796: 		if ($tdom) {
                   7797: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7798: 		}
1.896     albertel 7799: 		if ($tuname) {
                   7800: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7801: 		}
                   7802: 		$access=($effect eq 'allow');
                   7803: 		last;
                   7804: 	    }
                   7805: 	} else {
                   7806: 	    if ($role) {
                   7807: 		if ($role ne $urole) { next; }
                   7808: 	    }
                   7809: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7810: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7811: 		if ($tdom) {
                   7812: 		    if ($tdom ne $udom) { next; }
                   7813: 		}
                   7814: 		if ($tcrs) {
                   7815: 		    if ($tcrs ne $ucrs) { next; }
                   7816: 		}
                   7817: 		if ($tsec) {
                   7818: 		    if ($tsec ne $usec) { next; }
                   7819: 		}
                   7820: 		$access=($effect eq 'allow');
                   7821: 		last;
                   7822: 	    }
                   7823: 	    if ($realm eq '' && $role eq '') {
                   7824: 		$access=($effect eq 'allow');
                   7825: 	    }
1.402     bowersj2 7826: 	}
1.341     www      7827:     }
                   7828:     return $access;
                   7829: }
                   7830: 
1.103     harris41 7831: # ------------------------------------------------- Check for a user privilege
1.12      www      7832: 
                   7833: sub allowed {
1.1172.2.118.  .8(raebu 7834:20):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7835:     my $ver_orguri=$uri;
1.439     www      7836:     $uri=&deversion($uri);
1.152     www      7837:     my $orguri=$uri;
1.52      www      7838:     $uri=&declutter($uri);
1.809     raeburn  7839: 
1.810     raeburn  7840:     if ($priv eq 'evb') {
                   7841: # Evade communication block restrictions for specified role in a course
                   7842:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7843:             return $1;
                   7844:         } else {
                   7845:             return;
                   7846:         }
                   7847:     }
                   7848: 
1.620     albertel 7849:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7850: # Free bre access to adm and meta resources
1.1172.2.118.  .1(raebu 7851:20):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7852: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7853: 	&& ($priv eq 'bre')) {
1.14      www      7854: 	return 'F';
1.159     www      7855:     }
                   7856: 
1.545     banghart 7857: # Free bre access to user's own portfolio contents
1.714     raeburn  7858:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7859:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7860: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7861:         my %setters;
                   7862:         my ($startblock,$endblock) = 
                   7863:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7864:         if ($startblock && $endblock) {
                   7865:             return 'B';
                   7866:         } else {
                   7867:             return 'F';
                   7868:         }
1.545     banghart 7869:     }
                   7870: 
1.762     raeburn  7871: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7872:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7873:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7874:         if (exists($env{'request.course.id'})) {
                   7875:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7876:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7877:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7878:                 my $courseprivid=$env{'request.course.id'};
                   7879:                 $courseprivid=~s/\_/\//;
                   7880:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7881:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7882:                     return $1; 
1.762     raeburn  7883:                 } else {
                   7884:                     if ($env{'request.course.sec'}) {
                   7885:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7886:                     }
                   7887:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7888:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7889:                         return $2;
                   7890:                     }
1.714     raeburn  7891:                 }
                   7892:             }
                   7893:         }
                   7894:     }
                   7895: 
1.159     www      7896: # Free bre to public access
                   7897: 
                   7898:     if ($priv eq 'bre') {
1.238     www      7899:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7900: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7901:            return 'F'; 
                   7902:         }
1.238     www      7903:         if ($copyright eq 'priv') {
                   7904:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7905: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7906: 		return '';
                   7907:             }
                   7908:         }
                   7909:         if ($copyright eq 'domain') {
                   7910:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7911: 	    unless (($env{'user.domain'} eq $1) ||
                   7912:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7913: 		return '';
                   7914:             }
1.262     matthew  7915:         }
1.620     albertel 7916:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7917:             # Library role, so allow browsing of resources in this domain.
                   7918:             return 'F';
1.238     www      7919:         }
1.341     www      7920:         if ($copyright eq 'custom') {
                   7921: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7922:         }
1.14      www      7923:     }
1.264     matthew  7924:     # Domain coordinator is trying to create a course
1.620     albertel 7925:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7926:         # uri is the requested domain in this case.
                   7927:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7928:         # a role of dc for the domain in question.
1.620     albertel 7929:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7930:     }
1.29      www      7931: 
1.52      www      7932:     my $thisallowed='';
                   7933:     my $statecond=0;
                   7934:     my $courseprivid='';
                   7935: 
1.1039    raeburn  7936:     my $ownaccess;
1.1043    raeburn  7937:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7938:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7939:         if ($uri eq '') {
                   7940:             $ownaccess = 1;
                   7941:         } else {
                   7942:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7943:                 my $udom = $env{'user.domain'};
                   7944:                 my $uname = $env{'user.name'};
                   7945:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7946:                     $ownaccess = 1;
1.1040    raeburn  7947:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7948:                     unless ($uri =~ m{\.\./}) {
                   7949:                         $ownaccess = 1;
                   7950:                     }
                   7951:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7952:                     my $now = time;
                   7953:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7954:                         my $adom = $1;
                   7955:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7956:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7957:                                 my ($start,$end) = split('.',$env{$key});
                   7958:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7959:                                     $ownaccess = 1;
                   7960:                                     last;
                   7961:                                 }
                   7962:                             }
                   7963:                         }
                   7964:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7965:                         my $adom = $1;
                   7966:                         my $aname = $2;
1.1042    raeburn  7967:                         foreach my $role ('ca','aa') { 
                   7968:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7969:                                 my ($start,$end) =
                   7970:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7971:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7972:                                     $ownaccess = 1;
                   7973:                                     last;
                   7974:                                 }
1.1039    raeburn  7975:                             }
                   7976:                         }
                   7977:                     }
                   7978:                 }
                   7979:             }
                   7980:         }
                   7981:     }
                   7982: 
1.52      www      7983: # Course
                   7984: 
1.620     albertel 7985:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7986:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7987:             $thisallowed.=$1;
                   7988:         }
1.52      www      7989:     }
1.29      www      7990: 
1.52      www      7991: # Domain
                   7992: 
1.620     albertel 7993:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7994:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7995:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7996:             $thisallowed.=$1;
                   7997:         }
1.12      www      7998:     }
1.52      www      7999: 
1.1141    raeburn  8000: # User who is not author or co-author might still be able to edit
                   8001: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8002:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8003:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8004:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8005:             $thisallowed.=$1;
                   8006:         }
                   8007:     }
                   8008: 
1.52      www      8009: # Course: uri itself is a course
1.66      www      8010:     my $courseuri=$uri;
                   8011:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8012:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8013: 
1.620     albertel 8014:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8015:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8016:         if ($priv eq 'mip') {
                   8017:             my $rem = $1;
                   8018:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8019:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8020:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8021:                 if ($cdom ne '') {
                   8022:                     my %passwdconf = &get_passwdconf($cdom);
                   8023:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8024:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8025:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8026:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8027:                                 unless (@inststatuses) {
                   8028:                                     @inststatuses = ('default');
                   8029:                                 }
                   8030:                                 foreach my $status (@inststatuses) {
                   8031:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8032:                                         $thisallowed.=$rem;
                   8033:                                     }
                   8034:                                 }
                   8035:                             }
                   8036:                         }
                   8037:                     }
                   8038:                 }
                   8039:             }
                   8040:         } else {
                   8041:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8042:                 $thisallowed.=$1;
                   8043:             }
1.1039    raeburn  8044:         }
1.12      www      8045:     }
1.29      www      8046: 
1.665     albertel 8047: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8048: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8049:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8050: 	$thisallowed='';
1.671     raeburn  8051:         my ($match)=&is_on_map($uri);
                   8052:         if ($match) {
                   8053:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8054:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8055:                 my $value = $1;
                   8056:                 if ($noblockcheck) {
                   8057:                     $thisallowed.=$value;
1.1162    raeburn  8058:                 } else {
1.1172.2.118.  .8(raebu 8059:20):                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8060:                     if (@blockers > 0) {
                   8061:                         $thisallowed = 'B';
                   8062:                     } else {
                   8063:                         $thisallowed.=$value;
                   8064:                     }
1.1162    raeburn  8065:                 }
1.671     raeburn  8066:             }
                   8067:         } else {
1.705     albertel 8068:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8069:             if ($refuri) {
                   8070:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8071:                     $thisallowed='F';
1.671     raeburn  8072:                 } else {
                   8073:                     $refuri=&declutter($refuri);
                   8074:                     my ($match) = &is_on_map($refuri);
                   8075:                     if ($match) {
1.1172.2.65  raeburn  8076:                         if ($noblockcheck) {
1.1162    raeburn  8077:                             $thisallowed='F';
1.1172.2.65  raeburn  8078:                         } else {
1.1172.2.118.  .8(raebu 8079:20):                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8080:                             if (@blockers > 0) {
                   8081:                                 $thisallowed = 'B';
                   8082:                             } else {
                   8083:                                 $thisallowed='F';
                   8084:                             }
1.1162    raeburn  8085:                         }
1.671     raeburn  8086:                     }
1.669     raeburn  8087:                 }
1.671     raeburn  8088:             }
                   8089:         }
1.314     www      8090:     }
1.492     albertel 8091: 
1.766     albertel 8092:     if ($priv eq 'bre'
                   8093: 	&& $thisallowed ne 'F' 
                   8094: 	&& $thisallowed ne '2'
                   8095: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8096: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8097:     }
1.1172.2.118.  .8(raebu 8098:20): 
1.52      www      8099: # Full access at system, domain or course-wide level? Exit.
1.29      www      8100:     if ($thisallowed=~/F/) {
                   8101: 	return 'F';
                   8102:     }
                   8103: 
1.52      www      8104: # If this is generating or modifying users, exit with special codes
1.29      www      8105: 
1.643     www      8106:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8107: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8108: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8109: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8110: 	    unless ($auname) { return $thisallowed; }
                   8111: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8112: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8113: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8114: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8115: 	}
1.52      www      8116: 	return $thisallowed;
                   8117:     }
                   8118: #
1.103     harris41 8119: # Gathered so far: system, domain and course wide privileges
1.52      www      8120: #
                   8121: # Course: See if uri or referer is an individual resource that is part of 
                   8122: # the course
                   8123: 
1.620     albertel 8124:     if ($env{'request.course.id'}) {
1.232     www      8125: 
1.1172.2.115  raeburn  8126: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8127: 
                   8128:         if ($priv eq 'mip') {
                   8129:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8130:                 return $thisallowed;
                   8131:             } else {
                   8132:                 return '';
                   8133:             }
                   8134:         }
                   8135: 
1.620     albertel 8136:        $courseprivid=$env{'request.course.id'};
                   8137:        if ($env{'request.course.sec'}) {
                   8138:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8139:        }
                   8140:        $courseprivid=~s/\_/\//;
                   8141:        my $checkreferer=1;
1.232     www      8142:        my ($match,$cond)=&is_on_map($uri);
                   8143:        if ($match) {
                   8144:            $statecond=$cond;
1.620     albertel 8145:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8146:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8147:                my $value = $1;
                   8148:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8149:                    if ($noblockcheck) {
1.1162    raeburn  8150:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8151:                    } else {
1.1172.2.118.  .8(raebu 8152:20):                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8153:                        if (@blockers > 0) {
                   8154:                            $thisallowed = 'B';
                   8155:                        } else {
                   8156:                            $thisallowed.=$value;
                   8157:                        }
1.1162    raeburn  8158:                    }
                   8159:                } else {
                   8160:                    $thisallowed.=$value;
                   8161:                }
1.52      www      8162:                $checkreferer=0;
                   8163:            }
1.29      www      8164:        }
1.1172.2.118.  .8(raebu 8165:20): 
1.148     www      8166:        if ($checkreferer) {
1.620     albertel 8167: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8168:             unless ($refuri) {
1.800     albertel 8169:                 foreach my $key (keys(%env)) {
                   8170: 		    if ($key=~/^httpref\..*\*/) {
                   8171: 			my $pattern=$key;
1.156     www      8172:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8173:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8174:                         $pattern=~s/\//\\\//g;
1.152     www      8175:                         if ($orguri=~/$pattern/) {
1.800     albertel 8176: 			    $refuri=$env{$key};
1.148     www      8177:                         }
                   8178:                     }
1.191     harris41 8179:                 }
1.148     www      8180:             }
1.232     www      8181: 
1.148     www      8182:          if ($refuri) { 
1.152     www      8183: 	  $refuri=&declutter($refuri);
1.232     www      8184:           my ($match,$cond)=&is_on_map($refuri);
                   8185:             if ($match) {
                   8186:               my $refstatecond=$cond;
1.620     albertel 8187:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8188:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8189:                   my $value = $1;
                   8190:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8191:                       if ($noblockcheck) {
1.1162    raeburn  8192:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8193:                       } else {
1.1172.2.118.  .8(raebu 8194:20):                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8195:                           if (@blockers > 0) {
                   8196:                               $thisallowed = 'B';
                   8197:                           } else {
                   8198:                               $thisallowed.=$value;
                   8199:                           }
1.1162    raeburn  8200:                       }
                   8201:                   } else {
                   8202:                       $thisallowed.=$value;
                   8203:                   }
1.53      www      8204:                   $uri=$refuri;
                   8205:                   $statecond=$refstatecond;
1.52      www      8206:               }
                   8207:           }
1.148     www      8208:         }
1.29      www      8209:        }
1.52      www      8210:    }
1.29      www      8211: 
1.52      www      8212: #
1.103     harris41 8213: # Gathered now: all privileges that could apply, and condition number
1.52      www      8214: # 
                   8215: #
                   8216: # Full or no access?
                   8217: #
1.29      www      8218: 
1.52      www      8219:     if ($thisallowed=~/F/) {
                   8220: 	return 'F';
                   8221:     }
1.29      www      8222: 
1.52      www      8223:     unless ($thisallowed) {
                   8224:         return '';
                   8225:     }
1.29      www      8226: 
1.52      www      8227: # Restrictions exist, deal with them
                   8228: #
                   8229: #   C:according to course preferences
                   8230: #   R:according to resource settings
                   8231: #   L:unless locked
                   8232: #   X:according to user session state
                   8233: #
                   8234: 
                   8235: # Possibly locked functionality, check all courses
1.54      www      8236: # Locks might take effect only after 10 minutes cache expiration for other
                   8237: # courses, and 2 minutes for current course
1.52      www      8238: 
                   8239:     my $envkey;
                   8240:     if ($thisallowed=~/L/) {
1.1000    raeburn  8241:         foreach $envkey (keys(%env)) {
1.54      www      8242:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8243:                my $courseid=$2;
                   8244:                my $roleid=$1.'.'.$2;
1.92      www      8245:                $courseid=~s/^\///;
1.54      www      8246:                my $expiretime=600;
1.620     albertel 8247:                if ($env{'request.role'} eq $roleid) {
1.54      www      8248: 		  $expiretime=120;
                   8249:                }
                   8250: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8251:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8252:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8253: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8254:                }
1.620     albertel 8255:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8256:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8257: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8258:                        &log($env{'user.domain'},$env{'user.name'},
                   8259:                             $env{'user.home'},
1.57      www      8260:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8261:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8262:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8263: 		       return '';
                   8264:                    }
                   8265:                }
1.620     albertel 8266:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8267:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8268: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8269:                        &log($env{'user.domain'},$env{'user.name'},
                   8270:                             $env{'user.home'},
1.57      www      8271:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8272:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8273:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8274: 		       return '';
                   8275:                    }
                   8276:                }
                   8277: 	   }
1.29      www      8278:        }
1.52      www      8279:     }
1.1172.2.118.  .8(raebu 8280:20): 
1.52      www      8281: #
                   8282: # Rest of the restrictions depend on selected course
                   8283: #
                   8284: 
1.620     albertel 8285:     unless ($env{'request.course.id'}) {
1.766     albertel 8286: 	if ($thisallowed eq 'A') {
                   8287: 	    return 'A';
1.814     raeburn  8288:         } elsif ($thisallowed eq 'B') {
                   8289:             return 'B';
1.766     albertel 8290: 	} else {
                   8291: 	    return '1';
                   8292: 	}
1.52      www      8293:     }
1.29      www      8294: 
1.52      www      8295: #
                   8296: # Now user is definitely in a course
                   8297: #
1.53      www      8298: 
                   8299: 
                   8300: # Course preferences
                   8301: 
                   8302:    if ($thisallowed=~/C/) {
1.620     albertel 8303:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8304:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8305:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8306: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8307: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8308: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8309: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8310: 			$env{'request.course.id'});
                   8311: 	   }
1.237     www      8312:            return '';
                   8313:        }
                   8314: 
1.620     albertel 8315:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8316: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8317: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8318: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8319: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8320: 			$env{'request.course.id'});
                   8321: 	   }
1.54      www      8322:            return '';
                   8323:        }
1.53      www      8324:    }
                   8325: 
                   8326: # Resource preferences
                   8327: 
                   8328:    if ($thisallowed=~/R/) {
1.620     albertel 8329:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8330:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8331: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8332: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8333: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8334: 	   }
                   8335: 	   return '';
1.54      www      8336:        }
1.53      www      8337:    }
1.30      www      8338: 
1.246     www      8339: # Restricted by state or randomout?
1.30      www      8340: 
1.52      www      8341:    if ($thisallowed=~/X/) {
1.620     albertel 8342:       if ($env{'acc.randomout'}) {
1.579     albertel 8343: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8344:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8345:             return ''; 
                   8346:          }
1.247     www      8347:       }
                   8348:       if (&condval($statecond)) {
1.52      www      8349: 	 return '2';
                   8350:       } else {
                   8351:          return '';
                   8352:       }
                   8353:    }
1.30      www      8354: 
1.766     albertel 8355:     if ($thisallowed eq 'A') {
                   8356: 	return 'A';
1.814     raeburn  8357:     } elsif ($thisallowed eq 'B') {
                   8358:         return 'B';
1.766     albertel 8359:     }
1.52      www      8360:    return 'F';
1.232     www      8361: }
1.1162    raeburn  8362: 
1.1172.2.13  raeburn  8363: # ------------------------------------------- Check construction space access
                   8364: 
                   8365: sub constructaccess {
                   8366:     my ($url,$setpriv)=@_;
                   8367: 
                   8368: # We do not allow editing of previous versions of files
                   8369:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8370: 
                   8371: # Get username and domain from URL
                   8372:     my ($ownername,$ownerdomain,$ownerhome);
                   8373: 
                   8374:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8375:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8376: 
                   8377: # The URL does not really point to any authorspace, forget it
                   8378:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8379: 
                   8380: # Now we need to see if the user has access to the authorspace of
                   8381: # $ownername at $ownerdomain
                   8382: 
                   8383:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8384: # Real author for this?
                   8385:        $ownerhome = $env{'user.home'};
                   8386:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8387:           return ($ownername,$ownerdomain,$ownerhome);
                   8388:        }
                   8389:     } else {
                   8390: # Co-author for this?
                   8391:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8392:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8393:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8394:             return ($ownername,$ownerdomain,$ownerhome);
                   8395:         }
                   8396:     }
                   8397: 
                   8398: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8399: # we might as well leave
                   8400:    unless ($setpriv) { return ''; }
                   8401: 
                   8402: # Backdoor access?
                   8403:     my $allowed=&allowed('eco',$ownerdomain);
                   8404: # Nope
                   8405:     unless ($allowed) { return ''; }
                   8406: # Looks like we may have access, but could be locked by the owner of the construction space
                   8407:     if ($allowed eq 'U') {
                   8408:         my %blocked=&get('environment',['domcoord.author'],
                   8409:                          $ownerdomain,$ownername);
                   8410: # Is blocked by owner
                   8411:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8412:     }
                   8413:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8414: # Grant temporary access
                   8415:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8416:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8417:         if (!$update) { $update = $then; }
                   8418:         my $refresh=$env{'user.refresh.time'};
                   8419:         if (!$refresh) { $refresh = $update; }
                   8420:         my $now = time;
                   8421:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8422:                            $now,'ca','constructaccess');
                   8423:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8424:         return($ownername,$ownerdomain,$ownerhome);
                   8425:     }
                   8426: # No business here
                   8427:     return '';
                   8428: }
                   8429: 
1.1172.2.66  raeburn  8430: # ----------------------------------------------------------- Content Blocking
                   8431: 
                   8432: {
                   8433: # Caches for faster Course Contents display where content blocking
                   8434: # is in operation (i.e., interval param set) for timed quiz.
                   8435: #
                   8436: # User for whom data are being temporarily cached.
                   8437: my $cacheduser='';
1.1172.2.118.  .8(raebu 8438:20): # Course for which data are being temporarily cached.
                   8439:20): my $cachedcid='';
1.1172.2.66  raeburn  8440: # Cached blockers for this user (a hash of blocking items).
                   8441: my %cachedblockers=();
                   8442: # When the data were last cached.
                   8443: my $cachedlast='';
                   8444: 
                   8445: sub load_all_blockers {
1.1172.2.118.  .9(raebu 8446:20):     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8447:     if (($uname ne '') && ($udom ne '')) {
                   8448:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.118.  .8(raebu 8449:20):             ($cachedcid eq $env{'request.course.id'}) &&
          .9(raebu 8450:20):             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8451:             return;
                   8452:         }
                   8453:     }
                   8454:     $cachedlast=time;
                   8455:     $cacheduser=$uname.':'.$udom;
1.1172.2.118.  .8(raebu 8456:20):     $cachedcid=$env{'request.course.id'};
          .9(raebu 8457:20):     %cachedblockers = &get_commblock_resources();
          .8(raebu 8458:20):     return;
1.1172.2.66  raeburn  8459: }
                   8460: 
1.1162    raeburn  8461: sub get_comm_blocks {
                   8462:     my ($cdom,$cnum) = @_;
                   8463:     if ($cdom eq '' || $cnum eq '') {
                   8464:         return unless ($env{'request.course.id'});
                   8465:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8466:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8467:     }
                   8468:     my %commblocks;
                   8469:     my $hashid=$cdom.'_'.$cnum;
                   8470:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8471:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8472:         %commblocks = %{$blocksref};
                   8473:     } else {
                   8474:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8475:         my $cachetime = 600;
                   8476:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8477:     }
                   8478:     return %commblocks;
                   8479: }
                   8480: 
1.1172.2.66  raeburn  8481: sub get_commblock_resources {
                   8482:     my ($blocks) = @_;
                   8483:     my %blockers = ();
                   8484:     return %blockers unless ($env{'request.course.id'});
                   8485:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8486:     my %commblocks;
                   8487:     if (ref($blocks) eq 'HASH') {
                   8488:         %commblocks = %{$blocks};
                   8489:     } else {
                   8490:         %commblocks = &get_comm_blocks();
                   8491:     }
1.1172.2.66  raeburn  8492:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8493:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8494:     return %blockers unless (ref($navmap));
                   8495:     my $now = time;
1.1162    raeburn  8496:     foreach my $block (keys(%commblocks)) {
                   8497:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8498:             my ($start,$end) = ($1,$2);
                   8499:             if ($start <= $now && $end >= $now) {
                   8500:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8501:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8502:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8503:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8504:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8505:                             }
                   8506:                         }
                   8507:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8508:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8509:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8510:                             }
                   8511:                         }
                   8512:                     }
                   8513:                 }
                   8514:             }
                   8515:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8516:             my $item = $1;
1.1163    raeburn  8517:             my @to_test;
1.1162    raeburn  8518:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8519:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8520:                     my @interval;
                   8521:                     my $type = 'map';
                   8522:                     if ($item eq 'course') {
                   8523:                         $type = 'course';
                   8524:                         @interval=&EXT("resource.0.interval");
                   8525:                     } else {
                   8526:                         if ($item =~ /___\d+___/) {
                   8527:                             $type = 'resource';
                   8528:                             @interval=&EXT("resource.0.interval",$item);
                   8529:                             if (ref($navmap)) {
                   8530:                                 my $res = $navmap->getBySymb($item);
                   8531:                                 push(@to_test,$res);
                   8532:                             }
1.1162    raeburn  8533:                         } else {
1.1172.2.66  raeburn  8534:                             my $mapsymb = &symbread($item,1);
                   8535:                             if ($mapsymb) {
                   8536:                                 if (ref($navmap)) {
                   8537:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8538:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8539:                                     foreach my $res (@to_test) {
                   8540:                                         my $symb = $res->symb();
                   8541:                                         next if ($symb eq $mapsymb);
                   8542:                                         if ($symb ne '') {
                   8543:                                             @interval=&EXT("resource.0.interval",$symb);
                   8544:                                             if ($interval[1] eq 'map') {
                   8545:                                                 last;
1.1162    raeburn  8546:                                             }
                   8547:                                         }
                   8548:                                     }
                   8549:                                 }
                   8550:                             }
                   8551:                         }
1.1172.2.66  raeburn  8552:                     }
1.1172.2.118.  .1(raebu 8553:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8554:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8555:                         my $first_access;
                   8556:                         if ($type eq 'resource') {
                   8557:                             $first_access=&get_first_access($interval[1],$item);
                   8558:                         } elsif ($type eq 'map') {
                   8559:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8560:                         } else {
                   8561:                             $first_access=&get_first_access($interval[1]);
                   8562:                         }
                   8563:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8564:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8565:                             if ($timesup > $now) {
                   8566:                                 my $activeblock;
                   8567:                                 foreach my $res (@to_test) {
                   8568:                                     if ($res->answerable()) {
                   8569:                                         $activeblock = 1;
                   8570:                                         last;
                   8571:                                     }
                   8572:                                 }
                   8573:                                 if ($activeblock) {
                   8574:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8575:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8576:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8577:                                          }
                   8578:                                     }
                   8579:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8580:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8581:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8582:                                         }
1.1162    raeburn  8583:                                     }
                   8584:                                 }
                   8585:                             }
                   8586:                         }
                   8587:                     }
                   8588:                 }
                   8589:             }
                   8590:         }
                   8591:     }
1.1172.2.66  raeburn  8592:     return %blockers;
1.1162    raeburn  8593: }
                   8594: 
1.1172.2.66  raeburn  8595: sub has_comm_blocking {
1.1172.2.118.  .9(raebu 8596:20):     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8597:     my @blockers;
                   8598:     return unless ($env{'request.course.id'});
                   8599:     return unless ($priv eq 'bre');
                   8600:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8601:     return if ($env{'request.state'} eq 'construct');
1.1172.2.118.  .9(raebu 8602:20):     my %blockinfo;
                   8603:20):     if (ref($blocks) eq 'HASH') {
                   8604:20):         %blockinfo = &get_commblock_resources($blocks);
                   8605:20):     } else {
                   8606:20):         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8607:20):         %blockinfo = %cachedblockers;
                   8608:20):     }
                   8609:20):     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8610:     my (%possibles,@symbs);
                   8611:     if (!$symb) {
1.1172.2.118.  .9(raebu 8612:20):         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8613:     }
1.1172.2.66  raeburn  8614:     if ($symb) {
                   8615:         @symbs = ($symb);
                   8616:     } elsif (keys(%possibles)) {
                   8617:         @symbs = keys(%possibles);
                   8618:     }
                   8619:     my $noblock;
                   8620:     foreach my $symb (@symbs) {
                   8621:         last if ($noblock);
                   8622:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.118.  .9(raebu 8623:20):         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8624:             if ($block =~ /^firstaccess____(.+)$/) {
                   8625:                 my $item = $1;
1.1172.2.118.  .8(raebu 8626:20):                 unless ($blocked) {
                   8627:20):                     if (($item eq $map) || ($item eq $symb)) {
                   8628:20):                         $noblock = 1;
                   8629:20):                         last;
                   8630:20):                     }
1.1172.2.66  raeburn  8631:                 }
1.1162    raeburn  8632:             }
1.1172.2.118.  .9(raebu 8633:20):             if (ref($blockinfo{$block}) eq 'HASH') {
                   8634:20):                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8635:20):                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8636:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8637:                             push(@blockers,$block);
                   8638:                         }
                   8639:                     }
                   8640:                 }
1.1172.2.118.  .9(raebu 8641:20):                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8642:20):                     if ($blockinfo{$block}{'maps'}{$map}) {
          .8(raebu 8643:20):                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8644:20):                             push(@blockers,$block);
                   8645:20):                         }
1.1172.2.66  raeburn  8646:                     }
                   8647:                 }
1.1162    raeburn  8648:             }
                   8649:         }
                   8650:     }
1.1172.2.118.  .8(raebu 8651:20):     unless ($noblock) {
                   8652:20):         return @blockers;
                   8653:20):     }
                   8654:20):     return;
1.1172.2.66  raeburn  8655: }
1.1162    raeburn  8656: }
                   8657: 
1.1172.2.66  raeburn  8658: # -------------------------------- Deversion and split uri into path an filename
                   8659: 
1.1133    foxr     8660: #
1.1172.2.66  raeburn  8661: #   Removes the version from a URI and
1.1133    foxr     8662: #   splits it in to its filename and path to the filename.
                   8663: #   Seems like File::Basename could have done this more clearly.
                   8664: #   Parameters:
                   8665: #      $uri   - input URI
                   8666: #   Returns:
                   8667: #     Two element list consisting of 
                   8668: #     $pathname  - the URI up to and excluding the trailing /
                   8669: #     $filename  - The part of the URI following the last /
                   8670: #  NOTE:
                   8671: #    Another realization of this is simply:
                   8672: #    use File::Basename;
                   8673: #    ...
                   8674: #    $uri = shift;
                   8675: #    $filename = basename($uri);
                   8676: #    $path     = dirname($uri);
                   8677: #    return ($filename, $path);
                   8678: #
                   8679: #     The implementation below is probably faster however.
                   8680: #
1.710     albertel 8681: sub split_uri_for_cond {
                   8682:     my $uri=&deversion(&declutter(shift));
                   8683:     my @uriparts=split(/\//,$uri);
                   8684:     my $filename=pop(@uriparts);
                   8685:     my $pathname=join('/',@uriparts);
                   8686:     return ($pathname,$filename);
                   8687: }
1.232     www      8688: # --------------------------------------------------- Is a resource on the map?
                   8689: 
                   8690: sub is_on_map {
1.710     albertel 8691:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8692:     #Trying to find the conditional for the file
1.620     albertel 8693:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8694: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8695:     if ($match) {
1.289     bowersj2 8696: 	return (1,$1);
                   8697:     } else {
1.434     www      8698: 	return (0,0);
1.289     bowersj2 8699:     }
1.12      www      8700: }
                   8701: 
1.427     www      8702: # --------------------------------------------------------- Get symb from alias
                   8703: 
                   8704: sub get_symb_from_alias {
                   8705:     my $symb=shift;
                   8706:     my ($map,$resid,$url)=&decode_symb($symb);
                   8707: # Already is a symb
                   8708:     if ($url) { return $symb; }
                   8709: # Must be an alias
                   8710:     my $aliassymb='';
                   8711:     my %bighash;
1.620     albertel 8712:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8713:                             &GDBM_READER(),0640)) {
                   8714:         my $rid=$bighash{'mapalias_'.$symb};
                   8715: 	if ($rid) {
                   8716: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8717: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8718: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8719: 	}
                   8720:         untie %bighash;
                   8721:     }
                   8722:     return $aliassymb;
                   8723: }
                   8724: 
1.12      www      8725: # ----------------------------------------------------------------- Define Role
                   8726: 
                   8727: sub definerole {
                   8728:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8729:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8730:     foreach my $role (split(':',$sysrole)) {
                   8731: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8732:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8733:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8734: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8735:                return "refused:s:$crole&$cqual"; 
                   8736:             }
                   8737:         }
1.191     harris41 8738:     }
1.800     albertel 8739:     foreach my $role (split(':',$domrole)) {
                   8740: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8741:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8742:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8743: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8744:                return "refused:d:$crole&$cqual"; 
                   8745:             }
                   8746:         }
1.191     harris41 8747:     }
1.800     albertel 8748:     foreach my $role (split(':',$courole)) {
                   8749: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8750:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8751:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8752: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8753:                return "refused:c:$crole&$cqual"; 
                   8754:             }
                   8755:         }
1.191     harris41 8756:     }
1.1172.2.84  raeburn  8757:     my $uhome;
                   8758:     if (($uname ne '') && ($udom ne '')) {
                   8759:         $uhome = &homeserver($uname,$udom);
                   8760:         return $uhome if ($uhome eq 'no_host');
                   8761:     } else {
                   8762:         $uname = $env{'user.name'};
                   8763:         $udom = $env{'user.domain'};
                   8764:         $uhome = $env{'user.home'};
                   8765:     }
1.620     albertel 8766:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8767:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8768:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8769:     return reply($command,$uhome);
1.12      www      8770:   } else {
                   8771:     return 'refused';
                   8772:   }
1.105     harris41 8773: }
                   8774: 
                   8775: # ---------------- Make a metadata query against the network of library servers
                   8776: 
                   8777: sub metadata_query {
1.1172.2.33  raeburn  8778:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8779:     my %rhash;
1.845     albertel 8780:     my %libserv = &all_library();
1.244     matthew  8781:     my @server_list = (defined($server_array) ? @$server_array
                   8782:                                               : keys(%libserv) );
                   8783:     for my $server (@server_list) {
1.1172.2.33  raeburn  8784:         my $domains = '';
                   8785:         if (ref($domains_hash) eq 'HASH') {
                   8786:             $domains = $domains_hash->{$server};    
                   8787:         }
1.118     harris41 8788: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8789: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8790: 	    $rhash{$server}=$reply;
                   8791: 	}
                   8792: 	else {
                   8793: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8794: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8795: 			     $server);
                   8796: 	    $rhash{$server}=$reply;
                   8797: 	}
1.112     harris41 8798:     }
1.118     harris41 8799:     return \%rhash;
1.240     www      8800: }
                   8801: 
                   8802: # ----------------------------------------- Send log queries and wait for reply
                   8803: 
                   8804: sub log_query {
                   8805:     my ($uname,$udom,$query,%filters)=@_;
                   8806:     my $uhome=&homeserver($uname,$udom);
                   8807:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8808:     my $uhost=&hostname($uhome);
1.800     albertel 8809:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8810:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8811:                        $uhome);
1.479     albertel 8812:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8813:     return get_query_reply($queryid);
                   8814: }
                   8815: 
1.818     raeburn  8816: # -------------------------- Update MySQL table for portfolio file
                   8817: 
                   8818: sub update_portfolio_table {
1.821     raeburn  8819:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8820:     if ($group ne '') {
                   8821:         $file_name =~s /^\Q$group\E//;
                   8822:     }
1.818     raeburn  8823:     my $homeserver = &homeserver($uname,$udom);
                   8824:     my $queryid=
1.821     raeburn  8825:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8826:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8827:     my $reply = &get_query_reply($queryid);
                   8828:     return $reply;
                   8829: }
                   8830: 
1.899     raeburn  8831: # -------------------------- Update MySQL allusers table
                   8832: 
                   8833: sub update_allusers_table {
                   8834:     my ($uname,$udom,$names) = @_;
                   8835:     my $homeserver = &homeserver($uname,$udom);
                   8836:     my $queryid=
                   8837:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8838:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8839:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8840:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8841:                'generation='.&escape($names->{'generation'}).'%%'.
                   8842:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8843:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8844:     return;
1.899     raeburn  8845: }
                   8846: 
1.508     raeburn  8847: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8848: 
                   8849: sub fetch_enrollment_query {
1.511     raeburn  8850:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8851:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8852:     my $maxtries = 1;
1.508     raeburn  8853:     if ($context eq 'automated') {
                   8854:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8855:         $sleep = 2;
                   8856:         $loopmax = 100;
1.547     raeburn  8857:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8858:     } else {
                   8859:         $homeserver = &homeserver($cnum,$dom);
                   8860:     }
1.838     albertel 8861:     my $host=&hostname($homeserver);
1.506     raeburn  8862:     my $cmd = '';
1.1000    raeburn  8863:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8864:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8865:     }
                   8866:     $cmd =~ s/%%$//;
                   8867:     $cmd = &escape($cmd);
                   8868:     my $query = 'fetchenrollment';
1.620     albertel 8869:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8870:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8871:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8872:         return 'error: '.$queryid;
                   8873:     }
1.1172.2.93  raeburn  8874:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8875:     my $tries = 1;
                   8876:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8877:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8878:         $tries ++;
                   8879:     }
1.526     raeburn  8880:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8881:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8882:     } else {
1.901     albertel 8883:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8884:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8885:             foreach my $line (@responses) {
                   8886:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8887:                 $$replyref{$key} = $value;
                   8888:             }
                   8889:         } else {
1.1117    foxr     8890:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8891:             foreach my $line (@responses) {
                   8892:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8893:                 $$replyref{$key} = $value;
                   8894:                 if ($value > 0) {
1.800     albertel 8895:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8896:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8897:                         my $destname = $pathname.'/'.$filename;
                   8898:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8899:                         if ($xml_classlist =~ /^error/) {
                   8900:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8901:                         } else {
1.1172.2.96  raeburn  8902:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8903:                                 print FILE &unescape($xml_classlist);
                   8904:                                 close(FILE);
1.526     raeburn  8905:                             } else {
                   8906:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8907:                             }
                   8908:                         }
                   8909:                     }
                   8910:                 }
                   8911:             }
                   8912:         }
                   8913:         return 'ok';
                   8914:     }
                   8915:     return 'error';
                   8916: }
                   8917: 
1.242     www      8918: sub get_query_reply {
1.1172.2.79  raeburn  8919:     my ($queryid,$sleep,$loopmax) = @_;
                   8920:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8921:         $sleep = 0.2;
                   8922:     }
                   8923:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8924:         $loopmax = 100;
                   8925:     }
1.1117    foxr     8926:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8927:     my $reply='';
1.1172.2.79  raeburn  8928:     for (1..$loopmax) {
                   8929: 	sleep($sleep);
1.240     www      8930:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8931: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8932: 		$reply = join('',<$fh>);
                   8933: 		close($fh);
1.240     www      8934: 	   } else { return 'error: reply_file_error'; }
1.242     www      8935:            return &unescape($reply);
                   8936: 	}
1.240     www      8937:     }
1.242     www      8938:     return 'timeout:'.$queryid;
1.240     www      8939: }
                   8940: 
                   8941: sub courselog_query {
1.241     www      8942: #
                   8943: # possible filters:
                   8944: # url: url or symb
                   8945: # username
                   8946: # domain
                   8947: # action: view, submit, grade
                   8948: # start: timestamp
                   8949: # end: timestamp
                   8950: #
1.240     www      8951:     my (%filters)=@_;
1.620     albertel 8952:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8953:     if ($filters{'url'}) {
                   8954: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8955:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8956:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8957:     }
1.620     albertel 8958:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8959:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8960:     return &log_query($cname,$cdom,'courselog',%filters);
                   8961: }
                   8962: 
                   8963: sub userlog_query {
1.858     raeburn  8964: #
                   8965: # possible filters:
                   8966: # action: log check role
                   8967: # start: timestamp
                   8968: # end: timestamp
                   8969: #
1.240     www      8970:     my ($uname,$udom,%filters)=@_;
                   8971:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8972: }
                   8973: 
1.506     raeburn  8974: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8975: 
                   8976: sub auto_run {
1.508     raeburn  8977:     my ($cnum,$cdom) = @_;
1.876     raeburn  8978:     my $response = 0;
                   8979:     my $settings;
                   8980:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8981:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8982:         $settings = $domconfig{'autoenroll'};
                   8983:         if ($settings->{'run'} eq '1') {
                   8984:             $response = 1;
                   8985:         }
                   8986:     } else {
1.934     raeburn  8987:         my $homeserver;
                   8988:         if (&is_course($cdom,$cnum)) {
                   8989:             $homeserver = &homeserver($cnum,$cdom);
                   8990:         } else {
                   8991:             $homeserver = &domain($cdom,'primary');
                   8992:         }
                   8993:         if ($homeserver ne 'no_host') {
                   8994:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8995:         }
1.876     raeburn  8996:     }
1.506     raeburn  8997:     return $response;
                   8998: }
1.776     albertel 8999: 
1.506     raeburn  9000: sub auto_get_sections {
1.508     raeburn  9001:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9002:     my $homeserver;
                   9003:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9004:         $homeserver = &homeserver($cnum,$cdom);
                   9005:     }
                   9006:     if (!defined($homeserver)) { 
                   9007:         if ($cdom =~ /^$match_domain$/) {
                   9008:             $homeserver = &domain($cdom,'primary');
                   9009:         }
                   9010:     }
                   9011:     my @secs;
                   9012:     if (defined($homeserver)) {
                   9013:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9014:         unless ($response eq 'refused') {
                   9015:             @secs = split(/:/,$response);
                   9016:         }
1.506     raeburn  9017:     }
                   9018:     return @secs;
                   9019: }
1.776     albertel 9020: 
1.506     raeburn  9021: sub auto_new_course {
1.1099    raeburn  9022:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9023:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9024:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9025:     return $response;
                   9026: }
1.776     albertel 9027: 
1.506     raeburn  9028: sub auto_validate_courseID {
1.508     raeburn  9029:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9030:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9031:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9032:     return $response;
                   9033: }
1.776     albertel 9034: 
1.1007    raeburn  9035: sub auto_validate_instcode {
1.1020    raeburn  9036:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9037:     my ($homeserver,$response);
                   9038:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9039:         $homeserver = &homeserver($cnum,$cdom);
                   9040:     }
                   9041:     if (!defined($homeserver)) {
                   9042:         if ($cdom =~ /^$match_domain$/) {
                   9043:             $homeserver = &domain($cdom,'primary');
                   9044:         }
                   9045:     }
1.1065    raeburn  9046:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9047:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9048:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9049:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9050: }
                   9051: 
1.506     raeburn  9052: sub auto_create_password {
1.873     raeburn  9053:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9054:     my ($homeserver,$response);
1.506     raeburn  9055:     my $create_passwd = 0;
                   9056:     my $authchk = '';
1.873     raeburn  9057:     if ($udom =~ /^$match_domain$/) {
                   9058:         $homeserver = &domain($udom,'primary');
                   9059:     }
                   9060:     if ($homeserver eq '') {
                   9061:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9062:             $homeserver = &homeserver($cnum,$cdom);
                   9063:         }
                   9064:     }
                   9065:     if ($homeserver eq '') {
                   9066:         $authchk = 'nodomain';
1.506     raeburn  9067:     } else {
1.873     raeburn  9068:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9069:         if ($response eq 'refused') {
                   9070:             $authchk = 'refused';
                   9071:         } else {
1.901     albertel 9072:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9073:         }
1.506     raeburn  9074:     }
                   9075:     return ($authparam,$create_passwd,$authchk);
                   9076: }
                   9077: 
1.706     raeburn  9078: sub auto_photo_permission {
                   9079:     my ($cnum,$cdom,$students) = @_;
                   9080:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9081:     my ($outcome,$perm_reqd,$conditions) = 
                   9082: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9083:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9084: 	return (undef,undef);
                   9085:     }
1.706     raeburn  9086:     return ($outcome,$perm_reqd,$conditions);
                   9087: }
                   9088: 
                   9089: sub auto_checkphotos {
                   9090:     my ($uname,$udom,$pid) = @_;
                   9091:     my $homeserver = &homeserver($uname,$udom);
                   9092:     my ($result,$resulttype);
                   9093:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9094: 				   &escape($uname).':'.&escape($pid),
                   9095: 				   $homeserver));
1.709     albertel 9096:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9097: 	return (undef,undef);
                   9098:     }
1.706     raeburn  9099:     if ($outcome) {
                   9100:         ($result,$resulttype) = split(/:/,$outcome);
                   9101:     } 
                   9102:     return ($result,$resulttype);
                   9103: }
                   9104: 
                   9105: sub auto_photochoice {
                   9106:     my ($cnum,$cdom) = @_;
                   9107:     my $homeserver = &homeserver($cnum,$cdom);
                   9108:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9109: 						       &escape($cdom),
                   9110: 						       $homeserver)));
1.709     albertel 9111:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9112: 	return (undef,undef);
                   9113:     }
1.706     raeburn  9114:     return ($update,$comment);
                   9115: }
                   9116: 
                   9117: sub auto_photoupdate {
                   9118:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9119:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9120:     my $host=&hostname($homeserver);
1.706     raeburn  9121:     my $cmd = '';
                   9122:     my $maxtries = 1;
1.800     albertel 9123:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9124:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9125:     }
                   9126:     $cmd =~ s/%%$//;
                   9127:     $cmd = &escape($cmd);
                   9128:     my $query = 'institutionalphotos';
                   9129:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9130:     unless ($queryid=~/^\Q$host\E\_/) {
                   9131:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9132:         return 'error: '.$queryid;
                   9133:     }
                   9134:     my $reply = &get_query_reply($queryid);
                   9135:     my $tries = 1;
                   9136:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9137:         $reply = &get_query_reply($queryid);
                   9138:         $tries ++;
                   9139:     }
                   9140:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9141:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9142:     } else {
                   9143:         my @responses = split(/:/,$reply);
                   9144:         my $outcome = shift(@responses); 
                   9145:         foreach my $item (@responses) {
                   9146:             my ($key,$value) = split(/=/,$item);
                   9147:             $$photo{$key} = $value;
                   9148:         }
                   9149:         return $outcome;
                   9150:     }
                   9151:     return 'error';
                   9152: }
                   9153: 
1.521     raeburn  9154: sub auto_instcode_format {
1.793     albertel 9155:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9156: 	$cat_order) = @_;
1.521     raeburn  9157:     my $courses = '';
1.772     raeburn  9158:     my @homeservers;
1.521     raeburn  9159:     if ($caller eq 'global') {
1.841     albertel 9160: 	my %servers = &get_servers($codedom,'library');
                   9161: 	foreach my $tryserver (keys(%servers)) {
                   9162: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9163: 		push(@homeservers,$tryserver);
                   9164: 	    }
1.584     raeburn  9165:         }
1.1022    raeburn  9166:     } elsif ($caller eq 'requests') {
                   9167:         if ($codedom =~ /^$match_domain$/) {
                   9168:             my $chome = &domain($codedom,'primary');
                   9169:             unless ($chome eq 'no_host') {
                   9170:                 push(@homeservers,$chome);
                   9171:             }
                   9172:         }
1.521     raeburn  9173:     } else {
1.772     raeburn  9174:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9175:     }
1.793     albertel 9176:     foreach my $code (keys(%{$instcodes})) {
                   9177:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9178:     }
                   9179:     chop($courses);
1.772     raeburn  9180:     my $ok_response = 0;
                   9181:     my $response;
                   9182:     while (@homeservers > 0 && $ok_response == 0) {
                   9183:         my $server = shift(@homeservers); 
                   9184:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9185:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9186:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9187: 		split(/:/,$response);
1.772     raeburn  9188:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9189:             push(@{$codetitles},&str2array($codetitles_str));
                   9190:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9191:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9192:             $ok_response = 1;
                   9193:         }
                   9194:     }
                   9195:     if ($ok_response) {
1.521     raeburn  9196:         return 'ok';
1.772     raeburn  9197:     } else {
                   9198:         return $response;
1.521     raeburn  9199:     }
                   9200: }
                   9201: 
1.792     raeburn  9202: sub auto_instcode_defaults {
                   9203:     my ($domain,$returnhash,$code_order) = @_;
                   9204:     my @homeservers;
1.841     albertel 9205: 
                   9206:     my %servers = &get_servers($domain,'library');
                   9207:     foreach my $tryserver (keys(%servers)) {
                   9208: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9209: 	    push(@homeservers,$tryserver);
                   9210: 	}
1.792     raeburn  9211:     }
1.841     albertel 9212: 
1.792     raeburn  9213:     my $response;
1.841     albertel 9214:     foreach my $server (@homeservers) {
1.792     raeburn  9215:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9216:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9217: 	
                   9218: 	foreach my $pair (split(/\&/,$response)) {
                   9219: 	    my ($name,$value)=split(/\=/,$pair);
                   9220: 	    if ($name eq 'code_order') {
                   9221: 		@{$code_order} = split(/\&/,&unescape($value));
                   9222: 	    } else {
                   9223: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9224: 	    }
                   9225: 	}
                   9226: 	return 'ok';
1.792     raeburn  9227:     }
1.841     albertel 9228: 
                   9229:     return $response;
1.1003    raeburn  9230: }
                   9231: 
                   9232: sub auto_possible_instcodes {
1.1007    raeburn  9233:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9234:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9235:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9236:         return;
                   9237:     }
1.1003    raeburn  9238:     my (@homeservers,$uhome);
                   9239:     if (defined(&domain($domain,'primary'))) {
                   9240:         $uhome=&domain($domain,'primary');
                   9241:         push(@homeservers,&domain($domain,'primary'));
                   9242:     } else {
                   9243:         my %servers = &get_servers($domain,'library');
                   9244:         foreach my $tryserver (keys(%servers)) {
                   9245:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9246:                 push(@homeservers,$tryserver);
                   9247:             }
                   9248:         }
                   9249:     }
                   9250:     my $response;
                   9251:     foreach my $server (@homeservers) {
                   9252:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9253:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9254:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9255:             split(':',$response);
                   9256:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9257:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9258:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9259:             my ($name,$value)=split('=',$item);
                   9260:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9261:         }
                   9262:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9263:             my ($name,$value)=split('=',$item);
                   9264:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9265:         }
                   9266:         return 'ok';
                   9267:     }
                   9268:     return $response;
                   9269: }
1.792     raeburn  9270: 
1.1010    raeburn  9271: sub auto_courserequest_checks {
                   9272:     my ($dom) = @_;
1.1020    raeburn  9273:     my ($homeserver,%validations);
                   9274:     if ($dom =~ /^$match_domain$/) {
                   9275:         $homeserver = &domain($dom,'primary');
                   9276:     }
                   9277:     unless ($homeserver eq 'no_host') {
                   9278:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9279:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9280:             my @items = split(/&/,$response);
                   9281:             foreach my $item (@items) {
                   9282:                 my ($key,$value) = split('=',$item);
                   9283:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9284:             }
                   9285:         }
                   9286:     }
1.1010    raeburn  9287:     return %validations; 
                   9288: }
                   9289: 
1.1020    raeburn  9290: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9291:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9292:     my ($homeserver,$response);
                   9293:     if ($dom =~ /^$match_domain$/) {
                   9294:         $homeserver = &domain($dom,'primary');
                   9295:     }
1.1172.2.43  raeburn  9296:     unless ($homeserver eq 'no_host') {
                   9297:         my $customdata;
                   9298:         if (ref($custominfo) eq 'HASH') {
                   9299:             $customdata = &freeze_escape($custominfo);
                   9300:         }
1.1020    raeburn  9301:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9302:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9303:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9304:                                     $customdata,$homeserver));
1.1020    raeburn  9305:     }
                   9306:     return $response;
                   9307: }
                   9308: 
1.777     albertel 9309: sub auto_validate_class_sec {
1.918     raeburn  9310:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9311:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9312:     my $ownerlist;
                   9313:     if (ref($owners) eq 'ARRAY') {
                   9314:         $ownerlist = join(',',@{$owners});
                   9315:     } else {
                   9316:         $ownerlist = $owners;
                   9317:     }
1.773     raeburn  9318:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9319:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9320:     return $response;
                   9321: }
                   9322: 
1.1172.2.94  raeburn  9323: sub auto_validate_instclasses {
                   9324:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9325:     my ($homeserver,%validations);
                   9326:     $homeserver = &homeserver($cnum,$cdom);
                   9327:     unless ($homeserver eq 'no_host') {
                   9328:         my $ownerlist;
                   9329:         if (ref($owners) eq 'ARRAY') {
                   9330:             $ownerlist = join(',',@{$owners});
                   9331:         } else {
                   9332:             $ownerlist = $owners;
                   9333:         }
                   9334:         if (ref($classesref) eq 'HASH') {
                   9335:             my $classes = &freeze_escape($classesref);
                   9336:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9337:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9338:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9339:                 my @items = split(/&/,$response);
                   9340:                 foreach my $item (@items) {
                   9341:                     my ($key,$value) = split('=',$item);
                   9342:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9343:                 }
                   9344:             }
                   9345:         }
                   9346:     }
                   9347:     return %validations;
                   9348: }
                   9349: 
1.1172.2.38  raeburn  9350: sub auto_crsreq_update {
                   9351:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9352:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9353:     my ($homeserver,%crsreqresponse);
                   9354:     if ($cdom =~ /^$match_domain$/) {
                   9355:         $homeserver = &domain($cdom,'primary');
                   9356:     }
                   9357:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9358:         my $info;
                   9359:         if (ref($inbound) eq 'HASH') {
                   9360:             $info = &freeze_escape($inbound);
                   9361:         }
                   9362:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9363:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9364:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9365:                             &escape($title).':'.&escape($code).':'.
                   9366:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9367:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9368:             my @items = split(/&/,$response);
                   9369:             foreach my $item (@items) {
                   9370:                 my ($key,$value) = split('=',$item);
                   9371:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9372:             }
                   9373:         }
                   9374:     }
                   9375:     return \%crsreqresponse;
                   9376: }
                   9377: 
1.1172.2.78  raeburn  9378: sub auto_export_grades {
                   9379:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9380:     my ($homeserver,%exportresponse);
                   9381:     if ($cdom =~ /^$match_domain$/) {
                   9382:         $homeserver = &domain($cdom,'primary');
                   9383:     }
                   9384:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9385:         my $info;
                   9386:         if (ref($inforef) eq 'HASH') {
                   9387:             $info = &freeze_escape($inforef);
                   9388:         }
                   9389:         if (ref($gradesref) eq 'HASH') {
                   9390:             my $grades = &freeze_escape($gradesref);
                   9391:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9392:                                 $info.':'.$grades,$homeserver);
                   9393:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9394:                 my @items = split(/&/,$response);
                   9395:                 foreach my $item (@items) {
                   9396:                     my ($key,$value) = split('=',$item);
                   9397:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9398:                 }
                   9399:             }
                   9400:         }
                   9401:     }
                   9402:     return \%exportresponse;
                   9403: }
                   9404: 
1.1172.2.68  raeburn  9405: sub check_instcode_cloning {
                   9406:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9407:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9408:         return;
                   9409:     }
                   9410:     my $canclone;
                   9411:     if (@{$code_order} > 0) {
                   9412:         my $instcoderegexp ='^';
                   9413:         my @clonecodes = split(/\&/,$cloner);
                   9414:         foreach my $item (@{$code_order}) {
                   9415:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9416:                 foreach my $pair (@clonecodes) {
                   9417:                     my ($key,$val) = split(/\=/,$pair,2);
                   9418:                     $val = &unescape($val);
                   9419:                     if ($key eq $item) {
                   9420:                         $instcoderegexp .= '('.$val.')';
                   9421:                         last;
                   9422:                     }
                   9423:                 }
                   9424:             } else {
                   9425:                 $instcoderegexp .= $codedefaults->{$item};
                   9426:             }
                   9427:         }
                   9428:         $instcoderegexp .= '$';
                   9429:         my (@from,@to);
                   9430:         eval {
                   9431:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9432:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9433:         };
                   9434:         if ((@from > 0) && (@to > 0)) {
                   9435:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9436:             if (!@diffs) {
                   9437:                 $canclone = 1;
                   9438:             }
                   9439:         }
                   9440:     }
                   9441:     return $canclone;
                   9442: }
                   9443: 
                   9444: sub default_instcode_cloning {
                   9445:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9446:     my (%codedefaults,@code_order,$canclone);
                   9447:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9448:         %codedefaults = %{$codedefaultsref};
                   9449:         @code_order = @{$codeorderref};
                   9450:     } elsif ($clonedom) {
                   9451:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9452:     }
                   9453:     if (($domdefclone) && (@code_order)) {
                   9454:         my @clonecodes = split(/\+/,$domdefclone);
                   9455:         my $instcoderegexp ='^';
                   9456:         foreach my $item (@code_order) {
                   9457:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9458:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9459:             } else {
                   9460:                 $instcoderegexp .= $codedefaults{$item};
                   9461:             }
                   9462:         }
                   9463:         $instcoderegexp .= '$';
                   9464:         my (@from,@to);
                   9465:         eval {
                   9466:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9467:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9468:         };
                   9469:         if ((@from > 0) && (@to > 0)) {
                   9470:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9471:             if (!@diffs) {
                   9472:                 $canclone = 1;
                   9473:             }
                   9474:         }
                   9475:     }
                   9476:     return $canclone;
                   9477: }
                   9478: 
1.679     raeburn  9479: # ------------------------------------------------------- Course Group routines
                   9480: 
                   9481: sub get_coursegroups {
1.809     raeburn  9482:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9483:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9484: }
                   9485: 
1.679     raeburn  9486: sub modify_coursegroup {
                   9487:     my ($cdom,$cnum,$groupsettings) = @_;
                   9488:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9489: }
                   9490: 
1.809     raeburn  9491: sub toggle_coursegroup_status {
                   9492:     my ($cdom,$cnum,$group,$action) = @_;
                   9493:     my ($from_namespace,$to_namespace);
                   9494:     if ($action eq 'delete') {
                   9495:         $from_namespace = 'coursegroups';
                   9496:         $to_namespace = 'deleted_groups';
                   9497:     } else {
                   9498:         $from_namespace = 'deleted_groups';
                   9499:         $to_namespace = 'coursegroups';
                   9500:     }
                   9501:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9502:     if (my $tmp = &error(%curr_group)) {
                   9503:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9504:         return ('read error',$tmp);
                   9505:     } else {
                   9506:         my %savedsettings = %curr_group; 
1.809     raeburn  9507:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9508:         my $deloutcome;
                   9509:         if ($result eq 'ok') {
1.809     raeburn  9510:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9511:         } else {
                   9512:             return ('write error',$result);
                   9513:         }
                   9514:         if ($deloutcome eq 'ok') {
                   9515:             return 'ok';
                   9516:         } else {
                   9517:             return ('delete error',$deloutcome);
                   9518:         }
                   9519:     }
                   9520: }
                   9521: 
1.679     raeburn  9522: sub modify_group_roles {
1.957     raeburn  9523:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9524:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9525:     my $role = 'gr/'.&escape($userprivs);
                   9526:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9527:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9528:     if ($result eq 'ok') {
                   9529:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9530:     }
1.679     raeburn  9531:     return $result;
                   9532: }
                   9533: 
                   9534: sub modify_coursegroup_membership {
                   9535:     my ($cdom,$cnum,$membership) = @_;
                   9536:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9537:     return $result;
                   9538: }
                   9539: 
1.682     raeburn  9540: sub get_active_groups {
                   9541:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9542:     my $now = time;
                   9543:     my %groups = ();
                   9544:     foreach my $key (keys(%env)) {
1.811     albertel 9545:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9546:             my ($start,$end) = split(/\./,$env{$key});
                   9547:             if (($end!=0) && ($end<$now)) { next; }
                   9548:             if (($start!=0) && ($start>$now)) { next; }
                   9549:             if ($1 eq $cdom && $2 eq $cnum) {
                   9550:                 $groups{$3} = $env{$key} ;
                   9551:             }
                   9552:         }
                   9553:     }
                   9554:     return %groups;
                   9555: }
                   9556: 
1.683     raeburn  9557: sub get_group_membership {
                   9558:     my ($cdom,$cnum,$group) = @_;
                   9559:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9560: }
                   9561: 
                   9562: sub get_users_groups {
                   9563:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9564:     my @usersgroups;
1.683     raeburn  9565:     my $cachetime=1800;
                   9566: 
                   9567:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9568:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9569:     if (defined($cached)) {
1.734     albertel 9570:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9571:     } else {  
                   9572:         $grouplist = '';
1.816     raeburn  9573:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9574:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9575:         my $access_end = $env{'course.'.$courseid.
                   9576:                               '.default_enrollment_end_date'};
                   9577:         my $now = time;
                   9578:         foreach my $key (keys(%roleshash)) {
                   9579:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9580:                 my $group = $1;
                   9581:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9582:                     my $start = $2;
                   9583:                     my $end = $1;
                   9584:                     if ($start == -1) { next; } # deleted from group
                   9585:                     if (($start!=0) && ($start>$now)) { next; }
                   9586:                     if (($end!=0) && ($end<$now)) {
                   9587:                         if ($access_end && $access_end < $now) {
                   9588:                             if ($access_end - $end < 86400) {
                   9589:                                 push(@usersgroups,$group);
1.733     raeburn  9590:                             }
                   9591:                         }
1.817     raeburn  9592:                         next;
1.733     raeburn  9593:                     }
1.817     raeburn  9594:                     push(@usersgroups,$group);
1.683     raeburn  9595:                 }
                   9596:             }
                   9597:         }
1.817     raeburn  9598:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9599:         $grouplist = join(':',@usersgroups);
                   9600:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9601:     }
1.733     raeburn  9602:     return @usersgroups;
1.683     raeburn  9603: }
                   9604: 
                   9605: sub devalidate_getgroups_cache {
                   9606:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9607:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9608: 
1.683     raeburn  9609:     my $hashid="$udom:$uname:$courseid";
                   9610:     &devalidate_cache_new('getgroups',$hashid);
                   9611: }
                   9612: 
1.12      www      9613: # ------------------------------------------------------------------ Plain Text
                   9614: 
                   9615: sub plaintext {
1.988     raeburn  9616:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9617:     if ($short =~ m{^cr/}) {
1.758     albertel 9618: 	return (split('/',$short))[-1];
                   9619:     }
1.742     raeburn  9620:     if (!defined($cid)) {
                   9621:         $cid = $env{'request.course.id'};
                   9622:     }
                   9623:     my %rolenames = (
1.1008    raeburn  9624:                       Course    => 'std',
                   9625:                       Community => 'alt1',
1.742     raeburn  9626:                     );
1.1037    raeburn  9627:     if ($cid ne '') {
                   9628:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9629:             unless ($forcedefault) {
                   9630:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9631:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9632:                 return &Apache::lonlocal::mt($roletext);
                   9633:             }
                   9634:         }
                   9635:     }
                   9636:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9637:         (defined($rolenames{$type})) && 
                   9638:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9639:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9640:     } elsif ($cid ne '') {
                   9641:         my $crstype = $env{'course.'.$cid.'.type'};
                   9642:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9643:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9644:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9645:         }
1.742     raeburn  9646:     }
1.1037    raeburn  9647:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9648: }
                   9649: 
                   9650: # ----------------------------------------------------------------- Assign Role
                   9651: 
                   9652: sub assignrole {
1.957     raeburn  9653:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9654:         $context)=@_;
1.21      www      9655:     my $mrole;
                   9656:     if ($role =~ /^cr\//) {
1.393     www      9657:         my $cwosec=$url;
1.811     albertel 9658:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9659: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9660:            my $refused = 1;
                   9661:            if ($context eq 'requestcourses') {
                   9662:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9663:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9664:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9665:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9666:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9667:                            if ($crsenv{'internal.courseowner'} eq
                   9668:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9669:                                $refused = '';
                   9670:                            }
                   9671:                        }
                   9672:                    }
                   9673:                }
                   9674:            }
                   9675:            if ($refused) {
                   9676:                &logthis('Refused custom assignrole: '.
                   9677:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9678:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9679:                return 'refused';
                   9680:            }
1.104     www      9681:         }
1.21      www      9682:         $mrole='cr';
1.678     raeburn  9683:     } elsif ($role =~ /^gr\//) {
                   9684:         my $cwogrp=$url;
1.811     albertel 9685:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9686:         unless (&allowed('mdg',$cwogrp)) {
                   9687:             &logthis('Refused group assignrole: '.
                   9688:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9689:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9690:             return 'refused';
                   9691:         }
                   9692:         $mrole='gr';
1.21      www      9693:     } else {
1.82      www      9694:         my $cwosec=$url;
1.811     albertel 9695:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9696:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9697:             my $refused;
                   9698:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9699:                 if (!(&allowed('c'.$role,$url))) {
                   9700:                     $refused = 1;
                   9701:                 }
                   9702:             } else {
                   9703:                 $refused = 1;
                   9704:             }
1.947     raeburn  9705:             if ($refused) {
1.1045    raeburn  9706:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9707:                 if (!$selfenroll && $context eq 'course') {
                   9708:                     my %crsenv;
                   9709:                     if ($role eq 'cc' || $role eq 'co') {
                   9710:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9711:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9712:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9713:                                 if ($crsenv{'internal.courseowner'} eq 
                   9714:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9715:                                     $refused = '';
                   9716:                                 }
                   9717:                             }
                   9718:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9719:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9720:                                 if ($crsenv{'internal.courseowner'} eq 
                   9721:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9722:                                     $refused = '';
                   9723:                                 }
                   9724:                             }
                   9725:                         }
                   9726:                     }
                   9727:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9728:                     $refused = '';
1.1017    raeburn  9729:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9730:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9731:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9732:                         my $wrongcc;
                   9733:                         if ($cnum =~ /^$match_community$/) {
                   9734:                             $wrongcc = 1 if ($role eq 'cc');
                   9735:                         } else {
                   9736:                             $wrongcc = 1 if ($role eq 'co');
                   9737:                         }
                   9738:                         unless ($wrongcc) {
                   9739:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9740:                             if ($crsenv{'internal.courseowner'} eq 
                   9741:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9742:                                 $refused = '';
                   9743:                             }
1.1017    raeburn  9744:                         }
                   9745:                     }
1.1172.2.9  raeburn  9746:                 } elsif ($context eq 'requestauthor') {
                   9747:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9748:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9749:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9750:                             $refused = '';
                   9751:                         } else {
                   9752:                             my %domdefaults = &get_domain_defaults($udom);
                   9753:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9754:                                 my $checkbystatus;
                   9755:                                 if ($env{'user.adv'}) {
                   9756:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9757:                                     if ($disposition eq 'automatic') {
                   9758:                                         $refused = '';
                   9759:                                     } elsif ($disposition eq '') {
                   9760:                                         $checkbystatus = 1;
                   9761:                                     }
                   9762:                                 } else {
                   9763:                                     $checkbystatus = 1;
                   9764:                                 }
                   9765:                                 if ($checkbystatus) {
                   9766:                                     if ($env{'environment.inststatus'}) {
                   9767:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9768:                                         foreach my $type (@inststatuses) {
                   9769:                                             if (($type ne '') &&
                   9770:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9771:                                                 $refused = '';
                   9772:                                             }
                   9773:                                         }
                   9774:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9775:                                         $refused = '';
                   9776:                                     }
                   9777:                                 }
                   9778:                             }
                   9779:                         }
                   9780:                     }
1.1017    raeburn  9781:                 }
                   9782:                 if ($refused) {
1.947     raeburn  9783:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9784:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9785: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9786:                     return 'refused';
                   9787:                 }
1.932     raeburn  9788:             }
1.1131    raeburn  9789:         } elsif ($role eq 'au') {
                   9790:             if ($url ne '/'.$udom.'/') {
                   9791:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9792:                          ' to assign author role for '.$uname.':'.$udom.
                   9793:                          ' in domain: '.$url.' refused (wrong domain).');
                   9794:                 return 'refused';
                   9795:             }
1.104     www      9796:         }
1.21      www      9797:         $mrole=$role;
                   9798:     }
1.620     albertel 9799:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9800:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9801:     if ($end) { $command.='_'.$end; }
1.21      www      9802:     if ($start) {
                   9803: 	if ($end) { 
1.81      www      9804:            $command.='_'.$start; 
1.21      www      9805:         } else {
1.81      www      9806:            $command.='_0_'.$start;
1.21      www      9807:         }
                   9808:     }
1.739     raeburn  9809:     my $origstart = $start;
                   9810:     my $origend = $end;
1.957     raeburn  9811:     my $delflag;
1.357     www      9812: # actually delete
                   9813:     if ($deleteflag) {
1.373     www      9814: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9815: # modify command to delete the role
1.620     albertel 9816:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9817:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9818: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9819: # set start and finish to negative values for userrolelog
                   9820:            $start=-1;
                   9821:            $end=-1;
1.957     raeburn  9822:            $delflag = 1;
1.357     www      9823:         }
                   9824:     }
                   9825: # send command
1.349     www      9826:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9827: # log new user role if status is ok
1.349     www      9828:     if ($answer eq 'ok') {
1.663     raeburn  9829: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9830:         if (($role eq 'cc') || ($role eq 'in') ||
                   9831:             ($role eq 'ep') || ($role eq 'ad') ||
                   9832:             ($role eq 'ta') || ($role eq 'st') ||
                   9833:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9834:             ($role eq 'co')) {
1.1172.2.13  raeburn  9835: # for course roles, perform group memberships changes triggered by role change.
                   9836:             unless ($role =~ /^gr/) {
                   9837:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9838:                                                  $origstart,$selfenroll,$context);
                   9839:             }
1.1172.2.9  raeburn  9840:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9841:                            $selfenroll,$context);
                   9842:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9843:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9844:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9845:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9846:                            $context);
                   9847:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9848:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9849:                              $context);
                   9850:         }
1.1053    raeburn  9851:         if ($role eq 'cc') {
                   9852:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9853:         }
1.349     www      9854:     }
                   9855:     return $answer;
1.169     harris41 9856: }
                   9857: 
1.1053    raeburn  9858: sub autoupdate_coowners {
                   9859:     my ($url,$end,$start,$uname,$udom) = @_;
                   9860:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9861:     if (($cdom ne '') && ($cnum ne '')) {
                   9862:         my $now = time;
                   9863:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9864:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9865:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9866:             my $instcode = $coursehash{'internal.coursecode'};
                   9867:             if ($instcode ne '') {
1.1056    raeburn  9868:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9869:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9870:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9871:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9872:                         if ($result eq 'valid') {
                   9873:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9874:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9875:                                     push(@newcoowners,$coowner);
                   9876:                                 }
                   9877:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9878:                                     push(@newcoowners,$uname.':'.$udom);
                   9879:                                 }
                   9880:                                 @newcoowners = sort(@newcoowners);
                   9881:                             } else {
                   9882:                                 push(@newcoowners,$uname.':'.$udom);
                   9883:                             }
                   9884:                         } else {
                   9885:                             if ($coursehash{'internal.co-owners'}) {
                   9886:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9887:                                     unless ($coowner eq $uname.':'.$udom) {
                   9888:                                         push(@newcoowners,$coowner);
                   9889:                                     }
                   9890:                                 }
                   9891:                                 unless (@newcoowners > 0) {
                   9892:                                     $delcoowners = 1;
                   9893:                                     $coowners = '';
                   9894:                                 }
                   9895:                             }
                   9896:                         }
                   9897:                         if (@newcoowners || $delcoowners) {
                   9898:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9899:                                             $delcoowners,@newcoowners);
                   9900:                         }
                   9901:                     }
                   9902:                 }
                   9903:             }
                   9904:         }
                   9905:     }
                   9906: }
                   9907: 
                   9908: sub store_coowners {
                   9909:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9910:     my $cid = $cdom.'_'.$cnum;
                   9911:     my ($coowners,$delresult,$putresult);
                   9912:     if (@newcoowners) {
                   9913:         $coowners = join(',',@newcoowners);
                   9914:         my %coownershash = (
                   9915:                             'internal.co-owners' => $coowners,
                   9916:                            );
                   9917:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9918:         if ($putresult eq 'ok') {
                   9919:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9920:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9921:             }
                   9922:         }
                   9923:     }
                   9924:     if ($delcoowners) {
                   9925:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9926:         if ($delresult eq 'ok') {
                   9927:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9928:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9929:             }
                   9930:         }
                   9931:     }
                   9932:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9933:         my %crsinfo =
                   9934:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9935:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9936:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9937:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9938:         }
                   9939:     }
                   9940: }
                   9941: 
1.169     harris41 9942: # -------------------------------------------------- Modify user authentication
1.197     www      9943: # Overrides without validation
                   9944: 
1.169     harris41 9945: sub modifyuserauth {
                   9946:     my ($udom,$uname,$umode,$upass)=@_;
                   9947:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9948:     my $allowed;
                   9949:     if (&allowed('mau',$udom)) {
                   9950:         $allowed = 1;
                   9951:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9952:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9953:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9954:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9955:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9956:         if (($cdom ne '') && ($cnum ne '')) {
                   9957:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9958:             if ($is_owner) {
                   9959:                 $allowed = 1;
                   9960:             }
                   9961:         }
                   9962:     }
                   9963:     unless ($allowed) { return 'refused'; }
1.197     www      9964:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9965:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9966:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9967:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9968: 		     &escape($upass),$uhome);
1.620     albertel 9969:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9970:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9971:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9972:     &log($udom,,$uname,$uhome,
1.620     albertel 9973:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9974:                                      $env{'user.name'}.', '.$umode.
1.197     www      9975:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9976:     unless ($reply eq 'ok') {
1.197     www      9977:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9978: 	return 'error: '.$reply;
                   9979:     }   
1.170     harris41 9980:     return 'ok';
1.80      www      9981: }
                   9982: 
1.81      www      9983: # --------------------------------------------------------------- Modify a user
1.80      www      9984: 
1.81      www      9985: sub modifyuser {
1.206     matthew  9986:     my ($udom,    $uname, $uid,
                   9987:         $umode,   $upass, $first,
                   9988:         $middle,  $last,  $gene,
1.1058    raeburn  9989:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9990:     $udom= &LONCAPA::clean_domain($udom);
                   9991:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9992:     my $showcandelete = 'none';
                   9993:     if (ref($candelete) eq 'ARRAY') {
                   9994:         if (@{$candelete} > 0) {
                   9995:             $showcandelete = join(', ',@{$candelete});
                   9996:         }
                   9997:     }
1.81      www      9998:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9999:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10000: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10001:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10002:                                      ' desiredhome not specified'). 
1.620     albertel 10003:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10004:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10005:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10006:     my $newuser;
                   10007:     if ($uhome eq 'no_host') {
                   10008:         $newuser = 1;
                   10009:     }
1.80      www      10010: # ----------------------------------------------------------------- Create User
1.406     albertel 10011:     if (($uhome eq 'no_host') && 
                   10012: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10013:         my $unhome='';
1.844     albertel 10014:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10015:             $unhome = $desiredhome;
1.620     albertel 10016: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10017: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10018:         } else { # load balancing routine for determining $unhome
1.81      www      10019:             my $loadm=10000000;
1.841     albertel 10020: 	    my %servers = &get_servers($udom,'library');
                   10021: 	    foreach my $tryserver (keys(%servers)) {
                   10022: 		my $answer=reply('load',$tryserver);
                   10023: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10024: 		    $loadm=$answer;
                   10025: 		    $unhome=$tryserver;
                   10026: 		}
1.80      www      10027: 	    }
                   10028:         }
                   10029:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10030: 	    return 'error: unable to find a home server for '.$uname.
                   10031:                    ' in domain '.$udom;
1.80      www      10032:         }
                   10033:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10034:                          &escape($upass),$unhome);
                   10035: 	unless ($reply eq 'ok') {
                   10036:             return 'error: '.$reply;
                   10037:         }   
1.230     stredwic 10038:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10039:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10040: 	    return 'error: unable verify users home machine.';
1.80      www      10041:         }
1.209     matthew  10042:     }   # End of creation of new user
1.80      www      10043: # ---------------------------------------------------------------------- Add ID
                   10044:     if ($uid) {
                   10045:        $uid=~tr/A-Z/a-z/;
                   10046:        my %uidhash=&idrget($udom,$uname);
1.196     www      10047:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10048:          && (!$forceid)) {
1.80      www      10049: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10050: 	      return 'error: user id "'.$uid.'" does not match '.
                   10051:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10052:           }
                   10053:        } else {
                   10054: 	  &idput($udom,($uname => $uid));
                   10055:        }
                   10056:     }
                   10057: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10058:     my @tmp=&get('environment',
1.899     raeburn  10059: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10060:                     'permanentemail','inststatus'],
1.134     albertel 10061: 		   $udom,$uname);
1.1075    raeburn  10062:     my (%names,%oldnames);
1.313     matthew  10063:     if ($tmp[0] =~ m/^error:.*/) { 
                   10064:         %names=(); 
                   10065:     } else {
                   10066:         %names = @tmp;
1.1075    raeburn  10067:         %oldnames = %names;
1.313     matthew  10068:     }
1.388     www      10069: #
1.1058    raeburn  10070: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10071: # of users did not contain them), do not overwrite existing values
                   10072: # unless field is in $candelete array ref.  
                   10073: #
                   10074: 
                   10075:     my @fields = ('firstname','middlename','lastname','generation',
                   10076:                   'permanentemail','id');
                   10077:     my %newvalues;
                   10078:     if (ref($candelete) eq 'ARRAY') {
                   10079:         foreach my $field (@fields) {
                   10080:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10081:                 if ($field eq 'firstname') {
                   10082:                     $names{$field} = $first;
                   10083:                 } elsif ($field eq 'middlename') {
                   10084:                     $names{$field} = $middle;
                   10085:                 } elsif ($field eq 'lastname') {
                   10086:                     $names{$field} = $last;
                   10087:                 } elsif ($field eq 'generation') { 
                   10088:                     $names{$field} = $gene;
                   10089:                 } elsif ($field eq 'permanentemail') {
                   10090:                     $names{$field} = $email;
                   10091:                 } elsif ($field eq 'id') {
                   10092:                     $names{$field}  = $uid;
                   10093:                 }
                   10094:             }
                   10095:         }
                   10096:     }
1.388     www      10097:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10098:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10099:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10100:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10101:     if ($email) {
                   10102:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10103:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10104:     }
1.899     raeburn  10105:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10106:     if (defined($inststatus)) {
                   10107:         $names{'inststatus'} = '';
                   10108:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10109:         if (ref($usertypes) eq 'HASH') {
                   10110:             my @okstatuses; 
                   10111:             foreach my $item (split(/:/,$inststatus)) {
                   10112:                 if (defined($usertypes->{$item})) {
                   10113:                     push(@okstatuses,$item);  
                   10114:                 }
                   10115:             }
                   10116:             if (@okstatuses) {
                   10117:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10118:             }
                   10119:         }
                   10120:     }
1.1075    raeburn  10121:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10122:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10123:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10124:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10125:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10126:     } else {
                   10127:         $logmsg .= ' during self creation';
                   10128:     }
1.1075    raeburn  10129:     my $changed;
                   10130:     if ($newuser) {
                   10131:         $changed = 1;
                   10132:     } else {
                   10133:         foreach my $field (@fields) {
                   10134:             if ($names{$field} ne $oldnames{$field}) {
                   10135:                 $changed = 1;
                   10136:                 last;
                   10137:             }
                   10138:         }
                   10139:     }
                   10140:     unless ($changed) {
                   10141:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10142:         &logthis($logmsg);
                   10143:         return 'ok';
                   10144:     }
                   10145:     my $reply = &put('environment', \%names, $udom,$uname);
                   10146:     if ($reply ne 'ok') { 
                   10147:         return 'error: '.$reply;
                   10148:     }
1.1087    raeburn  10149:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10150:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10151:     }
1.1075    raeburn  10152:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10153:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10154:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10155:     &logthis($logmsg);
1.134     albertel 10156:     return 'ok';
1.80      www      10157: }
                   10158: 
1.81      www      10159: # -------------------------------------------------------------- Modify student
1.80      www      10160: 
1.81      www      10161: sub modifystudent {
                   10162:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10163:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10164:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10165:     if (!$cid) {
1.620     albertel 10166: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10167: 	    return 'not_in_class';
                   10168: 	}
1.80      www      10169:     }
                   10170: # --------------------------------------------------------------- Make the user
1.81      www      10171:     my $reply=&modifyuser
1.209     matthew  10172: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10173:          $desiredhome,$email,$inststatus);
1.80      www      10174:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10175:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10176:     # student's environment
1.297     matthew  10177:     $uid = undef if (!$forceid);
1.455     albertel 10178:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10179: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10180:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10181:     return $reply;
                   10182: }
                   10183: 
                   10184: sub modify_student_enrollment {
1.1172.2.23  raeburn  10185:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10186:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10187:     my ($cdom,$cnum,$chome);
                   10188:     if (!$cid) {
1.620     albertel 10189: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10190: 	    return 'not_in_class';
                   10191: 	}
1.620     albertel 10192: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10193: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10194:     } else {
                   10195: 	($cdom,$cnum)=split(/_/,$cid);
                   10196:     }
1.620     albertel 10197:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10198:     if (!$chome) {
1.457     raeburn  10199: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10200:     }
1.455     albertel 10201:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10202:     # Make sure the user exists
1.81      www      10203:     my $uhome=&homeserver($uname,$udom);
                   10204:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10205: 	return 'error: no such user';
                   10206:     }
1.297     matthew  10207:     # Get student data if we were not given enough information
                   10208:     if (!defined($first)  || $first  eq '' || 
                   10209:         !defined($last)   || $last   eq '' || 
                   10210:         !defined($uid)    || $uid    eq '' || 
                   10211:         !defined($middle) || $middle eq '' || 
                   10212:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10213:         # They did not supply us with enough data to enroll the student, so
                   10214:         # we need to pick up more information.
1.297     matthew  10215:         my %tmp = &get('environment',
1.294     matthew  10216:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10217:                        ,$udom,$uname);
                   10218: 
1.800     albertel 10219:         #foreach my $key (keys(%tmp)) {
                   10220:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10221:         #}
1.294     matthew  10222:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10223:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10224:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10225:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10226:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10227:     }
1.556     albertel 10228:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10229:     my $user = "$uname:$udom";
                   10230:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10231:     my $reply=cput('classlist',
1.1148    raeburn  10232: 		   {$user => 
1.1172.2.76  raeburn  10233: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10234: 		   $cdom,$cnum);
1.1148    raeburn  10235:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10236:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10237:     } else { 
1.81      www      10238: 	return 'error: '.$reply;
                   10239:     }
1.297     matthew  10240:     # Add student role to user
1.83      www      10241:     my $uurl='/'.$cid;
1.81      www      10242:     $uurl=~s/\_/\//g;
                   10243:     if ($usec) {
                   10244: 	$uurl.='/'.$usec;
                   10245:     }
1.1148    raeburn  10246:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10247:                              $selfenroll,$context);
                   10248:     if ($result ne 'ok') {
                   10249:         if ($old_entry{$user} ne '') {
                   10250:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10251:         } else {
                   10252:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10253:         }
                   10254:     }
                   10255:     return $result; 
1.21      www      10256: }
                   10257: 
1.556     albertel 10258: sub format_name {
                   10259:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10260:     my $name;
                   10261:     if ($first ne 'lastname') {
                   10262: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10263:     } else {
                   10264: 	if ($lastname=~/\S/) {
                   10265: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10266: 	    $name=~s/\s+,/,/;
                   10267: 	} else {
                   10268: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10269: 	}
                   10270:     }
                   10271:     $name=~s/^\s+//;
                   10272:     $name=~s/\s+$//;
                   10273:     $name=~s/\s+/ /g;
                   10274:     return $name;
                   10275: }
                   10276: 
1.84      www      10277: # ------------------------------------------------- Write to course preferences
                   10278: 
                   10279: sub writecoursepref {
                   10280:     my ($courseid,%prefs)=@_;
                   10281:     $courseid=~s/^\///;
                   10282:     $courseid=~s/\_/\//g;
                   10283:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10284:     my $chome=homeserver($cnum,$cdomain);
                   10285:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10286: 	return 'error: no such course';
                   10287:     }
                   10288:     my $cstring='';
1.800     albertel 10289:     foreach my $pref (keys(%prefs)) {
                   10290: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10291:     }
1.84      www      10292:     $cstring=~s/\&$//;
                   10293:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10294: }
                   10295: 
                   10296: # ---------------------------------------------------------- Make/modify course
                   10297: 
                   10298: sub createcourse {
1.741     raeburn  10299:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.118.  .6(raebu 10300:20):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10301:     $url=&declutter($url);
                   10302:     my $cid='';
1.1028    raeburn  10303:     if ($context eq 'requestcourses') {
                   10304:         my $can_create = 0;
                   10305:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10306:         if ($udom eq $ownerdom) {
1.1172.2.118.  .6(raebu 10307:20):             my $reload;
                   10308:20):             if (($callercontext eq 'auto') &&
                   10309:20):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10310:20):                 $reload = 'reload';
                   10311:20):             }
                   10312:20):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10313:                                   $context)) {
                   10314:                 $can_create = 1;
                   10315:             }
                   10316:         } else {
                   10317:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10318:                                            $category);
                   10319:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10320:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10321:                 if (@curr > 0) {
                   10322:                     my @options = qw(approval validate autolimit);
                   10323:                     my $optregex = join('|',@options);
                   10324:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10325:                         $can_create = 1;
                   10326:                     }
                   10327:                 }
                   10328:             }
                   10329:         }
                   10330:         if ($can_create) {
                   10331:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10332:                 unless (&allowed('ccc',$udom)) {
                   10333:                     return 'refused'; 
                   10334:                 }
1.1017    raeburn  10335:             }
                   10336:         } else {
                   10337:             return 'refused';
                   10338:         }
1.1028    raeburn  10339:     } elsif (!&allowed('ccc',$udom)) {
                   10340:         return 'refused';
1.84      www      10341:     }
1.1011    raeburn  10342: # --------------------------------------------------------------- Get Unique ID
                   10343:     my $uname;
                   10344:     if ($cnum =~ /^$match_courseid$/) {
                   10345:         my $chome=&homeserver($cnum,$udom,'true');
                   10346:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10347:             $uname = $cnum;
                   10348:         } else {
1.1038    raeburn  10349:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10350:         }
                   10351:     } else {
1.1038    raeburn  10352:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10353:     }
                   10354:     return $uname if ($uname =~ /^error/);
                   10355: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10356:     if (!defined($course_server)) {
                   10357:         if (defined(&domain($udom,'primary'))) {
                   10358:             $course_server = &domain($udom,'primary');
                   10359:         } else {
                   10360:             $course_server = $env{'user.home'}; 
                   10361:         }
                   10362:     }
                   10363:     my %host_servers =
                   10364:         &Apache::lonnet::get_servers($udom,'library');
                   10365:     unless ($host_servers{$course_server}) {
                   10366:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10367:     }
1.84      www      10368: # ------------------------------------------------------------- Make the course
                   10369:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10370:                       $course_server);
1.84      www      10371:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10372:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10373:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10374: 	return 'error: no such course';
                   10375:     }
1.271     www      10376: # ----------------------------------------------------------------- Course made
1.516     raeburn  10377: # log existence
1.1029    raeburn  10378:     my $now = time;
1.918     raeburn  10379:     my $newcourse = {
                   10380:                     $udom.'_'.$uname => {
1.921     raeburn  10381:                                      description => $description,
                   10382:                                      inst_code   => $inst_code,
                   10383:                                      owner       => $course_owner,
                   10384:                                      type        => $crstype,
1.1029    raeburn  10385:                                      creator     => $env{'user.name'}.':'.
                   10386:                                                     $env{'user.domain'},
                   10387:                                      created     => $now,
                   10388:                                      context     => $context,
1.918     raeburn  10389:                                                 },
                   10390:                     };
1.921     raeburn  10391:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10392: # set toplevel url
1.271     www      10393:     my $topurl=$url;
                   10394:     unless ($nonstandard) {
                   10395: # ------------------------------------------ For standard courses, make top url
                   10396:         my $mapurl=&clutter($url);
1.278     www      10397:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10398:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10399: <map>
                   10400: <resource id="1" type="start"></resource>
                   10401: <resource id="2" src="$mapurl"></resource>
                   10402: <resource id="3" type="finish"></resource>
                   10403: <link index="1" from="1" to="2"></link>
                   10404: <link index="2" from="2" to="3"></link>
                   10405: </map>
                   10406: ENDINITMAP
                   10407:         $topurl=&declutter(
1.638     albertel 10408:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10409:                           );
                   10410:     }
                   10411: # ----------------------------------------------------------- Write preferences
1.84      www      10412:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10413:                      ('description'              => $description,
                   10414:                       'url'                      => $topurl,
                   10415:                       'internal.creator'         => $env{'user.name'}.':'.
                   10416:                                                     $env{'user.domain'},
                   10417:                       'internal.created'         => $now,
                   10418:                       'internal.creationcontext' => $context)
                   10419:                     );
1.84      www      10420:     return '/'.$udom.'/'.$uname;
                   10421: }
                   10422: 
1.1011    raeburn  10423: # ------------------------------------------------------------------- Create ID
                   10424: sub generate_coursenum {
1.1038    raeburn  10425:     my ($udom,$crstype) = @_;
1.1011    raeburn  10426:     my $domdesc = &domain($udom);
                   10427:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10428:     my $first;
                   10429:     if ($crstype eq 'Community') {
                   10430:         $first = '0';
                   10431:     } else {
                   10432:         $first = int(1+rand(9)); 
                   10433:     } 
                   10434:     my $uname=$first.
1.1011    raeburn  10435:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10436:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10437:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10438: # ----------------------------------------------- Make sure that does not exist
                   10439:     my $uhome=&homeserver($uname,$udom,'true');
                   10440:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10441:         if ($crstype eq 'Community') {
                   10442:             $first = '0';
                   10443:         } else {
                   10444:             $first = int(1+rand(9));
                   10445:         }
                   10446:         $uname=$first.
1.1011    raeburn  10447:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10448:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10449:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10450:         $uhome=&homeserver($uname,$udom,'true');
                   10451:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10452:             return 'error: unable to generate unique course-ID';
                   10453:         }
                   10454:     }
                   10455:     return $uname;
                   10456: }
                   10457: 
1.813     albertel 10458: sub is_course {
1.1167    droeschl 10459:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10460:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10461:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10462:     my $uhome=&homeserver($cnum,$cdom);
                   10463:     my $iscourse;
                   10464:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10465:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10466:     } else {
                   10467:         my $hashid = $cdom.':'.$cnum;
                   10468:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10469:         unless (defined($cached)) {
                   10470:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10471:                                         $cnum,undef,undef,'.');
                   10472:             $iscourse = 0;
                   10473:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10474:                 $iscourse = 1;
                   10475:             }
                   10476:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10477:         }
                   10478:     }
                   10479:     return unless($iscourse);
1.1167    droeschl 10480:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10481: }
                   10482: 
1.1015    raeburn  10483: sub store_userdata {
                   10484:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10485:     my $result;
1.1016    raeburn  10486:     if ($datakey ne '') {
1.1013    raeburn  10487:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10488:             if ($udom eq '' || $uname eq '') {
                   10489:                 $udom = $env{'user.domain'};
                   10490:                 $uname = $env{'user.name'};
                   10491:             }
                   10492:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10493:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10494:                 $result = 'error: no_host';
                   10495:             } else {
                   10496:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10497:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10498: 
                   10499:                 my $namevalue='';
                   10500:                 foreach my $key (keys(%{$storehash})) {
                   10501:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10502:                 }
                   10503:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10504:                 unless ($namespace eq 'courserequests') {
                   10505:                     $datakey = &escape($datakey);
                   10506:                 }
1.1105    raeburn  10507:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10508:                                   $namevalue,$uhome);
1.1013    raeburn  10509:             }
                   10510:         } else {
                   10511:             $result = 'error: data to store was not a hash reference'; 
                   10512:         }
                   10513:     } else {
                   10514:         $result= 'error: invalid requestkey'; 
                   10515:     }
                   10516:     return $result;
                   10517: }
                   10518: 
1.21      www      10519: # ---------------------------------------------------------- Assign Custom Role
                   10520: 
                   10521: sub assigncustomrole {
1.957     raeburn  10522:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10523:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10524:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10525: }
                   10526: 
                   10527: # ----------------------------------------------------------------- Revoke Role
                   10528: 
                   10529: sub revokerole {
1.957     raeburn  10530:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10531:     my $now=time;
1.965     raeburn  10532:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10533: }
                   10534: 
                   10535: # ---------------------------------------------------------- Revoke Custom Role
                   10536: 
                   10537: sub revokecustomrole {
1.957     raeburn  10538:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10539:     my $now=time;
1.357     www      10540:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10541:            $deleteflag,$selfenroll,$context);
1.17      www      10542: }
                   10543: 
1.533     banghart 10544: # ------------------------------------------------------------ Disk usage
1.535     albertel 10545: sub diskusage {
1.955     raeburn  10546:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10547:     $directorypath =~ s/\/$//;
                   10548:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10549:                        .&escape($getpropath).':'.&escape($uname).':'
                   10550:                        .&escape($udom),homeserver($uname,$udom));
                   10551:     if ($listing eq 'unknown_cmd') {
                   10552:         if ($getpropath) {
                   10553:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10554:         }
                   10555:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10556:     }
1.514     albertel 10557:     return $listing;
1.512     banghart 10558: }
                   10559: 
1.566     banghart 10560: sub is_locked {
1.1096    raeburn  10561:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10562:     my @check;
                   10563:     my $is_locked;
1.1093    raeburn  10564:     push (@check,$file_name);
1.613     albertel 10565:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10566: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10567:     my ($tmp)=keys(%locked);
                   10568:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10569:     
1.566     banghart 10570:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10571:         $is_locked = 'false';
                   10572:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10573:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10574:                $is_locked = 'true';
1.1096    raeburn  10575:                if (ref($which) eq 'ARRAY') {
                   10576:                    push(@{$which},$entry);
                   10577:                } else {
                   10578:                    last;
                   10579:                }
1.745     raeburn  10580:            }
                   10581:        }
1.566     banghart 10582:     } else {
                   10583:         $is_locked = 'false';
                   10584:     }
1.1093    raeburn  10585:     return $is_locked;
1.566     banghart 10586: }
                   10587: 
1.759     albertel 10588: sub declutter_portfile {
                   10589:     my ($file) = @_;
1.833     albertel 10590:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10591:     return $file;
                   10592: }
                   10593: 
1.559     banghart 10594: # ------------------------------------------------------------- Mark as Read Only
                   10595: 
                   10596: sub mark_as_readonly {
                   10597:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10598:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10599:     my ($tmp)=keys(%current_permissions);
                   10600:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10601:     foreach my $file (@{$files}) {
1.759     albertel 10602: 	$file = &declutter_portfile($file);
1.561     banghart 10603:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10604:     }
1.613     albertel 10605:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10606:     return;
                   10607: }
                   10608: 
1.572     banghart 10609: # ------------------------------------------------------------Save Selected Files
                   10610: 
                   10611: sub save_selected_files {
                   10612:     my ($user, $path, @files) = @_;
                   10613:     my $filename = $user."savedfiles";
1.573     banghart 10614:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10615:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10616:     foreach my $file (@files) {
1.620     albertel 10617:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10618:     }
                   10619:     foreach my $file (@other_files) {
1.574     banghart 10620:         print (OUT $file."\n");
1.572     banghart 10621:     }
1.574     banghart 10622:     close (OUT);
1.572     banghart 10623:     return 'ok';
                   10624: }
                   10625: 
1.574     banghart 10626: sub clear_selected_files {
                   10627:     my ($user) = @_;
                   10628:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10629:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10630:     print (OUT undef);
                   10631:     close (OUT);
                   10632:     return ("ok");    
                   10633: }
                   10634: 
1.572     banghart 10635: sub files_in_path {
                   10636:     my ($user, $path) = @_;
                   10637:     my $filename = $user."savedfiles";
                   10638:     my %return_files;
1.1172.2.96  raeburn  10639:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10640:     while (my $line_in = <IN>) {
1.574     banghart 10641:         chomp ($line_in);
                   10642:         my @paths_and_file = split (m!/!, $line_in);
                   10643:         my $file_part = pop (@paths_and_file);
                   10644:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10645:         $path_part.='/';
                   10646:         my $path_and_file = $path_part.$file_part;
                   10647:         if ($path_part eq $path) {
                   10648:             $return_files{$file_part}= 'selected';
                   10649:         }
                   10650:     }
1.574     banghart 10651:     close (IN);
                   10652:     return (\%return_files);
1.572     banghart 10653: }
                   10654: 
                   10655: # called in portfolio select mode, to show files selected NOT in current directory
                   10656: sub files_not_in_path {
                   10657:     my ($user, $path) = @_;
                   10658:     my $filename = $user."savedfiles";
                   10659:     my @return_files;
                   10660:     my $path_part;
1.1172.2.96  raeburn  10661:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10662:     while (my $line = <IN>) {
1.572     banghart 10663:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10664:         my @paths_and_file = split(m|/|, $line);
                   10665:         my $file_part = pop(@paths_and_file);
                   10666:         chomp($file_part);
                   10667:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10668:         $path_part .= '/';
                   10669:         my $path_and_file = $path_part.$file_part;
                   10670:         if ($path_part ne $path) {
1.800     albertel 10671:             push(@return_files, ($path_and_file));
1.572     banghart 10672:         }
                   10673:     }
1.800     albertel 10674:     close(OUT);
1.574     banghart 10675:     return (@return_files);
1.572     banghart 10676: }
                   10677: 
1.745     raeburn  10678: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10679: 
1.745     raeburn  10680: sub get_portfile_permissions {
                   10681:     my ($domain,$user) = @_;
1.613     albertel 10682:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10683:     my ($tmp)=keys(%current_permissions);
                   10684:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10685:     return \%current_permissions;
                   10686: }
                   10687: 
                   10688: #---------------------------------------------Get portfolio file access controls
                   10689: 
1.749     raeburn  10690: sub get_access_controls {
1.745     raeburn  10691:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10692:     my %access;
                   10693:     my $real_file = $file;
                   10694:     $file =~ s/\.meta$//;
1.745     raeburn  10695:     if (defined($file)) {
1.749     raeburn  10696:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10697:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10698:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10699:             }
                   10700:         }
1.745     raeburn  10701:     } else {
1.749     raeburn  10702:         foreach my $key (keys(%{$current_permissions})) {
                   10703:             if ($key =~ /\0accesscontrol$/) {
                   10704:                 if (defined($group)) {
                   10705:                     if ($key !~ m-^\Q$group\E/-) {
                   10706:                         next;
                   10707:                     }
                   10708:                 }
                   10709:                 my ($fullpath) = split(/\0/,$key);
                   10710:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10711:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10712:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10713:                     }
                   10714:                 }
                   10715:             }
                   10716:         }
                   10717:     }
                   10718:     return %access;
                   10719: }
                   10720: 
                   10721: sub modify_access_controls {
                   10722:     my ($file_name,$changes,$domain,$user)=@_;
                   10723:     my ($outcome,$deloutcome);
                   10724:     my %store_permissions;
                   10725:     my %new_values;
                   10726:     my %new_control;
                   10727:     my %translation;
                   10728:     my @deletions = ();
                   10729:     my $now = time;
                   10730:     if (exists($$changes{'activate'})) {
                   10731:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10732:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10733:             my $numnew = scalar(@newitems);
                   10734:             for (my $i=0; $i<$numnew; $i++) {
                   10735:                 my $newkey = $newitems[$i];
                   10736:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10737:                 if ($newkey =~ /^\d+:/) { 
                   10738:                     $newkey =~ s/^(\d+)/$newid/;
                   10739:                     $translation{$1} = $newid;
                   10740:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10741:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10742:                     $translation{$1} = $newid;
                   10743:                 }
1.749     raeburn  10744:                 $new_values{$file_name."\0".$newkey} = 
                   10745:                                           $$changes{'activate'}{$newitems[$i]};
                   10746:                 $new_control{$newkey} = $now;
                   10747:             }
                   10748:         }
                   10749:     }
                   10750:     my %todelete;
                   10751:     my %changed_items;
                   10752:     foreach my $action ('delete','update') {
                   10753:         if (exists($$changes{$action})) {
                   10754:             if (ref($$changes{$action}) eq 'HASH') {
                   10755:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10756:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10757:                     if ($action eq 'delete') { 
                   10758:                         $todelete{$itemnum} = 1;
                   10759:                     } else {
                   10760:                         $changed_items{$itemnum} = $key;
                   10761:                     }
                   10762:                 }
1.745     raeburn  10763:             }
                   10764:         }
1.749     raeburn  10765:     }
                   10766:     # get lock on access controls for file.
                   10767:     my $lockhash = {
                   10768:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10769:                                                        ':'.$env{'user.domain'},
                   10770:                    }; 
                   10771:     my $tries = 0;
                   10772:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10773:    
1.1172.2.79  raeburn  10774:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10775:         $tries ++;
1.1172.2.79  raeburn  10776:         sleep(0.1);
1.749     raeburn  10777:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10778:     }
                   10779:     if ($gotlock eq 'ok') {
                   10780:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10781:         my ($tmp)=keys(%curr_permissions);
                   10782:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10783:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10784:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10785:             if (ref($curr_controls) eq 'HASH') {
                   10786:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10787:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10788:                     if (defined($todelete{$itemnum})) {
                   10789:                         push(@deletions,$file_name."\0".$control_item);
                   10790:                     } else {
                   10791:                         if (defined($changed_items{$itemnum})) {
                   10792:                             $new_control{$changed_items{$itemnum}} = $now;
                   10793:                             push(@deletions,$file_name."\0".$control_item);
                   10794:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10795:                         } else {
                   10796:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10797:                         }
                   10798:                     }
1.745     raeburn  10799:                 }
                   10800:             }
                   10801:         }
1.970     raeburn  10802:         my ($group);
                   10803:         if (&is_course($domain,$user)) {
                   10804:             ($group,my $file) = split(/\//,$file_name,2);
                   10805:         }
1.749     raeburn  10806:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10807:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10808:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10809:         #  remove lock
                   10810:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10811:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10812:         my $sqlresult =
1.970     raeburn  10813:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10814:                                     $group);
1.749     raeburn  10815:     } else {
                   10816:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10817:     }
1.749     raeburn  10818:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10819: }
                   10820: 
1.827     raeburn  10821: sub make_public_indefinitely {
                   10822:     my ($requrl) = @_;
                   10823:     my $now = time;
                   10824:     my $action = 'activate';
                   10825:     my $aclnum = 0;
                   10826:     if (&is_portfolio_url($requrl)) {
                   10827:         my (undef,$udom,$unum,$file_name,$group) =
                   10828:             &parse_portfolio_url($requrl);
                   10829:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10830:         my %access_controls = &get_access_controls($current_perms,
                   10831:                                                    $group,$file_name);
                   10832:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10833:             my ($num,$scope,$end,$start) = 
                   10834:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10835:             if ($scope eq 'public') {
                   10836:                 if ($start <= $now && $end == 0) {
                   10837:                     $action = 'none';
                   10838:                 } else {
                   10839:                     $action = 'update';
                   10840:                     $aclnum = $num;
                   10841:                 }
                   10842:                 last;
                   10843:             }
                   10844:         }
                   10845:         if ($action eq 'none') {
                   10846:              return 'ok';
                   10847:         } else {
                   10848:             my %changes;
                   10849:             my $newend = 0;
                   10850:             my $newstart = $now;
                   10851:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10852:             $changes{$action}{$newkey} = {
                   10853:                 type => 'public',
                   10854:                 time => {
                   10855:                     start => $newstart,
                   10856:                     end   => $newend,
                   10857:                 },
                   10858:             };
                   10859:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10860:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10861:             return $outcome;
                   10862:         }
                   10863:     } else {
                   10864:         return 'invalid';
                   10865:     }
                   10866: }
                   10867: 
1.745     raeburn  10868: #------------------------------------------------------Get Marked as Read Only
                   10869: 
                   10870: sub get_marked_as_readonly {
                   10871:     my ($domain,$user,$what,$group) = @_;
                   10872:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10873:     my @readonly_files;
1.629     banghart 10874:     my $cmp1=$what;
                   10875:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10876:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10877:         if (defined($group)) {
                   10878:             if ($file_name !~ m-^\Q$group\E/-) {
                   10879:                 next;
                   10880:             }
                   10881:         }
1.561     banghart 10882:         if (ref($value) eq "ARRAY"){
                   10883:             foreach my $stored_what (@{$value}) {
1.629     banghart 10884:                 my $cmp2=$stored_what;
1.759     albertel 10885:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10886:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10887:                 }
1.629     banghart 10888:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10889:                     push(@readonly_files, $file_name);
1.745     raeburn  10890:                     last;
1.563     banghart 10891:                 } elsif (!defined($what)) {
                   10892:                     push(@readonly_files, $file_name);
1.745     raeburn  10893:                     last;
1.561     banghart 10894:                 }
                   10895:             }
1.745     raeburn  10896:         }
1.561     banghart 10897:     }
                   10898:     return @readonly_files;
                   10899: }
1.577     banghart 10900: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10901: 
1.577     banghart 10902: sub get_marked_as_readonly_hash {
1.745     raeburn  10903:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10904:     my %readonly_files;
1.745     raeburn  10905:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10906:         if (defined($group)) {
                   10907:             if ($file_name !~ m-^\Q$group\E/-) {
                   10908:                 next;
                   10909:             }
                   10910:         }
1.577     banghart 10911:         if (ref($value) eq "ARRAY"){
                   10912:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10913:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10914:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10915:                         if ($lock_descriptor eq 'graded') {
                   10916:                             $readonly_files{$file_name} = 'graded';
                   10917:                         } elsif ($lock_descriptor eq 'handback') {
                   10918:                             $readonly_files{$file_name} = 'handback';
                   10919:                         } else {
                   10920:                             if (!exists($readonly_files{$file_name})) {
                   10921:                                 $readonly_files{$file_name} = 'locked';
                   10922:                             }
                   10923:                         }
1.745     raeburn  10924:                     }
1.750     banghart 10925:                 } 
1.577     banghart 10926:             }
                   10927:         } 
                   10928:     }
                   10929:     return %readonly_files;
                   10930: }
1.559     banghart 10931: # ------------------------------------------------------------ Unmark as Read Only
                   10932: 
                   10933: sub unmark_as_readonly {
1.629     banghart 10934:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10935:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10936:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10937:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10938:     my $symb_crs = $what;
                   10939:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10940:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10941:     my ($tmp)=keys(%current_permissions);
                   10942:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10943:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10944:     foreach my $file (@readonly_files) {
1.759     albertel 10945: 	my $clean_file = &declutter_portfile($file);
                   10946: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10947: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10948:         my @new_locks;
                   10949:         my @del_keys;
                   10950:         if (ref($current_locks) eq "ARRAY"){
                   10951:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10952:                 my $compare=$locker;
1.749     raeburn  10953:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10954:                     $compare=join('',@{$locker});
1.746     raeburn  10955:                     if ($compare ne $symb_crs) {
                   10956:                         push(@new_locks, $locker);
                   10957:                     }
1.563     banghart 10958:                 }
                   10959:             }
1.650     albertel 10960:             if (scalar(@new_locks) > 0) {
1.563     banghart 10961:                 $current_permissions{$file} = \@new_locks;
                   10962:             } else {
                   10963:                 push(@del_keys, $file);
1.613     albertel 10964:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10965:                 delete($current_permissions{$file});
1.563     banghart 10966:             }
                   10967:         }
1.561     banghart 10968:     }
1.613     albertel 10969:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10970:     return;
                   10971: }
1.512     banghart 10972: 
1.17      www      10973: # ------------------------------------------------------------ Directory lister
                   10974: 
                   10975: sub dirlist {
1.955     raeburn  10976:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10977:     $uri=~s/^\///;
                   10978:     $uri=~s/\/$//;
1.253     stredwic 10979:     my ($udom, $uname);
1.955     raeburn  10980:     if ($getuserdir) {
1.253     stredwic 10981:         $udom = $userdomain;
                   10982:         $uname = $username;
1.955     raeburn  10983:     } else {
                   10984:         (undef,$udom,$uname)=split(/\//,$uri);
                   10985:         if(defined($userdomain)) {
                   10986:             $udom = $userdomain;
                   10987:         }
                   10988:         if(defined($username)) {
                   10989:             $uname = $username;
                   10990:         }
1.253     stredwic 10991:     }
1.955     raeburn  10992:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10993: 
1.955     raeburn  10994:     $dirRoot = $perlvar{'lonDocRoot'};
                   10995:     if (defined($getpropath)) {
                   10996:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10997:         $dirRoot =~ s/\/$//;
1.955     raeburn  10998:     } elsif (defined($getuserdir)) {
                   10999:         my $subdir=$uname.'__';
                   11000:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11001:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11002:                    ."/$udom/$subdir/$uname";
                   11003:     } elsif (defined($alternateRoot)) {
                   11004:         $dirRoot = $alternateRoot;
1.751     banghart 11005:     }
1.253     stredwic 11006: 
                   11007:     if($udom) {
                   11008:         if($uname) {
1.1135    raeburn  11009:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11010:             if ($uhome eq 'no_host') {
                   11011:                 return ([],'no_host');
                   11012:             }
1.955     raeburn  11013:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11014:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11015:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11016:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11017:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11018:             } else {
                   11019:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11020:             }
1.605     matthew  11021:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11022:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11023:                 @listing_results = split(/:/,$listing);
                   11024:             } else {
                   11025:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11026:             }
1.1135    raeburn  11027:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11028:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11029:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11030:                 return ([],$listing);
                   11031:             } else {
                   11032:                 return (\@listing_results);
1.1135    raeburn  11033:             }
1.955     raeburn  11034:         } elsif(!$alternateRoot) {
1.1136    raeburn  11035:             my (%allusers,%listerror);
1.841     albertel 11036: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11037:  	    foreach my $tryserver (keys(%servers)) {
                   11038:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11039:                                   &escape($udom),$tryserver);
                   11040:                 if ($listing eq 'unknown_cmd') {
                   11041: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11042: 				      $udom, $tryserver);
                   11043:                 } else {
                   11044:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11045:                 }
1.841     albertel 11046: 		if ($listing eq 'unknown_cmd') {
                   11047: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11048: 				      $udom, $tryserver);
                   11049: 		    @listing_results = split(/:/,$listing);
                   11050: 		} else {
                   11051: 		    @listing_results =
                   11052: 			map { &unescape($_); } split(/:/,$listing);
                   11053: 		}
1.1136    raeburn  11054:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11055:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11056:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11057:                     $listerror{$tryserver} = $listing;
                   11058:                 } else {
1.841     albertel 11059: 		    foreach my $line (@listing_results) {
                   11060: 			my ($entry) = split(/&/,$line,2);
                   11061: 			$allusers{$entry} = 1;
                   11062: 		    }
                   11063: 		}
1.253     stredwic 11064:             }
1.1136    raeburn  11065:             my @alluserslist=();
1.800     albertel 11066:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11067:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11068:             }
1.1172.2.80  raeburn  11069:             if (!%listerror) {
                   11070:                 # no errors
                   11071:                 return (\@alluserslist);
                   11072:             } elsif (scalar(keys(%servers)) == 1) {
                   11073:                 # one library server, one error
                   11074:                 my ($key) = keys(%listerror);
                   11075:                 return (\@alluserslist, $listerror{$key});
                   11076:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11077:                 # con_lost indicates that we might miss data from at least one
                   11078:                 # library server
                   11079:                 return (\@alluserslist, 'con_lost');
                   11080:             } else {
                   11081:                 # multiple library servers and no con_lost -> data should be
                   11082:                 # complete.
                   11083:                 return (\@alluserslist);
                   11084:             }
                   11085: 
1.253     stredwic 11086:         } else {
1.1136    raeburn  11087:             return ([],'missing username');
1.253     stredwic 11088:         }
1.955     raeburn  11089:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11090:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11091:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11092:         return (\@all_domains);
1.955     raeburn  11093:     } else {
1.1136    raeburn  11094:         return ([],'missing domain');
1.275     stredwic 11095:     }
                   11096: }
                   11097: 
                   11098: # --------------------------------------------- GetFileTimestamp
                   11099: # This function utilizes dirlist and returns the date stamp for
                   11100: # when it was last modified.  It will also return an error of -1
                   11101: # if an error occurs
                   11102: 
                   11103: sub GetFileTimestamp {
1.955     raeburn  11104:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11105:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11106:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11107:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11108:                                     undef,$getuserdir);
                   11109:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11110:         return -1;
                   11111:     }
                   11112:     if (ref($fileref) eq 'ARRAY') {
                   11113:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11114:         # @stats contains first the filename, then the stat output
                   11115:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11116:     } else {
                   11117:         return -1;
1.253     stredwic 11118:     }
1.26      www      11119: }
                   11120: 
1.712     albertel 11121: sub stat_file {
                   11122:     my ($uri) = @_;
1.787     albertel 11123:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11124: 
1.955     raeburn  11125:     my ($udom,$uname,$file);
1.712     albertel 11126:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11127: 	($udom,$uname,$file) =
1.811     albertel 11128: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11129: 	$file = 'userfiles/'.$file;
                   11130:     }
                   11131:     if ($uri =~ m-^/res/-) {
                   11132: 	($udom,$uname) = 
1.807     albertel 11133: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11134: 	$file = $uri;
                   11135:     }
                   11136: 
                   11137:     if (!$udom || !$uname || !$file) {
                   11138: 	# unable to handle the uri
                   11139: 	return ();
                   11140:     }
1.956     raeburn  11141:     my $getpropath;
                   11142:     if ($file =~ /^userfiles\//) {
                   11143:         $getpropath = 1;
                   11144:     }
1.1136    raeburn  11145:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11146:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11147:         return ();
                   11148:     } else {
                   11149:         if (ref($listref) eq 'ARRAY') {
                   11150:             my @stats = split('&',$listref->[0]);
                   11151: 	    shift(@stats); #filename is first
                   11152: 	    return @stats;
                   11153:         }
1.712     albertel 11154:     }
                   11155:     return ();
                   11156: }
                   11157: 
1.26      www      11158: # -------------------------------------------------------- Value of a Condition
                   11159: 
1.713     albertel 11160: # gets the value of a specific preevaluated condition
                   11161: #    stored in the string  $env{user.state.<cid>}
                   11162: # or looks up a condition reference in the bighash and if if hasn't
                   11163: # already been evaluated recurses into docondval to get the value of
                   11164: # the condition, then memoizing it to 
                   11165: #   $env{user.state.<cid>.<condition>}
1.40      www      11166: sub directcondval {
                   11167:     my $number=shift;
1.620     albertel 11168:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11169: 	&Apache::lonuserstate::evalstate();
                   11170:     }
1.713     albertel 11171:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11172: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11173:     } elsif ($number =~ /^_/) {
                   11174: 	my $sub_condition;
                   11175: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11176: 		&GDBM_READER(),0640)) {
                   11177: 	    $sub_condition=$bighash{'conditions'.$number};
                   11178: 	    untie(%bighash);
                   11179: 	}
                   11180: 	my $value = &docondval($sub_condition);
1.949     raeburn  11181: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11182: 	return $value;
                   11183:     }
1.620     albertel 11184:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11185:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11186:     } else {
                   11187:        return 2;
                   11188:     }
                   11189: }
                   11190: 
1.713     albertel 11191: # get the collection of conditions for this resource
1.26      www      11192: sub condval {
                   11193:     my $condidx=shift;
1.54      www      11194:     my $allpathcond='';
1.713     albertel 11195:     foreach my $cond (split(/\|/,$condidx)) {
                   11196: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11197: 	    $allpathcond.=
                   11198: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11199: 	}
1.191     harris41 11200:     }
1.54      www      11201:     $allpathcond=~s/\|$//;
1.713     albertel 11202:     return &docondval($allpathcond);
                   11203: }
                   11204: 
                   11205: #evaluates an expression of conditions
                   11206: sub docondval {
                   11207:     my ($allpathcond) = @_;
                   11208:     my $result=0;
                   11209:     if ($env{'request.course.id'}
                   11210: 	&& defined($allpathcond)) {
                   11211: 	my $operand='|';
                   11212: 	my @stack;
                   11213: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11214: 	    if ($chunk eq '(') {
                   11215: 		push @stack,($operand,$result);
                   11216: 	    } elsif ($chunk eq ')') {
                   11217: 		my $before=pop @stack;
                   11218: 		if (pop @stack eq '&') {
                   11219: 		    $result=$result>$before?$before:$result;
                   11220: 		} else {
                   11221: 		    $result=$result>$before?$result:$before;
                   11222: 		}
                   11223: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11224: 		$operand=$chunk;
                   11225: 	    } else {
                   11226: 		my $new=directcondval($chunk);
                   11227: 		if ($operand eq '&') {
                   11228: 		    $result=$result>$new?$new:$result;
                   11229: 		} else {
                   11230: 		    $result=$result>$new?$result:$new;
                   11231: 		}
                   11232: 	    }
                   11233: 	}
1.26      www      11234:     }
                   11235:     return $result;
1.421     albertel 11236: }
                   11237: 
                   11238: # ---------------------------------------------------- Devalidate courseresdata
                   11239: 
                   11240: sub devalidatecourseresdata {
                   11241:     my ($coursenum,$coursedomain)=@_;
                   11242:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11243:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11244: }
                   11245: 
1.763     www      11246: 
1.200     www      11247: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11248: #
                   11249: #  Parameters:
                   11250: #      $coursenum    - Number of the course.
                   11251: #      $coursedomain - Domain at which the course was created.
                   11252: #  Returns:
                   11253: #     A hash of the course parameters along (I think) with timestamps
                   11254: #     and version info.
1.877     foxr     11255: 
1.624     albertel 11256: sub get_courseresdata {
                   11257:     my ($coursenum,$coursedomain)=@_;
1.200     www      11258:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11259:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11260:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11261:     my %dumpreply;
1.417     albertel 11262:     unless (defined($cached)) {
1.624     albertel 11263: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11264: 	$result=\%dumpreply;
1.251     albertel 11265: 	my ($tmp) = keys(%dumpreply);
                   11266: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11267: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11268: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11269: 	    return $tmp;
1.416     albertel 11270: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11271: 	    $result=undef;
1.599     albertel 11272: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11273: 	}
                   11274:     }
1.624     albertel 11275:     return $result;
                   11276: }
                   11277: 
1.633     albertel 11278: sub devalidateuserresdata {
                   11279:     my ($uname,$udom)=@_;
                   11280:     my $hashid="$udom:$uname";
                   11281:     &devalidate_cache_new('userres',$hashid);
                   11282: }
                   11283: 
1.624     albertel 11284: sub get_userresdata {
                   11285:     my ($uname,$udom)=@_;
                   11286:     #most student don\'t have any data set, check if there is some data
                   11287:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11288: 
                   11289:     my $hashid="$udom:$uname";
                   11290:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11291:     if (!defined($cached)) {
                   11292: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11293: 	$result=\%resourcedata;
                   11294: 	&do_cache_new('userres',$hashid,$result,600);
                   11295:     }
                   11296:     my ($tmp)=keys(%$result);
                   11297:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11298: 	return $result;
                   11299:     }
                   11300:     #error 2 occurs when the .db doesn't exist
                   11301:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11302:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11303: 	    &logthis("<font color=\"blue\">WARNING:".
                   11304: 		     " Trying to get resource data for ".
                   11305: 		     $uname." at ".$udom.": ".
                   11306: 		     $tmp."</font>");
                   11307:         }
1.624     albertel 11308:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11309: 	#&EXT_cache_set($udom,$uname);
                   11310: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11311: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11312:     }
                   11313:     return $tmp;
                   11314: }
1.879     foxr     11315: #----------------------------------------------- resdata - return resource data
                   11316: #  Purpose:
                   11317: #    Return resource data for either users or for a course.
                   11318: #  Parameters:
                   11319: #     $name      - Course/user name.
                   11320: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11321:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11322: #     @which     - Array of names of resources desired.
                   11323: #  Returns:
                   11324: #     The value of the first reasource in @which that is found in the
                   11325: #     resource hash.
                   11326: #  Exceptional Conditions:
                   11327: #     If the $type passed in is not valid (not the string 'course' or 
                   11328: #     'user', an undefined  reference is returned.
                   11329: #     If none of the resources are found, an undef is returned
1.624     albertel 11330: sub resdata {
                   11331:     my ($name,$domain,$type,@which)=@_;
                   11332:     my $result;
                   11333:     if ($type eq 'course') {
                   11334: 	$result=&get_courseresdata($name,$domain);
                   11335:     } elsif ($type eq 'user') {
                   11336: 	$result=&get_userresdata($name,$domain);
                   11337:     }
                   11338:     if (!ref($result)) { return $result; }    
1.251     albertel 11339:     foreach my $item (@which) {
1.1172.2.118.  .8(raebu 11340:20): 	if (defined($result->{$item->[0]})) {
                   11341:20): 	    return [$result->{$item->[0]},$item->[1]];
          .1(raebu 11342:20):         }
1.250     albertel 11343:     }
1.291     albertel 11344:     return undef;
1.200     www      11345: }
                   11346: 
1.1172.2.118.  .1(raebu 11347:20): sub get_domain_ltitools {
                   11348:20):     my ($cdom) = @_;
                   11349:20):     my %ltitools;
                   11350:20):     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   11351:20):     if (defined($cached)) {
                   11352:20):         if (ref($result) eq 'HASH') {
                   11353:20):             %ltitools = %{$result};
                   11354:20):         }
                   11355:20):     } else {
                   11356:20):         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   11357:20):         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   11358:20):             %ltitools = %{$domconfig{'ltitools'}};
                   11359:20):             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
                   11360:20):             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
                   11361:20):                 foreach my $id (keys(%ltitools)) {
                   11362:20):                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
                   11363:20):                         foreach my $item ('key','secret') {
                   11364:20):                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
                   11365:20):                         }
                   11366:20):                     }
                   11367:20):                 }
                   11368:20):             }
                   11369:20):         }
                   11370:20):         my $cachetime = 24*60*60;
                   11371:20):         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   11372:20):     }
                   11373:20):     return %ltitools;
                   11374:20): }
                   11375:20): 
1.1172.2.31  raeburn  11376: sub get_numsuppfiles {
                   11377:     my ($cnum,$cdom,$ignorecache)=@_;
                   11378:     my $hashid=$cnum.':'.$cdom;
                   11379:     my ($suppcount,$cached);
                   11380:     unless ($ignorecache) {
                   11381:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11382:     }
                   11383:     unless (defined($cached)) {
                   11384:         my $chome=&homeserver($cnum,$cdom);
                   11385:         unless ($chome eq 'no_host') {
                   11386:             ($suppcount,my $errors) = (0,0);
                   11387:             my $suppmap = 'supplemental.sequence';
                   11388:             ($suppcount,$errors) =
                   11389:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11390:         }
                   11391:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11392:     }
                   11393:     return $suppcount;
                   11394: }
                   11395: 
1.379     matthew  11396: #
                   11397: # EXT resource caching routines
                   11398: #
                   11399: 
                   11400: sub clear_EXT_cache_status {
1.383     albertel 11401:     &delenv('cache.EXT.');
1.379     matthew  11402: }
                   11403: 
                   11404: sub EXT_cache_status {
                   11405:     my ($target_domain,$target_user) = @_;
1.383     albertel 11406:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11407:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11408:         # We know already the user has no data
                   11409:         return 1;
                   11410:     } else {
                   11411:         return 0;
                   11412:     }
                   11413: }
                   11414: 
                   11415: sub EXT_cache_set {
                   11416:     my ($target_domain,$target_user) = @_;
1.383     albertel 11417:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11418:     #&appenv({$cachename => time});
1.379     matthew  11419: }
                   11420: 
1.28      www      11421: # --------------------------------------------------------- Value of a Variable
1.58      www      11422: sub EXT {
1.715     albertel 11423: 
1.1172.2.28  raeburn  11424:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11425:     unless ($varname) { return ''; }
1.218     albertel 11426:     #get real user name/domain, courseid and symb
                   11427:     my $courseid;
1.359     albertel 11428:     my $publicuser;
1.427     www      11429:     if ($symbparm) {
                   11430: 	$symbparm=&get_symb_from_alias($symbparm);
                   11431:     }
1.218     albertel 11432:     if (!($uname && $udom)) {
1.790     albertel 11433:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11434:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11435:     } else {
1.620     albertel 11436: 	$courseid=$env{'request.course.id'};
1.218     albertel 11437:     }
1.48      www      11438:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11439:     my $rest;
1.320     albertel 11440:     if (defined($therest[0])) {
1.48      www      11441:        $rest=join('.',@therest);
                   11442:     } else {
                   11443:        $rest='';
                   11444:     }
1.320     albertel 11445: 
1.57      www      11446:     my $qualifierrest=$qualifier;
                   11447:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11448:     my $spacequalifierrest=$space;
                   11449:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11450:     if ($realm eq 'user') {
1.48      www      11451: # --------------------------------------------------------------- user.resource
                   11452: 	if ($space eq 'resource') {
1.651     albertel 11453: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11454: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11455: 		 &&
1.744     albertel 11456: 		 ($symbparm eq &symbread()) ) {	
                   11457: 		# if we are in the middle of processing the resource the
                   11458: 		# get the value we are planning on committing
                   11459:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11460:                     return $Apache::lonhomework::results{$qualifierrest};
                   11461:                 } else {
                   11462:                     return $Apache::lonhomework::history{$qualifierrest};
                   11463:                 }
1.335     albertel 11464: 	    } else {
1.359     albertel 11465: 		my %restored;
1.620     albertel 11466: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11467: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11468: 		} else {
                   11469: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11470: 		}
1.335     albertel 11471: 		return $restored{$qualifierrest};
                   11472: 	    }
1.48      www      11473: # ----------------------------------------------------------------- user.access
                   11474:         } elsif ($space eq 'access') {
1.218     albertel 11475: 	    # FIXME - not supporting calls for a specific user
1.48      www      11476:             return &allowed($qualifier,$rest);
                   11477: # ------------------------------------------ user.preferences, user.environment
                   11478:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11479: 	    if (($uname eq $env{'user.name'}) &&
                   11480: 		($udom eq $env{'user.domain'})) {
                   11481: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11482: 	    } else {
1.359     albertel 11483: 		my %returnhash;
                   11484: 		if (!$publicuser) {
                   11485: 		    %returnhash=&userenvironment($udom,$uname,
                   11486: 						 $qualifierrest);
                   11487: 		}
1.218     albertel 11488: 		return $returnhash{$qualifierrest};
                   11489: 	    }
1.48      www      11490: # ----------------------------------------------------------------- user.course
                   11491:         } elsif ($space eq 'course') {
1.218     albertel 11492: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11493:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11494: # ------------------------------------------------------------------- user.role
                   11495:         } elsif ($space eq 'role') {
1.218     albertel 11496: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11497:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11498:             if ($qualifier eq 'value') {
                   11499: 		return $role;
                   11500:             } elsif ($qualifier eq 'extent') {
                   11501:                 return $where;
                   11502:             }
                   11503: # ----------------------------------------------------------------- user.domain
                   11504:         } elsif ($space eq 'domain') {
1.218     albertel 11505:             return $udom;
1.48      www      11506: # ------------------------------------------------------------------- user.name
                   11507:         } elsif ($space eq 'name') {
1.218     albertel 11508:             return $uname;
1.48      www      11509: # ---------------------------------------------------- Any other user namespace
1.29      www      11510:         } else {
1.359     albertel 11511: 	    my %reply;
                   11512: 	    if (!$publicuser) {
                   11513: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11514: 	    }
                   11515: 	    return $reply{$qualifierrest};
1.48      www      11516:         }
1.236     www      11517:     } elsif ($realm eq 'query') {
                   11518: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11519:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11520: 						[$spacequalifierrest]);
1.620     albertel 11521: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11522:    } elsif ($realm eq 'request') {
1.48      www      11523: # ------------------------------------------------------------- request.browser
                   11524:         if ($space eq 'browser') {
1.1145    bisitz   11525:             return $env{'browser.'.$qualifier};
1.57      www      11526: # ------------------------------------------------------------ request.filename
                   11527:         } else {
1.620     albertel 11528:             return $env{'request.'.$spacequalifierrest};
1.29      www      11529:         }
1.28      www      11530:     } elsif ($realm eq 'course') {
1.48      www      11531: # ---------------------------------------------------------- course.description
1.620     albertel 11532:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11533:     } elsif ($realm eq 'resource') {
1.165     www      11534: 
1.620     albertel 11535: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11536: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11537: 	}
1.693     albertel 11538: 
1.1172.2.30  raeburn  11539:         if ($qualifier eq '') {
                   11540: 	    if ($space eq 'title') {
                   11541: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11542: 	        return &gettitle($symbparm);
                   11543: 	    }
1.693     albertel 11544: 	
1.1172.2.30  raeburn  11545: 	    if ($space eq 'map') {
                   11546: 	        my ($map) = &decode_symb($symbparm);
                   11547: 	        return &symbread($map);
                   11548: 	    }
                   11549:             if ($space eq 'maptitle') {
                   11550:                 my ($map) = &decode_symb($symbparm);
                   11551:                 return &gettitle($map);
                   11552:             }
                   11553: 	    if ($space eq 'filename') {
                   11554: 	        if ($symbparm) {
                   11555: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11556: 	        }
                   11557: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11558: 	    }
1.1172.2.30  raeburn  11559: 
                   11560:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11561:                 if ($space eq 'visibleparts') {
                   11562:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11563:                     my $item;
                   11564:                     if (ref($navmap)) {
                   11565:                         my $res = $navmap->getBySymb($symbparm);
                   11566:                         my $parts = $res->parts();
                   11567:                         if (ref($parts) eq 'ARRAY') {
                   11568:                             $item = join(',',@{$parts});
                   11569:                         }
                   11570:                         undef($navmap);
                   11571:                     }
                   11572:                     return $item;
                   11573:                 }
                   11574:             }
                   11575:         }
1.693     albertel 11576: 
                   11577: 	my ($section, $group, @groups);
1.593     albertel 11578: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11579:         if (($courseid eq '') && ($cid)) {
                   11580:             $courseid = $cid;
                   11581:         }
                   11582: 	if (($symbparm && $courseid) && 
                   11583: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11584: 
1.218     albertel 11585: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11586: 
1.60      www      11587: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11588: 	    my $symbp=$symbparm;
1.735     albertel 11589: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11590: 
                   11591: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11592: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11593: 
1.620     albertel 11594: 	    if (($env{'user.name'} eq $uname) &&
                   11595: 		($env{'user.domain'} eq $udom)) {
                   11596: 		$section=$env{'request.course.sec'};
1.733     raeburn  11597:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11598:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11599: 	    } else {
1.539     albertel 11600: 		if (! defined($usection)) {
1.551     albertel 11601: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11602: 		} else {
                   11603: 		    $section = $usection;
                   11604: 		}
1.733     raeburn  11605:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11606: 	    }
                   11607: 
                   11608: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11609: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11610: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11611: 
1.593     albertel 11612: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11613: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11614: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11615: 
1.60      www      11616: # ----------------------------------------------------------- first, check user
1.624     albertel 11617: 
                   11618: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11619: 				       ([$courselevelr,'resource'],
                   11620: 					[$courselevelm,'map'     ],
                   11621: 					[$courselevel, 'course'  ]));
1.931     albertel 11622: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11623: 
1.594     albertel 11624: # ------------------------------------------------ second, check some of course
1.684     raeburn  11625:             my $coursereply;
1.691     raeburn  11626:             if (@groups > 0) {
                   11627:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11628:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11629:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11630:             }
1.96      www      11631: 
1.684     raeburn  11632: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11633: 				  $env{'course.'.$courseid.'.domain'},
                   11634: 				  'course',
                   11635: 				  ([$seclevelr,   'resource'],
                   11636: 				   [$seclevelm,   'map'     ],
                   11637: 				   [$seclevel,    'course'  ],
                   11638: 				   [$courselevelr,'resource']));
                   11639: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11640: 
1.60      www      11641: # ------------------------------------------------------ third, check map parms
1.218     albertel 11642: 	    my %parmhash=();
                   11643: 	    my $thisparm='';
                   11644: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11645: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11646: 		    &GDBM_READER(),0640)) {
1.218     albertel 11647: 		$thisparm=$parmhash{$symbparm};
                   11648: 		untie(%parmhash);
                   11649: 	    }
1.927     albertel 11650: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11651: 	}
1.594     albertel 11652: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11653: 
1.218     albertel 11654: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11655: 	my $filename;
                   11656: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11657: 	if ($symbparm) {
1.409     www      11658: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11659: 	} else {
1.620     albertel 11660: 	    $filename=$env{'request.filename'};
1.282     albertel 11661: 	}
                   11662: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11663: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11664: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11665: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11666: 
1.927     albertel 11667: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11668: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11669: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11670: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11671: 				     $env{'course.'.$courseid.'.domain'},
                   11672: 				     'course',
1.927     albertel 11673: 				     ([$courselevelm,'map'   ],
                   11674: 				      [$courselevel, 'course']));
                   11675: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11676: 	}
1.145     www      11677: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11678: 	unless ($space eq '0') {
1.336     albertel 11679: 	    my @parts=split(/_/,$space);
                   11680: 	    my $id=pop(@parts);
                   11681: 	    my $part=join('_',@parts);
                   11682: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11683: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11684: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11685: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11686: 	}
1.395     albertel 11687: 	if ($recurse) { return undef; }
                   11688: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11689: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11690: # ---------------------------------------------------- Any other user namespace
                   11691:     } elsif ($realm eq 'environment') {
                   11692: # ----------------------------------------------------------------- environment
1.620     albertel 11693: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11694: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11695: 	} else {
1.770     albertel 11696: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11697: 		return '';
                   11698: 	    }
1.219     albertel 11699: 	    my %returnhash=&userenvironment($udom,$uname,
                   11700: 					    $spacequalifierrest);
                   11701: 	    return $returnhash{$spacequalifierrest};
                   11702: 	}
1.28      www      11703:     } elsif ($realm eq 'system') {
1.48      www      11704: # ----------------------------------------------------------------- system.time
                   11705: 	if ($space eq 'time') {
                   11706: 	    return time;
                   11707:         }
1.696     albertel 11708:     } elsif ($realm eq 'server') {
                   11709: # ----------------------------------------------------------------- system.time
                   11710: 	if ($space eq 'name') {
                   11711: 	    return $ENV{'SERVER_NAME'};
                   11712:         }
1.28      www      11713:     }
1.48      www      11714:     return '';
1.61      www      11715: }
                   11716: 
1.927     albertel 11717: sub get_reply {
                   11718:     my ($reply_value) = @_;
1.940     raeburn  11719:     if (ref($reply_value) eq 'ARRAY') {
                   11720:         if (wantarray) {
                   11721: 	    return @$reply_value;
                   11722:         }
                   11723:         return $reply_value->[0];
                   11724:     } else {
                   11725:         return $reply_value;
1.927     albertel 11726:     }
                   11727: }
                   11728: 
1.691     raeburn  11729: sub check_group_parms {
                   11730:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11731:     my @groupitems = ();
                   11732:     my $resultitem;
1.927     albertel 11733:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11734:     foreach my $group (@{$groups}) {
                   11735:         foreach my $level (@levels) {
1.927     albertel 11736:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11737:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11738:         }
                   11739:     }
                   11740:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11741:                             $env{'course.'.$courseid.'.domain'},
                   11742:                                      'course',@groupitems);
                   11743:     return $coursereply;
                   11744: }
                   11745: 
                   11746: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11747:     my ($courseid,@groups) = @_;
                   11748:     @groups = sort(@groups);
1.691     raeburn  11749:     return @groups;
                   11750: }
                   11751: 
1.395     albertel 11752: sub packages_tab_default {
                   11753:     my ($uri,$varname)=@_;
                   11754:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11755: 
                   11756:     my (@extension,@specifics,$do_default);
                   11757:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11758: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11759: 	if ($pack_type eq 'default') {
                   11760: 	    $do_default=1;
                   11761: 	} elsif ($pack_type eq 'extension') {
                   11762: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11763: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11764: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11765: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11766: 	}
                   11767:     }
                   11768:     # first look for a package that matches the requested part id
                   11769:     foreach my $package (@specifics) {
                   11770: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11771: 	next if ($pack_part ne $part);
                   11772: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11773: 	    return $packagetab{"$pack_type&$name&default"};
                   11774: 	}
                   11775:     }
                   11776:     # look for any possible matching non extension_ package
                   11777:     foreach my $package (@specifics) {
                   11778: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11779: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11780: 	    return $packagetab{"$pack_type&$name&default"};
                   11781: 	}
1.585     albertel 11782: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11783: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11784: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11785: 	}
                   11786:     }
1.738     albertel 11787:     # look for any posible extension_ match
                   11788:     foreach my $package (@extension) {
                   11789: 	my ($package,$pack_type)=@{$package};
                   11790: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11791: 	    return $packagetab{"$pack_type&$name&default"};
                   11792: 	}
                   11793: 	if (defined($packagetab{$package."&$name&default"})) {
                   11794: 	    return $packagetab{$package."&$name&default"};
                   11795: 	}
                   11796:     }
                   11797:     # look for a global default setting
                   11798:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11799: 	return $packagetab{"default&$name&default"};
                   11800:     }
1.395     albertel 11801:     return undef;
                   11802: }
                   11803: 
1.334     albertel 11804: sub add_prefix_and_part {
                   11805:     my ($prefix,$part)=@_;
                   11806:     my $keyroot;
                   11807:     if (defined($prefix) && $prefix !~ /^__/) {
                   11808: 	# prefix that has a part already
                   11809: 	$keyroot=$prefix;
                   11810:     } elsif (defined($prefix)) {
                   11811: 	# prefix that is missing a part
                   11812: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11813:     } else {
                   11814: 	# no prefix at all
                   11815: 	if (defined($part)) { $keyroot='_'.$part; }
                   11816:     }
                   11817:     return $keyroot;
                   11818: }
                   11819: 
1.71      www      11820: # ---------------------------------------------------------------- Get metadata
                   11821: 
1.599     albertel 11822: my %metaentry;
1.1070    www      11823: my %importedpartids;
1.1172.2.99  raeburn  11824: my %importedrespids;
1.71      www      11825: sub metadata {
1.176     www      11826:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11827:     $uri=&declutter($uri);
1.288     albertel 11828:     # if it is a non metadata possible uri return quickly
1.529     albertel 11829:     if (($uri eq '') || 
                   11830: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11831:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11832:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11833: 	return undef;
                   11834:     }
1.1172.2.49  raeburn  11835:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11836: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11837: 	return undef;
1.288     albertel 11838:     }
1.73      www      11839:     my $filename=$uri;
                   11840:     $uri=~s/\.meta$//;
1.172     www      11841: #
                   11842: # Is the metadata already cached?
1.177     www      11843: # Look at timestamp of caching
1.172     www      11844: # Everything is cached by the main uri, libraries are never directly cached
                   11845: #
1.428     albertel 11846:     if (!defined($liburi)) {
1.599     albertel 11847: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11848: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11849:     }
                   11850:     {
1.1069    www      11851: # Imported parts would go here
1.1172.2.99  raeburn  11852:         my @origfiletagids=();
1.1069    www      11853:         my $importedparts=0;
1.1172.2.99  raeburn  11854: 
                   11855: # Imported responseids would go here
                   11856:         my $importedresponses=0;
1.172     www      11857: #
                   11858: # Is this a recursive call for a library?
                   11859: #
1.599     albertel 11860: #	if (! exists($metacache{$uri})) {
                   11861: #	    $metacache{$uri}={};
                   11862: #	}
1.924     albertel 11863: 	my $cachetime = 60*60;
1.171     www      11864:         if ($liburi) {
                   11865: 	    $liburi=&declutter($liburi);
                   11866:             $filename=$liburi;
1.401     bowersj2 11867:         } else {
1.599     albertel 11868: 	    &devalidate_cache_new('meta',$uri);
                   11869: 	    undef(%metaentry);
1.401     bowersj2 11870: 	}
1.140     www      11871:         my %metathesekeys=();
1.73      www      11872:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11873: 	my $metastring;
1.1140    www      11874: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11875: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11876: 	    $metastring = 
1.929     albertel 11877: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11878: 					  ('grade_target' => 'meta'));
                   11879: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11880: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11881:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11882: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11883: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11884: 	    $metastring=&getfile($file);
1.489     albertel 11885: 	}
1.208     albertel 11886:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11887:         my $token;
1.140     www      11888:         undef %metathesekeys;
1.71      www      11889:         while ($token=$parser->get_token) {
1.339     albertel 11890: 	    if ($token->[0] eq 'S') {
                   11891: 		if (defined($token->[2]->{'package'})) {
1.172     www      11892: #
                   11893: # This is a package - get package info
                   11894: #
1.339     albertel 11895: 		    my $package=$token->[2]->{'package'};
                   11896: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11897: 		    if (defined($token->[2]->{'id'})) { 
                   11898: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11899: 		    }
1.599     albertel 11900: 		    if ($metaentry{':packages'}) {
                   11901: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11902: 		    } else {
1.599     albertel 11903: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11904: 		    }
1.736     albertel 11905: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11906: 			my $part=$keyroot;
                   11907: 			$part=~s/^\_//;
1.736     albertel 11908: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11909: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11910: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11911: 			    # ignore package.tab specified default values
                   11912:                             # here &package_tab_default() will fetch those
                   11913: 			    if ($subp eq 'default') { next; }
1.736     albertel 11914: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11915: 			    my $unikey;
                   11916: 			    if ($pack =~ /_0$/) {
                   11917: 				$unikey='parameter_0_'.$name;
                   11918: 				$part=0;
                   11919: 			    } else {
                   11920: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11921: 			    }
1.339     albertel 11922: 			    if ($subp eq 'display') {
                   11923: 				$value.=' [Part: '.$part.']';
                   11924: 			    }
1.599     albertel 11925: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11926: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11927: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11928: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11929: 			    }
1.599     albertel 11930: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11931: 				$metaentry{':'.$unikey}=
                   11932: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11933: 			    }
1.339     albertel 11934: 			}
                   11935: 		    }
                   11936: 		} else {
1.172     www      11937: #
                   11938: # This is not a package - some other kind of start tag
1.339     albertel 11939: #
                   11940: 		    my $entry=$token->[1];
1.1068    www      11941: 		    my $unikey='';
1.175     www      11942: 
1.339     albertel 11943: 		    if ($entry eq 'import') {
1.175     www      11944: #
                   11945: # Importing a library here
1.339     albertel 11946: #
1.1067    www      11947:                         my $location=$parser->get_text('/import');
                   11948:                         my $dir=$filename;
                   11949:                         $dir=~s|[^/]*$||;
                   11950:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11951: 
                   11952:                         my $importid=$token->[2]->{'id'};
1.1068    www      11953:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11954: #
                   11955: # Check metadata for imported file to
                   11956: # see if it contained response items
                   11957: #
                   11958:                         my %currmetaentry = %metaentry;
                   11959:                         my $libresponseorder = &metadata($location,'responseorder');
                   11960:                         my $origfile;
                   11961:                         if ($libresponseorder ne '') {
                   11962:                             if ($#origfiletagids<0) {
                   11963:                                 undef(%importedrespids);
                   11964:                                 undef(%importedpartids);
                   11965:                             }
                   11966:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11967:                             if (@{$importedrespids{$importid}} > 0) {
                   11968:                                 $importedresponses = 1;
                   11969: # We need to get the original file and the imported file to get the response order correct
                   11970: # Load and inspect original file
                   11971:                                 if ($#origfiletagids<0) {
                   11972:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11973:                                     $origfile=&getfile($origfilelocation);
                   11974:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11975:                                 }
                   11976:                             }
                   11977:                         }
                   11978: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11979: # hash populated for imported library file
                   11980:                         %metaentry = %currmetaentry;
                   11981:                         undef(%currmetaentry);
1.1068    www      11982:                         if ($importmode eq 'problem') {
1.1069    www      11983: # Import as problem/response
1.1068    www      11984:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11985:                         } elsif ($importmode eq 'part') {
                   11986: # Import as part(s)
1.1069    www      11987:                            $importedparts=1;
                   11988: # We need to get the original file and the imported file to get the part order correct
                   11989: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11990: # Load and inspect original file if we didn't do that already
                   11991:                            if ($#origfiletagids<0) {
                   11992:                                undef(%importedrespids);
                   11993:                                undef(%importedpartids);
                   11994:                                if ($origfile eq '') {
                   11995:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11996:                                    $origfile=&getfile($origfilelocation);
                   11997:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11998:                                }
1.1070    www      11999:                            }
                   12000: 
1.1069    www      12001: # Load and inspect imported file
                   12002:                            my $impfile=&getfile($location);
                   12003:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12004:                            if ($#impfilepartids>=0) {
                   12005: # This problem had parts
1.1070    www      12006:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12007:                            } else {
                   12008: # Importing by turning a single problem into a problem part
                   12009: # It gets the import-tags ID as part-ID
                   12010:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12011:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12012:                            }
1.1068    www      12013:                         } else {
                   12014: # Normal import
                   12015:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12016:                            if (defined($token->[2]->{'id'})) {
                   12017:                               $unikey.='_'.$token->[2]->{'id'};
                   12018:                            }
1.1067    www      12019:                         }
                   12020: 
1.339     albertel 12021: 			if ($depthcount<20) {
1.736     albertel 12022: 			    my $metadata = 
                   12023: 				&metadata($uri,'keys', $location,$unikey,
                   12024: 					  $depthcount+1);
                   12025: 			    foreach my $meta (split(',',$metadata)) {
                   12026: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12027: 				$metathesekeys{$meta}=1;
1.339     albertel 12028: 			    }
1.1068    www      12029: 			
                   12030:                         }
1.1067    www      12031: 		    } else {
                   12032: #
                   12033: # Not importing, some other kind of non-package, non-library start tag
                   12034: # 
                   12035:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12036:                         if (defined($token->[2]->{'id'})) {
                   12037:                             $unikey.='_'.$token->[2]->{'id'};
                   12038:                         }
1.339     albertel 12039: 			if (defined($token->[2]->{'name'})) { 
                   12040: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12041: 			}
                   12042: 			$metathesekeys{$unikey}=1;
1.736     albertel 12043: 			foreach my $param (@{$token->[3]}) {
                   12044: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12045: 				$token->[2]->{$param};
1.339     albertel 12046: 			}
                   12047: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12048: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12049: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12050: 		 # only ws inside the tag, and not in default, so use default
                   12051: 		 # as value
1.599     albertel 12052: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12053: 			} elsif ( $internaltext =~ /\S/ ) {
                   12054: 		  # something interesting inside the tag
                   12055: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12056: 			} else {
1.908     albertel 12057: 		  # no interesting values, don't set a default
1.339     albertel 12058: 			}
1.172     www      12059: # end of not-a-package not-a-library import
1.339     albertel 12060: 		    }
1.172     www      12061: # end of not-a-package start tag
1.339     albertel 12062: 		}
1.172     www      12063: # the next is the end of "start tag"
1.339     albertel 12064: 	    }
                   12065: 	}
1.483     albertel 12066: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12067: 	$extension = lc($extension);
                   12068: 	if ($extension eq 'htm') { $extension='html'; }
                   12069: 
1.737     albertel 12070: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12071: 	    #no specific packages #how's our extension
                   12072: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12073: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12074: 					 \%metathesekeys);
                   12075: 	}
1.883     albertel 12076: 
                   12077: 	if (!exists($metaentry{':packages'})
                   12078: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12079: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12080: 		#no specific packages well let's get default then
                   12081: 		if ($key!~/^default&/) { next; }
1.488     albertel 12082: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12083: 					     \%metathesekeys);
                   12084: 	    }
                   12085: 	}
1.338     www      12086: # are there custom rights to evaluate
1.599     albertel 12087: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12088: 
1.338     www      12089:     #
                   12090:     # Importing a rights file here
1.339     albertel 12091:     #
                   12092: 	    unless ($depthcount) {
1.599     albertel 12093: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12094: 		my $dir=$filename;
                   12095: 		$dir=~s|[^/]*$||;
                   12096: 		$location=&filelocation($dir,$location);
1.736     albertel 12097: 		my $rights_metadata =
                   12098: 		    &metadata($uri,'keys',$location,'_rights',
                   12099: 			      $depthcount+1);
                   12100: 		foreach my $rights (split(',',$rights_metadata)) {
                   12101: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12102: 		    $metathesekeys{$rights}=1;
1.339     albertel 12103: 		}
                   12104: 	    }
                   12105: 	}
1.737     albertel 12106: 	# uniqifiy package listing
                   12107: 	my %seen;
                   12108: 	my @uniq_packages =
                   12109: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12110: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12111: 
1.1172.2.99  raeburn  12112:         if (($importedresponses) || ($importedparts)) {
                   12113:             if ($importedparts) {
1.1070    www      12114: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12115:                 $metaentry{':partorder'}='';
                   12116:                 $metathesekeys{'partorder'}=1;
                   12117:             }
                   12118:             if ($importedresponses) {
                   12119: # We had imported responses and need to rebuild responseorder
                   12120:                 $metaentry{':responseorder'}='';
                   12121:                 $metathesekeys{'responseorder'}=1;
                   12122:             }
                   12123:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12124:                 my $origid = $origfiletagids[$index+1];
                   12125:                 if ($origfiletagids[$index] eq 'part') {
                   12126: # Original part, part of the problem
                   12127:                     if ($importedparts) {
                   12128:                         $metaentry{':partorder'}.=','.$origid;
                   12129:                     }
                   12130:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12131:                     if ($importedparts) {
                   12132: # We have imported parts at this position
                   12133:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12134:                     }
                   12135:                     if ($importedresponses) {
                   12136: # We have imported responses at this position
                   12137:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12138:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12139:                         }
                   12140:                     }
                   12141:                 } else {
                   12142: # Original response item, part of the problem
                   12143:                     if ($importedresponses) {
                   12144:                         $metaentry{':responseorder'}.=','.$origid;
                   12145:                     }
                   12146:                 }
                   12147:             }
                   12148:             if ($importedparts) {
                   12149:                 $metaentry{':partorder'}=~s/^\,//;
                   12150:             }
                   12151:             if ($importedresponses) {
                   12152:                 $metaentry{':responseorder'}=~s/^\,//;
                   12153:             }
1.1070    www      12154:         }
                   12155: 
1.737     albertel 12156: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12157: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12158: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12159: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12160: # this is the end of "was not already recently cached
1.71      www      12161:     }
1.599     albertel 12162:     return $metaentry{':'.$what};
1.261     albertel 12163: }
                   12164: 
1.488     albertel 12165: sub metadata_create_package_def {
1.483     albertel 12166:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12167:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12168:     if ($subp eq 'default') { next; }
                   12169:     
1.599     albertel 12170:     if (defined($metaentry{':packages'})) {
                   12171: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12172:     } else {
1.599     albertel 12173: 	$metaentry{':packages'}=$package;
1.483     albertel 12174:     }
                   12175:     my $value=$packagetab{$key};
                   12176:     my $unikey;
                   12177:     $unikey='parameter_0_'.$name;
1.599     albertel 12178:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12179:     $$metathesekeys{$unikey}=1;
1.599     albertel 12180:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12181: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12182:     }
1.599     albertel 12183:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12184: 	$metaentry{':'.$unikey}=
                   12185: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12186:     }
                   12187: }
                   12188: 
1.261     albertel 12189: sub metadata_generate_part0 {
                   12190:     my ($metadata,$metacache,$uri) = @_;
                   12191:     my %allnames;
1.737     albertel 12192:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12193: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12194: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12195: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12196: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12197: 	    $allnames{$name}=$part;
                   12198: 	  }
                   12199: 	}
                   12200:     }
                   12201:     foreach my $name (keys(%allnames)) {
                   12202:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12203:       my $key=":parameter_0_$name";
1.261     albertel 12204:       $$metacache{"$key.part"}='0';
                   12205:       $$metacache{"$key.name"}=$name;
1.428     albertel 12206:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12207: 					   $allnames{$name}.'_'.$name.
                   12208: 					   '.type'};
1.428     albertel 12209:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12210: 			     '.display'};
1.644     www      12211:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12212:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12213:       $$metacache{"$key.display"}=$olddis;
                   12214:     }
1.71      www      12215: }
                   12216: 
1.764     albertel 12217: # ------------------------------------------------------ Devalidate title cache
                   12218: 
                   12219: sub devalidate_title_cache {
                   12220:     my ($url)=@_;
                   12221:     if (!$env{'request.course.id'}) { return; }
                   12222:     my $symb=&symbread($url);
                   12223:     if (!$symb) { return; }
                   12224:     my $key=$env{'request.course.id'}."\0".$symb;
                   12225:     &devalidate_cache_new('title',$key);
                   12226: }
                   12227: 
1.1014    droeschl 12228: # ------------------------------------------------- Get the title of a course
                   12229: 
                   12230: sub current_course_title {
                   12231:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12232: }
1.301     www      12233: # ------------------------------------------------- Get the title of a resource
                   12234: 
                   12235: sub gettitle {
                   12236:     my $urlsymb=shift;
                   12237:     my $symb=&symbread($urlsymb);
1.534     albertel 12238:     if ($symb) {
1.620     albertel 12239: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12240: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12241: 	if (defined($cached)) { 
                   12242: 	    return $result;
                   12243: 	}
1.534     albertel 12244: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12245: 	my $title='';
1.907     albertel 12246: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12247: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12248: 	} else {
                   12249: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12250: 		    &GDBM_READER(),0640)) {
                   12251: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12252: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12253: 		untie(%bighash);
                   12254: 	    }
1.534     albertel 12255: 	}
                   12256: 	$title=~s/\&colon\;/\:/gs;
                   12257: 	if ($title) {
1.1159    www      12258: # Remember both $symb and $title for dynamic metadata
                   12259:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12260:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12261: # Cache this title and then return it
1.599     albertel 12262: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12263: 	}
                   12264: 	$urlsymb=$url;
                   12265:     }
                   12266:     my $title=&metadata($urlsymb,'title');
                   12267:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12268:     return $title;
1.301     www      12269: }
1.613     albertel 12270: 
1.614     albertel 12271: sub get_slot {
                   12272:     my ($which,$cnum,$cdom)=@_;
                   12273:     if (!$cnum || !$cdom) {
1.790     albertel 12274: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12275: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12276: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12277:     }
1.703     albertel 12278:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12279:     my %slotinfo;
                   12280:     if (exists($remembered{$key})) {
                   12281: 	$slotinfo{$which} = $remembered{$key};
                   12282:     } else {
                   12283: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12284: 	&Apache::lonhomework::showhash(%slotinfo);
                   12285: 	my ($tmp)=keys(%slotinfo);
                   12286: 	if ($tmp=~/^error:/) { return (); }
                   12287: 	$remembered{$key} = $slotinfo{$which};
                   12288:     }
1.616     albertel 12289:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12290: 	return %{$slotinfo{$which}};
                   12291:     }
                   12292:     return $slotinfo{$which};
1.614     albertel 12293: }
1.1150    raeburn  12294: 
                   12295: sub get_reservable_slots {
                   12296:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12297:     my $now = time;
                   12298:     my $reservable_info;
                   12299:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12300:     if (exists($remembered{$key})) {
                   12301:         $reservable_info = $remembered{$key};
                   12302:     } else {
                   12303:         my %resv;
                   12304:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12305:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12306:         $reservable_info = \%resv;
                   12307:         $remembered{$key} = $reservable_info;
                   12308:     }
                   12309:     return $reservable_info;
                   12310: }
                   12311: 
                   12312: sub get_course_slots {
                   12313:     my ($cnum,$cdom) = @_;
                   12314:     my $hashid=$cnum.':'.$cdom;
                   12315:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12316:     if (defined($cached)) {
                   12317:         if (ref($result) eq 'HASH') {
                   12318:             return %{$result};
                   12319:         }
                   12320:     } else {
                   12321:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12322:         my ($tmp) = keys(%slots);
                   12323:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12324:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12325:             return %slots;
                   12326:         }
                   12327:     }
                   12328:     return;
                   12329: }
                   12330: 
                   12331: sub devalidate_slots_cache {
                   12332:     my ($cnum,$cdom)=@_;
                   12333:     my $hashid=$cnum.':'.$cdom;
                   12334:     &devalidate_cache_new('allslots',$hashid);
                   12335: }
                   12336: 
1.1172.2.8  raeburn  12337: sub get_coursechange {
                   12338:     my ($cdom,$cnum) = @_;
                   12339:     if ($cdom eq '' || $cnum eq '') {
                   12340:         return unless ($env{'request.course.id'});
                   12341:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12342:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12343:     }
                   12344:     my $hashid=$cdom.'_'.$cnum;
                   12345:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12346:     if ((defined($cached)) && ($change ne '')) {
                   12347:         return $change;
                   12348:     } else {
                   12349:         my %crshash;
                   12350:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12351:         if ($crshash{'internal.contentchange'} eq '') {
                   12352:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12353:             if ($change eq '') {
                   12354:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12355:                 $change = $crshash{'internal.created'};
                   12356:             }
                   12357:         } else {
                   12358:             $change = $crshash{'internal.contentchange'};
                   12359:         }
                   12360:         my $cachetime = 600;
                   12361:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12362:     }
                   12363:     return $change;
                   12364: }
                   12365: 
                   12366: sub devalidate_coursechange_cache {
                   12367:     my ($cnum,$cdom)=@_;
                   12368:     my $hashid=$cnum.':'.$cdom;
                   12369:     &devalidate_cache_new('crschange',$hashid);
                   12370: }
                   12371: 
1.31      www      12372: # ------------------------------------------------- Update symbolic store links
                   12373: 
                   12374: sub symblist {
                   12375:     my ($mapname,%newhash)=@_;
1.438     www      12376:     $mapname=&deversion(&declutter($mapname));
1.31      www      12377:     my %hash;
1.620     albertel 12378:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12379:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12380:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12381: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12382: 		next if ($url eq 'last_known'
                   12383: 			 && $env{'form.no_update_last_known'});
                   12384: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12385: 						    $newhash{$url}->[1],
                   12386: 						    $newhash{$url}->[0]);
1.191     harris41 12387:             }
1.31      www      12388:             if (untie(%hash)) {
                   12389: 		return 'ok';
                   12390:             }
                   12391:         }
                   12392:     }
                   12393:     return 'error';
1.212     www      12394: }
                   12395: 
                   12396: # --------------------------------------------------------------- Verify a symb
                   12397: 
                   12398: sub symbverify {
1.1172.2.11  raeburn  12399:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12400:     my $thisfn=$thisurl;
1.439     www      12401:     $thisfn=&declutter($thisfn);
1.215     www      12402: # direct jump to resource in page or to a sequence - will construct own symbs
                   12403:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12404: # check URL part
1.409     www      12405:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12406: 
1.431     www      12407:     unless ($url eq $thisfn) { return 0; }
1.213     www      12408: 
1.216     www      12409:     $symb=&symbclean($symb);
1.510     www      12410:     $thisurl=&deversion($thisurl);
1.439     www      12411:     $thisfn=&deversion($thisfn);
1.213     www      12412: 
                   12413:     my %bighash;
                   12414:     my $okay=0;
1.431     www      12415: 
1.620     albertel 12416:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12417:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12418:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12419:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12420:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12421:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12422:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12423:             }
                   12424:         }
                   12425:         my $ids;
1.1172.2.118.  .5(raebu 12426:20):         if ($map =~ m{^uploaded/.+\.page$}) {
                   12427:20):             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12428:         } else {
                   12429:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12430:         }
1.1102    raeburn  12431:         unless ($ids) {
1.1172.2.13  raeburn  12432:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12433:             $ids=$bighash{$idkey};
1.216     www      12434:         }
                   12435:         if ($ids) {
                   12436: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12437:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12438:                 $symb =~ s/\?.+$//;
                   12439:             }
1.800     albertel 12440: 	    foreach my $id (split(/\,/,$ids)) {
                   12441: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12442:                if (
                   12443:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12444:    eq $symb) {
1.1172.2.11  raeburn  12445:                    if (ref($encstate)) {
                   12446:                        $$encstate = $bighash{'encrypted_'.$id};
                   12447:                    }
1.1172.2.13  raeburn  12448:                    if (($env{'request.role.adv'}) ||
                   12449:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12450:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12451:                        $okay=1;
                   12452:                        last;
                   12453:                    }
                   12454:                }
                   12455:            }
1.216     www      12456:         }
1.213     www      12457: 	untie(%bighash);
                   12458:     }
                   12459:     return $okay;
1.31      www      12460: }
                   12461: 
1.210     www      12462: # --------------------------------------------------------------- Clean-up symb
                   12463: 
                   12464: sub symbclean {
                   12465:     my $symb=shift;
1.568     albertel 12466:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12467: # remove version from map
                   12468:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12469: 
1.210     www      12470: # remove version from URL
                   12471:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12472: 
1.507     www      12473: # remove wrapper
                   12474: 
1.510     www      12475:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12476:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12477:     return $symb;
1.409     www      12478: }
                   12479: 
                   12480: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12481: 
                   12482: sub encode_symb {
                   12483:     my ($map,$resid,$url)=@_;
                   12484:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12485: }
1.409     www      12486: 
                   12487: sub decode_symb {
1.568     albertel 12488:     my $symb=shift;
                   12489:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12490:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12491:     return (&fixversion($map),$resid,&fixversion($url));
                   12492: }
                   12493: 
                   12494: sub fixversion {
                   12495:     my $fn=shift;
1.609     banghart 12496:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12497:     my %bighash;
                   12498:     my $uri=&clutter($fn);
1.620     albertel 12499:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12500: # is this cached?
1.599     albertel 12501:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12502:     if (defined($cached)) { return $result; }
                   12503: # unfortunately not cached, or expired
1.620     albertel 12504:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12505: 	    &GDBM_READER(),0640)) {
                   12506:  	if ($bighash{'version_'.$uri}) {
                   12507:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12508:  	    unless (($version eq 'mostrecent') || 
                   12509: 		    ($version==&getversion($uri))) {
1.440     www      12510:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12511:  	    }
                   12512:  	}
                   12513:  	untie %bighash;
1.413     www      12514:     }
1.599     albertel 12515:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12516: }
                   12517: 
                   12518: sub deversion {
                   12519:     my $url=shift;
                   12520:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12521:     return $url;
1.210     www      12522: }
                   12523: 
1.31      www      12524: # ------------------------------------------------------ Return symb list entry
                   12525: 
                   12526: sub symbread {
1.1172.2.118.  .8(raebu 12527:20):     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
          .9(raebu 12528:20):         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12529:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.118.  .9(raebu 12530:20):     if (defined($env{$cache_str})) {
          .8(raebu 12531:20):         unless (ref($possibles) eq 'HASH') {
                   12532:20):             if ($ignorecachednull) {
                   12533:20):                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12534:20):             } else {
                   12535:20):                 return $env{$cache_str};
                   12536:20):             }
1.1172.2.66  raeburn  12537:         }
                   12538:     }
1.242     www      12539: # no filename provided? try from environment
1.1172.2.54  raeburn  12540:     unless ($thisfn) {
1.620     albertel 12541:         if ($env{'request.symb'}) {
1.1172.2.118.  .9(raebu 12542:20):             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12543:         }
                   12544:         $thisfn=$env{'request.filename'};
1.44      www      12545:     }
1.569     albertel 12546:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12547: # is that filename actually a symb? Verify, clean, and return
                   12548:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12549: 	if (&symbverify($thisfn,$1)) {
1.1172.2.118.  .9(raebu 12550:20): 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12551: 	}
1.242     www      12552:     }
1.44      www      12553:     $thisfn=declutter($thisfn);
1.31      www      12554:     my %hash;
1.37      www      12555:     my %bighash;
                   12556:     my $syval='';
1.620     albertel 12557:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12558:         my $targetfn = $thisfn;
1.609     banghart 12559:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12560:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12561:         }
1.687     albertel 12562: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12563: 	    $targetfn=$1;
                   12564: 	}
1.1172.2.118.  .9(raebu 12565:20):         unless ($ignoresymbdb) {
          .8(raebu 12566:20):             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12567:20):                           &GDBM_READER(),0640)) {
                   12568:20): 	        $syval=$hash{$targetfn};
                   12569:20):                 untie(%hash);
                   12570:20):             }
          .9(raebu 12571:20):             if ($syval && $checkforblock) {
                   12572:20):                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
          .8(raebu 12573:20):                 if (@blockers) {
                   12574:20):                     $syval='';
                   12575:20):                 }
                   12576:20):             }
1.37      www      12577:         }
                   12578: # ---------------------------------------------------------- There was an entry
                   12579:         if ($syval) {
1.601     albertel 12580: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12581: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12582: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12583: 		    #return $env{$cache_str}='';
1.601     albertel 12584: 		#}    
                   12585: 		#$syval.=$1;
                   12586: 	    #}
1.37      www      12587:         } else {
                   12588: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12589:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12590:                             &GDBM_READER(),0640)) {
1.37      www      12591: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12592:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12593:               unless ($ids) { 
                   12594:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12595:               }
                   12596:               unless ($ids) {
                   12597: # alias?
                   12598: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12599:               }
1.37      www      12600:               if ($ids) {
                   12601: # ------------------------------------------------------------------- Has ID(s)
                   12602:                  my @possibilities=split(/\,/,$ids);
1.39      www      12603:                  if ($#possibilities==0) {
                   12604: # ----------------------------------------------- There is only one possibility
1.37      www      12605: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12606: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12607: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12608:                      if (ref($possibles) eq 'HASH') {
1.1172.2.118.  .8(raebu 12609:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12610:20):                              $possibles->{$syval} = 1;
                   12611:20):                          }
1.1172.2.66  raeburn  12612:                      }
                   12613:                      if ($checkforblock) {
1.1172.2.118.  .8(raebu 12614:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12615:20):                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
                   12616:20):                              if (@blockers) {
                   12617:20):                                  $syval = '';
                   12618:20):                                  untie(%bighash);
                   12619:20):                                  return $env{$cache_str}='';
                   12620:20):                              }
1.1172.2.66  raeburn  12621:                          }
                   12622:                      }
                   12623:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12624: # ------------------------------------------ There is more than one possibility
                   12625:                      my $realpossible=0;
1.800     albertel 12626:                      foreach my $id (@possibilities) {
                   12627: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12628:                          my $canaccess;
                   12629:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12630:                              $canaccess = 1;
                   12631:                          } else {
                   12632:                              $canaccess = &allowed('bre',$file);
                   12633:                          }
                   12634:                          if ($canaccess) {
                   12635:          		     my ($mapid,$resid)=split(/\./,$id);
                   12636:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12637:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12638:                                                              $resid,$thisfn);
1.1172.2.118.  .8(raebu 12639:20):                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
                   12640:20):                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12641:                                  if ($checkforblock) {
1.1172.2.118.  .8(raebu 12642:20):                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
                   12643:20):                                      if (@blockers > 0) {
                   12644:20):                                          $syval = '';
                   12645:20):                                      } else {
1.1172.2.66  raeburn  12646:                                          $syval = $poss_syval;
                   12647:                                          $realpossible++;
                   12648:                                      }
                   12649:                                  } else {
                   12650:                                      $syval = $poss_syval;
                   12651:                                      $realpossible++;
                   12652:                                  }
1.1172.2.118.  .8(raebu 12653:20):                                  if ($syval) {
                   12654:20):                                      if (ref($possibles) eq 'HASH') {
                   12655:20):                                          $possibles->{$syval} = 1;
                   12656:20):                                      }
                   12657:20):                                  }
1.1172.2.66  raeburn  12658:                              }
1.39      www      12659: 			 }
1.191     harris41 12660:                      }
1.39      www      12661: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12662:                  } else {
                   12663:                      $syval='';
1.37      www      12664:                  }
                   12665: 	      }
1.1172.2.66  raeburn  12666:               untie(%bighash);
1.481     raeburn  12667:            }
1.31      www      12668:         }
1.62      www      12669:         if ($syval) {
1.1172.2.118.  .9(raebu 12670:20): 	    return $env{$cache_str}=$syval;
1.62      www      12671:         }
1.31      www      12672:     }
1.949     raeburn  12673:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12674:     return $env{$cache_str}='';
1.31      www      12675: }
                   12676: 
                   12677: # ---------------------------------------------------------- Return random seed
                   12678: 
1.32      www      12679: sub numval {
                   12680:     my $txt=shift;
                   12681:     $txt=~tr/A-J/0-9/;
                   12682:     $txt=~tr/a-j/0-9/;
                   12683:     $txt=~tr/K-T/0-9/;
                   12684:     $txt=~tr/k-t/0-9/;
                   12685:     $txt=~tr/U-Z/0-5/;
                   12686:     $txt=~tr/u-z/0-5/;
                   12687:     $txt=~s/\D//g;
1.564     albertel 12688:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12689:     return int($txt);
1.368     albertel 12690: }
                   12691: 
1.484     albertel 12692: sub numval2 {
                   12693:     my $txt=shift;
                   12694:     $txt=~tr/A-J/0-9/;
                   12695:     $txt=~tr/a-j/0-9/;
                   12696:     $txt=~tr/K-T/0-9/;
                   12697:     $txt=~tr/k-t/0-9/;
                   12698:     $txt=~tr/U-Z/0-5/;
                   12699:     $txt=~tr/u-z/0-5/;
                   12700:     $txt=~s/\D//g;
                   12701:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12702:     my $total;
                   12703:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12704:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12705:     return int($total);
                   12706: }
                   12707: 
1.575     albertel 12708: sub numval3 {
                   12709:     use integer;
                   12710:     my $txt=shift;
                   12711:     $txt=~tr/A-J/0-9/;
                   12712:     $txt=~tr/a-j/0-9/;
                   12713:     $txt=~tr/K-T/0-9/;
                   12714:     $txt=~tr/k-t/0-9/;
                   12715:     $txt=~tr/U-Z/0-5/;
                   12716:     $txt=~tr/u-z/0-5/;
                   12717:     $txt=~s/\D//g;
                   12718:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12719:     my $total;
                   12720:     foreach my $val (@txts) { $total+=$val; }
                   12721:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12722:     return $total;
                   12723: }
                   12724: 
1.675     albertel 12725: sub digest {
                   12726:     my ($data)=@_;
                   12727:     my $digest=&Digest::MD5::md5($data);
                   12728:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12729:     my ($e,$f);
                   12730:     {
                   12731:         use integer;
                   12732:         $e=($a+$b);
                   12733:         $f=($c+$d);
                   12734:         if ($_64bit) {
                   12735:             $e=(($e<<32)>>32);
                   12736:             $f=(($f<<32)>>32);
                   12737:         }
                   12738:     }
                   12739:     if (wantarray) {
                   12740: 	return ($e,$f);
                   12741:     } else {
                   12742: 	my $g;
                   12743: 	{
                   12744: 	    use integer;
                   12745: 	    $g=($e+$f);
                   12746: 	    if ($_64bit) {
                   12747: 		$g=(($g<<32)>>32);
                   12748: 	    }
                   12749: 	}
                   12750: 	return $g;
                   12751:     }
                   12752: }
                   12753: 
1.368     albertel 12754: sub latest_rnd_algorithm_id {
1.675     albertel 12755:     return '64bit5';
1.366     albertel 12756: }
1.32      www      12757: 
1.503     albertel 12758: sub get_rand_alg {
                   12759:     my ($courseid)=@_;
1.790     albertel 12760:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12761:     if ($courseid) {
1.620     albertel 12762: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12763:     }
                   12764:     return &latest_rnd_algorithm_id();
                   12765: }
                   12766: 
1.562     albertel 12767: sub validCODE {
                   12768:     my ($CODE)=@_;
                   12769:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12770:     return 0;
                   12771: }
                   12772: 
1.491     albertel 12773: sub getCODE {
1.620     albertel 12774:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12775:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12776: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12777: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12778: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12779:     }
                   12780:     return undef;
                   12781: }
1.1133    foxr     12782: #
                   12783: #  Determines the random seed for a specific context:
                   12784: #
                   12785: # parameters:
                   12786: #   symb      - in course context the symb for the seed.
                   12787: #   course_id - The course id of the form domain_coursenum.
                   12788: #   domain    - Domain for the user.
                   12789: #   course    - Course for the user.
                   12790: #   cenv      - environment of the course.
                   12791: #
                   12792: # NOTE:
                   12793: #   All parameters are picked out of the environment if missing
                   12794: #   or not defined.
                   12795: #   If a symb cannot be determined the current time is used instead.
                   12796: #
                   12797: #  For a given well defined symb, courside, domain, username,
                   12798: #  and course environment, the seed is reproducible.
                   12799: #
1.31      www      12800: sub rndseed {
1.1133    foxr     12801:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12802:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12803:     if (!defined($symb)) {
1.366     albertel 12804: 	unless ($symb=$wsymb) { return time; }
                   12805:     }
1.1146    foxr     12806:     if (!defined $courseid) { 
                   12807: 	$courseid=$wcourseid; 
                   12808:     }
                   12809:     if (!defined $domain) { $domain=$wdomain; }
                   12810:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12811: 
                   12812:     my $which;
                   12813:     if (defined($cenv->{'rndseed'})) {
                   12814: 	$which = $cenv->{'rndseed'};
                   12815:     } else {
                   12816: 	$which =&get_rand_alg($courseid);
                   12817:     }
1.491     albertel 12818:     if (defined(&getCODE())) {
1.675     albertel 12819: 	if ($which eq '64bit5') {
                   12820: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12821: 	} elsif ($which eq '64bit4') {
1.575     albertel 12822: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12823: 	} else {
                   12824: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12825: 	}
1.675     albertel 12826:     } elsif ($which eq '64bit5') {
                   12827: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12828:     } elsif ($which eq '64bit4') {
                   12829: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12830:     } elsif ($which eq '64bit3') {
                   12831: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12832:     } elsif ($which eq '64bit2') {
                   12833: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12834:     } elsif ($which eq '64bit') {
                   12835: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12836:     }
                   12837:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12838: }
                   12839: 
                   12840: sub rndseed_32bit {
                   12841:     my ($symb,$courseid,$domain,$username)=@_;
                   12842:     {
                   12843: 	use integer;
                   12844: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12845: 	my $symbseed=numval($symb) << 22;
                   12846: 	my $namechck=unpack("%32C*",$username) << 17;
                   12847: 	my $nameseed=numval($username) << 12;
                   12848: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12849: 	my $courseseed=unpack("%32C*",$courseid);
                   12850: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12851: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12852: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12853: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12854: 	return $num;
                   12855:     }
                   12856: }
                   12857: 
                   12858: sub rndseed_64bit {
                   12859:     my ($symb,$courseid,$domain,$username)=@_;
                   12860:     {
                   12861: 	use integer;
                   12862: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12863: 	my $symbseed=numval($symb) << 10;
                   12864: 	my $namechck=unpack("%32S*",$username);
                   12865: 	
                   12866: 	my $nameseed=numval($username) << 21;
                   12867: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12868: 	my $courseseed=unpack("%32S*",$courseid);
                   12869: 	
                   12870: 	my $num1=$symbchck+$symbseed+$namechck;
                   12871: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12872: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12873: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12874: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12875: 	return "$num1,$num2";
1.155     albertel 12876:     }
1.366     albertel 12877: }
                   12878: 
1.443     albertel 12879: sub rndseed_64bit2 {
                   12880:     my ($symb,$courseid,$domain,$username)=@_;
                   12881:     {
                   12882: 	use integer;
                   12883: 	# strings need to be an even # of cahracters long, it it is odd the
                   12884:         # last characters gets thrown away
                   12885: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12886: 	my $symbseed=numval($symb) << 10;
                   12887: 	my $namechck=unpack("%32S*",$username.' ');
                   12888: 	
                   12889: 	my $nameseed=numval($username) << 21;
1.501     albertel 12890: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12891: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12892: 	
                   12893: 	my $num1=$symbchck+$symbseed+$namechck;
                   12894: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12895: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12896: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12897: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12898: 	return "$num1,$num2";
                   12899:     }
                   12900: }
                   12901: 
                   12902: sub rndseed_64bit3 {
                   12903:     my ($symb,$courseid,$domain,$username)=@_;
                   12904:     {
                   12905: 	use integer;
                   12906: 	# strings need to be an even # of cahracters long, it it is odd the
                   12907:         # last characters gets thrown away
                   12908: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12909: 	my $symbseed=numval2($symb) << 10;
                   12910: 	my $namechck=unpack("%32S*",$username.' ');
                   12911: 	
                   12912: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12913: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12914: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12915: 	
                   12916: 	my $num1=$symbchck+$symbseed+$namechck;
                   12917: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12918: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12919: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12920: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12921: 	
1.503     albertel 12922: 	return "$num1:$num2";
1.443     albertel 12923:     }
                   12924: }
                   12925: 
1.575     albertel 12926: sub rndseed_64bit4 {
                   12927:     my ($symb,$courseid,$domain,$username)=@_;
                   12928:     {
                   12929: 	use integer;
                   12930: 	# strings need to be an even # of cahracters long, it it is odd the
                   12931:         # last characters gets thrown away
                   12932: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12933: 	my $symbseed=numval3($symb) << 10;
                   12934: 	my $namechck=unpack("%32S*",$username.' ');
                   12935: 	
                   12936: 	my $nameseed=numval3($username) << 21;
                   12937: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12938: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12939: 	
                   12940: 	my $num1=$symbchck+$symbseed+$namechck;
                   12941: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12942: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12943: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12944: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12945: 	
1.575     albertel 12946: 	return "$num1:$num2";
                   12947:     }
                   12948: }
                   12949: 
1.675     albertel 12950: sub rndseed_64bit5 {
                   12951:     my ($symb,$courseid,$domain,$username)=@_;
                   12952:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12953:     return "$num1:$num2";
                   12954: }
                   12955: 
1.366     albertel 12956: sub rndseed_CODE_64bit {
                   12957:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12958:     {
1.366     albertel 12959: 	use integer;
1.443     albertel 12960: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12961: 	my $symbseed=numval2($symb);
1.491     albertel 12962: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12963: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12964: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12965: 	my $num1=$symbseed+$CODEchck;
                   12966: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12967: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12968: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12969: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12970: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12971: 	return "$num1:$num2";
1.366     albertel 12972:     }
                   12973: }
                   12974: 
1.575     albertel 12975: sub rndseed_CODE_64bit4 {
                   12976:     my ($symb,$courseid,$domain,$username)=@_;
                   12977:     {
                   12978: 	use integer;
                   12979: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12980: 	my $symbseed=numval3($symb);
                   12981: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12982: 	my $CODEseed=numval3(&getCODE());
                   12983: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12984: 	my $num1=$symbseed+$CODEchck;
                   12985: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12986: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12987: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12988: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12989: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12990: 	return "$num1:$num2";
                   12991:     }
                   12992: }
                   12993: 
1.675     albertel 12994: sub rndseed_CODE_64bit5 {
                   12995:     my ($symb,$courseid,$domain,$username)=@_;
                   12996:     my $code = &getCODE();
                   12997:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12998:     return "$num1:$num2";
                   12999: }
                   13000: 
1.366     albertel 13001: sub setup_random_from_rndseed {
                   13002:     my ($rndseed)=@_;
1.503     albertel 13003:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13004: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13005:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13006:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13007:         } else {
                   13008:             &Math::Random::random_set_seed($num1,$num2);
                   13009:         }
1.366     albertel 13010:     } else {
                   13011: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13012:     }
1.36      albertel 13013: }
                   13014: 
1.474     albertel 13015: sub latest_receipt_algorithm_id {
1.835     albertel 13016:     return 'receipt3';
1.474     albertel 13017: }
                   13018: 
1.480     www      13019: sub recunique {
                   13020:     my $fucourseid=shift;
                   13021:     my $unique;
1.835     albertel 13022:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13023: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13024: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13025:     } else {
                   13026: 	$unique=$perlvar{'lonReceipt'};
                   13027:     }
                   13028:     return unpack("%32C*",$unique);
                   13029: }
                   13030: 
                   13031: sub recprefix {
                   13032:     my $fucourseid=shift;
                   13033:     my $prefix;
1.835     albertel 13034:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13035: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13036: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13037:     } else {
                   13038: 	$prefix=$perlvar{'lonHostID'};
                   13039:     }
                   13040:     return unpack("%32C*",$prefix);
                   13041: }
                   13042: 
1.76      www      13043: sub ireceipt {
1.474     albertel 13044:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13045: 
                   13046:     my $return =&recprefix($fucourseid).'-';
                   13047: 
                   13048:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13049: 	$env{'request.state'} eq 'construct') {
                   13050: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13051: 	return $return;
                   13052:     }
                   13053: 
1.76      www      13054:     my $cuname=unpack("%32C*",$funame);
                   13055:     my $cudom=unpack("%32C*",$fudom);
                   13056:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13057:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13058:     my $cunique=&recunique($fucourseid);
1.474     albertel 13059:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13060:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13061: 
1.790     albertel 13062: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13063: 			       
                   13064: 	$return.= ($cunique%$cuname+
                   13065: 		   $cunique%$cudom+
                   13066: 		   $cusymb%$cuname+
                   13067: 		   $cusymb%$cudom+
                   13068: 		   $cucourseid%$cuname+
                   13069: 		   $cucourseid%$cudom+
                   13070: 		   $cpart%$cuname+
                   13071: 		   $cpart%$cudom);
                   13072:     } else {
                   13073: 	$return.= ($cunique%$cuname+
                   13074: 		   $cunique%$cudom+
                   13075: 		   $cusymb%$cuname+
                   13076: 		   $cusymb%$cudom+
                   13077: 		   $cucourseid%$cuname+
                   13078: 		   $cucourseid%$cudom);
                   13079:     }
                   13080:     return $return;
1.76      www      13081: }
                   13082: 
                   13083: sub receipt {
1.474     albertel 13084:     my ($part)=@_;
1.790     albertel 13085:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13086:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13087: }
1.260     ng       13088: 
1.790     albertel 13089: sub whichuser {
                   13090:     my ($passedsymb)=@_;
                   13091:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13092:     if (defined($env{'form.grade_symb'})) {
                   13093: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13094: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13095: 	if (!$allowed &&
                   13096: 	    exists($env{'request.course.sec'}) &&
                   13097: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13098: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13099: 			      '/'.$env{'request.course.sec'});
                   13100: 	}
                   13101: 	if ($allowed) {
                   13102: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13103: 	    $courseid=$tmp_courseid;
                   13104: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13105: 	    ($name)=&get_env_multiple('form.grade_username');
                   13106: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13107: 	}
                   13108:     }
                   13109:     if (!$passedsymb) {
                   13110: 	$symb=&symbread();
                   13111:     } else {
                   13112: 	$symb=$passedsymb;
                   13113:     }
                   13114:     $courseid=$env{'request.course.id'};
                   13115:     $domain=$env{'user.domain'};
                   13116:     $name=$env{'user.name'};
                   13117:     if ($name eq 'public' && $domain eq 'public') {
                   13118: 	if (!defined($env{'form.username'})) {
                   13119: 	    $env{'form.username'}.=time.rand(10000000);
                   13120: 	}
                   13121: 	$name.=$env{'form.username'};
                   13122:     }
                   13123:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13124: 
                   13125: }
                   13126: 
1.36      albertel 13127: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13128: # returns either the contents of the file or 
                   13129: # -1 if the file doesn't exist
1.481     raeburn  13130: #
                   13131: # if the target is a file that was uploaded via DOCS, 
                   13132: # a check will be made to see if a current copy exists on the local server,
                   13133: # if it does this will be served, otherwise a copy will be retrieved from
                   13134: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13135: # the local server.   
1.472     albertel 13136: 
1.36      albertel 13137: sub getfile {
1.538     albertel 13138:     my ($file) = @_;
1.609     banghart 13139:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13140:     &repcopy($file);
                   13141:     return &readfile($file);
                   13142: }
                   13143: 
                   13144: sub repcopy_userfile {
                   13145:     my ($file)=@_;
1.1142    raeburn  13146:     my $londocroot = $perlvar{'lonDocRoot'};
                   13147:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13148:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13149:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13150: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13151:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13152:     if (-e "$file") {
1.828     www      13153: # we already have a local copy, check it out
1.538     albertel 13154: 	my @fileinfo = stat($file);
1.828     www      13155: 	my $rtncode;
                   13156: 	my $info;
1.538     albertel 13157: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13158: 	if ($lwpresp ne 'ok') {
1.828     www      13159: # there is no such file anymore, even though we had a local copy
1.482     albertel 13160: 	    if ($rtncode eq '404') {
1.538     albertel 13161: 		unlink($file);
1.482     albertel 13162: 	    }
                   13163: 	    return -1;
                   13164: 	}
                   13165: 	if ($info < $fileinfo[9]) {
1.828     www      13166: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13167: 	    return 'ok';
1.828     www      13168: 	} else {
                   13169: # the file is outdated, get rid of it
                   13170: 	    unlink($file);
1.482     albertel 13171: 	}
1.828     www      13172:     }
                   13173: # one way or the other, at this point, we don't have the file
                   13174: # construct the correct path for the file
                   13175:     my @parts = ($cdom,$cnum); 
                   13176:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13177: 	push @parts, split(/\//,$1);
                   13178:     }
                   13179:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13180:     foreach my $part (@parts) {
                   13181: 	$path .= '/'.$part;
                   13182: 	if (!-e $path) {
                   13183: 	    mkdir($path,0770);
1.482     albertel 13184: 	}
                   13185:     }
1.828     www      13186: # now the path exists for sure
                   13187: # get a user agent
                   13188:     my $ua=new LWP::UserAgent;
                   13189:     my $transferfile=$file.'.in.transfer';
                   13190: # FIXME: this should flock
                   13191:     if (-e $transferfile) { return 'ok'; }
                   13192:     my $request;
                   13193:     $uri=~s/^\///;
1.980     raeburn  13194:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13195:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13196:     my $protocol = $protocol{$homeserver};
                   13197:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13198:20):     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13199:     my $response=$ua->request($request,$transferfile);
                   13200: # did it work?
                   13201:     if ($response->is_error()) {
                   13202: 	unlink($transferfile);
                   13203: 	&logthis("Userfile repcopy failed for $uri");
                   13204: 	return -1;
                   13205:     }
                   13206: # worked, rename the transfer file
                   13207:     rename($transferfile,$file);
1.607     raeburn  13208:     return 'ok';
1.481     raeburn  13209: }
                   13210: 
1.517     albertel 13211: sub tokenwrapper {
                   13212:     my $uri=shift;
1.980     raeburn  13213:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13214:     $uri=~s|^/||;
1.620     albertel 13215:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13216:     my $token=$1;
1.552     albertel 13217:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13218:     if ($udom && $uname && $file) {
                   13219: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13220:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13221:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.118.  .3(raebu 13222:20):         my $hostname = &hostname($homeserver);
1.980     raeburn  13223:         my $protocol = $protocol{$homeserver};
                   13224:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13225:20):         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13226:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13227:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13228:     } else {
                   13229:         return '/adm/notfound.html';
                   13230:     }
                   13231: }
                   13232: 
1.828     www      13233: # call with reqtype HEAD: get last modification time
                   13234: # call with reqtype GET: get the file contents
                   13235: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13236: #
1.481     raeburn  13237: sub getuploaded {
                   13238:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13239:     $uri=~s/^\///;
1.980     raeburn  13240:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13241:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13242:     my $protocol = $protocol{$homeserver};
                   13243:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13244:20):     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13245:     my $ua=new LWP::UserAgent;
                   13246:     my $request=new HTTP::Request($reqtype,$uri);
                   13247:     my $response=$ua->request($request);
                   13248:     $$rtncode = $response->code;
1.482     albertel 13249:     if (! $response->is_success()) {
                   13250: 	return 'failed';
                   13251:     }      
                   13252:     if ($reqtype eq 'HEAD') {
1.486     www      13253: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13254:     } elsif ($reqtype eq 'GET') {
                   13255: 	$$info = $response->content;
1.472     albertel 13256:     }
1.482     albertel 13257:     return 'ok';
1.36      albertel 13258: }
                   13259: 
1.481     raeburn  13260: sub readfile {
                   13261:     my $file = shift;
                   13262:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13263:     my $fh;
1.1172.2.96  raeburn  13264:     open($fh,"<",$file);
1.481     raeburn  13265:     my $a='';
1.800     albertel 13266:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13267:     return $a;
                   13268: }
                   13269: 
1.36      albertel 13270: sub filelocation {
1.590     banghart 13271:     my ($dir,$file) = @_;
                   13272:     my $location;
                   13273:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13274: 
                   13275:     if ($file =~ m-^/adm/-) {
                   13276: 	$file=~s-^/adm/wrapper/-/-;
                   13277: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13278:     }
1.882     albertel 13279: 
1.1139    www      13280:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13281:         $location = $file;
1.609     banghart 13282:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13283:         my ($udom,$uname,$filename)=
1.811     albertel 13284:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13285:         my $home=&homeserver($uname,$udom);
                   13286:         my $is_me=0;
                   13287:         my @ids=&current_machine_ids();
                   13288:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13289:         if ($is_me) {
1.1117    foxr     13290:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13291:         } else {
                   13292:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13293:   	      $udom.'/'.$uname.'/'.$filename;
                   13294:         }
1.882     albertel 13295:     } elsif ($file =~ m-^/adm/-) {
                   13296: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13297:     } else {
                   13298:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13299:         $file=~s:^/(res|priv)/:/:;
                   13300:         my $space=$1;
1.590     banghart 13301:         if ( !( $file =~ m:^/:) ) {
                   13302:             $location = $dir. '/'.$file;
                   13303:         } else {
1.1142    raeburn  13304:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13305:         }
1.59      albertel 13306:     }
1.590     banghart 13307:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13308:     while ($location=~m{/\.\./}) {
                   13309: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13310: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13311: 	} else {
                   13312: 	    $location=~ s{/\.\./}{/}g;
                   13313: 	}
                   13314:     } #remove dir/..
1.590     banghart 13315:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13316:     return $location;
1.46      www      13317: }
1.36      albertel 13318: 
1.46      www      13319: sub hreflocation {
                   13320:     my ($dir,$file)=@_;
1.980     raeburn  13321:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13322: 	$file=filelocation($dir,$file);
1.700     albertel 13323:     } elsif ($file=~m-^/adm/-) {
                   13324: 	$file=~s-^/adm/wrapper/-/-;
                   13325: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13326:     }
                   13327:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13328: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13329:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13330: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13331: 	        {/uploaded/$1/$2/}x;
1.46      www      13332:     }
1.913     albertel 13333:     if ($file=~ m{^/userfiles/}) {
                   13334: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13335:     }
1.462     albertel 13336:     return $file;
1.465     albertel 13337: }
                   13338: 
1.1139    www      13339: 
                   13340: 
                   13341: 
                   13342: 
1.465     albertel 13343: sub current_machine_domains {
1.853     albertel 13344:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13345: }
                   13346: 
                   13347: sub machine_domains {
                   13348:     my ($hostname) = @_;
1.465     albertel 13349:     my @domains;
1.838     albertel 13350:     my %hostname = &all_hostnames();
1.465     albertel 13351:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13352: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13353: 	if ($hostname eq $name) {
1.844     albertel 13354: 	    push(@domains,&host_domain($id));
1.465     albertel 13355: 	}
                   13356:     }
                   13357:     return @domains;
                   13358: }
                   13359: 
                   13360: sub current_machine_ids {
1.853     albertel 13361:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13362: }
                   13363: 
                   13364: sub machine_ids {
                   13365:     my ($hostname) = @_;
                   13366:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13367:     my @ids;
1.888     albertel 13368:     my %name_to_host = &all_names();
1.889     albertel 13369:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13370: 	return @{ $name_to_host{$hostname} };
                   13371:     }
                   13372:     return;
1.31      www      13373: }
                   13374: 
1.824     raeburn  13375: sub additional_machine_domains {
                   13376:     my @domains;
1.1172.2.96  raeburn  13377:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13378:     while( my $line = <$fh>) {
                   13379:         $line =~ s/\s//g;
                   13380:         push(@domains,$line);
                   13381:     }
                   13382:     return @domains;
                   13383: }
                   13384: 
                   13385: sub default_login_domain {
                   13386:     my $domain = $perlvar{'lonDefDomain'};
                   13387:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13388:     foreach my $posdom (&current_machine_domains(),
                   13389:                         &additional_machine_domains()) {
                   13390:         if (lc($posdom) eq lc($testdomain)) {
                   13391:             $domain=$posdom;
                   13392:             last;
                   13393:         }
                   13394:     }
                   13395:     return $domain;
                   13396: }
                   13397: 
1.1172.2.106  raeburn  13398: sub shared_institution {
                   13399:     my ($dom) = @_;
                   13400:     my $same_intdom;
                   13401:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13402:     if ($hostintdom ne '') {
                   13403:         my %iphost = &get_iphost();
                   13404:         my $primary_id = &domain($dom,'primary');
                   13405:         my $primary_ip = &get_host_ip($primary_id);
                   13406:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13407:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13408:                 my $intdom = &internet_dom($id);
                   13409:                 if ($intdom eq $hostintdom) {
                   13410:                     $same_intdom = 1;
                   13411:                     last;
                   13412:                 }
                   13413:             }
                   13414:         }
                   13415:     }
                   13416:     return $same_intdom;
                   13417: }
                   13418: 
1.1172.2.118.  .3(raebu 13419:20): sub uses_sts {
                   13420:20):     my ($ignore_cache) = @_;
                   13421:20):     my $lonhost = $perlvar{'lonHostID'};
                   13422:20):     my $hostname = &hostname($lonhost);
                   13423:20):     my $sts_on;
                   13424:20):     if ($protocol{$lonhost} eq 'https') {
                   13425:20):         my $cachetime = 12*3600;
                   13426:20):         if (!$ignore_cache) {
                   13427:20):             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13428:20):             if (defined($cached)) {
                   13429:20):                 return $sts_on;
                   13430:20):             }
                   13431:20):         }
          .4(raebu 13432:20):         my $ua=new LWP::UserAgent;
          .3(raebu 13433:20):         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13434:20):         my $request=new HTTP::Request('HEAD',$url);
          .4(raebu 13435:20):         my $response=$ua->request($request);
          .3(raebu 13436:20):         if ($response->is_success) {
                   13437:20):             my $has_sts = $response->header('Strict-Transport-Security');
                   13438:20):             if ($has_sts eq '') {
                   13439:20):                 $sts_on = 0;
                   13440:20):             } else {
                   13441:20):                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13442:20):                     my $maxage = $1;
                   13443:20):                     if ($maxage) {
                   13444:20):                         $sts_on = 1;
                   13445:20):                     } else {
                   13446:20):                         $sts_on = 0;
                   13447:20):                     }
                   13448:20):                 } else {
                   13449:20):                     $sts_on = 0;
                   13450:20):                 }
                   13451:20):             }
                   13452:20):             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13453:20):         }
                   13454:20):     }
                   13455:20):     return;
                   13456:20): }
                   13457:20): 
1.31      www      13458: # ------------------------------------------------------------- Declutters URLs
                   13459: 
                   13460: sub declutter {
                   13461:     my $thisfn=shift;
1.569     albertel 13462:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13463:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13464:         $thisfn=~s{^/home/httpd/html}{};
                   13465:     }
1.31      www      13466:     $thisfn=~s/^\///;
1.697     albertel 13467:     $thisfn=~s|^adm/wrapper/||;
                   13468:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13469:     $thisfn=~s/^res\///;
1.1172    bisitz   13470:     $thisfn=~s/^priv\///;
1.1032    raeburn  13471:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13472:         $thisfn=~s/\?.+$//;
                   13473:     }
1.268     www      13474:     return $thisfn;
                   13475: }
                   13476: 
                   13477: # ------------------------------------------------------------- Clutter up URLs
                   13478: 
                   13479: sub clutter {
                   13480:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13481:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13482: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13483:        $thisfn='/res'.$thisfn; 
                   13484:     }
1.1031    raeburn  13485:     if ($thisfn !~m|^/adm|) {
                   13486: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13487: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13488: 	} else {
                   13489: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13490: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13491: 	    if ($embstyle eq 'ssi'
                   13492: 		|| ($embstyle eq 'hdn')
                   13493: 		|| ($embstyle eq 'rat')
                   13494: 		|| ($embstyle eq 'prv')
                   13495: 		|| ($embstyle eq 'ign')) {
                   13496: 		#do nothing with these
                   13497: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13498: 		|| ($embstyle eq 'emb')
                   13499: 		|| ($embstyle eq 'wrp')) {
                   13500: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13501: 	    } elsif ($embstyle eq 'unk'
                   13502: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13503: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13504: 	    } else {
1.718     www      13505: #		&logthis("Got a blank emb style");
1.695     albertel 13506: 	    }
1.694     albertel 13507: 	}
1.1172.2.118.  .1(raebu 13508:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13509:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13510:     }
1.31      www      13511:     return $thisfn;
1.12      www      13512: }
                   13513: 
1.787     albertel 13514: sub clutter_with_no_wrapper {
                   13515:     my $uri = &clutter(shift);
                   13516:     if ($uri =~ m-^/adm/-) {
                   13517: 	$uri =~ s-^/adm/wrapper/-/-;
                   13518: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13519:     }
                   13520:     return $uri;
                   13521: }
                   13522: 
1.557     albertel 13523: sub freeze_escape {
                   13524:     my ($value)=@_;
                   13525:     if (ref($value)) {
                   13526: 	$value=&nfreeze($value);
                   13527: 	return '__FROZEN__'.&escape($value);
                   13528:     }
                   13529:     return &escape($value);
                   13530: }
                   13531: 
1.11      www      13532: 
1.557     albertel 13533: sub thaw_unescape {
                   13534:     my ($value)=@_;
                   13535:     if ($value =~ /^__FROZEN__/) {
                   13536: 	substr($value,0,10,undef);
                   13537: 	$value=&unescape($value);
                   13538: 	return &thaw($value);
                   13539:     }
                   13540:     return &unescape($value);
                   13541: }
                   13542: 
1.436     albertel 13543: sub correct_line_ends {
                   13544:     my ($result)=@_;
                   13545:     $$result =~s/\r\n/\n/mg;
                   13546:     $$result =~s/\r/\n/mg;
1.415     albertel 13547: }
1.1       albertel 13548: # ================================================================ Main Program
                   13549: 
1.184     www      13550: sub goodbye {
1.204     albertel 13551:    &logthis("Starting Shut down");
1.443     albertel 13552: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13553:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13554: #converted
1.599     albertel 13555: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13556:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13557: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13558: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13559: #1.1 only
1.870     albertel 13560: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13561: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13562: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13563: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13564:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13565:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13566:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13567:    &flushcourselogs();
                   13568:    &logthis("Shutting down");
                   13569: }
                   13570: 
1.852     albertel 13571: sub get_dns {
1.1172.2.17  raeburn  13572:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13573:     if (!$ignore_cache) {
                   13574: 	my ($content,$cached)=
                   13575: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13576: 	if ($cached) {
1.1172.2.17  raeburn  13577: 	    &$func($content,$hashref);
1.869     albertel 13578: 	    return;
                   13579: 	}
                   13580:     }
                   13581: 
                   13582:     my %alldns;
1.1172.2.96  raeburn  13583:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13584:         foreach my $dns (<$config>) {
                   13585: 	    next if ($dns !~ /^\^(\S*)/x);
                   13586:             my $line = $1;
                   13587:             my ($host,$protocol) = split(/:/,$line);
                   13588:             if ($protocol ne 'https') {
                   13589:                 $protocol = 'http';
                   13590:             }
                   13591: 	    $alldns{$host} = $protocol;
1.979     raeburn  13592:         }
1.1172.2.96  raeburn  13593:         close($config);
1.869     albertel 13594:     }
                   13595:     while (%alldns) {
1.1172.2.52  raeburn  13596: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13597: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13598:         $ua->timeout(30);
1.979     raeburn  13599: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13600: 	my $response=$ua->request($request);
1.979     raeburn  13601:         delete($alldns{$dns});
1.852     albertel 13602: 	next if ($response->is_error());
                   13603: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13604:         unless ($nocache) {
1.1172.2.23  raeburn  13605: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13606:         }
                   13607: 	&$func(\@content,$hashref);
1.869     albertel 13608: 	return;
1.852     albertel 13609:     }
1.871     albertel 13610:     my $which = (split('/',$url))[3];
                   13611:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13612:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13613:         my @content = <$config>;
                   13614:         &$func(\@content,$hashref);
                   13615:     }
1.1172.2.17  raeburn  13616:     return;
                   13617: }
                   13618: 
                   13619: # ------------------------------------------------------Get DNS checksums file
                   13620: sub parse_dns_checksums_tab {
                   13621:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13622:     my $lonhost = $perlvar{'lonHostID'};
                   13623:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13624:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13625:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13626:     my $webconfdir = '/etc/httpd/conf';
                   13627:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13628:         $webconfdir = '/etc/apache2';
                   13629:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13630:         if ($1 >= 10) {
                   13631:             $webconfdir = '/etc/apache2';
                   13632:         }
                   13633:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13634:         if ($1 >= 10.0) {
                   13635:             $webconfdir = '/etc/apache2';
                   13636:         }
                   13637:     }
1.1172.2.17  raeburn  13638:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13639:     my (%chksum,%revnum);
                   13640:     if (ref($lines) eq 'ARRAY') {
                   13641:         chomp(@{$lines});
1.1172.2.34  raeburn  13642:         my $version = shift(@{$lines});
                   13643:         if ($version eq $release) {
1.1172.2.17  raeburn  13644:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13645:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13646:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13647:                     if ($webconfdir eq '/etc/apache2') {
                   13648:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13649:                     }
                   13650:                 }
1.1172.2.34  raeburn  13651:                 $chksum{$file} = $shasum;
                   13652:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13653:             }
                   13654:             if (ref($hashref) eq 'HASH') {
                   13655:                 %{$hashref} = (
                   13656:                                 sums     => \%chksum,
                   13657:                                 versions => \%revnum,
                   13658:                               );
                   13659:             }
                   13660:         }
                   13661:     }
1.869     albertel 13662:     return;
1.852     albertel 13663: }
1.1172.2.17  raeburn  13664: 
                   13665: sub fetch_dns_checksums {
                   13666:     my %checksums;
1.1172.2.34  raeburn  13667:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13668:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13669:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13670:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13671:              \%checksums);
                   13672:     return \%checksums;
                   13673: }
                   13674: 
1.327     albertel 13675: # ------------------------------------------------------------ Read domain file
                   13676: {
1.852     albertel 13677:     my $loaded;
1.846     albertel 13678:     my %domain;
                   13679: 
1.852     albertel 13680:     sub parse_domain_tab {
                   13681: 	my ($lines) = @_;
                   13682: 	foreach my $line (@$lines) {
                   13683: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13684: 
1.846     albertel 13685: 	    chomp($line);
1.852     albertel 13686: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13687: 	    my %this_domain;
                   13688: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13689: 			       'lang_def', 'city', 'longi', 'lati',
                   13690: 			       'primary') {
                   13691: 		$this_domain{$field} = shift(@elements);
                   13692: 	    }
                   13693: 	    $domain{$name} = \%this_domain;
1.852     albertel 13694: 	}
                   13695:     }
1.864     albertel 13696: 
                   13697:     sub reset_domain_info {
                   13698: 	undef($loaded);
                   13699: 	undef(%domain);
                   13700:     }
                   13701: 
1.852     albertel 13702:     sub load_domain_tab {
1.1172.2.70  raeburn  13703: 	my ($ignore_cache,$nocache) = @_;
                   13704: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13705: 	my $fh;
1.1172.2.96  raeburn  13706: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13707: 	    my @lines = <$fh>;
                   13708: 	    &parse_domain_tab(\@lines);
1.448     albertel 13709: 	}
1.852     albertel 13710: 	close($fh);
                   13711: 	$loaded = 1;
1.327     albertel 13712:     }
1.846     albertel 13713: 
                   13714:     sub domain {
1.852     albertel 13715: 	&load_domain_tab() if (!$loaded);
                   13716: 
1.846     albertel 13717: 	my ($name,$what) = @_;
                   13718: 	return if ( !exists($domain{$name}) );
                   13719: 
                   13720: 	if (!$what) {
                   13721: 	    return $domain{$name}{'description'};
                   13722: 	}
                   13723: 	return $domain{$name}{$what};
                   13724:     }
1.974     raeburn  13725: 
                   13726:     sub domain_info {
                   13727:         &load_domain_tab() if (!$loaded);
                   13728:         return %domain;
                   13729:     }
                   13730: 
1.327     albertel 13731: }
                   13732: 
                   13733: 
1.1       albertel 13734: # ------------------------------------------------------------- Read hosts file
                   13735: {
1.838     albertel 13736:     my %hostname;
1.844     albertel 13737:     my %hostdom;
1.845     albertel 13738:     my %libserv;
1.852     albertel 13739:     my $loaded;
1.888     albertel 13740:     my %name_to_host;
1.1074    raeburn  13741:     my %internetdom;
1.1107    raeburn  13742:     my %LC_dns_serv;
1.852     albertel 13743: 
                   13744:     sub parse_hosts_tab {
                   13745: 	my ($file) = @_;
                   13746: 	foreach my $configline (@$file) {
                   13747: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13748:             chomp($configline);
                   13749: 	    if ($configline =~ /^\^/) {
                   13750:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13751:                     $LC_dns_serv{$1} = 1;
                   13752:                 }
                   13753:                 next;
                   13754:             }
1.1074    raeburn  13755: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13756: 	    $name=~s/\s//g;
                   13757: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13758:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13759:                     my $curr = $hostname{$id};
                   13760:                     my $skip;
                   13761:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13762:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13763:                             $skip = 1;
                   13764:                         } else {
                   13765:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13766:                         }
                   13767:                     }
                   13768:                     unless ($skip) {
                   13769:                         push(@{$name_to_host{$name}},$id);
                   13770:                     }
                   13771:                 } else {
                   13772:                     push(@{$name_to_host{$name}},$id);
                   13773:                 }
1.852     albertel 13774: 		$hostname{$id}=$name;
                   13775: 		$hostdom{$id}=$domain;
                   13776: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13777:                 if (defined($protocol)) {
                   13778:                     if ($protocol eq 'https') {
                   13779:                         $protocol{$id} = $protocol;
                   13780:                     } else {
                   13781:                         $protocol{$id} = 'http'; 
                   13782:                     }
1.968     raeburn  13783:                 } else {
1.969     raeburn  13784:                     $protocol{$id} = 'http';
1.968     raeburn  13785:                 }
1.1074    raeburn  13786:                 if (defined($intdom)) {
                   13787:                     $internetdom{$id} = $intdom;
                   13788:                 }
1.852     albertel 13789: 	    }
                   13790: 	}
                   13791:     }
1.864     albertel 13792:     
                   13793:     sub reset_hosts_info {
1.897     albertel 13794: 	&purge_remembered();
1.864     albertel 13795: 	&reset_domain_info();
                   13796: 	&reset_hosts_ip_info();
1.892     albertel 13797: 	undef(%name_to_host);
1.864     albertel 13798: 	undef(%hostname);
                   13799: 	undef(%hostdom);
                   13800: 	undef(%libserv);
                   13801: 	undef($loaded);
                   13802:     }
1.1       albertel 13803: 
1.852     albertel 13804:     sub load_hosts_tab {
1.1172.2.70  raeburn  13805: 	my ($ignore_cache,$nocache) = @_;
                   13806: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13807: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13808: 	my @config = <$config>;
                   13809: 	&parse_hosts_tab(\@config);
                   13810: 	close($config);
                   13811: 	$loaded=1;
1.1       albertel 13812:     }
1.852     albertel 13813: 
1.838     albertel 13814:     sub hostname {
1.852     albertel 13815: 	&load_hosts_tab() if (!$loaded);
                   13816: 
1.838     albertel 13817: 	my ($lonid) = @_;
                   13818: 	return $hostname{$lonid};
                   13819:     }
1.845     albertel 13820: 
1.838     albertel 13821:     sub all_hostnames {
1.852     albertel 13822: 	&load_hosts_tab() if (!$loaded);
                   13823: 
1.838     albertel 13824: 	return %hostname;
                   13825:     }
1.845     albertel 13826: 
1.888     albertel 13827:     sub all_names {
1.1172.2.70  raeburn  13828:         my ($ignore_cache,$nocache) = @_;
                   13829: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13830: 
                   13831: 	return %name_to_host;
                   13832:     }
                   13833: 
1.974     raeburn  13834:     sub all_host_domain {
                   13835:         &load_hosts_tab() if (!$loaded);
                   13836:         return %hostdom;
                   13837:     }
                   13838: 
1.845     albertel 13839:     sub is_library {
1.852     albertel 13840: 	&load_hosts_tab() if (!$loaded);
                   13841: 
1.845     albertel 13842: 	return exists($libserv{$_[0]});
                   13843:     }
                   13844: 
                   13845:     sub all_library {
1.852     albertel 13846: 	&load_hosts_tab() if (!$loaded);
                   13847: 
1.845     albertel 13848: 	return %libserv;
                   13849:     }
                   13850: 
1.1062    droeschl 13851:     sub unique_library {
                   13852: 	#2x reverse removes all hostnames that appear more than once
                   13853:         my %unique = reverse &all_library();
                   13854:         return reverse %unique;
                   13855:     }
                   13856: 
1.841     albertel 13857:     sub get_servers {
1.852     albertel 13858: 	&load_hosts_tab() if (!$loaded);
                   13859: 
1.841     albertel 13860: 	my ($domain,$type) = @_;
                   13861: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13862: 	                                          : %hostname;
                   13863: 	my %result;
1.842     albertel 13864: 	if (ref($domain) eq 'ARRAY') {
                   13865: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13866: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13867: 		    $result{$host} = $hostname;
                   13868: 		}
                   13869: 	    }
                   13870: 	} else {
                   13871: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13872: 		if ($hostdom{$host} eq $domain) {
                   13873: 		    $result{$host} = $hostname;
                   13874: 		}
1.841     albertel 13875: 	    }
                   13876: 	}
                   13877: 	return %result;
                   13878:     }
1.845     albertel 13879: 
1.1062    droeschl 13880:     sub get_unique_servers {
                   13881:         my %unique = reverse &get_servers(@_);
                   13882: 	return reverse %unique;
                   13883:     }
                   13884: 
1.844     albertel 13885:     sub host_domain {
1.852     albertel 13886: 	&load_hosts_tab() if (!$loaded);
                   13887: 
1.844     albertel 13888: 	my ($lonid) = @_;
                   13889: 	return $hostdom{$lonid};
                   13890:     }
                   13891: 
1.841     albertel 13892:     sub all_domains {
1.852     albertel 13893: 	&load_hosts_tab() if (!$loaded);
                   13894: 
1.841     albertel 13895: 	my %seen;
                   13896: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13897: 	return @uniq;
                   13898:     }
1.1074    raeburn  13899: 
                   13900:     sub internet_dom {
                   13901:         &load_hosts_tab() if (!$loaded);
                   13902: 
                   13903:         my ($lonid) = @_;
                   13904:         return $internetdom{$lonid};
                   13905:     }
1.1107    raeburn  13906: 
                   13907:     sub is_LC_dns {
                   13908:         &load_hosts_tab() if (!$loaded);
                   13909: 
                   13910:         my ($hostname) = @_;
                   13911:         return exists($LC_dns_serv{$hostname});
                   13912:     }
                   13913: 
1.1       albertel 13914: }
                   13915: 
1.847     albertel 13916: { 
                   13917:     my %iphost;
1.856     albertel 13918:     my %name_to_ip;
                   13919:     my %lonid_to_ip;
1.869     albertel 13920: 
1.847     albertel 13921:     sub get_hosts_from_ip {
                   13922: 	my ($ip) = @_;
                   13923: 	my %iphosts = &get_iphost();
                   13924: 	if (ref($iphosts{$ip})) {
                   13925: 	    return @{$iphosts{$ip}};
                   13926: 	}
                   13927: 	return;
1.839     albertel 13928:     }
1.864     albertel 13929:     
                   13930:     sub reset_hosts_ip_info {
                   13931: 	undef(%iphost);
                   13932: 	undef(%name_to_ip);
                   13933: 	undef(%lonid_to_ip);
                   13934:     }
1.856     albertel 13935: 
                   13936:     sub get_host_ip {
                   13937: 	my ($lonid) = @_;
                   13938: 	if (exists($lonid_to_ip{$lonid})) {
                   13939: 	    return $lonid_to_ip{$lonid};
                   13940: 	}
                   13941: 	my $name=&hostname($lonid);
                   13942:    	my $ip = gethostbyname($name);
                   13943: 	return if (!$ip || length($ip) ne 4);
                   13944: 	$ip=inet_ntoa($ip);
                   13945: 	$name_to_ip{$name}   = $ip;
                   13946: 	$lonid_to_ip{$lonid} = $ip;
                   13947: 	return $ip;
                   13948:     }
1.847     albertel 13949:     
                   13950:     sub get_iphost {
1.1172.2.70  raeburn  13951: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13952: 
1.869     albertel 13953: 	if (!$ignore_cache) {
                   13954: 	    if (%iphost) {
                   13955: 		return %iphost;
                   13956: 	    }
                   13957: 	    my ($ip_info,$cached)=
                   13958: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13959: 	    if ($cached) {
                   13960: 		%iphost      = %{$ip_info->[0]};
                   13961: 		%name_to_ip  = %{$ip_info->[1]};
                   13962: 		%lonid_to_ip = %{$ip_info->[2]};
                   13963: 		return %iphost;
                   13964: 	    }
                   13965: 	}
1.894     albertel 13966: 
                   13967: 	# get yesterday's info for fallback
                   13968: 	my %old_name_to_ip;
                   13969: 	my ($ip_info,$cached)=
                   13970: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13971: 	if ($cached) {
                   13972: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13973: 	}
                   13974: 
1.1172.2.70  raeburn  13975: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13976: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13977: 	    my $ip;
                   13978: 	    if (!exists($name_to_ip{$name})) {
                   13979: 		$ip = gethostbyname($name);
                   13980: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13981: 		    if (defined($old_name_to_ip{$name})) {
                   13982: 			$ip = $old_name_to_ip{$name};
                   13983: 			&logthis("Can't find $name defaulting to old $ip");
                   13984: 		    } else {
                   13985: 			&logthis("Name $name no IP found");
                   13986: 			next;
                   13987: 		    }
                   13988: 		} else {
                   13989: 		    $ip=inet_ntoa($ip);
1.847     albertel 13990: 		}
                   13991: 		$name_to_ip{$name} = $ip;
                   13992: 	    } else {
                   13993: 		$ip = $name_to_ip{$name};
1.653     albertel 13994: 	    }
1.888     albertel 13995: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13996: 		$lonid_to_ip{$id} = $ip;
                   13997: 	    }
                   13998: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13999: 	}
1.1172.2.70  raeburn  14000:         unless ($nocache) {
                   14001: 	    &do_cache_new('iphost','iphost',
                   14002: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14003: 		          48*60*60);
                   14004:         }
1.869     albertel 14005: 
1.847     albertel 14006: 	return %iphost;
1.598     albertel 14007:     }
                   14008: 
1.992     raeburn  14009:     #
                   14010:     #  Given a DNS returns the loncapa host name for that DNS 
                   14011:     # 
                   14012:     sub host_from_dns {
                   14013:         my ($dns) = @_;
                   14014:         my @hosts;
                   14015:         my $ip;
                   14016: 
1.993     raeburn  14017:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14018:             $ip = $name_to_ip{$dns};
                   14019:         }
                   14020:         if (!$ip) {
                   14021:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14022:             if (length($ip) == 4) { 
                   14023: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14024:             }
                   14025:         }
                   14026:         if ($ip) {
                   14027: 	    @hosts = get_hosts_from_ip($ip);
                   14028: 	    return $hosts[0];
                   14029:         }
                   14030:         return undef;
1.986     foxr     14031:     }
1.992     raeburn  14032: 
1.1074    raeburn  14033:     sub get_internet_names {
                   14034:         my ($lonid) = @_;
                   14035:         return if ($lonid eq '');
                   14036:         my ($idnref,$cached)=
                   14037:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14038:         if ($cached) {
                   14039:             return $idnref;
                   14040:         }
                   14041:         my $ip = &get_host_ip($lonid);
                   14042:         my @hosts = &get_hosts_from_ip($ip);
                   14043:         my %iphost = &get_iphost();
                   14044:         my (@idns,%seen);
                   14045:         foreach my $id (@hosts) {
                   14046:             my $dom = &host_domain($id);
                   14047:             my $prim_id = &domain($dom,'primary');
                   14048:             my $prim_ip = &get_host_ip($prim_id);
                   14049:             next if ($seen{$prim_ip});
                   14050:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14051:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14052:                     my $intdom = &internet_dom($id);
                   14053:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14054:                         push(@idns,$intdom);
                   14055:                     }
                   14056:                 }
                   14057:             }
                   14058:             $seen{$prim_ip} = 1;
                   14059:         }
1.1172.2.23  raeburn  14060:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14061:     }
                   14062: 
1.986     foxr     14063: }
                   14064: 
1.1079    raeburn  14065: sub all_loncaparevs {
1.1172.2.39  raeburn  14066:     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  14067: }
                   14068: 
1.1172.2.27  raeburn  14069: # ------------------------------------------------------- Read loncaparev table
                   14070: {
                   14071:     sub load_loncaparevs {
                   14072:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14073:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14074:                 while (my $configline=<$config>) {
                   14075:                     chomp($configline);
                   14076:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14077:                     $loncaparevs{$hostid}=$loncaparev;
                   14078:                 }
                   14079:                 close($config);
                   14080:             }
                   14081:         }
                   14082:     }
                   14083: }
                   14084: 
                   14085: # ----------------------------------------------------- Read serverhostID table
                   14086: {
                   14087:     sub load_serverhomeIDs {
                   14088:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14089:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14090:                 while (my $configline=<$config>) {
                   14091:                     chomp($configline);
                   14092:                     my ($name,$id)=split(/:/,$configline);
                   14093:                     $serverhomeIDs{$name}=$id;
                   14094:                 }
                   14095:                 close($config);
                   14096:             }
                   14097:         }
                   14098:     }
                   14099: }
                   14100: 
                   14101: 
1.862     albertel 14102: BEGIN {
                   14103: 
                   14104: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14105:     unless ($readit) {
                   14106: {
                   14107:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14108:     %perlvar = (%perlvar,%{$configvars});
                   14109: }
                   14110: 
                   14111: 
1.1       albertel 14112: # ------------------------------------------------------ Read spare server file
                   14113: {
1.1172.2.96  raeburn  14114:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14115: 
                   14116:     while (my $configline=<$config>) {
                   14117:        chomp($configline);
1.284     matthew  14118:        if ($configline) {
1.784     albertel 14119: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14120: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14121: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14122:        }
                   14123:     }
1.448     albertel 14124:     close($config);
1.1       albertel 14125: }
1.11      www      14126: # ------------------------------------------------------------ Read permissions
                   14127: {
1.1172.2.96  raeburn  14128:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14129: 
                   14130:     while (my $configline=<$config>) {
1.448     albertel 14131: 	chomp($configline);
                   14132: 	if ($configline) {
                   14133: 	    my ($role,$perm)=split(/ /,$configline);
                   14134: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14135: 	}
1.11      www      14136:     }
1.448     albertel 14137:     close($config);
1.11      www      14138: }
                   14139: 
                   14140: # -------------------------------------------- Read plain texts for permissions
                   14141: {
1.1172.2.96  raeburn  14142:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14143: 
                   14144:     while (my $configline=<$config>) {
1.448     albertel 14145: 	chomp($configline);
                   14146: 	if ($configline) {
1.742     raeburn  14147: 	    my ($short,@plain)=split(/:/,$configline);
                   14148:             %{$prp{$short}} = ();
                   14149: 	    if (@plain > 0) {
                   14150:                 $prp{$short}{'std'} = $plain[0];
                   14151:                 for (my $i=1; $i<@plain; $i++) {
                   14152:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14153:                 }
                   14154:             }
1.448     albertel 14155: 	}
1.135     www      14156:     }
1.448     albertel 14157:     close($config);
1.135     www      14158: }
                   14159: 
                   14160: # ---------------------------------------------------------- Read package table
                   14161: {
1.1172.2.96  raeburn  14162:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14163: 
                   14164:     while (my $configline=<$config>) {
1.483     albertel 14165: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14166: 	chomp($configline);
                   14167: 	my ($short,$plain)=split(/:/,$configline);
                   14168: 	my ($pack,$name)=split(/\&/,$short);
                   14169: 	if ($plain ne '') {
                   14170: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14171: 	    $packagetab{$short}=$plain; 
                   14172: 	}
1.11      www      14173:     }
1.448     albertel 14174:     close($config);
1.329     matthew  14175: }
                   14176: 
1.1172.2.27  raeburn  14177: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14178: 
1.1172.2.27  raeburn  14179: &load_loncaparevs();
                   14180: 
                   14181: # ------------------------------------------------------- Read serverhostID table
                   14182: 
                   14183: &load_serverhomeIDs();
1.1074    raeburn  14184: 
1.1172.2.27  raeburn  14185: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14186: {
                   14187:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14188:     if (-e $file) {
                   14189:         my $parser = HTML::LCParser->new($file);
                   14190:         while (my $token = $parser->get_token()) {
                   14191:             if ($token->[0] eq 'S') {
                   14192:                 my $item = $token->[1];
                   14193:                 my $name = $token->[2]{'name'};
                   14194:                 my $value = $token->[2]{'value'};
                   14195:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14196:                     my $release = $parser->get_text();
                   14197:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14198:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14199:                 }
                   14200:             }
                   14201:         }
                   14202:     }
1.1073    raeburn  14203: }
                   14204: 
1.1138    raeburn  14205: # ---------------------------------------------------------- Read managers table
                   14206: {
                   14207:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14208:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14209:             while (my $configline=<$config>) {
                   14210:                 chomp($configline);
                   14211:                 next if ($configline =~ /^\#/);
                   14212:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14213:                     $managerstab{$configline} = 1;
                   14214:                 }
                   14215:             }
                   14216:             close($config);
                   14217:         }
                   14218:     }
                   14219: }
                   14220: 
1.329     matthew  14221: # ------------- set up temporary directory
                   14222: {
1.1117    foxr     14223:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14224: 
1.11      www      14225: }
                   14226: 
1.1172.2.104  raeburn  14227: # ------------- set default texengine (domain default overrides this)
                   14228: {
                   14229:     $deftex = LONCAPA::texengine();
                   14230: }
                   14231: 
1.1172.2.114  raeburn  14232: # ------------- set default minimum length for passwords for internal auth users
                   14233: {
                   14234:     $passwdmin = LONCAPA::passwd_min();
                   14235: }
                   14236: 
1.794     albertel 14237: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14238: 				'compress_threshold'=> 20_000,
                   14239:  			        });
1.185     www      14240: 
1.281     www      14241: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14242: $dumpcount=0;
1.958     www      14243: $locknum=0;
1.22      www      14244: 
1.163     harris41 14245: &logtouch();
1.672     albertel 14246: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14247: $readit=1;
1.564     albertel 14248:     {
                   14249: 	use integer;
                   14250: 	my $test=(2**32)+1;
1.568     albertel 14251: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14252: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14253:     }
1.195     www      14254: }
1.1       albertel 14255: }
1.179     www      14256: 
1.1       albertel 14257: 1;
1.191     harris41 14258: __END__
                   14259: 
1.243     albertel 14260: =pod
                   14261: 
1.191     harris41 14262: =head1 NAME
                   14263: 
1.243     albertel 14264: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14265: 
                   14266: =head1 SYNOPSIS
                   14267: 
1.243     albertel 14268: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14269: 
                   14270:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14271: 
1.243     albertel 14272: Common parameters:
                   14273: 
                   14274: =over 4
                   14275: 
                   14276: =item *
                   14277: 
                   14278: $uname : an internal username (if $cname expecting a course Id specifically)
                   14279: 
                   14280: =item *
                   14281: 
                   14282: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14283: 
                   14284: =item *
                   14285: 
                   14286: $symb : a resource instance identifier
                   14287: 
                   14288: =item *
                   14289: 
                   14290: $namespace : the name of a .db file that contains the data needed or
                   14291: being set.
                   14292: 
                   14293: =back
                   14294: 
1.394     bowersj2 14295: =head1 OVERVIEW
1.191     harris41 14296: 
1.394     bowersj2 14297: lonnet provides subroutines which interact with the
                   14298: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14299: about classes, users, and resources.
1.243     albertel 14300: 
                   14301: For many of these objects you can also use this to store data about
                   14302: them or modify them in various ways.
1.191     harris41 14303: 
1.394     bowersj2 14304: =head2 Symbs
1.191     harris41 14305: 
1.394     bowersj2 14306: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14307: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14308: map, the resource number of the resource in the map, and the URL of
                   14309: the resource itself. The latter is somewhat redundant, but might help
                   14310: if maps change.
                   14311: 
                   14312: An example is
                   14313: 
                   14314:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14315: 
                   14316: The respective map entry is
                   14317: 
                   14318:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14319:   title="Problem 2">
                   14320:  </resource>
                   14321: 
                   14322: Symbs are used by the random number generator, as well as to store and
                   14323: restore data specific to a certain instance of for example a problem.
                   14324: 
                   14325: =head2 Storing And Retrieving Data
                   14326: 
                   14327: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14328: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14329: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14330: is is the non-critical message twin of cstore. These functions are for
                   14331: handlers to store a perl hash to a user's permanent data space in an
                   14332: easy manner, and to retrieve it again on another call. It is expected
                   14333: that a handler would use this once at the beginning to retrieve data,
                   14334: and then again once at the end to send only the new data back.
                   14335: 
                   14336: The data is stored in the user's data directory on the user's
                   14337: homeserver under the ID of the course.
                   14338: 
                   14339: The hash that is returned by restore will have all of the previous
                   14340: value for all of the elements of the hash.
                   14341: 
                   14342: Example:
                   14343: 
                   14344:  #creating a hash
                   14345:  my %hash;
                   14346:  $hash{'foo'}='bar';
                   14347: 
                   14348:  #storing it
                   14349:  &Apache::lonnet::cstore(\%hash);
                   14350: 
                   14351:  #changing a value
                   14352:  $hash{'foo'}='notbar';
                   14353: 
                   14354:  #adding a new value
                   14355:  $hash{'bar'}='foo';
                   14356:  &Apache::lonnet::cstore(\%hash);
                   14357: 
                   14358:  #retrieving the hash
                   14359:  my %history=&Apache::lonnet::restore();
                   14360: 
                   14361:  #print the hash
                   14362:  foreach my $key (sort(keys(%history))) {
                   14363:    print("\%history{$key} = $history{$key}");
                   14364:  }
                   14365: 
                   14366: Will print out:
1.191     harris41 14367: 
1.394     bowersj2 14368:  %history{1:foo} = bar
                   14369:  %history{1:keys} = foo:timestamp
                   14370:  %history{1:timestamp} = 990455579
                   14371:  %history{2:bar} = foo
                   14372:  %history{2:foo} = notbar
                   14373:  %history{2:keys} = foo:bar:timestamp
                   14374:  %history{2:timestamp} = 990455580
                   14375:  %history{bar} = foo
                   14376:  %history{foo} = notbar
                   14377:  %history{timestamp} = 990455580
                   14378:  %history{version} = 2
                   14379: 
                   14380: Note that the special hash entries C<keys>, C<version> and
                   14381: C<timestamp> were added to the hash. C<version> will be equal to the
                   14382: total number of versions of the data that have been stored. The
                   14383: C<timestamp> attribute will be the UNIX time the hash was
                   14384: stored. C<keys> is available in every historical section to list which
                   14385: keys were added or changed at a specific historical revision of a
                   14386: hash.
                   14387: 
                   14388: B<Warning>: do not store the hash that restore returns directly. This
                   14389: will cause a mess since it will restore the historical keys as if the
                   14390: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14391: 
1.394     bowersj2 14392: Calling convention:
1.191     harris41 14393: 
1.1172.2.27  raeburn  14394:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14395:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14396: 
1.394     bowersj2 14397: For more detailed information, see lonnet specific documentation.
1.191     harris41 14398: 
1.394     bowersj2 14399: =head1 RETURN MESSAGES
1.191     harris41 14400: 
1.394     bowersj2 14401: =over 4
1.191     harris41 14402: 
1.394     bowersj2 14403: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14404: 
1.394     bowersj2 14405: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14406: when the connection is brought back up
1.191     harris41 14407: 
1.394     bowersj2 14408: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14409: for later delivery
1.191     harris41 14410: 
1.967     bisitz   14411: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14412: 
1.394     bowersj2 14413: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14414: that was requested
1.191     harris41 14415: 
1.243     albertel 14416: =back
1.191     harris41 14417: 
1.243     albertel 14418: =head1 PUBLIC SUBROUTINES
1.191     harris41 14419: 
1.243     albertel 14420: =head2 Session Environment Functions
1.191     harris41 14421: 
1.243     albertel 14422: =over 4
1.191     harris41 14423: 
1.394     bowersj2 14424: =item * 
                   14425: X<appenv()>
1.949     raeburn  14426: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14427: the user envirnoment file, and will be restored for each access this
1.620     albertel 14428: user makes during this session, also modifies the %env for the current
1.949     raeburn  14429: process. Optional rolesarrayref - if defined contains a reference to an array
                   14430: of roles which are exempt from the restriction on modifying user.role entries 
                   14431: in the user's environment.db and in %env.    
1.191     harris41 14432: 
                   14433: =item *
1.394     bowersj2 14434: X<delenv()>
1.987     raeburn  14435: B<delenv($delthis,$regexp)>: removes all items from the session
                   14436: environment file that begin with $delthis. If the 
                   14437: optional second arg - $regexp - is true, $delthis is treated as a 
                   14438: regular expression, otherwise \Q$delthis\E is used. 
                   14439: The values are also deleted from the current processes %env.
1.191     harris41 14440: 
1.795     albertel 14441: =item * get_env_multiple($name) 
                   14442: 
                   14443: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14444: values may be defined and end up as an array ref.
                   14445: 
                   14446: returns an array of values
                   14447: 
1.243     albertel 14448: =back
                   14449: 
                   14450: =head2 User Information
1.191     harris41 14451: 
1.243     albertel 14452: =over 4
1.191     harris41 14453: 
                   14454: =item *
1.394     bowersj2 14455: X<queryauthenticate()>
                   14456: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14457: authentication scheme
                   14458: 
                   14459: =item *
1.394     bowersj2 14460: X<authenticate()>
1.1073    raeburn  14461: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14462: authenticate user from domain's lib servers (first use the current
                   14463: one). C<$upass> should be the users password.
1.1073    raeburn  14464: $checkdefauth is optional (value is 1 if a check should be made to
                   14465:    authenticate user using default authentication method, and allow
                   14466:    account creation if username does not have account in the domain).
                   14467: $clientcancheckhost is optional (value is 1 if checking whether the
                   14468:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14469: 
                   14470: =item *
1.394     bowersj2 14471: X<homeserver()>
                   14472: B<homeserver($uname,$udom)>: find the server which has
                   14473: the user's directory and files (there must be only one), this caches
                   14474: the answer, and also caches if there is a borken connection.
1.191     harris41 14475: 
                   14476: =item *
1.394     bowersj2 14477: X<idget()>
                   14478: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14479: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14480: username, and only 1 username per ID in a specific domain) (returns
                   14481: hash: id=>name,id=>name)
1.191     harris41 14482: 
                   14483: =item *
1.394     bowersj2 14484: X<idrget()>
                   14485: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14486: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14487: 
                   14488: =item *
1.394     bowersj2 14489: X<idput()>
                   14490: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14491: 
                   14492: =item *
1.394     bowersj2 14493: X<rolesinit()>
1.1169    droeschl 14494: B<rolesinit($udom,$username)>: get user privileges.
                   14495: returns user role, first access and timer interval hashes
1.243     albertel 14496: 
                   14497: =item *
1.1171    droeschl 14498: X<privileged()>
                   14499: B<privileged($username,$domain)>: returns a true if user has a
                   14500: privileged and active role (i.e. su or dc), false otherwise.
                   14501: 
                   14502: =item *
1.551     albertel 14503: X<getsection()>
                   14504: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14505: course $cname, return section name/number or '' for "not in course"
                   14506: and '-1' for "no section"
                   14507: 
                   14508: =item *
1.394     bowersj2 14509: X<userenvironment()>
                   14510: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14511: passed in @what from the requested user's environment, returns a hash
                   14512: 
1.858     raeburn  14513: =item * 
                   14514: X<userlog_query()>
1.859     albertel 14515: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14516: activity.log file. %filters defines filters applied when parsing the
                   14517: log file. These can be start or end timestamps, or the type of action
                   14518: - log to look for Login or Logout events, check for Checkin or
                   14519: Checkout, role for role selection. The response is in the form
                   14520: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14521: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14522: 
1.243     albertel 14523: =back
                   14524: 
                   14525: =head2 User Roles
                   14526: 
                   14527: =over 4
                   14528: 
                   14529: =item *
                   14530: 
1.1172.2.65  raeburn  14531: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14532: returns codes for allowed actions.
                   14533: 
                   14534: The first argument is required, all others are optional.
                   14535: 
                   14536: $priv is the privilege being checked.
                   14537: $uri contains additional information about what is being checked for access (e.g.,
                   14538: URL, course ID etc.).
                   14539: $symb is the unique resource instance identifier in a course; if needed,
                   14540: but not provided, it will be retrieved via a call to &symbread().
                   14541: $role is the role for which a priv is being checked (only used if priv is evb).
                   14542: $clientip is the user's IP address (only used when checking for access to portfolio
                   14543: files).
                   14544: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14545: prevents recursive calls to &allowed.
                   14546: 
1.243     albertel 14547:  F: full access
                   14548:  U,I,K: authentication modes (cxx only)
                   14549:  '': forbidden
                   14550:  1: user needs to choose course
                   14551:  2: browse allowed
1.766     albertel 14552:  A: passphrase authentication needed
1.1172.2.65  raeburn  14553:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14554: 
                   14555: =item *
                   14556: 
1.1172.2.13  raeburn  14557: constructaccess($url,$setpriv) : check for access to construction space URL
                   14558: 
                   14559: See if the owner domain and name in the URL match those in the
                   14560: expected environment.  If so, return three element list
                   14561: ($ownername,$ownerdomain,$ownerhome).
                   14562: 
                   14563: Otherwise return the null string.
                   14564: 
                   14565: If second argument 'setpriv' is true, it assigns the privileges,
                   14566: and returns the same three element list, unless the owner has
                   14567: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14568: in which case the null string is returned.
                   14569: 
                   14570: =item *
                   14571: 
1.1172.2.84  raeburn  14572: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14573: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14574: for system, domain, and course level. $uname and $udom are optional (current
                   14575: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14576: 
                   14577: =item *
                   14578: 
1.988     raeburn  14579: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14580: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14581: $type is Course (default) or Community.
1.988     raeburn  14582: If $forcedefault evaluates to true, text returned will be default 
                   14583: text for $type. Otherwise, if this is a course, the text returned 
                   14584: will be a custom name for the role (if defined in the course's 
                   14585: environment).  If no custom name is defined the default is returned.
                   14586:    
1.832     raeburn  14587: =item *
                   14588: 
1.1172.2.23  raeburn  14589: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14590: All arguments are optional. Returns a hash of a roles, either for
                   14591: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14592: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14593: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14594: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14595: For each key, value is set to colon-separated start and end times for
                   14596: the role.  If no username and domain are specified, will default to
1.934     raeburn  14597: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14598: of role statuses (active, future or previous), roles 
                   14599: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14600: to restrict the list of roles reported. If no array ref is 
                   14601: provided for types, will default to return only active roles.
1.834     albertel 14602: 
1.1172.2.13  raeburn  14603: =item *
                   14604: 
                   14605: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14606: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14607: 
                   14608: Additional optional arguments are: $type (if role checking is to be restricted
                   14609: to certain user status types -- previous (expired roles), active (currently
                   14610: available roles) or future (roles available in the future), and
                   14611: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14612: have active Domain Coordinator role in course's domain or in additional
                   14613: domains (specified in 'Domains to check for privileged users' in course
                   14614: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14615: 
                   14616: =item *
                   14617: 
                   14618: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14619: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14620: $possdomains and $possroles are optional array refs -- to domains to check and
                   14621: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14622: users' roles.db to check for a dc or su role in any domain. This can be
                   14623: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14624: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14625: this then allows &privileged_by_domain() to be used, which caches the identity
                   14626: of privileged users, eliminating the need for repeated calls to &dump().
                   14627: 
                   14628: =item *
                   14629: 
                   14630: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14631: where the outer hash keys are domains specified in the $possdomains array ref,
                   14632: next inner hash keys are privileged roles specified in the $roles array ref,
                   14633: and the innermost hash contains key = value pairs for username:domain = end:start
                   14634: for active or future "privileged" users with that role in that domain. To avoid
                   14635: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14636: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14637: 
1.243     albertel 14638: =back
                   14639: 
                   14640: =head2 User Modification
                   14641: 
                   14642: =over 4
                   14643: 
                   14644: =item *
                   14645: 
1.957     raeburn  14646: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14647: user for the level given by URL.  Optional start and end dates (leave empty
                   14648: string or zero for "no date")
1.191     harris41 14649: 
                   14650: =item *
                   14651: 
1.243     albertel 14652: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14653: change a users, password, possible return values are: ok,
                   14654: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14655: refused
1.191     harris41 14656: 
                   14657: =item *
                   14658: 
1.243     albertel 14659: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14660: 
                   14661: =item *
                   14662: 
1.1058    raeburn  14663: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14664:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14665: 
                   14666: will update user information (firstname,middlename,lastname,generation,
                   14667: permanentemail), and if forceid is true, student/employee ID also.
                   14668: A user's institutional affiliation(s) can also be updated.
                   14669: User information fields will not be overwritten with empty entries 
                   14670: unless the field is included in the $candelete array reference.
                   14671: This array is included when a single user is modified via "Manage Users",
                   14672: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14673: 
                   14674: =item *
                   14675: 
1.286     matthew  14676: modifystudent
                   14677: 
1.957     raeburn  14678: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14679: The course id is resolved based on the current user's environment.  
                   14680: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14681: associated with a course.
                   14682: 
1.297     matthew  14683: This call is essentially a wrapper for lonnet::modifyuser and
                   14684: lonnet::modify_student_enrollment
1.286     matthew  14685: 
                   14686: Inputs: 
                   14687: 
                   14688: =over 4
                   14689: 
1.957     raeburn  14690: =item B<$udom> Student's loncapa domain
1.286     matthew  14691: 
1.957     raeburn  14692: =item B<$uname> Student's loncapa login name
1.286     matthew  14693: 
1.964     bisitz   14694: =item B<$uid> Student/Employee ID
1.286     matthew  14695: 
1.957     raeburn  14696: =item B<$umode> Student's authentication mode
1.286     matthew  14697: 
1.957     raeburn  14698: =item B<$upass> Student's password
1.286     matthew  14699: 
1.957     raeburn  14700: =item B<$first> Student's first name
1.286     matthew  14701: 
1.957     raeburn  14702: =item B<$middle> Student's middle name
1.286     matthew  14703: 
1.957     raeburn  14704: =item B<$last> Student's last name
1.286     matthew  14705: 
1.957     raeburn  14706: =item B<$gene> Student's generation
1.286     matthew  14707: 
1.957     raeburn  14708: =item B<$usec> Student's section in course
1.286     matthew  14709: 
                   14710: =item B<$end> Unix time of the roles expiration
                   14711: 
                   14712: =item B<$start> Unix time of the roles start date
                   14713: 
                   14714: =item B<$forceid> If defined, allow $uid to be changed
                   14715: 
                   14716: =item B<$desiredhome> server to use as home server for student
                   14717: 
1.957     raeburn  14718: =item B<$email> Student's permanent e-mail address
                   14719: 
                   14720: =item B<$type> Type of enrollment (auto or manual)
                   14721: 
1.963     raeburn  14722: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14723: 
                   14724: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14725: 
1.963     raeburn  14726: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14727: 
1.963     raeburn  14728: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14729: 
1.1172.2.19  raeburn  14730: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14731: 
                   14732: =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  14733: 
1.286     matthew  14734: =back
1.297     matthew  14735: 
                   14736: =item *
                   14737: 
                   14738: modify_student_enrollment
                   14739: 
1.1172.2.31  raeburn  14740: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14741: 'role.request.course' must be defined for this function to proceed.
                   14742: 
                   14743: Inputs:
                   14744: 
                   14745: =over 4
                   14746: 
1.1172.2.31  raeburn  14747: =item $udom, student's domain
1.297     matthew  14748: 
1.1172.2.31  raeburn  14749: =item $uname, student's name
1.297     matthew  14750: 
1.1172.2.31  raeburn  14751: =item $uid, student's user id
1.297     matthew  14752: 
1.1172.2.31  raeburn  14753: =item $first, student's first name
1.297     matthew  14754: 
                   14755: =item $middle
                   14756: 
                   14757: =item $last
                   14758: 
                   14759: =item $gene
                   14760: 
                   14761: =item $usec
                   14762: 
                   14763: =item $end
                   14764: 
                   14765: =item $start
                   14766: 
1.957     raeburn  14767: =item $type
                   14768: 
                   14769: =item $locktype
                   14770: 
                   14771: =item $cid
                   14772: 
                   14773: =item $selfenroll
                   14774: 
                   14775: =item $context
                   14776: 
1.1172.2.19  raeburn  14777: =item $credits, number of credits student will earn from this class
                   14778: 
1.1172.2.76  raeburn  14779: =item $instsec, institutional course section code for student
                   14780: 
1.297     matthew  14781: =back
                   14782: 
1.191     harris41 14783: 
                   14784: =item *
                   14785: 
1.243     albertel 14786: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14787: custom role; give a custom role to a user for the level given by URL.  Specify
                   14788: name and domain of role author, and role name
1.191     harris41 14789: 
                   14790: =item *
                   14791: 
1.243     albertel 14792: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14793: 
                   14794: =item *
                   14795: 
1.243     albertel 14796: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14797: 
                   14798: =back
                   14799: 
                   14800: =head2 Course Infomation
                   14801: 
                   14802: =over 4
1.191     harris41 14803: 
                   14804: =item *
                   14805: 
1.1118    foxr     14806: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14807: specified course id, including all environment settings for the
                   14808: course, the description of the course will be in the hash under the
                   14809: key 'description'
1.191     harris41 14810: 
1.1118    foxr     14811: $options is an optional parameter that if supplied is a hash reference that controls
                   14812: what how this function works.  It has the following key/values:
                   14813: 
                   14814: =over 4
                   14815: 
                   14816: =item freshen_cache
                   14817: 
                   14818: If defined, and the environment cache for the course is valid, it is 
                   14819: returned in the returned hash.
                   14820: 
                   14821: =item one_time
                   14822: 
                   14823: If defined, the last cache time is set to _now_
                   14824: 
                   14825: =item user
                   14826: 
                   14827: If defined, the supplied username is used instead of the current user.
                   14828: 
                   14829: 
                   14830: =back
                   14831: 
1.191     harris41 14832: =item *
                   14833: 
1.624     albertel 14834: resdata($name,$domain,$type,@which) : request for current parameter
                   14835: setting for a specific $type, where $type is either 'course' or 'user',
                   14836: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14837: answers for 10 minutes.
1.243     albertel 14838: 
1.877     foxr     14839: =item *
                   14840: 
                   14841: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14842: data base, returning a hash that is keyed by the resource name and has
                   14843: values that are the resource value.  I believe that the timestamps and
                   14844: versions are also returned.
                   14845: 
1.1172.2.31  raeburn  14846: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14847: supplemental content area. This routine caches the number of files for
                   14848: 10 minutes.
                   14849: 
1.243     albertel 14850: =back
                   14851: 
                   14852: =head2 Course Modification
                   14853: 
                   14854: =over 4
1.191     harris41 14855: 
                   14856: =item *
                   14857: 
1.243     albertel 14858: writecoursepref($courseid,%prefs) : write preferences (environment
                   14859: database) for a course
1.191     harris41 14860: 
                   14861: =item *
                   14862: 
1.1011    raeburn  14863: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14864: 
                   14865: =item *
                   14866: 
1.1038    raeburn  14867: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14868: 
1.1167    droeschl 14869: =item *
                   14870: 
                   14871: is_course($courseid), is_course($cdom, $cnum)
                   14872: 
                   14873: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14874: two component version $cdom, $cnum. It checks if the specified course exists.
                   14875: 
                   14876: Returns:
                   14877:     undef if the course doesn't exist, otherwise
                   14878:     in scalar context the combined courseid.
                   14879:     in list context the two components of the course identifier, domain and 
                   14880:     courseid.    
                   14881: 
1.243     albertel 14882: =back
                   14883: 
1.1172.2.109  raeburn  14884: =head2 Bubblesheet Configuration
                   14885: 
                   14886: =over 4
                   14887: 
                   14888: =item *
                   14889: 
                   14890: get_scantron_config($which)
                   14891: 
                   14892: $which - the name of the configuration to parse from the file.
                   14893: 
                   14894: Parses and returns the bubblesheet configuration line selected as a
                   14895: hash of configuration file fields.
                   14896: 
                   14897: 
                   14898: Returns:
                   14899:     If the named configuration is not in the file, an empty
                   14900:     hash is returned.
                   14901: 
                   14902:     a hash with the fields
                   14903:       name         - internal name for the this configuration setup
                   14904:       description  - text to display to operator that describes this config
                   14905:       CODElocation - if 0 or the string 'none'
                   14906:                           - no CODE exists for this config
                   14907:                      if -1 || the string 'letter'
                   14908:                           - a CODE exists for this config and is
                   14909:                             a string of letters
                   14910:                      Unsupported value (but planned for future support)
                   14911:                           if a positive integer
                   14912:                                - The CODE exists as the first n items from
                   14913:                                  the question section of the form
                   14914:                           if the string 'number'
                   14915:                                - The CODE exists for this config and is
                   14916:                                  a string of numbers
                   14917:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14918:                      the CODE starts
                   14919:       CODElength  - length of the CODE
                   14920:       IDstart     - column where the student/employee ID starts
                   14921:       IDlength    - length of the student/employee ID info
                   14922:       Qstart      - column where the information from the bubbled
                   14923:                     'questions' start
                   14924:       Qlength     - number of columns comprising a single bubble line from
                   14925:                     the sheet. (usually either 1 or 10)
                   14926:       Qon         - either a single character representing the character used
                   14927:                     to signal a bubble was chosen in the positional setup, or
                   14928:                     the string 'letter' if the letter of the chosen bubble is
                   14929:                     in the final, or 'number' if a number representing the
                   14930:                     chosen bubble is in the file (1->A 0->J)
                   14931:       Qoff        - the character used to represent that a bubble was
                   14932:                     left blank
                   14933:       PaperID     - if the scanning process generates a unique number for each
                   14934:                     sheet scanned the column that this ID number starts in
                   14935:       PaperIDlength - number of columns that comprise the unique ID number
                   14936:                       for the sheet of paper
                   14937:       FirstName   - column that the first name starts in
                   14938:       FirstNameLength - number of columns that the first name spans
                   14939:       LastName    - column that the last name starts in
                   14940:       LastNameLength - number of columns that the last name spans
                   14941:       BubblesPerRow - number of bubbles available in each row used to
                   14942:                       bubble an answer. (If not specified, 10 assumed).
                   14943: 
                   14944: 
                   14945: =item *
                   14946: 
                   14947: get_scantronformat_file($cdom)
                   14948: 
                   14949: $cdom - the course's domain (optional); if not supplied, uses
                   14950: domain for current $env{'request.course.id'}.
                   14951: 
                   14952: Returns an array containing lines from the scantron format file for
                   14953: the domain of the course.
                   14954: 
                   14955: If a url for a custom.tab file is listed in domain's configuration.db,
                   14956: lines are from this file.
                   14957: 
                   14958: Otherwise, if a default.tab has been published in RES space by the
                   14959: domainconfig user, lines are from this file.
                   14960: 
                   14961: Otherwise, fall back to getting lines from the legacy file on the
                   14962: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14963: 
                   14964: =back
                   14965: 
1.243     albertel 14966: =head2 Resource Subroutines
                   14967: 
                   14968: =over 4
1.191     harris41 14969: 
                   14970: =item *
                   14971: 
1.243     albertel 14972: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14973: 
                   14974: =item *
                   14975: 
1.243     albertel 14976: repcopy($filename) : subscribes to the requested file, and attempts to
                   14977: replicate from the owning library server, Might return
1.607     raeburn  14978: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14979: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14980: resource. Expects the local filesystem pathname
                   14981: (/home/httpd/html/res/....)
                   14982: 
                   14983: =back
                   14984: 
                   14985: =head2 Resource Information
                   14986: 
                   14987: =over 4
1.191     harris41 14988: 
                   14989: =item *
                   14990: 
1.1172.2.28  raeburn  14991: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14992: and returns the value of a variety of different possible values,
                   14993: $varname should be a request string, and the other parameters can be
                   14994: used to specify who and what one is asking about. Ordinarily, $cid 
                   14995: does not need to be specified, as it is retrived from 
                   14996: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14997: within lonuserstate::loadmap() when initializing a course, before
                   14998: $env{'request.course.id'} has been set, so it needs to be provided
                   14999: in that one case.
1.243     albertel 15000: 
                   15001: Possible values for $varname are environment.lastname (or other item
                   15002: from the envirnment hash), user.name (or someother aspect about the
                   15003: user), resource.0.maxtries (or some other part and parameter of a
                   15004: resource)
1.204     albertel 15005: 
                   15006: =item *
                   15007: 
1.243     albertel 15008: directcondval($number) : get current value of a condition; reads from a state
                   15009: string
1.204     albertel 15010: 
                   15011: =item *
                   15012: 
1.243     albertel 15013: condval($condidx) : value of condition index based on state
1.204     albertel 15014: 
                   15015: =item *
                   15016: 
1.243     albertel 15017: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15018: resource's metadata, $what should be either a specific key, or either
                   15019: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15020: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15021: 
                   15022: this function automatically caches all requests
1.191     harris41 15023: 
                   15024: =item *
                   15025: 
1.243     albertel 15026: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15027: network of library servers; returns file handle of where SQL and regex results
                   15028: will be stored for query
1.191     harris41 15029: 
                   15030: =item *
                   15031: 
1.1172.2.66  raeburn  15032: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15033: return symbolic list entry (all arguments optional).
                   15034: 
                   15035: Args: filename is the filename (including path) for the file for which a symb
                   15036: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15037: to check access status if more than one resource was found in the bighash
                   15038: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15039: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15040: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15041: cause possible symbs to be checked to determine if they are subject to content
                   15042: blocking, if so they will not be included as possible symbs; possibles is a
                   15043: ref to a hash, which, as a side effect, will be populated with all possible
                   15044: symbs (content blocking not tested).
                   15045: 
1.243     albertel 15046: returns the data handle
1.191     harris41 15047: 
                   15048: =item *
                   15049: 
1.1172.2.17  raeburn  15050: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15051: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15052: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15053: on failure, user must be in a course, as it assumes the existence of
                   15054: the course initial hash, and uses $env('request.course.id'}.  The third
                   15055: arg is an optional reference to a scalar.  If this arg is passed in the
                   15056: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15057: encrypted; otherwise it will be null.
1.243     albertel 15058: 
1.191     harris41 15059: =item *
                   15060: 
1.243     albertel 15061: symbclean($symb) : removes versions numbers from a symb, returns the
                   15062: cleaned symb
1.191     harris41 15063: 
                   15064: =item *
                   15065: 
1.243     albertel 15066: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15067: course map, user must be in a course for it to work.
1.191     harris41 15068: 
                   15069: =item *
                   15070: 
1.243     albertel 15071: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15072: 
                   15073: =item *
                   15074: 
1.243     albertel 15075: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15076: a random seed, all arguments are optional, if they aren't sent it uses the
                   15077: environment to derive them. Note: if symb isn't sent and it can't get one
                   15078: from &symbread it will use the current time as its return value
1.191     harris41 15079: 
                   15080: =item *
                   15081: 
1.243     albertel 15082: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15083: unfakeable, receipt
1.191     harris41 15084: 
                   15085: =item *
                   15086: 
1.620     albertel 15087: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15088: 
                   15089: =item *
                   15090: 
1.243     albertel 15091: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15092: 
                   15093: =item *
                   15094: 
1.243     albertel 15095: 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 15096: 
                   15097: =item *
                   15098: 
1.243     albertel 15099: 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 15100: 
                   15101: =item *
                   15102: 
1.243     albertel 15103: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15104: 
                   15105: =item *
                   15106: 
1.243     albertel 15107: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15108: forcing spreadsheet to reevaluate the resource scores next time.
                   15109: 
1.1172.2.13  raeburn  15110: =item *
                   15111: 
                   15112: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15113: when viewing in course context.
                   15114: 
                   15115:  input: six args -- filename (decluttered), course number, course domain,
                   15116:                     url, symb (if registered) and group (if this is a
                   15117:                     group item -- e.g., bulletin board, group page etc.).
                   15118: 
                   15119:  output: array of five scalars --
                   15120:          $cfile -- url for file editing if editable on current server
                   15121:          $home -- homeserver of resource (i.e., for author if published,
                   15122:                                           or course if uploaded.).
                   15123:          $switchserver --  1 if server switch will be needed.
                   15124:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15125:          $forceview -- 1 if icon/link should be to go to view mode
                   15126: 
                   15127: =item *
                   15128: 
                   15129: is_course_upload($file,$cnum,$cdom)
                   15130: 
                   15131: Used in course context to determine if current file was uploaded to
                   15132: the course (i.e., would be found in /userfiles/docs on the course's
                   15133: homeserver.
                   15134: 
                   15135:   input: 3 args -- filename (decluttered), course number and course domain.
                   15136:   output: boolean -- 1 if file was uploaded.
                   15137: 
1.243     albertel 15138: =back
                   15139: 
                   15140: =head2 Storing/Retreiving Data
                   15141: 
                   15142: =over 4
1.191     harris41 15143: 
                   15144: =item *
                   15145: 
1.1172.2.64  raeburn  15146: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15147: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15148: the remaining args aren't required and if they aren't passed or are '' they will
                   15149: be derived from the env (with the exception of $laststore, which is an
                   15150: optional arg used when a user's submission is stored in grading).
                   15151: $laststore is $version=$timestamp, where $version is the most recent version
                   15152: number retrieved for the corresponding $symb in the $namespace db file, and
                   15153: $timestamp is the timestamp for that transaction (UNIX time).
                   15154: $laststore is currently only passed when cstore() is called by
                   15155: structuretags::finalize_storage().
1.191     harris41 15156: 
                   15157: =item *
                   15158: 
1.1172.2.64  raeburn  15159: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15160: but uses critical subroutine
1.191     harris41 15161: 
                   15162: =item *
                   15163: 
1.243     albertel 15164: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15165: all args are optional
1.191     harris41 15166: 
                   15167: =item *
                   15168: 
1.717     albertel 15169: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15170: dumps the complete (or key matching regexp) namespace into a hash
                   15171: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15172: normally &store()ed into
                   15173: 
                   15174: $range should be either an integer '100' (give me the first 100
                   15175:                                            matching records)
                   15176:               or be  two integers sperated by a - with no spaces
                   15177:                  '30-50' (give me the 30th through the 50th matching
                   15178:                           records)
                   15179: 
                   15180: 
                   15181: =item *
                   15182: 
1.1172.2.59  raeburn  15183: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15184: replaces a &store() version of data with a replacement set of data
                   15185: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15186: reference. If $tolog is true, the transaction is logged in the courselog
                   15187: with an action=PUTSTORE.
1.717     albertel 15188: 
                   15189: =item *
                   15190: 
1.243     albertel 15191: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15192: works very similar to store/cstore, but all data is stored in a
                   15193: temporary location and can be reset using tmpreset, $storehash should
                   15194: be a hash reference, returns nothing on success
1.191     harris41 15195: 
                   15196: =item *
                   15197: 
1.243     albertel 15198: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15199: similar to restore, but all data is stored in a temporary location and
                   15200: can be reset using tmpreset. Returns a hash of values on success,
                   15201: error string otherwise.
1.191     harris41 15202: 
                   15203: =item *
                   15204: 
1.243     albertel 15205: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15206: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15207: 
                   15208: =item *
                   15209: 
1.243     albertel 15210: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15211: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15212: 
                   15213: =item *
                   15214: 
1.243     albertel 15215: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15216: namesp ($udom and $uname are optional)
1.191     harris41 15217: 
                   15218: =item *
                   15219: 
1.702     albertel 15220: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15221: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15222: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15223: 
1.702     albertel 15224: $range should be either an integer '100' (give me the first 100
                   15225:                                            matching records)
                   15226:               or be  two integers sperated by a - with no spaces
                   15227:                  '30-50' (give me the 30th through the 50th matching
                   15228:                           records)
1.449     matthew  15229: =item *
                   15230: 
                   15231: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15232: $store can be a scalar, an array reference, or if the amount to be 
                   15233: incremented is > 1, a hash reference.
                   15234: 
                   15235: ($udom and $uname are optional)
1.191     harris41 15236: 
                   15237: =item *
                   15238: 
1.243     albertel 15239: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15240: ($udom and $uname are optional)
1.191     harris41 15241: 
                   15242: =item *
                   15243: 
1.243     albertel 15244: cput($namespace,$storehash,$udom,$uname) : critical put
                   15245: ($udom and $uname are optional)
1.191     harris41 15246: 
                   15247: =item *
                   15248: 
1.748     albertel 15249: newput($namespace,$storehash,$udom,$uname) :
                   15250: 
                   15251: Attempts to store the items in the $storehash, but only if they don't
                   15252: currently exist, if this succeeds you can be certain that you have 
                   15253: successfully created a new key value pair in the $namespace db.
                   15254: 
                   15255: 
                   15256: Args:
                   15257:  $namespace: name of database to store values to
                   15258:  $storehash: hashref to store to the db
                   15259:  $udom: (optional) domain of user containing the db
                   15260:  $uname: (optional) name of user caontaining the db
                   15261: 
                   15262: Returns:
                   15263:  'ok' -> succeeded in storing all keys of $storehash
                   15264:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15265:                         least <key> already existed in the db (other
                   15266:                         requested keys may also already exist)
1.967     bisitz   15267:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15268:  'con_lost' -> unable to contact request server
                   15269:  'refused' -> action was not allowed by remote machine
                   15270: 
                   15271: 
                   15272: =item *
                   15273: 
1.243     albertel 15274: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15275: reference filled in from namesp (encrypts the return communication)
                   15276: ($udom and $uname are optional)
1.191     harris41 15277: 
                   15278: =item *
                   15279: 
1.243     albertel 15280: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15281: critical subroutine
                   15282: 
1.806     raeburn  15283: =item *
                   15284: 
1.860     raeburn  15285: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15286: array reference filled in from namespace found in domain level on either
                   15287: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15288: 
                   15289: =item *
                   15290: 
1.860     raeburn  15291: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15292: domain level either on specified domain server ($uhome) or primary domain 
                   15293: server ($udom and $uhome are optional)
1.806     raeburn  15294: 
1.943     raeburn  15295: =item * 
                   15296: 
1.1172.2.35  raeburn  15297: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15298: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15299: the target domain.
                   15300: 
                   15301: May also include additional key => value pairs for the following groups:
                   15302: 
                   15303: =over
                   15304: 
                   15305: =item
                   15306: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15307: 
                   15308: =over
                   15309: 
                   15310: =item defaultquota, authorquota
                   15311: 
                   15312: =back
                   15313: 
                   15314: =item
                   15315: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15316: portfolio for users).
                   15317: 
                   15318: =over
                   15319: 
                   15320: =item
                   15321: aboutme, blog, webdav, portfolio
                   15322: 
                   15323: =back
                   15324: 
                   15325: =item
                   15326: requestcourses: ability to request courses, and how requests are processed.
                   15327: 
                   15328: =over
                   15329: 
                   15330: =item
1.1172.2.37  raeburn  15331: official, unofficial, community, textbook
1.1172.2.35  raeburn  15332: 
                   15333: =back
                   15334: 
                   15335: =item
                   15336: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15337: 
                   15338: =over
                   15339: 
                   15340: =item
1.1172.2.44  raeburn  15341: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15342: 
                   15343: =back
                   15344: 
                   15345: =item
                   15346: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15347: for course's uploaded content.
                   15348: 
                   15349: =over
                   15350: 
                   15351: =item
1.1172.2.68  raeburn  15352: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15353: communityquota, textbookquota
1.1172.2.35  raeburn  15354: 
                   15355: =back
                   15356: 
                   15357: =item
                   15358: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15359: on your servers.
                   15360: 
                   15361: =over
                   15362: 
                   15363: =item
                   15364: remotesessions, hostedsessions
                   15365: 
                   15366: =back
                   15367: 
                   15368: =back
                   15369: 
                   15370: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15371: utility to create a configuration.db file on a domain's primary library server
                   15372: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15373: -- corresponding values are authentication type (internal, krb4, krb5,
                   15374: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15375: will be available. Values are retrieved from cache (if current), unless the
                   15376: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15377: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15378: 
                   15379: Typical usage:
1.943     raeburn  15380: 
1.1172.2.35  raeburn  15381: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15382: 
1.243     albertel 15383: =back
                   15384: 
                   15385: =head2 Network Status Functions
                   15386: 
                   15387: =over 4
1.191     harris41 15388: 
                   15389: =item *
                   15390: 
1.1137    raeburn  15391: dirlist() : return directory list based on URI (first arg).
                   15392: 
                   15393: Inputs: 1 required, 5 optional.
                   15394: 
                   15395: =over
                   15396: 
                   15397: =item 
                   15398: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15399: 
                   15400: =item
                   15401: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15402: 
                   15403: =item
                   15404: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15405: 
                   15406: =item
                   15407: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15408: 
                   15409: =item
                   15410: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15411: 
                   15412: =item 
                   15413: $alternateRoot - path to prepend in place of path from $uri.
                   15414: 
                   15415: =back
                   15416: 
                   15417: Returns: Array of up to two items.
                   15418: 
                   15419: =over
                   15420: 
                   15421: a reference to an array of files/subdirectories
                   15422: 
                   15423: =over
                   15424: 
                   15425: Each element in the array of files/subdirectories is a & separated list of
                   15426: item name and the result of running stat on the item.  If dirlist was requested
                   15427: for a file instead of a directory, the item name will be ''. For a directory 
                   15428: listing, if the item is a metadata file, the element will end &N&M 
                   15429: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15430: default copyright set (1).  
                   15431: 
                   15432: =back
                   15433: 
                   15434: a scalar containing error condition (if encountered).
                   15435: 
                   15436: =over
                   15437: 
                   15438: =item 
                   15439: no_host (no homeserver identified for $username:$domain).
                   15440: 
                   15441: =item 
                   15442: no_such_host (server contacted for listing not identified as valid host).
                   15443: 
                   15444: =item 
                   15445: con_lost (connection to remote server failed).
                   15446: 
                   15447: =item 
                   15448: refused (invalid $username:$domain received on lond side).
                   15449: 
                   15450: =item 
                   15451: no_such_dir (directory at specified path on lond side does not exist). 
                   15452: 
                   15453: =item 
                   15454: empty (directory at specified path on lond side is empty).
                   15455: 
                   15456: =over
                   15457: 
                   15458: This is currently not encountered because the &ls3, &ls2, 
                   15459: &ls (_handler) routines on the lond side do not filter out
                   15460: . and .. from a directory listing. 
                   15461: 
                   15462: =back
                   15463: 
                   15464: =back
                   15465: 
                   15466: =back
1.191     harris41 15467: 
                   15468: =item *
                   15469: 
1.243     albertel 15470: spareserver() : find server with least workload from spare.tab
                   15471: 
1.986     foxr     15472: 
                   15473: =item *
                   15474: 
                   15475: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15476: if there is no corresponding loncapa host.
                   15477: 
1.243     albertel 15478: =back
                   15479: 
1.986     foxr     15480: 
1.243     albertel 15481: =head2 Apache Request
                   15482: 
                   15483: =over 4
1.191     harris41 15484: 
                   15485: =item *
                   15486: 
1.243     albertel 15487: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15488: localhost, posts hash
                   15489: 
                   15490: =back
                   15491: 
                   15492: =head2 Data to String to Data
                   15493: 
                   15494: =over 4
1.191     harris41 15495: 
                   15496: =item *
                   15497: 
1.243     albertel 15498: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15499: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15500: 
                   15501: =item *
                   15502: 
1.243     albertel 15503: hashref2str($hashref) : convert a hashref into a string complete with
                   15504: escaping and '=' and '&' separators, supports elements that are
                   15505: arrayrefs and hashrefs
1.191     harris41 15506: 
                   15507: =item *
                   15508: 
1.243     albertel 15509: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15510: with escaping and '&' separators, supports elements that are arrayrefs
                   15511: and hashrefs
1.191     harris41 15512: 
                   15513: =item *
                   15514: 
1.243     albertel 15515: str2hash($string) : convert string to hash using unescaping and
                   15516: splitting on '=' and '&', supports elements that are arrayrefs and
                   15517: hashrefs
1.191     harris41 15518: 
                   15519: =item *
                   15520: 
1.243     albertel 15521: str2array($string) : convert string to hash using unescaping and
                   15522: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15523: 
                   15524: =back
                   15525: 
                   15526: =head2 Logging Routines
                   15527: 
                   15528: 
                   15529: These routines allow one to make log messages in the lonnet.log and
                   15530: lonnet.perm logfiles.
1.191     harris41 15531: 
1.1119    foxr     15532: =over 4
                   15533: 
1.191     harris41 15534: =item *
                   15535: 
1.243     albertel 15536: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15537: 
                   15538: =item *
                   15539: 
1.243     albertel 15540: logthis() : append message to the normal lonnet.log file, it gets
                   15541: preiodically rolled over and deleted.
1.191     harris41 15542: 
                   15543: =item *
                   15544: 
1.243     albertel 15545: logperm() : append a permanent message to lonnet.perm.log, this log
                   15546: file never gets deleted by any automated portion of the system, only
                   15547: messages of critical importance should go in here.
                   15548: 
1.1119    foxr     15549: 
1.243     albertel 15550: =back
                   15551: 
                   15552: =head2 General File Helper Routines
                   15553: 
                   15554: =over 4
1.191     harris41 15555: 
                   15556: =item *
                   15557: 
1.481     raeburn  15558: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15559: (a) files in /uploaded
                   15560:   (i) If a local copy of the file exists - 
                   15561:       compares modification date of local copy with last-modified date for 
                   15562:       definitive version stored on home server for course. If local copy is 
                   15563:       stale, requests a new version from the home server and stores it. 
                   15564:       If the original has been removed from the home server, then local copy 
                   15565:       is unlinked.
                   15566:   (ii) If local copy does not exist -
                   15567:       requests the file from the home server and stores it. 
                   15568:   
                   15569:   If $caller is 'uploadrep':  
                   15570:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15571:     for request for files originally uploaded via DOCS. 
                   15572:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15573:   
                   15574:   Otherwise:
                   15575:      This indicates a call from the content generation phase of the request.
                   15576:      -  returns the entire contents of the file or -1.
                   15577:      
                   15578: (b) files in /res
                   15579:    - returns the entire contents of a file or -1; 
                   15580:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15581: 
1.712     albertel 15582: 
                   15583: =item *
                   15584: 
                   15585: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15586:                   reference
                   15587: 
                   15588: returns either a stat() list of data about the file or an empty list
                   15589: if the file doesn't exist or couldn't find out about it (connection
                   15590: problems or user unknown)
                   15591: 
1.191     harris41 15592: =item *
                   15593: 
1.243     albertel 15594: filelocation($dir,$file) : returns file system location of a file
                   15595: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15596: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15597: and a file of ../bob will become /a/bob)
1.191     harris41 15598: 
                   15599: =item *
                   15600: 
                   15601: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15602: filelocation except for hrefs
                   15603: 
                   15604: =item *
                   15605: 
1.1172.2.49  raeburn  15606: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15607: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15608: 
1.243     albertel 15609: =back
                   15610: 
1.608     albertel 15611: =head2 Usererfile file routines (/uploaded*)
                   15612: 
                   15613: =over 4
                   15614: 
                   15615: =item *
                   15616: 
                   15617: userfileupload(): main rotine for putting a file in a user or course's
                   15618:                   filespace, arguments are,
                   15619: 
1.620     albertel 15620:  formname - required - this is the name of the element in $env where the
1.608     albertel 15621:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15622:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15623:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15624:  context - if coursedoc, store the file in the course of the active role
                   15625:              of the current user; 
                   15626:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15627:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15628:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15629:          if undefined, it will be placed in "unknown"
                   15630: 
                   15631:  (This routine calls clean_filename() to remove any dangerous
                   15632:  characters from the filename, and then calls finuserfileupload() to
                   15633:  complete the transaction)
                   15634: 
                   15635:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15636:  and /adm/notfound.html if unsuccessful
                   15637: 
                   15638: =item *
                   15639: 
                   15640: clean_filename(): routine for cleaing a filename up for storage in
                   15641:                  userfile space, argument is:
                   15642: 
                   15643:  filename - proposed filename
                   15644: 
                   15645: returns: the new clean filename
                   15646: 
                   15647: =item *
                   15648: 
1.1090    raeburn  15649: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15650: userspace, probably shouldn't be called directly
                   15651: 
                   15652:   docuname: username or courseid of destination for the file
                   15653:   docudom: domain of user/course of destination for the file
                   15654:   formname: same as for userfileupload()
1.1090    raeburn  15655:   fname: filename (including subdirectories) for the file
                   15656:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15657:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15658:   allfiles: reference to hash used to store objects found by parser
                   15659:   codebase: reference to hash used for codebases of java objects found by parser
                   15660:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15661:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15662:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15663:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15664:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15665:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15666:   mimetype: reference to scalar to accommodate mime type determined
                   15667:             from File::MMagic if $parser = parse.
1.608     albertel 15668: 
                   15669:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15670:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15671:  was 'overwrite').
                   15672:  
1.608     albertel 15673: 
                   15674: =item *
                   15675: 
                   15676: renameuserfile(): renames an existing userfile to a new name
                   15677: 
                   15678:   Args:
                   15679:    docuname: username or courseid of destination for the file
                   15680:    docudom: domain of user/course of destination for the file
                   15681:    old: current file name (including any subdirs under userfiles)
                   15682:    new: desired file name (including any subdirs under userfiles)
                   15683: 
                   15684: =item *
                   15685: 
                   15686: mkdiruserfile(): creates a directory is a userfiles dir
                   15687: 
                   15688:   Args:
                   15689:    docuname: username or courseid of destination for the file
                   15690:    docudom: domain of user/course of destination for the file
                   15691:    dir: dir to create (including any subdirs under userfiles)
                   15692: 
                   15693: =item *
                   15694: 
                   15695: removeuserfile(): removes a file that exists in userfiles
                   15696: 
                   15697:   Args:
                   15698:    docuname: username or courseid of destination for the file
                   15699:    docudom: domain of user/course of destination for the file
                   15700:    fname: filname to delete (including any subdirs under userfiles)
                   15701: 
                   15702: =item *
                   15703: 
                   15704: removeuploadedurl(): convience function for removeuserfile()
                   15705: 
                   15706:   Args:
                   15707:    url:  a full /uploaded/... url to delete
                   15708: 
1.747     albertel 15709: =item * 
                   15710: 
                   15711: get_portfile_permissions():
                   15712:   Args:
                   15713:     domain: domain of user or course contain the portfolio files
                   15714:     user: name of user or num of course contain the portfolio files
                   15715:   Returns:
                   15716:     hashref of a dump of the proper file_permissions.db
                   15717:    
                   15718: 
                   15719: =item * 
                   15720: 
                   15721: get_access_controls():
                   15722: 
                   15723: Args:
                   15724:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15725:   group: (optional) the group you want the files associated with
                   15726:   file: (optional) the file you want access info on
                   15727: 
                   15728: Returns:
1.749     raeburn  15729:     a hash (keys are file names) of hashes containing
                   15730:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15731:         values are XML containing access control settings (see below) 
1.747     albertel 15732: 
                   15733: Internal notes:
                   15734: 
1.749     raeburn  15735:  access controls are stored in file_permissions.db as key=value pairs.
                   15736:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15737:         where scope -> public,guest,course,group,domains or users.
                   15738:               end -> UNIX time for end of access (0 -> no end date)
                   15739:               start -> UNIX time for start of access
                   15740: 
                   15741:     value -> XML description of access control
                   15742:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15743:             <start></start>
                   15744:             <end></end>
                   15745: 
                   15746:             <password></password>  for scope type = guest
                   15747: 
                   15748:             <domain></domain>     for scope type = course or group
                   15749:             <number></number>
                   15750:             <roles id="">
                   15751:              <role></role>
                   15752:              <access></access>
                   15753:              <section></section>
                   15754:              <group></group>
                   15755:             </roles>
                   15756: 
                   15757:             <dom></dom>         for scope type = domains
                   15758: 
                   15759:             <users>             for scope type = users
                   15760:              <user>
                   15761:               <uname></uname>
                   15762:               <udom></udom>
                   15763:              </user>
                   15764:             </users>
                   15765:            </scope> 
                   15766:               
                   15767:  Access data is also aggregated for each file in an additional key=value pair:
                   15768:  key -> path to file/file_name\0accesscontrol 
                   15769:  value -> reference to hash
                   15770:           hash contains key = value pairs
                   15771:           where key = uniqueID:scope_end_start
                   15772:                 value = UNIX time record was last updated
                   15773: 
                   15774:           Used to improve speed of look-ups of access controls for each file.  
                   15775:  
                   15776:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15777: 
1.1172.2.13  raeburn  15778: =item *
                   15779: 
1.749     raeburn  15780: modify_access_controls():
                   15781: 
                   15782: Modifies access controls for a portfolio file
                   15783: Args
                   15784: 1. file name
                   15785: 2. reference to hash of required changes,
                   15786: 3. domain
                   15787: 4. username
                   15788:   where domain,username are the domain of the portfolio owner 
                   15789:   (either a user or a course) 
                   15790: 
                   15791: Returns:
                   15792: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15793: 2. result of deletions ('ok' or 'error', with error message).
                   15794: 3. reference to hash of any new or updated access controls.
                   15795: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15796:    key = integer (inbound ID)
1.1172.2.13  raeburn  15797:    value = uniqueID
                   15798: 
                   15799: =item *
                   15800: 
                   15801: get_timebased_id():
                   15802: 
                   15803: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15804: course via the Course Editor (e.g., folders, composite pages,
                   15805: group bulletin boards).
                   15806: 
                   15807: Args: (first three required; six others optional)
                   15808: 
                   15809: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15810:    docssequence, or name of group
                   15811: 
                   15812: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15813:    e.g., num, boardids
                   15814: 
                   15815: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15816:    file will be named nohist_namespace.db
                   15817: 
                   15818: 4. cdom: domain of course; default is current course domain from %env
                   15819: 
                   15820: 5. cnum: course number; default is current course number from %env
                   15821: 
                   15822: 6. idtype: set to concat if an additional digit is to be appended to the
                   15823:    unix timestamp to form the suffix, if the plain timestamp is already
                   15824:    in use.  Default is to not do this, but simply increment the unix
                   15825:    timestamp by 1 until a unique key is obtained.
                   15826: 
                   15827: 7. who: holder of locking key; defaults to user:domain for user.
                   15828: 
                   15829: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15830:    retrying); default is 3.
                   15831: 
                   15832: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15833: 
                   15834: Returns:
                   15835: 
                   15836: 1. suffix obtained (numeric)
                   15837: 
                   15838: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15839: 
                   15840: 3. error: contains (localized) error message if an error occurred.
                   15841: 
1.747     albertel 15842: 
1.608     albertel 15843: =back
                   15844: 
1.243     albertel 15845: =head2 HTTP Helper Routines
                   15846: 
                   15847: =over 4
                   15848: 
1.191     harris41 15849: =item *
                   15850: 
                   15851: escape() : unpack non-word characters into CGI-compatible hex codes
                   15852: 
                   15853: =item *
                   15854: 
                   15855: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15856: 
1.243     albertel 15857: =back
                   15858: 
                   15859: =head1 PRIVATE SUBROUTINES
                   15860: 
                   15861: =head2 Underlying communication routines (Shouldn't call)
                   15862: 
                   15863: =over 4
                   15864: 
                   15865: =item *
                   15866: 
                   15867: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15868: 
                   15869: =item *
                   15870: 
                   15871: reply() : uses subreply to send a message to remote machine, logs all failures
                   15872: 
                   15873: =item *
                   15874: 
                   15875: critical() : passes a critical message to another server; if cannot
                   15876: get through then place message in connection buffer directory and
                   15877: returns con_delayed, if incapable of saving message, returns
                   15878: con_failed
                   15879: 
                   15880: =item *
                   15881: 
                   15882: reconlonc() : tries to reconnect lonc client processes.
                   15883: 
                   15884: =back
                   15885: 
                   15886: =head2 Resource Access Logging
                   15887: 
                   15888: =over 4
                   15889: 
                   15890: =item *
                   15891: 
                   15892: flushcourselogs() : flush (save) buffer logs and access logs
                   15893: 
                   15894: =item *
                   15895: 
                   15896: courselog($what) : save message for course in hash
                   15897: 
                   15898: =item *
                   15899: 
                   15900: courseacclog($what) : save message for course using &courselog().  Perform
                   15901: special processing for specific resource types (problems, exams, quizzes, etc).
                   15902: 
1.191     harris41 15903: =item *
                   15904: 
                   15905: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15906: as a PerlChildExitHandler
1.243     albertel 15907: 
                   15908: =back
                   15909: 
                   15910: =head2 Other
                   15911: 
                   15912: =over 4
                   15913: 
                   15914: =item *
                   15915: 
                   15916: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15917: 
                   15918: =back
                   15919: 
                   15920: =cut
1.877     foxr     15921: 

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